Reserve 10 chars for weekday name in agenda.
[org-mode.git] / org.el
blob0a7d9d368f122322e6cf5d9b22f992f5fed94f73
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 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.23a++
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.23a++"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 (defvar org-modules) ; defined below
160 (defvar org-modules-loaded nil
161 "Have the modules been loaded already?")
163 (defun org-load-modules-maybe (&optional force)
164 "Load all extensions listed in `org-default-extensions'."
165 (when (or force (not org-modules-loaded))
166 (mapc (lambda (ext)
167 (condition-case nil (require ext)
168 (error (message "Problems while trying to load feature `%s'" ext))))
169 org-modules)
170 (setq org-modules-loaded t)))
172 (defun org-set-modules (var value)
173 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
174 (set var value)
175 (when (featurep 'org)
176 (org-load-modules-maybe 'force)))
178 (defcustom org-modules '(org-bbdb org-gnus org-info org-irc org-mhe org-rmail org-vm org-wl)
179 "Modules that should always be loaded together with org.el.
180 If the description starts with <A>, this means the extension
181 will be autoloaded when needed, preloading is not necessary.
182 If a description starts with <C>, the file is not part of emacs
183 and loading it will require that you have downloaded and properly installed
184 the org-mode distribution."
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
191 (const :tag " info: Links to Info nodes" org-info)
192 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
193 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
194 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
195 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
196 (const :tag " vm: Links to VM folders/messages" org-vm)
197 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
198 (const :tag " mouse: Additional mouse support" org-mouse)
199 ; (const :tag "A export-latex: LaTeX export" org-export-latex)
200 ; (const :tag "A publish: Publishing" org-publish)
202 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
203 (const :tag "C bibtex: Org links to BibTeX entries" org-bibtex)
204 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
205 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
206 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
207 (const :tag "C id: Global id's for identifying entries" org-id)
208 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
209 (const :tag "C iswitchb: Use iswitchb to select Org buffer" org-iswitchb)
210 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
211 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
212 (const :tag "C mew: Support for links to messages in Mew" org-mew)
213 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
214 (const :tag "C registry: A registry for Org links" org-registry)
215 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
216 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
217 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)))
219 ;; FIXME: Needs a separate group...
220 (defcustom org-completion-fallback-command 'hippie-expand
221 "The expansion command called by \\[org-complete] in normal context.
222 Normal means, no org-mode-specific context."
223 :group 'org
224 :type 'function)
226 (defgroup org-startup nil
227 "Options concerning startup of Org-mode."
228 :tag "Org Startup"
229 :group 'org)
231 (defcustom org-startup-folded t
232 "Non-nil means, entering Org-mode will switch to OVERVIEW.
233 This can also be configured on a per-file basis by adding one of
234 the following lines anywhere in the buffer:
236 #+STARTUP: fold
237 #+STARTUP: nofold
238 #+STARTUP: content"
239 :group 'org-startup
240 :type '(choice
241 (const :tag "nofold: show all" nil)
242 (const :tag "fold: overview" t)
243 (const :tag "content: all headlines" content)))
245 (defcustom org-startup-truncated t
246 "Non-nil means, entering Org-mode will set `truncate-lines'.
247 This is useful since some lines containing links can be very long and
248 uninteresting. Also tables look terrible when wrapped."
249 :group 'org-startup
250 :type 'boolean)
252 (defcustom org-startup-align-all-tables nil
253 "Non-nil means, align all tables when visiting a file.
254 This is useful when the column width in tables is forced with <N> cookies
255 in table fields. Such tables will look correct only after the first re-align.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
258 #+STARTUP: align
259 #+STARTUP: noalign"
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-insert-mode-line-in-empty-file nil
264 "Non-nil means insert the first line setting Org-mode in empty files.
265 When the function `org-mode' is called interactively in an empty file, this
266 normally means that the file name does not automatically trigger Org-mode.
267 To ensure that the file will always be in Org-mode in the future, a
268 line enforcing Org-mode will be inserted into the buffer, if this option
269 has been set."
270 :group 'org-startup
271 :type 'boolean)
273 (defcustom org-replace-disputed-keys nil
274 "Non-nil means use alternative key bindings for some keys.
275 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
276 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
277 If you want to use Org-mode together with one of these other modes,
278 or more generally if you would like to move some Org-mode commands to
279 other keys, set this variable and configure the keys with the variable
280 `org-disputed-keys'.
282 This option is only relevant at load-time of Org-mode, and must be set
283 *before* org.el is loaded. Changing it requires a restart of Emacs to
284 become effective."
285 :group 'org-startup
286 :type 'boolean)
288 (if (fboundp 'defvaralias)
289 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
291 (defcustom org-disputed-keys
292 '(([(shift up)] . [(meta p)])
293 ([(shift down)] . [(meta n)])
294 ([(shift left)] . [(meta -)])
295 ([(shift right)] . [(meta +)])
296 ([(control shift right)] . [(meta shift +)])
297 ([(control shift left)] . [(meta shift -)]))
298 "Keys for which Org-mode and other modes compete.
299 This is an alist, cars are the default keys, second element specifies
300 the alternative to use when `org-replace-disputed-keys' is t.
302 Keys can be specified in any syntax supported by `define-key'.
303 The value of this option takes effect only at Org-mode's startup,
304 therefore you'll have to restart Emacs to apply it after changing."
305 :group 'org-startup
306 :type 'alist)
308 (defun org-key (key)
309 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
310 Or return the original if not disputed."
311 (if org-replace-disputed-keys
312 (let* ((nkey (key-description key))
313 (x (org-find-if (lambda (x)
314 (equal (key-description (car x)) nkey))
315 org-disputed-keys)))
316 (if x (cdr x) key))
317 key))
319 (defun org-find-if (predicate seq)
320 (catch 'exit
321 (while seq
322 (if (funcall predicate (car seq))
323 (throw 'exit (car seq))
324 (pop seq)))))
326 (defun org-defkey (keymap key def)
327 "Define a key, possibly translated, as returned by `org-key'."
328 (define-key keymap (org-key key) def))
330 (defcustom org-ellipsis nil
331 "The ellipsis to use in the Org-mode outline.
332 When nil, just use the standard three dots. When a string, use that instead,
333 When a face, use the standart 3 dots, but with the specified face.
334 The change affects only Org-mode (which will then use its own display table).
335 Changing this requires executing `M-x org-mode' in a buffer to become
336 effective."
337 :group 'org-startup
338 :type '(choice (const :tag "Default" nil)
339 (face :tag "Face" :value org-warning)
340 (string :tag "String" :value "...#")))
342 (defvar org-display-table nil
343 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
345 (defgroup org-keywords nil
346 "Keywords in Org-mode."
347 :tag "Org Keywords"
348 :group 'org)
350 (defcustom org-deadline-string "DEADLINE:"
351 "String to mark deadline entries.
352 A deadline is this string, followed by a time stamp. Should be a word,
353 terminated by a colon. You can insert a schedule keyword and
354 a timestamp with \\[org-deadline].
355 Changes become only effective after restarting Emacs."
356 :group 'org-keywords
357 :type 'string)
359 (defcustom org-scheduled-string "SCHEDULED:"
360 "String to mark scheduled TODO entries.
361 A schedule is this string, followed by a time stamp. Should be a word,
362 terminated by a colon. You can insert a schedule keyword and
363 a timestamp with \\[org-schedule].
364 Changes become only effective after restarting Emacs."
365 :group 'org-keywords
366 :type 'string)
368 (defcustom org-closed-string "CLOSED:"
369 "String used as the prefix for timestamps logging closing a TODO entry."
370 :group 'org-keywords
371 :type 'string)
373 (defcustom org-clock-string "CLOCK:"
374 "String used as prefix for timestamps clocking work hours on an item."
375 :group 'org-keywords
376 :type 'string)
378 (defcustom org-comment-string "COMMENT"
379 "Entries starting with this keyword will never be exported.
380 An entry can be toggled between COMMENT and normal with
381 \\[org-toggle-comment].
382 Changes become only effective after restarting Emacs."
383 :group 'org-keywords
384 :type 'string)
386 (defcustom org-quote-string "QUOTE"
387 "Entries starting with this keyword will be exported in fixed-width font.
388 Quoting applies only to the text in the entry following the headline, and does
389 not extend beyond the next headline, even if that is lower level.
390 An entry can be toggled between QUOTE and normal with
391 \\[org-toggle-fixed-width-section]."
392 :group 'org-keywords
393 :type 'string)
395 (defconst org-repeat-re
396 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
397 "Regular expression for specifying repeated events.
398 After a match, group 1 contains the repeat expression.")
400 (defgroup org-structure nil
401 "Options concerning the general structure of Org-mode files."
402 :tag "Org Structure"
403 :group 'org)
405 (defgroup org-reveal-location nil
406 "Options about how to make context of a location visible."
407 :tag "Org Reveal Location"
408 :group 'org-structure)
410 (defconst org-context-choice
411 '(choice
412 (const :tag "Always" t)
413 (const :tag "Never" nil)
414 (repeat :greedy t :tag "Individual contexts"
415 (cons
416 (choice :tag "Context"
417 (const agenda)
418 (const org-goto)
419 (const occur-tree)
420 (const tags-tree)
421 (const link-search)
422 (const mark-goto)
423 (const bookmark-jump)
424 (const isearch)
425 (const default))
426 (boolean))))
427 "Contexts for the reveal options.")
429 (defcustom org-show-hierarchy-above '((default . t))
430 "Non-nil means, show full hierarchy when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the hierarchy of headings
433 above the exposed location is shown.
434 Turning this off for example for sparse trees makes them very compact.
435 Instead of t, this can also be an alist specifying this option for different
436 contexts. Valid contexts are
437 agenda when exposing an entry from the agenda
438 org-goto when using the command `org-goto' on key C-c C-j
439 occur-tree when using the command `org-occur' on key C-c /
440 tags-tree when constructing a sparse tree based on tags matches
441 link-search when exposing search matches associated with a link
442 mark-goto when exposing the jump goal of a mark
443 bookmark-jump when exposing a bookmark location
444 isearch when exiting from an incremental search
445 default default for all contexts not set explicitly"
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-following-heading '((default . nil))
450 "Non-nil means, show following heading when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the heading following the
453 match is shown.
454 Turning this off for example for sparse trees makes them very compact,
455 but makes it harder to edit the location of the match. In such a case,
456 use the command \\[org-reveal] to show more context.
457 Instead of t, this can also be an alist specifying this option for different
458 contexts. See `org-show-hierarchy-above' for valid contexts."
459 :group 'org-reveal-location
460 :type org-context-choice)
462 (defcustom org-show-siblings '((default . nil) (isearch t))
463 "Non-nil means, show all sibling heading when revealing a location.
464 Org-mode often shows locations in an org-mode file which might have
465 been invisible before. When this is set, the sibling of the current entry
466 heading are all made visible. If `org-show-hierarchy-above' is t,
467 the same happens on each level of the hierarchy above the current entry.
469 By default this is on for the isearch context, off for all other contexts.
470 Turning this off for example for sparse trees makes them very compact,
471 but makes it harder to edit the location of the match. In such a case,
472 use the command \\[org-reveal] to show more context.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
478 (defcustom org-show-entry-below '((default . nil))
479 "Non-nil means, show the entry below a headline when revealing a location.
480 Org-mode often shows locations in an org-mode file which might have
481 been invisible before. When this is set, the text below the headline that is
482 exposed is also shown.
484 By default this is off for all contexts.
485 Instead of t, this can also be an alist specifying this option for different
486 contexts. See `org-show-hierarchy-above' for valid contexts."
487 :group 'org-reveal-location
488 :type org-context-choice)
490 (defgroup org-cycle nil
491 "Options concerning visibility cycling in Org-mode."
492 :tag "Org Cycle"
493 :group 'org-structure)
495 (defcustom org-drawers '("PROPERTIES" "CLOCK")
496 "Names of drawers. Drawers are not opened by cycling on the headline above.
497 Drawers only open with a TAB on the drawer line itself. A drawer looks like
498 this:
499 :DRAWERNAME:
500 .....
501 :END:
502 The drawer \"PROPERTIES\" is special for capturing properties through
503 the property API.
505 Drawers can be defined on the per-file basis with a line like:
507 #+DRAWERS: HIDDEN STATE PROPERTIES"
508 :group 'org-structure
509 :type '(repeat (string :tag "Drawer Name")))
511 (defcustom org-cycle-global-at-bob nil
512 "Cycle globally if cursor is at beginning of buffer and not at a headline.
513 This makes it possible to do global cycling without having to use S-TAB or
514 C-u TAB. For this special case to work, the first line of the buffer
515 must not be a headline - it may be empty ot some other text. When used in
516 this way, `org-cycle-hook' is disables temporarily, to make sure the
517 cursor stays at the beginning of the buffer.
518 When this option is nil, don't do anything special at the beginning
519 of the buffer."
520 :group 'org-cycle
521 :type 'boolean)
523 (defcustom org-cycle-emulate-tab t
524 "Where should `org-cycle' emulate TAB.
525 nil Never
526 white Only in completely white lines
527 whitestart Only at the beginning of lines, before the first non-white char
528 t Everywhere except in headlines
529 exc-hl-bol Everywhere except at the start of a headline
530 If TAB is used in a place where it does not emulate TAB, the current subtree
531 visibility is cycled."
532 :group 'org-cycle
533 :type '(choice (const :tag "Never" nil)
534 (const :tag "Only in completely white lines" white)
535 (const :tag "Before first char in a line" whitestart)
536 (const :tag "Everywhere except in headlines" t)
537 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
540 (defcustom org-cycle-separator-lines 2
541 "Number of empty lines needed to keep an empty line between collapsed trees.
542 If you leave an empty line between the end of a subtree and the following
543 headline, this empty line is hidden when the subtree is folded.
544 Org-mode will leave (exactly) one empty line visible if the number of
545 empty lines is equal or larger to the number given in this variable.
546 So the default 2 means, at least 2 empty lines after the end of a subtree
547 are needed to produce free space between a collapsed subtree and the
548 following headline.
550 Special case: when 0, never leave empty lines in collapsed view."
551 :group 'org-cycle
552 :type 'integer)
554 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
555 org-cycle-hide-drawers
556 org-cycle-show-empty-lines
557 org-optimize-window-after-visibility-change)
558 "Hook that is run after `org-cycle' has changed the buffer visibility.
559 The function(s) in this hook must accept a single argument which indicates
560 the new state that was set by the most recent `org-cycle' command. The
561 argument is a symbol. After a global state change, it can have the values
562 `overview', `content', or `all'. After a local state change, it can have
563 the values `folded', `children', or `subtree'."
564 :group 'org-cycle
565 :type 'hook)
567 (defgroup org-edit-structure nil
568 "Options concerning structure editing in Org-mode."
569 :tag "Org Edit Structure"
570 :group 'org-structure)
572 (defcustom org-odd-levels-only nil
573 "Non-nil means, skip even levels and only use odd levels for the outline.
574 This has the effect that two stars are being added/taken away in
575 promotion/demotion commands. It also influences how levels are
576 handled by the exporters.
577 Changing it requires restart of `font-lock-mode' to become effective
578 for fontification also in regions already fontified.
579 You may also set this on a per-file basis by adding one of the following
580 lines to the buffer:
582 #+STARTUP: odd
583 #+STARTUP: oddeven"
584 :group 'org-edit-structure
585 :group 'org-font-lock
586 :type 'boolean)
588 (defcustom org-adapt-indentation t
589 "Non-nil means, adapt indentation when promoting and demoting.
590 When this is set and the *entire* text in an entry is indented, the
591 indentation is increased by one space in a demotion command, and
592 decreased by one in a promotion command. If any line in the entry
593 body starts at column 0, indentation is not changed at all."
594 :group 'org-edit-structure
595 :type 'boolean)
597 (defcustom org-special-ctrl-a/e nil
598 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
599 When t, `C-a' will bring back the cursor to the beginning of the
600 headline text, i.e. after the stars and after a possible TODO keyword.
601 In an item, this will be the position after the bullet.
602 When the cursor is already at that position, another `C-a' will bring
603 it to the beginning of the line.
604 `C-e' will jump to the end of the headline, ignoring the presence of tags
605 in the headline. A second `C-e' will then jump to the true end of the
606 line, after any tags.
607 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
608 and only a directly following, identical keypress will bring the cursor
609 to the special positions."
610 :group 'org-edit-structure
611 :type '(choice
612 (const :tag "off" nil)
613 (const :tag "after bullet first" t)
614 (const :tag "border first" reversed)))
616 (if (fboundp 'defvaralias)
617 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
619 (defcustom org-special-ctrl-k nil
620 "Non-nil means `C-k' will behave specially in headlines.
621 When nil, `C-k' will call the default `kill-line' command.
622 When t, the following will happen while the cursor is in the headline:
624 - When the cursor is at the beginning of a headline, kill the entire
625 line and possible the folded subtree below the line.
626 - When in the middle of the headline text, kill the headline up to the tags.
627 - When after the headline text, kill the tags."
628 :group 'org-edit-structure
629 :type 'boolean)
631 (defcustom org-M-RET-may-split-line '((default . t))
632 "Non-nil means, M-RET will split the line at the cursor position.
633 When nil, it will go to the end of the line before making a
634 new line.
635 You may also set this option in a different way for different
636 contexts. Valid contexts are:
638 headline when creating a new headline
639 item when creating a new item
640 table in a table field
641 default the value to be used for all contexts not explicitly
642 customized"
643 :group 'org-structure
644 :group 'org-table
645 :type '(choice
646 (const :tag "Always" t)
647 (const :tag "Never" nil)
648 (repeat :greedy t :tag "Individual contexts"
649 (cons
650 (choice :tag "Context"
651 (const headline)
652 (const item)
653 (const table)
654 (const default))
655 (boolean)))))
658 (defcustom org-blank-before-new-entry '((heading . nil)
659 (plain-list-item . nil))
660 "Should `org-insert-heading' leave a blank line before new heading/item?
661 The value is an alist, with `heading' and `plain-list-item' as car,
662 and a boolean flag as cdr."
663 :group 'org-edit-structure
664 :type '(list
665 (cons (const heading) (boolean))
666 (cons (const plain-list-item) (boolean))))
668 (defcustom org-insert-heading-hook nil
669 "Hook being run after inserting a new heading."
670 :group 'org-edit-structure
671 :type 'hook)
673 (defcustom org-enable-fixed-width-editor t
674 "Non-nil means, lines starting with \":\" are treated as fixed-width.
675 This currently only means, they are never auto-wrapped.
676 When nil, such lines will be treated like ordinary lines.
677 See also the QUOTE keyword."
678 :group 'org-edit-structure
679 :type 'boolean)
681 (defcustom org-goto-auto-isearch t
682 "Non-nil means, typing characters in org-goto starts incremental search."
683 :group 'org-edit-structure
684 :type 'boolean)
686 (defgroup org-sparse-trees nil
687 "Options concerning sparse trees in Org-mode."
688 :tag "Org Sparse Trees"
689 :group 'org-structure)
691 (defcustom org-highlight-sparse-tree-matches t
692 "Non-nil means, highlight all matches that define a sparse tree.
693 The highlights will automatically disappear the next time the buffer is
694 changed by an edit command."
695 :group 'org-sparse-trees
696 :type 'boolean)
698 (defcustom org-remove-highlights-with-change t
699 "Non-nil means, any change to the buffer will remove temporary highlights.
700 Such highlights are created by `org-occur' and `org-clock-display'.
701 When nil, `C-c C-c needs to be used to get rid of the highlights.
702 The highlights created by `org-preview-latex-fragment' always need
703 `C-c C-c' to be removed."
704 :group 'org-sparse-trees
705 :group 'org-time
706 :type 'boolean)
709 (defcustom org-occur-hook '(org-first-headline-recenter)
710 "Hook that is run after `org-occur' has constructed a sparse tree.
711 This can be used to recenter the window to show as much of the structure
712 as possible."
713 :group 'org-sparse-trees
714 :type 'hook)
716 (defgroup org-plain-lists nil
717 "Options concerning plain lists in Org-mode."
718 :tag "Org Plain lists"
719 :group 'org-structure)
721 (defcustom org-cycle-include-plain-lists nil
722 "Non-nil means, include plain lists into visibility cycling.
723 This means that during cycling, plain list items will *temporarily* be
724 interpreted as outline headlines with a level given by 1000+i where i is the
725 indentation of the bullet. In all other operations, plain list items are
726 not seen as headlines. For example, you cannot assign a TODO keyword to
727 such an item."
728 :group 'org-plain-lists
729 :type 'boolean)
731 (defcustom org-plain-list-ordered-item-terminator t
732 "The character that makes a line with leading number an ordered list item.
733 Valid values are ?. and ?\). To get both terminators, use t. While
734 ?. may look nicer, it creates the danger that a line with leading
735 number may be incorrectly interpreted as an item. ?\) therefore is
736 the safe choice."
737 :group 'org-plain-lists
738 :type '(choice (const :tag "dot like in \"2.\"" ?.)
739 (const :tag "paren like in \"2)\"" ?\))
740 (const :tab "both" t)))
742 (defcustom org-auto-renumber-ordered-lists t
743 "Non-nil means, automatically renumber ordered plain lists.
744 Renumbering happens when the sequence have been changed with
745 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
746 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
747 :group 'org-plain-lists
748 :type 'boolean)
750 (defcustom org-provide-checkbox-statistics t
751 "Non-nil means, update checkbox statistics after insert and toggle.
752 When this is set, checkbox statistics is updated each time you either insert
753 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
754 with \\[org-ctrl-c-ctrl-c\\]."
755 :group 'org-plain-lists
756 :type 'boolean)
758 (defgroup org-archive nil
759 "Options concerning archiving in Org-mode."
760 :tag "Org Archive"
761 :group 'org-structure)
763 (defcustom org-archive-tag "ARCHIVE"
764 "The tag that marks a subtree as archived.
765 An archived subtree does not open during visibility cycling, and does
766 not contribute to the agenda listings.
767 After changing this, font-lock must be restarted in the relevant buffers to
768 get the proper fontification."
769 :group 'org-archive
770 :group 'org-keywords
771 :type 'string)
773 (defcustom org-agenda-skip-archived-trees t
774 "Non-nil means, the agenda will skip any items located in archived trees.
775 An archived tree is a tree marked with the tag ARCHIVE."
776 :group 'org-archive
777 :group 'org-agenda-skip
778 :type 'boolean)
780 (defcustom org-cycle-open-archived-trees nil
781 "Non-nil means, `org-cycle' will open archived trees.
782 An archived tree is a tree marked with the tag ARCHIVE.
783 When nil, archived trees will stay folded. You can still open them with
784 normal outline commands like `show-all', but not with the cycling commands."
785 :group 'org-archive
786 :group 'org-cycle
787 :type 'boolean)
789 (defcustom org-sparse-tree-open-archived-trees nil
790 "Non-nil means sparse tree construction shows matches in archived trees.
791 When nil, matches in these trees are highlighted, but the trees are kept in
792 collapsed state."
793 :group 'org-archive
794 :group 'org-sparse-trees
795 :type 'boolean)
797 (defcustom org-archive-location "%s_archive::"
798 "The location where subtrees should be archived.
799 This string consists of two parts, separated by a double-colon.
801 The first part is a file name - when omitted, archiving happens in the same
802 file. %s will be replaced by the current file name (without directory part).
803 Archiving to a different file is useful to keep archived entries from
804 contributing to the Org-mode Agenda.
806 The part after the double colon is a headline. The archived entries will be
807 filed under that headline. When omitted, the subtrees are simply filed away
808 at the end of the file, as top-level entries.
810 Here are a few examples:
811 \"%s_archive::\"
812 If the current file is Projects.org, archive in file
813 Projects.org_archive, as top-level trees. This is the default.
815 \"::* Archived Tasks\"
816 Archive in the current file, under the top-level headline
817 \"* Archived Tasks\".
819 \"~/org/archive.org::\"
820 Archive in file ~/org/archive.org (absolute path), as top-level trees.
822 \"basement::** Finished Tasks\"
823 Archive in file ./basement (relative path), as level 3 trees
824 below the level 2 heading \"** Finished Tasks\".
826 You may set this option on a per-file basis by adding to the buffer a
827 line like
829 #+ARCHIVE: basement::** Finished Tasks"
830 :group 'org-archive
831 :type 'string)
833 (defcustom org-archive-mark-done t
834 "Non-nil means, mark entries as DONE when they are moved to the archive file.
835 This can be a string to set the keyword to use. When t, Org-mode will
836 use the first keyword in its list that means done."
837 :group 'org-archive
838 :type '(choice
839 (const :tag "No" nil)
840 (const :tag "Yes" t)
841 (string :tag "Use this keyword")))
843 (defcustom org-archive-stamp-time t
844 "Non-nil means, add a time stamp to entries moved to an archive file.
845 This variable is obsolete and has no effect anymore, instead add ot remove
846 `time' from the variablle `org-archive-save-context-info'."
847 :group 'org-archive
848 :type 'boolean)
850 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
851 "Parts of context info that should be stored as properties when archiving.
852 When a subtree is moved to an archive file, it looses information given by
853 context, like inherited tags, the category, and possibly also the TODO
854 state (depending on the variable `org-archive-mark-done').
855 This variable can be a list of any of the following symbols:
857 time The time of archiving.
858 file The file where the entry originates.
859 itags The local tags, in the headline of the subtree.
860 ltags The tags the subtree inherits from further up the hierarchy.
861 todo The pre-archive TODO state.
862 category The category, taken from file name or #+CATEGORY lines.
863 olpath The outline path to the item. These are all headlines above
864 the current item, separated by /, like a file path.
866 For each symbol present in the list, a property will be created in
867 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
868 information."
869 :group 'org-archive
870 :type '(set :greedy t
871 (const :tag "Time" time)
872 (const :tag "File" file)
873 (const :tag "Category" category)
874 (const :tag "TODO state" todo)
875 (const :tag "TODO state" priority)
876 (const :tag "Inherited tags" itags)
877 (const :tag "Outline path" olpath)
878 (const :tag "Local tags" ltags)))
880 (defgroup org-imenu-and-speedbar nil
881 "Options concerning imenu and speedbar in Org-mode."
882 :tag "Org Imenu and Speedbar"
883 :group 'org-structure)
885 (defcustom org-imenu-depth 2
886 "The maximum level for Imenu access to Org-mode headlines.
887 This also applied for speedbar access."
888 :group 'org-imenu-and-speedbar
889 :type 'number)
891 (defgroup org-table nil
892 "Options concerning tables in Org-mode."
893 :tag "Org Table"
894 :group 'org)
896 (defcustom org-enable-table-editor 'optimized
897 "Non-nil means, lines starting with \"|\" are handled by the table editor.
898 When nil, such lines will be treated like ordinary lines.
900 When equal to the symbol `optimized', the table editor will be optimized to
901 do the following:
902 - Automatic overwrite mode in front of whitespace in table fields.
903 This makes the structure of the table stay in tact as long as the edited
904 field does not exceed the column width.
905 - Minimize the number of realigns. Normally, the table is aligned each time
906 TAB or RET are pressed to move to another field. With optimization this
907 happens only if changes to a field might have changed the column width.
908 Optimization requires replacing the functions `self-insert-command',
909 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
910 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
911 very good at guessing when a re-align will be necessary, but you can always
912 force one with \\[org-ctrl-c-ctrl-c].
914 If you would like to use the optimized version in Org-mode, but the
915 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
917 This variable can be used to turn on and off the table editor during a session,
918 but in order to toggle optimization, a restart is required.
920 See also the variable `org-table-auto-blank-field'."
921 :group 'org-table
922 :type '(choice
923 (const :tag "off" nil)
924 (const :tag "on" t)
925 (const :tag "on, optimized" optimized)))
927 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
928 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
929 In the optimized version, the table editor takes over all simple keys that
930 normally just insert a character. In tables, the characters are inserted
931 in a way to minimize disturbing the table structure (i.e. in overwrite mode
932 for empty fields). Outside tables, the correct binding of the keys is
933 restored.
935 The default for this option is t if the optimized version is also used in
936 Org-mode. See the variable `org-enable-table-editor' for details. Changing
937 this variable requires a restart of Emacs to become effective."
938 :group 'org-table
939 :type 'boolean)
941 (defcustom orgtbl-radio-table-templates
942 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
943 % END RECEIVE ORGTBL %n
944 \\begin{comment}
945 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
946 | | |
947 \\end{comment}\n")
948 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
949 @c END RECEIVE ORGTBL %n
950 @ignore
951 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
952 | | |
953 @end ignore\n")
954 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
955 <!-- END RECEIVE ORGTBL %n -->
956 <!--
957 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
958 | | |
959 -->\n"))
960 "Templates for radio tables in different major modes.
961 All occurrences of %n in a template will be replaced with the name of the
962 table, obtained by prompting the user."
963 :group 'org-table
964 :type '(repeat
965 (list (symbol :tag "Major mode")
966 (string :tag "Format"))))
968 (defgroup org-table-settings nil
969 "Settings for tables in Org-mode."
970 :tag "Org Table Settings"
971 :group 'org-table)
973 (defcustom org-table-default-size "5x2"
974 "The default size for newly created tables, Columns x Rows."
975 :group 'org-table-settings
976 :type 'string)
978 (defcustom org-table-number-regexp
979 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
980 "Regular expression for recognizing numbers in table columns.
981 If a table column contains mostly numbers, it will be aligned to the
982 right. If not, it will be aligned to the left.
984 The default value of this option is a regular expression which allows
985 anything which looks remotely like a number as used in scientific
986 context. For example, all of the following will be considered a
987 number:
988 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
990 Other options offered by the customize interface are more restrictive."
991 :group 'org-table-settings
992 :type '(choice
993 (const :tag "Positive Integers"
994 "^[0-9]+$")
995 (const :tag "Integers"
996 "^[-+]?[0-9]+$")
997 (const :tag "Floating Point Numbers"
998 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
999 (const :tag "Floating Point Number or Integer"
1000 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1001 (const :tag "Exponential, Floating point, Integer"
1002 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1003 (const :tag "Very General Number-Like, including hex"
1004 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
1005 (string :tag "Regexp:")))
1007 (defcustom org-table-number-fraction 0.5
1008 "Fraction of numbers in a column required to make the column align right.
1009 In a column all non-white fields are considered. If at least this
1010 fraction of fields is matched by `org-table-number-fraction',
1011 alignment to the right border applies."
1012 :group 'org-table-settings
1013 :type 'number)
1015 (defgroup org-table-editing nil
1016 "Behavior of tables during editing in Org-mode."
1017 :tag "Org Table Editing"
1018 :group 'org-table)
1020 (defcustom org-table-automatic-realign t
1021 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1022 When nil, aligning is only done with \\[org-table-align], or after column
1023 removal/insertion."
1024 :group 'org-table-editing
1025 :type 'boolean)
1027 (defcustom org-table-auto-blank-field t
1028 "Non-nil means, automatically blank table field when starting to type into it.
1029 This only happens when typing immediately after a field motion
1030 command (TAB, S-TAB or RET).
1031 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1032 :group 'org-table-editing
1033 :type 'boolean)
1035 (defcustom org-table-tab-jumps-over-hlines t
1036 "Non-nil means, tab in the last column of a table with jump over a hline.
1037 If a horizontal separator line is following the current line,
1038 `org-table-next-field' can either create a new row before that line, or jump
1039 over the line. When this option is nil, a new line will be created before
1040 this line."
1041 :group 'org-table-editing
1042 :type 'boolean)
1044 (defcustom org-table-tab-recognizes-table.el t
1045 "Non-nil means, TAB will automatically notice a table.el table.
1046 When it sees such a table, it moves point into it and - if necessary -
1047 calls `table-recognize-table'."
1048 :group 'org-table-editing
1049 :type 'boolean)
1051 (defgroup org-table-calculation nil
1052 "Options concerning tables in Org-mode."
1053 :tag "Org Table Calculation"
1054 :group 'org-table)
1056 (defcustom org-table-use-standard-references t
1057 "Should org-mode work with table refrences like B3 instead of @3$2?
1058 Possible values are:
1059 nil never use them
1060 from accept as input, do not present for editing
1061 t: accept as input and present for editing"
1062 :group 'org-table-calculation
1063 :type '(choice
1064 (const :tag "Never, don't even check unser input for them" nil)
1065 (const :tag "Always, both as user input, and when editing" t)
1066 (const :tag "Convert user input, don't offer during editing" 'from)))
1068 (defcustom org-table-copy-increment t
1069 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1070 :group 'org-table-calculation
1071 :type 'boolean)
1073 (defcustom org-calc-default-modes
1074 '(calc-internal-prec 12
1075 calc-float-format (float 5)
1076 calc-angle-mode deg
1077 calc-prefer-frac nil
1078 calc-symbolic-mode nil
1079 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1080 calc-display-working-message t
1082 "List with Calc mode settings for use in calc-eval for table formulas.
1083 The list must contain alternating symbols (Calc modes variables and values).
1084 Don't remove any of the default settings, just change the values. Org-mode
1085 relies on the variables to be present in the list."
1086 :group 'org-table-calculation
1087 :type 'plist)
1089 (defcustom org-table-formula-evaluate-inline t
1090 "Non-nil means, TAB and RET evaluate a formula in current table field.
1091 If the current field starts with an equal sign, it is assumed to be a formula
1092 which should be evaluated as described in the manual and in the documentation
1093 string of the command `org-table-eval-formula'. This feature requires the
1094 Emacs calc package.
1095 When this variable is nil, formula calculation is only available through
1096 the command \\[org-table-eval-formula]."
1097 :group 'org-table-calculation
1098 :type 'boolean)
1100 (defcustom org-table-formula-use-constants t
1101 "Non-nil means, interpret constants in formulas in tables.
1102 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1103 by the value given in `org-table-formula-constants', or by a value obtained
1104 from the `constants.el' package."
1105 :group 'org-table-calculation
1106 :type 'boolean)
1108 (defcustom org-table-formula-constants nil
1109 "Alist with constant names and values, for use in table formulas.
1110 The car of each element is a name of a constant, without the `$' before it.
1111 The cdr is the value as a string. For example, if you'd like to use the
1112 speed of light in a formula, you would configure
1114 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1116 and then use it in an equation like `$1*$c'.
1118 Constants can also be defined on a per-file basis using a line like
1120 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1121 :group 'org-table-calculation
1122 :type '(repeat
1123 (cons (string :tag "name")
1124 (string :tag "value"))))
1126 (defvar org-table-formula-constants-local nil
1127 "Local version of `org-table-formula-constants'.")
1128 (make-variable-buffer-local 'org-table-formula-constants-local)
1130 (defcustom org-table-allow-automatic-line-recalculation t
1131 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1132 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1133 :group 'org-table-calculation
1134 :type 'boolean)
1136 (defgroup org-link nil
1137 "Options concerning links in Org-mode."
1138 :tag "Org Link"
1139 :group 'org)
1141 (defvar org-link-abbrev-alist-local nil
1142 "Buffer-local version of `org-link-abbrev-alist', which see.
1143 The value of this is taken from the #+LINK lines.")
1144 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1146 (defcustom org-link-abbrev-alist nil
1147 "Alist of link abbreviations.
1148 The car of each element is a string, to be replaced at the start of a link.
1149 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1150 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1152 [[linkkey:tag][description]]
1154 If REPLACE is a string, the tag will simply be appended to create the link.
1155 If the string contains \"%s\", the tag will be inserted there.
1157 REPLACE may also be a function that will be called with the tag as the
1158 only argument to create the link, which should be returned as a string.
1160 See the manual for examples."
1161 :group 'org-link
1162 :type 'alist)
1164 (defcustom org-descriptive-links t
1165 "Non-nil means, hide link part and only show description of bracket links.
1166 Bracket links are like [[link][descritpion]]. This variable sets the initial
1167 state in new org-mode buffers. The setting can then be toggled on a
1168 per-buffer basis from the Org->Hyperlinks menu."
1169 :group 'org-link
1170 :type 'boolean)
1172 (defcustom org-link-file-path-type 'adaptive
1173 "How the path name in file links should be stored.
1174 Valid values are:
1176 relative Relative to the current directory, i.e. the directory of the file
1177 into which the link is being inserted.
1178 absolute Absolute path, if possible with ~ for home directory.
1179 noabbrev Absolute path, no abbreviation of home directory.
1180 adaptive Use relative path for files in the current directory and sub-
1181 directories of it. For other files, use an absolute path."
1182 :group 'org-link
1183 :type '(choice
1184 (const relative)
1185 (const absolute)
1186 (const noabbrev)
1187 (const adaptive)))
1189 (defcustom org-activate-links '(bracket angle plain radio tag date)
1190 "Types of links that should be activated in Org-mode files.
1191 This is a list of symbols, each leading to the activation of a certain link
1192 type. In principle, it does not hurt to turn on most link types - there may
1193 be a small gain when turning off unused link types. The types are:
1195 bracket The recommended [[link][description]] or [[link]] links with hiding.
1196 angular Links in angular brackes that may contain whitespace like
1197 <bbdb:Carsten Dominik>.
1198 plain Plain links in normal text, no whitespace, like http://google.com.
1199 radio Text that is matched by a radio target, see manual for details.
1200 tag Tag settings in a headline (link to tag search).
1201 date Time stamps (link to calendar).
1203 Changing this variable requires a restart of Emacs to become effective."
1204 :group 'org-link
1205 :type '(set (const :tag "Double bracket links (new style)" bracket)
1206 (const :tag "Angular bracket links (old style)" angular)
1207 (const :tag "Plain text links" plain)
1208 (const :tag "Radio target matches" radio)
1209 (const :tag "Tags" tag)
1210 (const :tag "Timestamps" date)))
1212 (defgroup org-link-store nil
1213 "Options concerning storing links in Org-mode."
1214 :tag "Org Store Link"
1215 :group 'org-link)
1217 (defcustom org-email-link-description-format "Email %c: %.30s"
1218 "Format of the description part of a link to an email or usenet message.
1219 The following %-excapes will be replaced by corresponding information:
1221 %F full \"From\" field
1222 %f name, taken from \"From\" field, address if no name
1223 %T full \"To\" field
1224 %t first name in \"To\" field, address if no name
1225 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1226 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1227 %s subject
1228 %m message-id.
1230 You may use normal field width specification between the % and the letter.
1231 This is for example useful to limit the length of the subject.
1233 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1234 :group 'org-link-store
1235 :type 'string)
1237 (defcustom org-from-is-user-regexp
1238 (let (r1 r2)
1239 (when (and user-mail-address (not (string= user-mail-address "")))
1240 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1241 (when (and user-full-name (not (string= user-full-name "")))
1242 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1243 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1244 "Regexp mached against the \"From:\" header of an email or usenet message.
1245 It should match if the message is from the user him/herself."
1246 :group 'org-link-store
1247 :type 'regexp)
1249 (defcustom org-context-in-file-links t
1250 "Non-nil means, file links from `org-store-link' contain context.
1251 A search string will be added to the file name with :: as separator and
1252 used to find the context when the link is activated by the command
1253 `org-open-at-point'.
1254 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1255 negates this setting for the duration of the command."
1256 :group 'org-link-store
1257 :type 'boolean)
1259 (defcustom org-keep-stored-link-after-insertion nil
1260 "Non-nil means, keep link in list for entire session.
1262 The command `org-store-link' adds a link pointing to the current
1263 location to an internal list. These links accumulate during a session.
1264 The command `org-insert-link' can be used to insert links into any
1265 Org-mode file (offering completion for all stored links). When this
1266 option is nil, every link which has been inserted once using \\[org-insert-link]
1267 will be removed from the list, to make completing the unused links
1268 more efficient."
1269 :group 'org-link-store
1270 :type 'boolean)
1272 (defgroup org-link-follow nil
1273 "Options concerning following links in Org-mode."
1274 :tag "Org Follow Link"
1275 :group 'org-link)
1277 (defcustom org-follow-link-hook nil
1278 "Hook that is run after a link has been followed."
1279 :group 'org-link-follow
1280 :type 'hook)
1282 (defcustom org-tab-follows-link nil
1283 "Non-nil means, on links TAB will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1288 (defcustom org-return-follows-link nil
1289 "Non-nil means, on links RET will follow the link.
1290 Needs to be set before org.el is loaded."
1291 :group 'org-link-follow
1292 :type 'boolean)
1294 (defcustom org-mouse-1-follows-link
1295 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1296 "Non-nil means, mouse-1 on a link will follow the link.
1297 A longer mouse click will still set point. Does not work on XEmacs.
1298 Needs to be set before org.el is loaded."
1299 :group 'org-link-follow
1300 :type 'boolean)
1302 (defcustom org-mark-ring-length 4
1303 "Number of different positions to be recorded in the ring
1304 Changing this requires a restart of Emacs to work correctly."
1305 :group 'org-link-follow
1306 :type 'interger)
1308 (defcustom org-link-frame-setup
1309 '((vm . vm-visit-folder-other-frame)
1310 (gnus . gnus-other-frame)
1311 (file . find-file-other-window))
1312 "Setup the frame configuration for following links.
1313 When following a link with Emacs, it may often be useful to display
1314 this link in another window or frame. This variable can be used to
1315 set this up for the different types of links.
1316 For VM, use any of
1317 `vm-visit-folder'
1318 `vm-visit-folder-other-frame'
1319 For Gnus, use any of
1320 `gnus'
1321 `gnus-other-frame'
1322 For FILE, use any of
1323 `find-file'
1324 `find-file-other-window'
1325 `find-file-other-frame'
1326 For the calendar, use the variable `calendar-setup'.
1327 For BBDB, it is currently only possible to display the matches in
1328 another window."
1329 :group 'org-link-follow
1330 :type '(list
1331 (cons (const vm)
1332 (choice
1333 (const vm-visit-folder)
1334 (const vm-visit-folder-other-window)
1335 (const vm-visit-folder-other-frame)))
1336 (cons (const gnus)
1337 (choice
1338 (const gnus)
1339 (const gnus-other-frame)))
1340 (cons (const file)
1341 (choice
1342 (const find-file)
1343 (const find-file-other-window)
1344 (const find-file-other-frame)))))
1346 (defcustom org-display-internal-link-with-indirect-buffer nil
1347 "Non-nil means, use indirect buffer to display infile links.
1348 Activating internal links (from one location in a file to another location
1349 in the same file) normally just jumps to the location. When the link is
1350 activated with a C-u prefix (or with mouse-3), the link is displayed in
1351 another window. When this option is set, the other window actually displays
1352 an indirect buffer clone of the current buffer, to avoid any visibility
1353 changes to the current buffer."
1354 :group 'org-link-follow
1355 :type 'boolean)
1357 (defcustom org-open-non-existing-files nil
1358 "Non-nil means, `org-open-file' will open non-existing files.
1359 When nil, an error will be generated."
1360 :group 'org-link-follow
1361 :type 'boolean)
1363 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1364 "Function and arguments to call for following mailto links.
1365 This is a list with the first element being a lisp function, and the
1366 remaining elements being arguments to the function. In string arguments,
1367 %a will be replaced by the address, and %s will be replaced by the subject
1368 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1369 :group 'org-link-follow
1370 :type '(choice
1371 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1372 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1373 (const :tag "message-mail" (message-mail "%a" "%s"))
1374 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1376 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1377 "Non-nil means, ask for confirmation before executing shell links.
1378 Shell links can be dangerous: just think about a link
1380 [[shell:rm -rf ~/*][Google Search]]
1382 This link would show up in your Org-mode document as \"Google Search\",
1383 but really it would remove your entire home directory.
1384 Therefore we advise against setting this variable to nil.
1385 Just change it to `y-or-n-p' of you want to confirm with a
1386 single keystroke rather than having to type \"yes\"."
1387 :group 'org-link-follow
1388 :type '(choice
1389 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1390 (const :tag "with y-or-n (faster)" y-or-n-p)
1391 (const :tag "no confirmation (dangerous)" nil)))
1393 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1394 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1395 Elisp links can be dangerous: just think about a link
1397 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1399 This link would show up in your Org-mode document as \"Google Search\",
1400 but really it would remove your entire home directory.
1401 Therefore we advise against setting this variable to nil.
1402 Just change it to `y-or-n-p' of you want to confirm with a
1403 single keystroke rather than having to type \"yes\"."
1404 :group 'org-link-follow
1405 :type '(choice
1406 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1407 (const :tag "with y-or-n (faster)" y-or-n-p)
1408 (const :tag "no confirmation (dangerous)" nil)))
1410 (defconst org-file-apps-defaults-gnu
1411 '((remote . emacs)
1412 (t . mailcap))
1413 "Default file applications on a UNIX or GNU/Linux system.
1414 See `org-file-apps'.")
1416 (defconst org-file-apps-defaults-macosx
1417 '((remote . emacs)
1418 (t . "open %s")
1419 ("ps" . "gv %s")
1420 ("ps.gz" . "gv %s")
1421 ("eps" . "gv %s")
1422 ("eps.gz" . "gv %s")
1423 ("dvi" . "xdvi %s")
1424 ("fig" . "xfig %s"))
1425 "Default file applications on a MacOS X system.
1426 The system \"open\" is known as a default, but we use X11 applications
1427 for some files for which the OS does not have a good default.
1428 See `org-file-apps'.")
1430 (defconst org-file-apps-defaults-windowsnt
1431 (list
1432 '(remote . emacs)
1433 (cons t
1434 (list (if (featurep 'xemacs)
1435 'mswindows-shell-execute
1436 'w32-shell-execute)
1437 "open" 'file)))
1438 "Default file applications on a Windows NT system.
1439 The system \"open\" is used for most files.
1440 See `org-file-apps'.")
1442 (defcustom org-file-apps
1444 ("txt" . emacs)
1445 ("tex" . emacs)
1446 ("ltx" . emacs)
1447 ("org" . emacs)
1448 ("el" . emacs)
1449 ("bib" . emacs)
1451 "External applications for opening `file:path' items in a document.
1452 Org-mode uses system defaults for different file types, but
1453 you can use this variable to set the application for a given file
1454 extension. The entries in this list are cons cells where the car identifies
1455 files and the cdr the corresponding command. Possible values for the
1456 file identifier are
1457 \"ext\" A string identifying an extension
1458 `directory' Matches a directory
1459 `remote' Matches a remote file, accessible through tramp or efs.
1460 Remote files most likely should be visited through Emacs
1461 because external applications cannot handle such paths.
1462 t Default for all remaining files
1464 Possible values for the command are:
1465 `emacs' The file will be visited by the current Emacs process.
1466 `default' Use the default application for this file type.
1467 string A command to be executed by a shell; %s will be replaced
1468 by the path to the file.
1469 sexp A Lisp form which will be evaluated. The file path will
1470 be available in the Lisp variable `file'.
1471 For more examples, see the system specific constants
1472 `org-file-apps-defaults-macosx'
1473 `org-file-apps-defaults-windowsnt'
1474 `org-file-apps-defaults-gnu'."
1475 :group 'org-link-follow
1476 :type '(repeat
1477 (cons (choice :value ""
1478 (string :tag "Extension")
1479 (const :tag "Default for unrecognized files" t)
1480 (const :tag "Remote file" remote)
1481 (const :tag "Links to a directory" directory))
1482 (choice :value ""
1483 (const :tag "Visit with Emacs" emacs)
1484 (const :tag "Use system default" default)
1485 (string :tag "Command")
1486 (sexp :tag "Lisp form")))))
1488 (defgroup org-remember nil
1489 "Options concerning interaction with remember.el."
1490 :tag "Org Remember"
1491 :group 'org)
1493 (defcustom org-directory "~/org"
1494 "Directory with org files.
1495 This directory will be used as default to prompt for org files.
1496 Used by the hooks for remember.el."
1497 :group 'org-remember
1498 :type 'directory)
1500 (defcustom org-default-notes-file "~/.notes"
1501 "Default target for storing notes.
1502 Used by the hooks for remember.el. This can be a string, or nil to mean
1503 the value of `remember-data-file'.
1504 You can set this on a per-template basis with the variable
1505 `org-remember-templates'."
1506 :group 'org-remember
1507 :type '(choice
1508 (const :tag "Default from remember-data-file" nil)
1509 file))
1511 (defcustom org-remember-store-without-prompt t
1512 "Non-nil means, `C-c C-c' stores remember note without further promts.
1513 In this case, you need `C-u C-c C-c' to get the prompts for
1514 note file and headline.
1515 When this variable is nil, `C-c C-c' give you the prompts, and
1516 `C-u C-c C-c' trigger the fasttrack."
1517 :group 'org-remember
1518 :type 'boolean)
1520 (defcustom org-remember-interactive-interface 'refile
1521 "The interface to be used for interactive filing of remember notes.
1522 This is only used when the interactive mode for selecting a filing
1523 location is used (see the variable `org-remember-store-without-prompt').
1524 Allowed vaues are:
1525 outline The interface shows an outline of the relevant file
1526 and the correct heading is found by moving through
1527 the outline or by searching with incremental search.
1528 outline-path-completion Headlines in the current buffer are offered via
1529 completion.
1530 refile Use the refile interface, and offer headlines,
1531 possibly from different buffers."
1532 :group 'org-remember
1533 :type '(choice
1534 (const :tag "Refile" refile)
1535 (const :tag "Outline" outline)
1536 (const :tag "Outline-path-completion" outline-path-completion)))
1538 (defcustom org-goto-interface 'outline
1539 "The default interface to be used for `org-goto'.
1540 Allowed vaues are:
1541 outline The interface shows an outline of the relevant file
1542 and the correct heading is found by moving through
1543 the outline or by searching with incremental search.
1544 outline-path-completion Headlines in the current buffer are offered via
1545 completion."
1546 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1547 :type '(choice
1548 (const :tag "Outline" outline)
1549 (const :tag "Outline-path-completion" outline-path-completion)))
1551 (defcustom org-remember-default-headline ""
1552 "The headline that should be the default location in the notes file.
1553 When filing remember notes, the cursor will start at that position.
1554 You can set this on a per-template basis with the variable
1555 `org-remember-templates'."
1556 :group 'org-remember
1557 :type 'string)
1559 (defcustom org-remember-templates nil
1560 "Templates for the creation of remember buffers.
1561 When nil, just let remember make the buffer.
1562 When not nil, this is a list of 5-element lists. In each entry, the first
1563 element is the name of the template, which should be a single short word.
1564 The second element is a character, a unique key to select this template.
1565 The third element is the template.
1567 The fourth element is optional and can specify a destination file for
1568 remember items created with this template. The default file is given
1569 by `org-default-notes-file'. If the file name is not an absolute path,
1570 it will be interpreted relative to `org-directory'.
1572 An optional fifth element can specify the headline in that file that should
1573 be offered first when the user is asked to file the entry. The default
1574 headline is given in the variable `org-remember-default-headline'.
1576 An optional sixth element specifies the contexts in which the user can
1577 select the template. This element can be either a list of major modes
1578 or a function. `org-remember' will first check whether the function
1579 returns `t' or if we are in any of the listed major modes, and select
1580 the template accordingly.
1582 The template specifies the structure of the remember buffer. It should have
1583 a first line starting with a star, to act as the org-mode headline.
1584 Furthermore, the following %-escapes will be replaced with content:
1586 %^{prompt} Prompt the user for a string and replace this sequence with it.
1587 A default value and a completion table ca be specified like this:
1588 %^{prompt|default|completion2|completion3|...}
1589 %t time stamp, date only
1590 %T time stamp with date and time
1591 %u, %U like the above, but inactive time stamps
1592 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1593 You may define a prompt like %^{Please specify birthday}t
1594 %n user name (taken from `user-full-name')
1595 %a annotation, normally the link created with org-store-link
1596 %i initial content, the region active. If %i is indented,
1597 the entire inserted text will be indented as well.
1598 %c content of the clipboard, or current kill ring head
1599 %^g prompt for tags, with completion on tags in target file
1600 %^G prompt for tags, with completion all tags in all agenda files
1601 %:keyword specific information for certain link types, see below
1602 %[pathname] insert the contents of the file given by `pathname'
1603 %(sexp) evaluate elisp `(sexp)' and replace with the result
1604 %! Store this note immediately after filling the template
1606 %? After completing the template, position cursor here.
1608 Apart from these general escapes, you can access information specific to the
1609 link type that is created. For example, calling `remember' in emails or gnus
1610 will record the author and the subject of the message, which you can access
1611 with %:author and %:subject, respectively. Here is a complete list of what
1612 is recorded for each link type.
1614 Link type | Available information
1615 -------------------+------------------------------------------------------
1616 bbdb | %:type %:name %:company
1617 vm, wl, mh, rmail | %:type %:subject %:message-id
1618 | %:from %:fromname %:fromaddress
1619 | %:to %:toname %:toaddress
1620 | %:fromto (either \"to NAME\" or \"from NAME\")
1621 gnus | %:group, for messages also all email fields
1622 w3, w3m | %:type %:url
1623 info | %:type %:file %:node
1624 calendar | %:type %:date"
1625 :group 'org-remember
1626 :get (lambda (var) ; Make sure all entries have at least 5 elements
1627 (mapcar (lambda (x)
1628 (if (not (stringp (car x))) (setq x (cons "" x)))
1629 (cond ((= (length x) 4) (append x '("")))
1630 ((= (length x) 3) (append x '("" "")))
1631 (t x)))
1632 (default-value var)))
1633 :type '(repeat
1634 :tag "enabled"
1635 (list :value ("" ?a "\n" nil nil nil)
1636 (string :tag "Name")
1637 (character :tag "Selection Key")
1638 (string :tag "Template")
1639 (choice
1640 (file :tag "Destination file")
1641 (const :tag "Prompt for file" nil))
1642 (choice
1643 (string :tag "Destination headline")
1644 (const :tag "Selection interface for heading"))
1645 (choice
1646 (const :tag "Use by default" nil)
1647 (const :tag "Use in all contexts" t)
1648 (repeat :tag "Use only if in major mode"
1649 (symbol :tag "Major mode"))
1650 (function :tag "Perform a check against function")))))
1652 (defcustom org-reverse-note-order nil
1653 "Non-nil means, store new notes at the beginning of a file or entry.
1654 When nil, new notes will be filed to the end of a file or entry.
1655 This can also be a list with cons cells of regular expressions that
1656 are matched against file names, and values."
1657 :group 'org-remember
1658 :type '(choice
1659 (const :tag "Reverse always" t)
1660 (const :tag "Reverse never" nil)
1661 (repeat :tag "By file name regexp"
1662 (cons regexp boolean))))
1664 (defcustom org-refile-targets nil
1665 "Targets for refiling entries with \\[org-refile].
1666 This is list of cons cells. Each cell contains:
1667 - a specification of the files to be considered, either a list of files,
1668 or a symbol whose function or value fields will be used to retrieve
1669 a file name or a list of file names. Nil means, refile to a different
1670 heading in the current buffer.
1671 - A specification of how to find candidate refile targets. This may be
1672 any of
1673 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1674 This tag has to be present in all target headlines, inheritance will
1675 not be considered.
1676 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1677 todo keyword.
1678 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1679 headlines that are refiling targets.
1680 - a cons cell (:level . N). Any headline of level N is considered a target.
1681 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1682 ;; FIXME: what if there are a var and func with same name???
1683 :group 'org-remember
1684 :type '(repeat
1685 (cons
1686 (choice :value org-agenda-files
1687 (const :tag "All agenda files" org-agenda-files)
1688 (const :tag "Current buffer" nil)
1689 (function) (variable) (file))
1690 (choice :tag "Identify target headline by"
1691 (cons :tag "Specific tag" (const :tag) (string))
1692 (cons :tag "TODO keyword" (const :todo) (string))
1693 (cons :tag "Regular expression" (const :regexp) (regexp))
1694 (cons :tag "Level number" (const :level) (integer))
1695 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1697 (defcustom org-refile-use-outline-path nil
1698 "Non-nil means, provide refile targets as paths.
1699 So a level 3 headline will be available as level1/level2/level3.
1700 When the value is `file', also include the file name (without directory)
1701 into the path. When `full-file-path', include the full file path."
1702 :group 'org-remember
1703 :type '(choice
1704 (const :tag "Not" nil)
1705 (const :tag "Yes" t)
1706 (const :tag "Start with file name" file)
1707 (const :tag "Start with full file path" full-file-path)))
1709 (defgroup org-todo nil
1710 "Options concerning TODO items in Org-mode."
1711 :tag "Org TODO"
1712 :group 'org)
1714 (defgroup org-progress nil
1715 "Options concerning Progress logging in Org-mode."
1716 :tag "Org Progress"
1717 :group 'org-time)
1719 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1720 "List of TODO entry keyword sequences and their interpretation.
1721 \\<org-mode-map>This is a list of sequences.
1723 Each sequence starts with a symbol, either `sequence' or `type',
1724 indicating if the keywords should be interpreted as a sequence of
1725 action steps, or as different types of TODO items. The first
1726 keywords are states requiring action - these states will select a headline
1727 for inclusion into the global TODO list Org-mode produces. If one of
1728 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1729 signify that no further action is necessary. If \"|\" is not found,
1730 the last keyword is treated as the only DONE state of the sequence.
1732 The command \\[org-todo] cycles an entry through these states, and one
1733 additional state where no keyword is present. For details about this
1734 cycling, see the manual.
1736 TODO keywords and interpretation can also be set on a per-file basis with
1737 the special #+SEQ_TODO and #+TYP_TODO lines.
1739 Each keyword can optionally specify a character for fast state selection
1740 \(in combination with the variable `org-use-fast-todo-selection')
1741 and specifiers for state change logging, using the same syntax
1742 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1743 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1744 indicates to record a time stamp each time this state is selected.
1746 Each keyword may also specify if a timestamp or a note should be
1747 recorded when entering or leaving the state, by adding additional
1748 characters in the parenthesis after the keyword. This looks like this:
1749 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1750 record only the time of the state change. With X and Y being either
1751 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1752 Y when leaving the state if and only if the *target* state does not
1753 define X. You may omit any of the fast-selection key or X or /Y,
1754 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1756 For backward compatibility, this variable may also be just a list
1757 of keywords - in this case the interptetation (sequence or type) will be
1758 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1759 :group 'org-todo
1760 :group 'org-keywords
1761 :type '(choice
1762 (repeat :tag "Old syntax, just keywords"
1763 (string :tag "Keyword"))
1764 (repeat :tag "New syntax"
1765 (cons
1766 (choice
1767 :tag "Interpretation"
1768 (const :tag "Sequence (cycling hits every state)" sequence)
1769 (const :tag "Type (cycling directly to DONE)" type))
1770 (repeat
1771 (string :tag "Keyword"))))))
1773 (defvar org-todo-keywords-1 nil
1774 "All TODO and DONE keywords active in a buffer.")
1775 (make-variable-buffer-local 'org-todo-keywords-1)
1776 (defvar org-todo-keywords-for-agenda nil)
1777 (defvar org-done-keywords-for-agenda nil)
1778 (defvar org-not-done-keywords nil)
1779 (make-variable-buffer-local 'org-not-done-keywords)
1780 (defvar org-done-keywords nil)
1781 (make-variable-buffer-local 'org-done-keywords)
1782 (defvar org-todo-heads nil)
1783 (make-variable-buffer-local 'org-todo-heads)
1784 (defvar org-todo-sets nil)
1785 (make-variable-buffer-local 'org-todo-sets)
1786 (defvar org-todo-log-states nil)
1787 (make-variable-buffer-local 'org-todo-log-states)
1788 (defvar org-todo-kwd-alist nil)
1789 (make-variable-buffer-local 'org-todo-kwd-alist)
1790 (defvar org-todo-key-alist nil)
1791 (make-variable-buffer-local 'org-todo-key-alist)
1792 (defvar org-todo-key-trigger nil)
1793 (make-variable-buffer-local 'org-todo-key-trigger)
1795 (defcustom org-todo-interpretation 'sequence
1796 "Controls how TODO keywords are interpreted.
1797 This variable is in principle obsolete and is only used for
1798 backward compatibility, if the interpretation of todo keywords is
1799 not given already in `org-todo-keywords'. See that variable for
1800 more information."
1801 :group 'org-todo
1802 :group 'org-keywords
1803 :type '(choice (const sequence)
1804 (const type)))
1806 (defcustom org-use-fast-todo-selection 'prefix
1807 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1808 This variable describes if and under what circumstances the cycling
1809 mechanism for TODO keywords will be replaced by a single-key, direct
1810 selection scheme.
1812 When nil, fast selection is never used.
1814 When the symbol `prefix', it will be used when `org-todo' is called with
1815 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1816 in an agenda buffer.
1818 When t, fast selection is used by default. In this case, the prefix
1819 argument forces cycling instead.
1821 In all cases, the special interface is only used if access keys have actually
1822 been assigned by the user, i.e. if keywords in the configuration are followed
1823 by a letter in parenthesis, like TODO(t)."
1824 :group 'org-todo
1825 :type '(choice
1826 (const :tag "Never" nil)
1827 (const :tag "By default" t)
1828 (const :tag "Only with C-u C-c C-t" prefix)))
1830 (defcustom org-after-todo-state-change-hook nil
1831 "Hook which is run after the state of a TODO item was changed.
1832 The new state (a string with a TODO keyword, or nil) is available in the
1833 Lisp variable `state'."
1834 :group 'org-todo
1835 :type 'hook)
1837 (defcustom org-log-done nil
1838 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1839 When equal to the list (done), also prompt for a closing note.
1840 This can also be configured on a per-file basis by adding one of
1841 the following lines anywhere in the buffer:
1843 #+STARTUP: logdone
1844 #+STARTUP: lognotedone
1845 #+STARTUP: nologdone"
1846 :group 'org-todo
1847 :group 'org-progress
1848 :type '(choice
1849 (const :tag "No logging" nil)
1850 (const :tag "Record CLOSED timestamp" time)
1851 (const :tag "Record CLOSED timestamp with closing note." note)))
1853 ;; Normalize old uses of org-log-done.
1854 (cond
1855 ((eq org-log-done t) (setq org-log-done 'time))
1856 ((and (listp org-log-done) (memq 'done org-log-done))
1857 (setq org-log-done 'note)))
1859 ;; FIXME: document
1860 (defcustom org-log-note-clock-out nil
1861 "Non-nil means, recored a note when clocking out of an item.
1862 This can also be configured on a per-file basis by adding one of
1863 the following lines anywhere in the buffer:
1865 #+STARTUP: lognoteclock-out
1866 #+STARTUP: nolognoteclock-out"
1867 :group 'org-todo
1868 :group 'org-progress
1869 :type 'boolean)
1871 (defcustom org-log-done-with-time t
1872 "Non-nil means, the CLOSED time stamp will contain date and time.
1873 When nil, only the date will be recorded."
1874 :group 'org-progress
1875 :type 'boolean)
1877 (defcustom org-log-note-headings
1878 '((done . "CLOSING NOTE %t")
1879 (state . "State %-12s %t")
1880 (clock-out . ""))
1881 "Headings for notes added when clocking out or closing TODO items.
1882 The value is an alist, with the car being a symbol indicating the note
1883 context, and the cdr is the heading to be used. The heading may also be the
1884 empty string.
1885 %t in the heading will be replaced by a time stamp.
1886 %s will be replaced by the new TODO state, in double quotes.
1887 %u will be replaced by the user name.
1888 %U will be replaced by the full user name."
1889 :group 'org-todo
1890 :group 'org-progress
1891 :type '(list :greedy t
1892 (cons (const :tag "Heading when closing an item" done) string)
1893 (cons (const :tag
1894 "Heading when changing todo state (todo sequence only)"
1895 state) string)
1896 (cons (const :tag "Heading when clocking out" clock-out) string)))
1898 (defcustom org-log-states-order-reversed t
1899 "Non-nil means, the latest state change note will be directly after heading.
1900 When nil, the notes will be orderer according to time."
1901 :group 'org-todo
1902 :group 'org-progress
1903 :type 'boolean)
1905 (defcustom org-log-repeat 'time
1906 "Non-nil means, record moving through the DONE state when triggering repeat.
1907 An auto-repeating tasks is immediately switched back to TODO when marked
1908 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1909 the TODO keyword definition, or recording a cloing note by setting
1910 `org-log-done', there will be no record of the task moving trhough DONE.
1911 This variable forces taking a note anyway. Possible values are:
1913 nil Don't force a record
1914 time Record a time stamp
1915 note Record a note
1917 This option can also be set with on a per-file-basis with
1919 #+STARTUP: logrepeat
1920 #+STARTUP: lognoterepeat
1921 #+STARTUP: nologrepeat
1923 You can have local logging settings for a subtree by setting the LOGGING
1924 property to one or more of these keywords."
1925 :group 'org-todo
1926 :group 'org-progress
1927 :type '(choice
1928 (const :tag "Don't force a record" nil)
1929 (const :tag "Force recording the DONE state" time)
1930 (const :tag "Force recording a note with the DONE state" note)))
1932 (defcustom org-clock-into-drawer 2
1933 "Should clocking info be wrapped into a drawer?
1934 When t, clocking info will always be inserted into a :CLOCK: drawer.
1935 If necessary, the drawer will be created.
1936 When nil, the drawer will not be created, but used when present.
1937 When an integer and the number of clocking entries in an item
1938 reaches or exceeds this number, a drawer will be created."
1939 :group 'org-todo
1940 :group 'org-progress
1941 :type '(choice
1942 (const :tag "Always" t)
1943 (const :tag "Only when drawer exists" nil)
1944 (integer :tag "When at least N clock entries")))
1946 (defcustom org-clock-out-when-done t
1947 "When t, the clock will be stopped when the relevant entry is marked DONE.
1948 Nil means, clock will keep running until stopped explicitly with
1949 `C-c C-x C-o', or until the clock is started in a different item."
1950 :group 'org-progress
1951 :type 'boolean)
1953 (defcustom org-clock-in-switch-to-state nil
1954 "Set task to a special todo state while clocking it.
1955 The value should be the state to which the entry should be switched."
1956 :group 'org-progress
1957 :group 'org-todo
1958 :type '(choice
1959 (const :tag "Don't force a state" nil)
1960 (string :tag "State")))
1962 (defgroup org-priorities nil
1963 "Priorities in Org-mode."
1964 :tag "Org Priorities"
1965 :group 'org-todo)
1967 (defcustom org-highest-priority ?A
1968 "The highest priority of TODO items. A character like ?A, ?B etc.
1969 Must have a smaller ASCII number than `org-lowest-priority'."
1970 :group 'org-priorities
1971 :type 'character)
1973 (defcustom org-lowest-priority ?C
1974 "The lowest priority of TODO items. A character like ?A, ?B etc.
1975 Must have a larger ASCII number than `org-highest-priority'."
1976 :group 'org-priorities
1977 :type 'character)
1979 (defcustom org-default-priority ?B
1980 "The default priority of TODO items.
1981 This is the priority an item get if no explicit priority is given."
1982 :group 'org-priorities
1983 :type 'character)
1985 (defcustom org-priority-start-cycle-with-default t
1986 "Non-nil means, start with default priority when starting to cycle.
1987 When this is nil, the first step in the cycle will be (depending on the
1988 command used) one higher or lower that the default priority."
1989 :group 'org-priorities
1990 :type 'boolean)
1992 (defgroup org-time nil
1993 "Options concerning time stamps and deadlines in Org-mode."
1994 :tag "Org Time"
1995 :group 'org)
1997 (defcustom org-insert-labeled-timestamps-at-point nil
1998 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1999 When nil, these labeled time stamps are forces into the second line of an
2000 entry, just after the headline. When scheduling from the global TODO list,
2001 the time stamp will always be forced into the second line."
2002 :group 'org-time
2003 :type 'boolean)
2005 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2006 "Formats for `format-time-string' which are used for time stamps.
2007 It is not recommended to change this constant.")
2009 (defcustom org-time-stamp-rounding-minutes '(0 5)
2010 "Number of minutes to round time stamps to.
2011 These are two values, the first applies when first creating a time stamp.
2012 The second applies when changing it with the commands `S-up' and `S-down'.
2013 When changing the time stamp, this means that it will change in steps
2014 of N minutes, as given by the second value.
2016 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2017 numbers should be factors of 60, so for example 5, 10, 15.
2019 When this is larger than 1, you can still force an exact time-stamp by using
2020 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2021 and by using a prefix arg to `S-up/down' to specify the exact number
2022 of minutes to shift."
2023 :group 'org-time
2024 :get '(lambda (var) ; Make sure all entries have 5 elements
2025 (if (integerp (default-value var))
2026 (list (default-value var) 5)
2027 (default-value var)))
2028 :type '(list
2029 (integer :tag "when inserting times")
2030 (integer :tag "when modifying times")))
2032 ;; Make sure old customizations of this variable don't lead to problems.
2033 (when (integerp org-time-stamp-rounding-minutes)
2034 (setq org-time-stamp-rounding-minutes
2035 (list org-time-stamp-rounding-minutes
2036 org-time-stamp-rounding-minutes)))
2038 (defcustom org-display-custom-times nil
2039 "Non-nil means, overlay custom formats over all time stamps.
2040 The formats are defined through the variable `org-time-stamp-custom-formats'.
2041 To turn this on on a per-file basis, insert anywhere in the file:
2042 #+STARTUP: customtime"
2043 :group 'org-time
2044 :set 'set-default
2045 :type 'sexp)
2046 (make-variable-buffer-local 'org-display-custom-times)
2048 (defcustom org-time-stamp-custom-formats
2049 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2050 "Custom formats for time stamps. See `format-time-string' for the syntax.
2051 These are overlayed over the default ISO format if the variable
2052 `org-display-custom-times' is set. Time like %H:%M should be at the
2053 end of the second format."
2054 :group 'org-time
2055 :type 'sexp)
2057 (defun org-time-stamp-format (&optional long inactive)
2058 "Get the right format for a time string."
2059 (let ((f (if long (cdr org-time-stamp-formats)
2060 (car org-time-stamp-formats))))
2061 (if inactive
2062 (concat "[" (substring f 1 -1) "]")
2063 f)))
2065 (defcustom org-read-date-prefer-future t
2066 "Non-nil means, assume future for incomplete date input from user.
2067 This affects the following situations:
2068 1. The user gives a day, but no month.
2069 For example, if today is the 15th, and you enter \"3\", Org-mode will
2070 read this as the third of *next* month. However, if you enter \"17\",
2071 it will be considered as *this* month.
2072 2. The user gives a month but not a year.
2073 For example, if it is april and you enter \"feb 2\", this will be read
2074 as feb 2, *next* year. \"May 5\", however, will be this year.
2076 Currently this does not work for ISO week specifications.
2078 When this option is nil, the current month and year will always be used
2079 as defaults."
2080 :group 'org-time
2081 :type 'boolean)
2083 (defcustom org-read-date-display-live t
2084 "Non-nil means, display current interpretation of date prompt live.
2085 This display will be in an overlay, in the minibuffer."
2086 :group 'org-time
2087 :type 'boolean)
2089 (defcustom org-read-date-popup-calendar t
2090 "Non-nil means, pop up a calendar when prompting for a date.
2091 In the calendar, the date can be selected with mouse-1. However, the
2092 minibuffer will also be active, and you can simply enter the date as well.
2093 When nil, only the minibuffer will be available."
2094 :group 'org-time
2095 :type 'boolean)
2096 (if (fboundp 'defvaralias)
2097 (defvaralias 'org-popup-calendar-for-date-prompt
2098 'org-read-date-popup-calendar))
2100 (defcustom org-extend-today-until 0
2101 "The hour when your day really ends.
2102 This has influence for the following applications:
2103 - When switching the agenda to \"today\". It it is still earlier than
2104 the time given here, the day recognized as TODAY is actually yesterday.
2105 - When a date is read from the user and it is still before the time given
2106 here, the current date and time will be assumed to be yesterday, 23:59.
2108 FIXME:
2109 IMPORTANT: This is still a very experimental feature, it may disappear
2110 again or it may be extended to mean more things."
2111 :group 'org-time
2112 :type 'number)
2114 (defcustom org-edit-timestamp-down-means-later nil
2115 "Non-nil means, S-down will increase the time in a time stamp.
2116 When nil, S-up will increase."
2117 :group 'org-time
2118 :type 'boolean)
2120 (defcustom org-calendar-follow-timestamp-change t
2121 "Non-nil means, make the calendar window follow timestamp changes.
2122 When a timestamp is modified and the calendar window is visible, it will be
2123 moved to the new date."
2124 :group 'org-time
2125 :type 'boolean)
2127 (defcustom org-clock-heading-function nil
2128 "When non-nil, should be a function to create `org-clock-heading'.
2129 This is the string shown in the mode line when a clock is running.
2130 The function is called with point at the beginning of the headline."
2131 :group 'org-time ; FIXME: Should we have a separate group????
2132 :type 'function)
2134 (defgroup org-tags nil
2135 "Options concerning tags in Org-mode."
2136 :tag "Org Tags"
2137 :group 'org)
2139 (defcustom org-tag-alist nil
2140 "List of tags allowed in Org-mode files.
2141 When this list is nil, Org-mode will base TAG input on what is already in the
2142 buffer.
2143 The value of this variable is an alist, the car of each entry must be a
2144 keyword as a string, the cdr may be a character that is used to select
2145 that tag through the fast-tag-selection interface.
2146 See the manual for details."
2147 :group 'org-tags
2148 :type '(repeat
2149 (choice
2150 (cons (string :tag "Tag name")
2151 (character :tag "Access char"))
2152 (const :tag "Start radio group" (:startgroup))
2153 (const :tag "End radio group" (:endgroup)))))
2155 (defcustom org-use-fast-tag-selection 'auto
2156 "Non-nil means, use fast tag selection scheme.
2157 This is a special interface to select and deselect tags with single keys.
2158 When nil, fast selection is never used.
2159 When the symbol `auto', fast selection is used if and only if selection
2160 characters for tags have been configured, either through the variable
2161 `org-tag-alist' or through a #+TAGS line in the buffer.
2162 When t, fast selection is always used and selection keys are assigned
2163 automatically if necessary."
2164 :group 'org-tags
2165 :type '(choice
2166 (const :tag "Always" t)
2167 (const :tag "Never" nil)
2168 (const :tag "When selection characters are configured" 'auto)))
2170 (defcustom org-fast-tag-selection-single-key nil
2171 "Non-nil means, fast tag selection exits after first change.
2172 When nil, you have to press RET to exit it.
2173 During fast tag selection, you can toggle this flag with `C-c'.
2174 This variable can also have the value `expert'. In this case, the window
2175 displaying the tags menu is not even shown, until you press C-c again."
2176 :group 'org-tags
2177 :type '(choice
2178 (const :tag "No" nil)
2179 (const :tag "Yes" t)
2180 (const :tag "Expert" expert)))
2182 (defvar org-fast-tag-selection-include-todo nil
2183 "Non-nil means, fast tags selection interface will also offer TODO states.
2184 This is an undocumented feature, you should not rely on it.")
2186 (defcustom org-tags-column -80
2187 "The column to which tags should be indented in a headline.
2188 If this number is positive, it specifies the column. If it is negative,
2189 it means that the tags should be flushright to that column. For example,
2190 -80 works well for a normal 80 character screen."
2191 :group 'org-tags
2192 :type 'integer)
2194 (defcustom org-auto-align-tags t
2195 "Non-nil means, realign tags after pro/demotion of TODO state change.
2196 These operations change the length of a headline and therefore shift
2197 the tags around. With this options turned on, after each such operation
2198 the tags are again aligned to `org-tags-column'."
2199 :group 'org-tags
2200 :type 'boolean)
2202 (defcustom org-use-tag-inheritance t
2203 "Non-nil means, tags in levels apply also for sublevels.
2204 When nil, only the tags directly given in a specific line apply there.
2205 If you turn off this option, you very likely want to turn on the
2206 companion option `org-tags-match-list-sublevels'.
2208 This may also be a list of tags that should be inherited, or a regexp that
2209 matches tags that should be inherited."
2210 :group 'org-tags
2211 :type '(choice
2212 (const :tag "Not" nil)
2213 (const :tag "Always" t)
2214 (repeat :tag "Specific tags" (string :tag "Tag"))
2215 (regexp :tag "Tags matched by regexp")))
2217 (defun org-tag-inherit-p (tag)
2218 "Check if TAG is one that should be inherited."
2219 (cond
2220 ((eq org-use-tag-inheritance t) t)
2221 ((not org-use-tag-inheritance) nil)
2222 ((stringp org-use-tag-inheritance)
2223 (string-match org-use-tag-inheritance tag))
2224 ((listp org-use-tag-inheritance)
2225 (member tag org-use-tag-inheritance))
2226 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2228 (defcustom org-tags-match-list-sublevels nil
2229 "Non-nil means list also sublevels of headlines matching tag search.
2230 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2231 the sublevels of a headline matching a tag search often also match
2232 the same search. Listing all of them can create very long lists.
2233 Setting this variable to nil causes subtrees of a match to be skipped.
2234 This option is off by default, because inheritance in on. If you turn
2235 inheritance off, you very likely want to turn this option on.
2237 As a special case, if the tag search is restricted to TODO items, the
2238 value of this variable is ignored and sublevels are always checked, to
2239 make sure all corresponding TODO items find their way into the list."
2240 :group 'org-tags
2241 :type 'boolean)
2243 (defvar org-tags-history nil
2244 "History of minibuffer reads for tags.")
2245 (defvar org-last-tags-completion-table nil
2246 "The last used completion table for tags.")
2247 (defvar org-after-tags-change-hook nil
2248 "Hook that is run after the tags in a line have changed.")
2250 (defgroup org-properties nil
2251 "Options concerning properties in Org-mode."
2252 :tag "Org Properties"
2253 :group 'org)
2255 (defcustom org-property-format "%-10s %s"
2256 "How property key/value pairs should be formatted by `indent-line'.
2257 When `indent-line' hits a property definition, it will format the line
2258 according to this format, mainly to make sure that the values are
2259 lined-up with respect to each other."
2260 :group 'org-properties
2261 :type 'string)
2263 (defcustom org-use-property-inheritance nil
2264 "Non-nil means, properties apply also for sublevels.
2266 This setting is chiefly used during property searches. Turning it on can
2267 cause significant overhead when doing a search, which is why it is not
2268 on by default.
2270 When nil, only the properties directly given in the current entry count.
2271 When t, every property is inherited. The value may also be a list of
2272 properties that should have inheritance, or a regular expression matching
2273 properties that should be inherited.
2275 However, note that some special properties use inheritance under special
2276 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2277 and the properties ending in \"_ALL\" when they are used as descriptor
2278 for valid values of a property.
2280 Note for programmers:
2281 When querying an entry with `org-entry-get', you can control if inheritance
2282 should be used. By default, `org-entry-get' looks only at the local
2283 properties. You can request inheritance by setting the inherit argument
2284 to t (to force inheritance) or to `selective' (to respect the setting
2285 in this variable)."
2286 :group 'org-properties
2287 :type '(choice
2288 (const :tag "Not" nil)
2289 (const :tag "Always" t)
2290 (repeat :tag "Specific properties" (string :tag "Property"))
2291 (regexp :tag "Properties matched by regexp")))
2293 (defun org-property-inherit-p (property)
2294 "Check if PROPERTY is one that should be inherited."
2295 (cond
2296 ((eq org-use-property-inheritance t) t)
2297 ((not org-use-property-inheritance) nil)
2298 ((stringp org-use-property-inheritance)
2299 (string-match org-use-property-inheritance property))
2300 ((listp org-use-property-inheritance)
2301 (member property org-use-property-inheritance))
2302 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2304 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2305 "The default column format, if no other format has been defined.
2306 This variable can be set on the per-file basis by inserting a line
2308 #+COLUMNS: %25ITEM ....."
2309 :group 'org-properties
2310 :type 'string)
2312 (defcustom org-global-properties nil
2313 "List of property/value pairs that can be inherited by any entry.
2314 You can set buffer-local values for this by adding lines like
2316 #+PROPERTY: NAME VALUE"
2317 :group 'org-properties
2318 :type '(repeat
2319 (cons (string :tag "Property")
2320 (string :tag "Value"))))
2322 (defvar org-local-properties nil
2323 "List of property/value pairs that can be inherited by any entry.
2324 Valid for the current buffer.
2325 This variable is populated from #+PROPERTY lines.")
2327 (defgroup org-agenda nil
2328 "Options concerning agenda views in Org-mode."
2329 :tag "Org Agenda"
2330 :group 'org)
2332 (defvar org-category nil
2333 "Variable used by org files to set a category for agenda display.
2334 Such files should use a file variable to set it, for example
2336 # -*- mode: org; org-category: \"ELisp\"
2338 or contain a special line
2340 #+CATEGORY: ELisp
2342 If the file does not specify a category, then file's base name
2343 is used instead.")
2344 (make-variable-buffer-local 'org-category)
2346 (defcustom org-agenda-files nil
2347 "The files to be used for agenda display.
2348 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2349 \\[org-remove-file]. You can also use customize to edit the list.
2351 If an entry is a directory, all files in that directory that are matched by
2352 `org-agenda-file-regexp' will be part of the file list.
2354 If the value of the variable is not a list but a single file name, then
2355 the list of agenda files is actually stored and maintained in that file, one
2356 agenda file per line."
2357 :group 'org-agenda
2358 :type '(choice
2359 (repeat :tag "List of files and directories" file)
2360 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2362 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2363 "Regular expression to match files for `org-agenda-files'.
2364 If any element in the list in that variable contains a directory instead
2365 of a normal file, all files in that directory that are matched by this
2366 regular expression will be included."
2367 :group 'org-agenda
2368 :type 'regexp)
2370 (defcustom org-agenda-skip-unavailable-files nil
2371 "t means to just skip non-reachable files in `org-agenda-files'.
2372 Nil means to remove them, after a query, from the list."
2373 :group 'org-agenda
2374 :type 'boolean)
2376 (defcustom org-agenda-text-search-extra-files nil
2377 "List of extra files to be searched by text search commands.
2378 These files will be search in addition to the agenda files bu the
2379 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2380 Note that these files will only be searched for text search commands,
2381 not for the other agenda views like todo lists, tag earches or the weekly
2382 agenda. This variable is intended to list notes and possibly archive files
2383 that should also be searched by these two commands."
2384 :group 'org-agenda
2385 :type '(repeat file))
2387 (if (fboundp 'defvaralias)
2388 (defvaralias 'org-agenda-multi-occur-extra-files
2389 'org-agenda-text-search-extra-files))
2391 (defcustom org-agenda-confirm-kill 1
2392 "When set, remote killing from the agenda buffer needs confirmation.
2393 When t, a confirmation is always needed. When a number N, confirmation is
2394 only needed when the text to be killed contains more than N non-white lines."
2395 :group 'org-agenda
2396 :type '(choice
2397 (const :tag "Never" nil)
2398 (const :tag "Always" t)
2399 (number :tag "When more than N lines")))
2401 (defcustom org-calendar-to-agenda-key [?c]
2402 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2403 The command `org-calendar-goto-agenda' will be bound to this key. The
2404 default is the character `c' because then `c' can be used to switch back and
2405 forth between agenda and calendar."
2406 :group 'org-agenda
2407 :type 'sexp)
2409 (defcustom org-agenda-compact-blocks nil
2410 "Non-nil means, make the block agenda more compact.
2411 This is done by leaving out unnecessary lines."
2412 :group 'org-agenda
2413 :type nil)
2415 (defgroup org-agenda-export nil
2416 "Options concerning exporting agenda views in Org-mode."
2417 :tag "Org Agenda Export"
2418 :group 'org-agenda)
2420 (defcustom org-agenda-with-colors t
2421 "Non-nil means, use colors in agenda views."
2422 :group 'org-agenda-export
2423 :type 'boolean)
2425 (defcustom org-agenda-exporter-settings nil
2426 "Alist of variable/value pairs that should be active during agenda export.
2427 This is a good place to set uptions for ps-print and for htmlize."
2428 :group 'org-agenda-export
2429 :type '(repeat
2430 (list
2431 (variable)
2432 (sexp :tag "Value"))))
2434 (defcustom org-agenda-export-html-style ""
2435 "The style specification for exported HTML Agenda files.
2436 If this variable contains a string, it will replace the default <style>
2437 section as produced by `htmlize'.
2438 Since there are different ways of setting style information, this variable
2439 needs to contain the full HTML structure to provide a style, including the
2440 surrounding HTML tags. The style specifications should include definitions
2441 the fonts used by the agenda, here is an example:
2443 <style type=\"text/css\">
2444 p { font-weight: normal; color: gray; }
2445 .org-agenda-structure {
2446 font-size: 110%;
2447 color: #003399;
2448 font-weight: 600;
2450 .org-todo {
2451 color: #cc6666;
2452 font-weight: bold;
2454 .org-done {
2455 color: #339933;
2457 .title { text-align: center; }
2458 .todo, .deadline { color: red; }
2459 .done { color: green; }
2460 </style>
2462 or, if you want to keep the style in a file,
2464 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2466 As the value of this option simply gets inserted into the HTML <head> header,
2467 you can \"misuse\" it to also add other text to the header. However,
2468 <style>...</style> is required, if not present the variable will be ignored."
2469 :group 'org-agenda-export
2470 :group 'org-export-html
2471 :type 'string)
2473 (defgroup org-agenda-custom-commands nil
2474 "Options concerning agenda views in Org-mode."
2475 :tag "Org Agenda Custom Commands"
2476 :group 'org-agenda)
2478 (defconst org-sorting-choice
2479 '(choice
2480 (const time-up) (const time-down)
2481 (const category-keep) (const category-up) (const category-down)
2482 (const tag-down) (const tag-up)
2483 (const priority-up) (const priority-down))
2484 "Sorting choices.")
2486 (defconst org-agenda-custom-commands-local-options
2487 `(repeat :tag "Local settings for this command. Remember to quote values"
2488 (choice :tag "Setting"
2489 (list :tag "Any variable"
2490 (variable :tag "Variable")
2491 (sexp :tag "Value"))
2492 (list :tag "Files to be searched"
2493 (const org-agenda-files)
2494 (list
2495 (const :format "" quote)
2496 (repeat
2497 (file))))
2498 (list :tag "Sorting strategy"
2499 (const org-agenda-sorting-strategy)
2500 (list
2501 (const :format "" quote)
2502 (repeat
2503 ,org-sorting-choice)))
2504 (list :tag "Prefix format"
2505 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2506 (string))
2507 (list :tag "Number of days in agenda"
2508 (const org-agenda-ndays)
2509 (integer :value 1))
2510 (list :tag "Fixed starting date"
2511 (const org-agenda-start-day)
2512 (string :value "2007-11-01"))
2513 (list :tag "Start on day of week"
2514 (const org-agenda-start-on-weekday)
2515 (choice :value 1
2516 (const :tag "Today" nil)
2517 (number :tag "Weekday No.")))
2518 (list :tag "Include data from diary"
2519 (const org-agenda-include-diary)
2520 (boolean))
2521 (list :tag "Deadline Warning days"
2522 (const org-deadline-warning-days)
2523 (integer :value 1))
2524 (list :tag "Standard skipping condition"
2525 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2526 (const org-agenda-skip-function)
2527 (list
2528 (const :format "" quote)
2529 (list
2530 (choice
2531 :tag "Skiping range"
2532 (const :tag "Skip entry" org-agenda-skip-entry-if)
2533 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2534 (repeat :inline t :tag "Conditions for skipping"
2535 (choice
2536 :tag "Condition type"
2537 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2538 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2539 (const :tag "scheduled" 'scheduled)
2540 (const :tag "not scheduled" 'notscheduled)
2541 (const :tag "deadline" 'deadline)
2542 (const :tag "no deadline" 'notdeadline))))))
2543 (list :tag "Non-standard skipping condition"
2544 :value (org-agenda-skip-function)
2545 (list
2546 (const org-agenda-skip-function)
2547 (sexp :tag "Function or form (quoted!)")))))
2548 "Selection of examples for agenda command settings.
2549 This will be spliced into the custom type of
2550 `org-agenda-custom-commands'.")
2553 (defcustom org-agenda-custom-commands nil
2554 "Custom commands for the agenda.
2555 These commands will be offered on the splash screen displayed by the
2556 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2558 (key desc type match settings files)
2560 key The key (one or more characters as a string) to be associated
2561 with the command.
2562 desc A description of the command, when omitted or nil, a default
2563 description is built using MATCH.
2564 type The command type, any of the following symbols:
2565 agenda The daily/weekly agenda.
2566 todo Entries with a specific TODO keyword, in all agenda files.
2567 search Entries containing search words entry or headline.
2568 tags Tags/Property/TODO match in all agenda files.
2569 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2570 todo-tree Sparse tree of specific TODO keyword in *current* file.
2571 tags-tree Sparse tree with all tags matches in *current* file.
2572 occur-tree Occur sparse tree for *current* file.
2573 ... A user-defined function.
2574 match What to search for:
2575 - a single keyword for TODO keyword searches
2576 - a tags match expression for tags searches
2577 - a word search expression for text searches.
2578 - a regular expression for occur searches
2579 For all other commands, this should be the empty string.
2580 settings A list of option settings, similar to that in a let form, so like
2581 this: ((opt1 val1) (opt2 val2) ...). The values will be
2582 evaluated at the moment of execution, so quote them when needed.
2583 files A list of files file to write the produced agenda buffer to
2584 with the command `org-store-agenda-views'.
2585 If a file name ends in \".html\", an HTML version of the buffer
2586 is written out. If it ends in \".ps\", a postscript version is
2587 produced. Otherwide, only the plain text is written to the file.
2589 You can also define a set of commands, to create a composite agenda buffer.
2590 In this case, an entry looks like this:
2592 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2594 where
2596 desc A description string to be displayed in the dispatcher menu.
2597 cmd An agenda command, similar to the above. However, tree commands
2598 are no allowed, but instead you can get agenda and global todo list.
2599 So valid commands for a set are:
2600 (agenda \"\" settings)
2601 (alltodo \"\" settings)
2602 (stuck \"\" settings)
2603 (todo \"match\" settings files)
2604 (search \"match\" settings files)
2605 (tags \"match\" settings files)
2606 (tags-todo \"match\" settings files)
2608 Each command can carry a list of options, and another set of options can be
2609 given for the whole set of commands. Individual command options take
2610 precedence over the general options.
2612 When using several characters as key to a command, the first characters
2613 are prefix commands. For the dispatcher to display useful information, you
2614 should provide a description for the prefix, like
2616 (setq org-agenda-custom-commands
2617 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2618 (\"hl\" tags \"+HOME+Lisa\")
2619 (\"hp\" tags \"+HOME+Peter\")
2620 (\"hk\" tags \"+HOME+Kim\")))"
2621 :group 'org-agenda-custom-commands
2622 :type `(repeat
2623 (choice :value ("x" "Describe command here" tags "" nil)
2624 (list :tag "Single command"
2625 (string :tag "Access Key(s) ")
2626 (option (string :tag "Description"))
2627 (choice
2628 (const :tag "Agenda" agenda)
2629 (const :tag "TODO list" alltodo)
2630 (const :tag "Search words" search)
2631 (const :tag "Stuck projects" stuck)
2632 (const :tag "Tags search (all agenda files)" tags)
2633 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2634 (const :tag "TODO keyword search (all agenda files)" todo)
2635 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2636 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2637 (const :tag "Occur tree (current buffer)" occur-tree)
2638 (sexp :tag "Other, user-defined function"))
2639 (string :tag "Match (only for some commands)")
2640 ,org-agenda-custom-commands-local-options
2641 (option (repeat :tag "Export" (file :tag "Export to"))))
2642 (list :tag "Command series, all agenda files"
2643 (string :tag "Access Key(s)")
2644 (string :tag "Description ")
2645 (repeat :tag "Component"
2646 (choice
2647 (list :tag "Agenda"
2648 (const :format "" agenda)
2649 (const :tag "" :format "" "")
2650 ,org-agenda-custom-commands-local-options)
2651 (list :tag "TODO list (all keywords)"
2652 (const :format "" alltodo)
2653 (const :tag "" :format "" "")
2654 ,org-agenda-custom-commands-local-options)
2655 (list :tag "Search words"
2656 (const :format "" search)
2657 (string :tag "Match")
2658 ,org-agenda-custom-commands-local-options)
2659 (list :tag "Stuck projects"
2660 (const :format "" stuck)
2661 (const :tag "" :format "" "")
2662 ,org-agenda-custom-commands-local-options)
2663 (list :tag "Tags search"
2664 (const :format "" tags)
2665 (string :tag "Match")
2666 ,org-agenda-custom-commands-local-options)
2667 (list :tag "Tags search, TODO entries only"
2668 (const :format "" tags-todo)
2669 (string :tag "Match")
2670 ,org-agenda-custom-commands-local-options)
2671 (list :tag "TODO keyword search"
2672 (const :format "" todo)
2673 (string :tag "Match")
2674 ,org-agenda-custom-commands-local-options)
2675 (list :tag "Other, user-defined function"
2676 (symbol :tag "function")
2677 (string :tag "Match")
2678 ,org-agenda-custom-commands-local-options)))
2680 (repeat :tag "Settings for entire command set"
2681 (list (variable :tag "Any variable")
2682 (sexp :tag "Value")))
2683 (option (repeat :tag "Export" (file :tag "Export to"))))
2684 (cons :tag "Prefix key documentation"
2685 (string :tag "Access Key(s)")
2686 (string :tag "Description ")))))
2688 (defcustom org-agenda-query-register ?o
2689 "The register holding the current query string.
2690 The prupose of this is that if you construct a query string interactively,
2691 you can then use it to define a custom command."
2692 :group 'org-agenda-custom-commands
2693 :type 'character)
2695 (defcustom org-stuck-projects
2696 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2697 "How to identify stuck projects.
2698 This is a list of four items:
2699 1. A tags/todo matcher string that is used to identify a project.
2700 The entire tree below a headline matched by this is considered one project.
2701 2. A list of TODO keywords identifying non-stuck projects.
2702 If the project subtree contains any headline with one of these todo
2703 keywords, the project is considered to be not stuck. If you specify
2704 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2705 3. A list of tags identifying non-stuck projects.
2706 If the project subtree contains any headline with one of these tags,
2707 the project is considered to be not stuck. If you specify \"*\" as
2708 a tag, any tag will mark the project unstuck.
2709 4. An arbitrary regular expression matching non-stuck projects.
2711 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2712 or `C-c a #' to produce the list."
2713 :group 'org-agenda-custom-commands
2714 :type '(list
2715 (string :tag "Tags/TODO match to identify a project")
2716 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2717 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2718 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2721 (defgroup org-agenda-skip nil
2722 "Options concerning skipping parts of agenda files."
2723 :tag "Org Agenda Skip"
2724 :group 'org-agenda)
2726 (defcustom org-agenda-todo-list-sublevels t
2727 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2728 When nil, the sublevels of a TODO entry are not checked, resulting in
2729 potentially much shorter TODO lists."
2730 :group 'org-agenda-skip
2731 :group 'org-todo
2732 :type 'boolean)
2734 (defcustom org-agenda-todo-ignore-with-date nil
2735 "Non-nil means, don't show entries with a date in the global todo list.
2736 You can use this if you prefer to mark mere appointments with a TODO keyword,
2737 but don't want them to show up in the TODO list.
2738 When this is set, it also covers deadlines and scheduled items, the settings
2739 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2740 will be ignored."
2741 :group 'org-agenda-skip
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-agenda-todo-ignore-scheduled nil
2746 "Non-nil means, don't show scheduled entries in the global todo list.
2747 The idea behind this is that by scheduling it, you have already taken care
2748 of this item.
2749 See also `org-agenda-todo-ignore-with-date'."
2750 :group 'org-agenda-skip
2751 :group 'org-todo
2752 :type 'boolean)
2754 (defcustom org-agenda-todo-ignore-deadlines nil
2755 "Non-nil means, don't show near deadline entries in the global todo list.
2756 Near means closer than `org-deadline-warning-days' days.
2757 The idea behind this is that such items will appear in the agenda anyway.
2758 See also `org-agenda-todo-ignore-with-date'."
2759 :group 'org-agenda-skip
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-agenda-skip-scheduled-if-done nil
2764 "Non-nil means don't show scheduled items in agenda when they are done.
2765 This is relevant for the daily/weekly agenda, not for the TODO list. And
2766 it applies only to the actual date of the scheduling. Warnings about
2767 an item with a past scheduling dates are always turned off when the item
2768 is DONE."
2769 :group 'org-agenda-skip
2770 :type 'boolean)
2772 (defcustom org-agenda-skip-deadline-if-done nil
2773 "Non-nil means don't show deadines when the corresponding item is done.
2774 When nil, the deadline is still shown and should give you a happy feeling.
2775 This is relevant for the daily/weekly agenda. And it applied only to the
2776 actualy date of the deadline. Warnings about approching and past-due
2777 deadlines are always turned off when the item is DONE."
2778 :group 'org-agenda-skip
2779 :type 'boolean)
2781 (defcustom org-agenda-skip-timestamp-if-done nil
2782 "Non-nil means don't select item by timestamp or -range if it is DONE."
2783 :group 'org-agenda-skip
2784 :type 'boolean)
2786 (defcustom org-timeline-show-empty-dates 3
2787 "Non-nil means, `org-timeline' also shows dates without an entry.
2788 When nil, only the days which actually have entries are shown.
2789 When t, all days between the first and the last date are shown.
2790 When an integer, show also empty dates, but if there is a gap of more than
2791 N days, just insert a special line indicating the size of the gap."
2792 :group 'org-agenda-skip
2793 :type '(choice
2794 (const :tag "None" nil)
2795 (const :tag "All" t)
2796 (number :tag "at most")))
2799 (defgroup org-agenda-startup nil
2800 "Options concerning initial settings in the Agenda in Org Mode."
2801 :tag "Org Agenda Startup"
2802 :group 'org-agenda)
2804 (defcustom org-finalize-agenda-hook nil
2805 "Hook run just before displaying an agenda buffer."
2806 :group 'org-agenda-startup
2807 :type 'hook)
2809 (defcustom org-agenda-mouse-1-follows-link nil
2810 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2811 A longer mouse click will still set point. Does not work on XEmacs.
2812 Needs to be set before org.el is loaded."
2813 :group 'org-agenda-startup
2814 :type 'boolean)
2816 (defcustom org-agenda-start-with-follow-mode nil
2817 "The initial value of follow-mode in a newly created agenda window."
2818 :group 'org-agenda-startup
2819 :type 'boolean)
2821 (defgroup org-agenda-windows nil
2822 "Options concerning the windows used by the Agenda in Org Mode."
2823 :tag "Org Agenda Windows"
2824 :group 'org-agenda)
2826 (defcustom org-agenda-window-setup 'reorganize-frame
2827 "How the agenda buffer should be displayed.
2828 Possible values for this option are:
2830 current-window Show agenda in the current window, keeping all other windows.
2831 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2832 other-window Use `switch-to-buffer-other-window' to display agenda.
2833 reorganize-frame Show only two windows on the current frame, the current
2834 window and the agenda.
2835 See also the variable `org-agenda-restore-windows-after-quit'."
2836 :group 'org-agenda-windows
2837 :type '(choice
2838 (const current-window)
2839 (const other-frame)
2840 (const other-window)
2841 (const reorganize-frame)))
2843 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2844 "The min and max height of the agenda window as a fraction of frame height.
2845 The value of the variable is a cons cell with two numbers between 0 and 1.
2846 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2847 :group 'org-agenda-windows
2848 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2850 (defcustom org-agenda-restore-windows-after-quit nil
2851 "Non-nil means, restore window configuration open exiting agenda.
2852 Before the window configuration is changed for displaying the agenda,
2853 the current status is recorded. When the agenda is exited with
2854 `q' or `x' and this option is set, the old state is restored. If
2855 `org-agenda-window-setup' is `other-frame', the value of this
2856 option will be ignored.."
2857 :group 'org-agenda-windows
2858 :type 'boolean)
2860 (defcustom org-indirect-buffer-display 'other-window
2861 "How should indirect tree buffers be displayed?
2862 This applies to indirect buffers created with the commands
2863 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2864 Valid values are:
2865 current-window Display in the current window
2866 other-window Just display in another window.
2867 dedicated-frame Create one new frame, and re-use it each time.
2868 new-frame Make a new frame each time. Note that in this case
2869 previously-made indirect buffers are kept, and you need to
2870 kill these buffers yourself."
2871 :group 'org-structure
2872 :group 'org-agenda-windows
2873 :type '(choice
2874 (const :tag "In current window" current-window)
2875 (const :tag "In current frame, other window" other-window)
2876 (const :tag "Each time a new frame" new-frame)
2877 (const :tag "One dedicated frame" dedicated-frame)))
2879 (defgroup org-agenda-daily/weekly nil
2880 "Options concerning the daily/weekly agenda."
2881 :tag "Org Agenda Daily/Weekly"
2882 :group 'org-agenda)
2884 (defcustom org-agenda-ndays 7
2885 "Number of days to include in overview display.
2886 Should be 1 or 7."
2887 :group 'org-agenda-daily/weekly
2888 :type 'number)
2890 (defcustom org-agenda-start-on-weekday 1
2891 "Non-nil means, start the overview always on the specified weekday.
2892 0 denotes Sunday, 1 denotes Monday etc.
2893 When nil, always start on the current day."
2894 :group 'org-agenda-daily/weekly
2895 :type '(choice (const :tag "Today" nil)
2896 (number :tag "Weekday No.")))
2898 (defcustom org-agenda-show-all-dates t
2899 "Non-nil means, `org-agenda' shows every day in the selected range.
2900 When nil, only the days which actually have entries are shown."
2901 :group 'org-agenda-daily/weekly
2902 :type 'boolean)
2904 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2905 "Format string for displaying dates in the agenda.
2906 Used by the daily/weekly agenda and by the timeline. This should be
2907 a format string understood by `format-time-string', or a function returning
2908 the formatted date as a string. The function must take a single argument,
2909 a calendar-style date list like (month day year)."
2910 :group 'org-agenda-daily/weekly
2911 :type '(choice
2912 (string :tag "Format string")
2913 (function :tag "Function")))
2915 (defun org-agenda-format-date-aligned (date)
2916 "Format a date string for display in the daily/weekly agenda, or timeline.
2917 This function makes sure that dates are aligned for easy reading."
2918 (require 'cal-iso)
2919 (let* ((dayname (calendar-day-name date))
2920 (day (extract-calendar-day date))
2921 (day-of-week (calendar-day-of-week date))
2922 (month (extract-calendar-month date))
2923 (monthname (calendar-month-name month))
2924 (year (extract-calendar-year date))
2925 (iso-week (org-days-to-iso-week
2926 (calendar-absolute-from-gregorian date)))
2927 (weekyear (cond ((and (= month 1) (>= iso-week 52))
2928 (1- year))
2929 ((and (= month 12) (<= iso-week 1))
2930 (1+ year))
2931 (t year)))
2932 (weekstring (if (= day-of-week 1)
2933 (format " W%02d" iso-week)
2934 "")))
2935 (format "%-10s %2d %s %4d%s"
2936 dayname day monthname year weekstring)))
2938 (defcustom org-agenda-include-diary nil
2939 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2940 :group 'org-agenda-daily/weekly
2941 :type 'boolean)
2943 (defcustom org-agenda-include-all-todo nil
2944 "Set means weekly/daily agenda will always contain all TODO entries.
2945 The TODO entries will be listed at the top of the agenda, before
2946 the entries for specific days."
2947 :group 'org-agenda-daily/weekly
2948 :type 'boolean)
2950 (defcustom org-agenda-repeating-timestamp-show-all t
2951 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2952 When nil, only one occurence is shown, either today or the
2953 nearest into the future."
2954 :group 'org-agenda-daily/weekly
2955 :type 'boolean)
2957 (defcustom org-deadline-warning-days 14
2958 "No. of days before expiration during which a deadline becomes active.
2959 This variable governs the display in sparse trees and in the agenda.
2960 When 0 or negative, it means use this number (the absolute value of it)
2961 even if a deadline has a different individual lead time specified."
2962 :group 'org-time
2963 :group 'org-agenda-daily/weekly
2964 :type 'number)
2966 (defcustom org-scheduled-past-days 10000
2967 "No. of days to continue listing scheduled items that are not marked DONE.
2968 When an item is scheduled on a date, it shows up in the agenda on this
2969 day and will be listed until it is marked done for the number of days
2970 given here."
2971 :group 'org-agenda-daily/weekly
2972 :type 'number)
2974 (defgroup org-agenda-time-grid nil
2975 "Options concerning the time grid in the Org-mode Agenda."
2976 :tag "Org Agenda Time Grid"
2977 :group 'org-agenda)
2979 (defcustom org-agenda-use-time-grid t
2980 "Non-nil means, show a time grid in the agenda schedule.
2981 A time grid is a set of lines for specific times (like every two hours between
2982 8:00 and 20:00). The items scheduled for a day at specific times are
2983 sorted in between these lines.
2984 For details about when the grid will be shown, and what it will look like, see
2985 the variable `org-agenda-time-grid'."
2986 :group 'org-agenda-time-grid
2987 :type 'boolean)
2989 (defcustom org-agenda-time-grid
2990 '((daily today require-timed)
2991 "----------------"
2992 (800 1000 1200 1400 1600 1800 2000))
2994 "The settings for time grid for agenda display.
2995 This is a list of three items. The first item is again a list. It contains
2996 symbols specifying conditions when the grid should be displayed:
2998 daily if the agenda shows a single day
2999 weekly if the agenda shows an entire week
3000 today show grid on current date, independent of daily/weekly display
3001 require-timed show grid only if at least one item has a time specification
3003 The second item is a string which will be places behing the grid time.
3005 The third item is a list of integers, indicating the times that should have
3006 a grid line."
3007 :group 'org-agenda-time-grid
3008 :type
3009 '(list
3010 (set :greedy t :tag "Grid Display Options"
3011 (const :tag "Show grid in single day agenda display" daily)
3012 (const :tag "Show grid in weekly agenda display" weekly)
3013 (const :tag "Always show grid for today" today)
3014 (const :tag "Show grid only if any timed entries are present"
3015 require-timed)
3016 (const :tag "Skip grid times already present in an entry"
3017 remove-match))
3018 (string :tag "Grid String")
3019 (repeat :tag "Grid Times" (integer :tag "Time"))))
3021 (defgroup org-agenda-sorting nil
3022 "Options concerning sorting in the Org-mode Agenda."
3023 :tag "Org Agenda Sorting"
3024 :group 'org-agenda)
3026 (defcustom org-agenda-sorting-strategy
3027 '((agenda time-up category-keep priority-down)
3028 (todo category-keep priority-down)
3029 (tags category-keep priority-down)
3030 (search category-keep))
3031 "Sorting structure for the agenda items of a single day.
3032 This is a list of symbols which will be used in sequence to determine
3033 if an entry should be listed before another entry. The following
3034 symbols are recognized:
3036 time-up Put entries with time-of-day indications first, early first
3037 time-down Put entries with time-of-day indications first, late first
3038 category-keep Keep the default order of categories, corresponding to the
3039 sequence in `org-agenda-files'.
3040 category-up Sort alphabetically by category, A-Z.
3041 category-down Sort alphabetically by category, Z-A.
3042 tag-up Sort alphabetically by last tag, A-Z.
3043 tag-down Sort alphabetically by last tag, Z-A.
3044 priority-up Sort numerically by priority, high priority last.
3045 priority-down Sort numerically by priority, high priority first.
3047 The different possibilities will be tried in sequence, and testing stops
3048 if one comparison returns a \"not-equal\". For example, the default
3049 '(time-up category-keep priority-down)
3050 means: Pull out all entries having a specified time of day and sort them,
3051 in order to make a time schedule for the current day the first thing in the
3052 agenda listing for the day. Of the entries without a time indication, keep
3053 the grouped in categories, don't sort the categories, but keep them in
3054 the sequence given in `org-agenda-files'. Within each category sort by
3055 priority.
3057 Leaving out `category-keep' would mean that items will be sorted across
3058 categories by priority.
3060 Instead of a single list, this can also be a set of list for specific
3061 contents, with a context symbol in the car of the list, any of
3062 `agenda', `todo', `tags' for the corresponding agenda views."
3063 :group 'org-agenda-sorting
3064 :type `(choice
3065 (repeat :tag "General" ,org-sorting-choice)
3066 (list :tag "Individually"
3067 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
3068 (repeat ,org-sorting-choice))
3069 (cons (const :tag "Strategy for TODO lists" todo)
3070 (repeat ,org-sorting-choice))
3071 (cons (const :tag "Strategy for Tags matches" tags)
3072 (repeat ,org-sorting-choice)))))
3074 (defcustom org-sort-agenda-notime-is-late t
3075 "Non-nil means, items without time are considered late.
3076 This is only relevant for sorting. When t, items which have no explicit
3077 time like 15:30 will be considered as 99:01, i.e. later than any items which
3078 do have a time. When nil, the default time is before 0:00. You can use this
3079 option to decide if the schedule for today should come before or after timeless
3080 agenda entries."
3081 :group 'org-agenda-sorting
3082 :type 'boolean)
3084 (defgroup org-agenda-line-format nil
3085 "Options concerning the entry prefix in the Org-mode agenda display."
3086 :tag "Org Agenda Line Format"
3087 :group 'org-agenda)
3089 (defcustom org-agenda-prefix-format
3090 '((agenda . " %-12:c%?-12t% s")
3091 (timeline . " % s")
3092 (todo . " %-12:c")
3093 (tags . " %-12:c")
3094 (search . " %-12:c"))
3095 "Format specifications for the prefix of items in the agenda views.
3096 An alist with four entries, for the different agenda types. The keys to the
3097 sublists are `agenda', `timeline', `todo', and `tags'. The values
3098 are format strings.
3099 This format works similar to a printf format, with the following meaning:
3101 %c the category of the item, \"Diary\" for entries from the diary, or
3102 as given by the CATEGORY keyword or derived from the file name.
3103 %T the *last* tag of the item. Last because inherited tags come
3104 first in the list.
3105 %t the time-of-day specification if one applies to the entry, in the
3106 format HH:MM
3107 %s Scheduling/Deadline information, a short string
3109 All specifiers work basically like the standard `%s' of printf, but may
3110 contain two additional characters: A question mark just after the `%' and
3111 a whitespace/punctuation character just before the final letter.
3113 If the first character after `%' is a question mark, the entire field
3114 will only be included if the corresponding value applies to the
3115 current entry. This is useful for fields which should have fixed
3116 width when present, but zero width when absent. For example,
3117 \"%?-12t\" will result in a 12 character time field if a time of the
3118 day is specified, but will completely disappear in entries which do
3119 not contain a time.
3121 If there is punctuation or whitespace character just before the final
3122 format letter, this character will be appended to the field value if
3123 the value is not empty. For example, the format \"%-12:c\" leads to
3124 \"Diary: \" if the category is \"Diary\". If the category were be
3125 empty, no additional colon would be interted.
3127 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3128 - Indent the line with two space characters
3129 - Give the category in a 12 chars wide field, padded with whitespace on
3130 the right (because of `-'). Append a colon if there is a category
3131 (because of `:').
3132 - If there is a time-of-day, put it into a 12 chars wide field. If no
3133 time, don't put in an empty field, just skip it (because of '?').
3134 - Finally, put the scheduling information and append a whitespace.
3136 As another example, if you don't want the time-of-day of entries in
3137 the prefix, you could use:
3139 (setq org-agenda-prefix-format \" %-11:c% s\")
3141 See also the variables `org-agenda-remove-times-when-in-prefix' and
3142 `org-agenda-remove-tags'."
3143 :type '(choice
3144 (string :tag "General format")
3145 (list :greedy t :tag "View dependent"
3146 (cons (const agenda) (string :tag "Format"))
3147 (cons (const timeline) (string :tag "Format"))
3148 (cons (const todo) (string :tag "Format"))
3149 (cons (const tags) (string :tag "Format"))
3150 (cons (const search) (string :tag "Format"))))
3151 :group 'org-agenda-line-format)
3153 (defvar org-prefix-format-compiled nil
3154 "The compiled version of the most recently used prefix format.
3155 See the variable `org-agenda-prefix-format'.")
3157 (defcustom org-agenda-todo-keyword-format "%-1s"
3158 "Format for the TODO keyword in agenda lines.
3159 Set this to something like \"%-12s\" if you want all TODO keywords
3160 to occupy a fixed space in the agenda display."
3161 :group 'org-agenda-line-format
3162 :type 'string)
3164 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3165 "Text preceeding scheduled items in the agenda view.
3166 This is a list with two strings. The first applies when the item is
3167 scheduled on the current day. The second applies when it has been scheduled
3168 previously, it may contain a %d to capture how many days ago the item was
3169 scheduled."
3170 :group 'org-agenda-line-format
3171 :type '(list
3172 (string :tag "Scheduled today ")
3173 (string :tag "Scheduled previously")))
3175 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3176 "Text preceeding deadline items in the agenda view.
3177 This is a list with two strings. The first applies when the item has its
3178 deadline on the current day. The second applies when it is in the past or
3179 in the future, it may contain %d to capture how many days away the deadline
3180 is (was)."
3181 :group 'org-agenda-line-format
3182 :type '(list
3183 (string :tag "Deadline today ")
3184 (string :tag "Deadline relative")))
3186 (defcustom org-agenda-remove-times-when-in-prefix t
3187 "Non-nil means, remove duplicate time specifications in agenda items.
3188 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3189 time-of-day specification in a headline or diary entry is extracted and
3190 placed into the prefix. If this option is non-nil, the original specification
3191 \(a timestamp or -range, or just a plain time(range) specification like
3192 11:30-4pm) will be removed for agenda display. This makes the agenda less
3193 cluttered.
3194 The option can be t or nil. It may also be the symbol `beg', indicating
3195 that the time should only be removed what it is located at the beginning of
3196 the headline/diary entry."
3197 :group 'org-agenda-line-format
3198 :type '(choice
3199 (const :tag "Always" t)
3200 (const :tag "Never" nil)
3201 (const :tag "When at beginning of entry" beg)))
3204 (defcustom org-agenda-default-appointment-duration nil
3205 "Default duration for appointments that only have a starting time.
3206 When nil, no duration is specified in such cases.
3207 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3208 :group 'org-agenda-line-format
3209 :type '(choice
3210 (integer :tag "Minutes")
3211 (const :tag "No default duration")))
3214 (defcustom org-agenda-remove-tags nil
3215 "Non-nil means, remove the tags from the headline copy in the agenda.
3216 When this is the symbol `prefix', only remove tags when
3217 `org-agenda-prefix-format' contains a `%T' specifier."
3218 :group 'org-agenda-line-format
3219 :type '(choice
3220 (const :tag "Always" t)
3221 (const :tag "Never" nil)
3222 (const :tag "When prefix format contains %T" prefix)))
3224 (if (fboundp 'defvaralias)
3225 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3226 'org-agenda-remove-tags))
3228 (defcustom org-agenda-tags-column -80
3229 "Shift tags in agenda items to this column.
3230 If this number is positive, it specifies the column. If it is negative,
3231 it means that the tags should be flushright to that column. For example,
3232 -80 works well for a normal 80 character screen."
3233 :group 'org-agenda-line-format
3234 :type 'integer)
3236 (if (fboundp 'defvaralias)
3237 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3239 (defcustom org-agenda-fontify-priorities t
3240 "Non-nil means, highlight low and high priorities in agenda.
3241 When t, the highest priority entries are bold, lowest priority italic.
3242 This may also be an association list of priority faces. The face may be
3243 a names face, or a list like `(:background \"Red\")'."
3244 :group 'org-agenda-line-format
3245 :type '(choice
3246 (const :tag "Never" nil)
3247 (const :tag "Defaults" t)
3248 (repeat :tag "Specify"
3249 (list (character :tag "Priority" :value ?A)
3250 (sexp :tag "face")))))
3252 (defgroup org-latex nil
3253 "Options for embedding LaTeX code into Org-mode."
3254 :tag "Org LaTeX"
3255 :group 'org)
3257 (defcustom org-format-latex-options
3258 '(:foreground default :background default :scale 1.0
3259 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3260 :matchers ("begin" "$" "$$" "\\(" "\\["))
3261 "Options for creating images from LaTeX fragments.
3262 This is a property list with the following properties:
3263 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3264 `default' means use the forground of the default face.
3265 :background the background color, or \"Transparent\".
3266 `default' means use the background of the default face.
3267 :scale a scaling factor for the size of the images
3268 :html-foreground, :html-background, :html-scale
3269 The same numbers for HTML export.
3270 :matchers a list indicating which matchers should be used to
3271 find LaTeX fragments. Valid members of this list are:
3272 \"begin\" find environments
3273 \"$\" find math expressions surrounded by $...$
3274 \"$$\" find math expressions surrounded by $$....$$
3275 \"\\(\" find math expressions surrounded by \\(...\\)
3276 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3277 :group 'org-latex
3278 :type 'plist)
3280 (defcustom org-format-latex-header "\\documentclass{article}
3281 \\usepackage{fullpage} % do not remove
3282 \\usepackage{amssymb}
3283 \\usepackage[usenames]{color}
3284 \\usepackage{amsmath}
3285 \\usepackage{latexsym}
3286 \\usepackage[mathscr]{eucal}
3287 \\pagestyle{empty} % do not remove"
3288 "The document header used for processing LaTeX fragments."
3289 :group 'org-latex
3290 :type 'string)
3292 (defgroup org-export nil
3293 "Options for exporting org-listings."
3294 :tag "Org Export"
3295 :group 'org)
3297 (defgroup org-export-general nil
3298 "General options for exporting Org-mode files."
3299 :tag "Org Export General"
3300 :group 'org-export)
3302 ;; FIXME
3303 (defvar org-export-publishing-directory nil)
3305 (defcustom org-export-with-special-strings t
3306 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3307 When this option is turned on, these strings will be exported as:
3309 Org HTML LaTeX
3310 -----+----------+--------
3311 \\- &shy; \\-
3312 -- &ndash; --
3313 --- &mdash; ---
3314 ... &hellip; \ldots
3316 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3317 :group 'org-export-translation
3318 :type 'boolean)
3320 (defcustom org-export-language-setup
3321 '(("en" "Author" "Date" "Table of Contents")
3322 ("cs" "Autor" "Datum" "Obsah")
3323 ("da" "Ophavsmand" "Dato" "Indhold")
3324 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3325 ("es" "Autor" "Fecha" "\xcdndice")
3326 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3327 ("it" "Autore" "Data" "Indice")
3328 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3329 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3330 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3331 "Terms used in export text, translated to different languages.
3332 Use the variable `org-export-default-language' to set the language,
3333 or use the +OPTION lines for a per-file setting."
3334 :group 'org-export-general
3335 :type '(repeat
3336 (list
3337 (string :tag "HTML language tag")
3338 (string :tag "Author")
3339 (string :tag "Date")
3340 (string :tag "Table of Contents"))))
3342 (defcustom org-export-default-language "en"
3343 "The default language of HTML export, as a string.
3344 This should have an association in `org-export-language-setup'."
3345 :group 'org-export-general
3346 :type 'string)
3348 (defcustom org-export-skip-text-before-1st-heading t
3349 "Non-nil means, skip all text before the first headline when exporting.
3350 When nil, that text is exported as well."
3351 :group 'org-export-general
3352 :type 'boolean)
3354 (defcustom org-export-headline-levels 3
3355 "The last level which is still exported as a headline.
3356 Inferior levels will produce itemize lists when exported.
3357 Note that a numeric prefix argument to an exporter function overrides
3358 this setting.
3360 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3361 :group 'org-export-general
3362 :type 'number)
3364 (defcustom org-export-with-section-numbers t
3365 "Non-nil means, add section numbers to headlines when exporting.
3367 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3368 :group 'org-export-general
3369 :type 'boolean)
3371 (defcustom org-export-with-toc t
3372 "Non-nil means, create a table of contents in exported files.
3373 The TOC contains headlines with levels up to`org-export-headline-levels'.
3374 When an integer, include levels up to N in the toc, this may then be
3375 different from `org-export-headline-levels', but it will not be allowed
3376 to be larger than the number of headline levels.
3377 When nil, no table of contents is made.
3379 Headlines which contain any TODO items will be marked with \"(*)\" in
3380 ASCII export, and with red color in HTML output, if the option
3381 `org-export-mark-todo-in-toc' is set.
3383 In HTML output, the TOC will be clickable.
3385 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3386 or \"toc:3\"."
3387 :group 'org-export-general
3388 :type '(choice
3389 (const :tag "No Table of Contents" nil)
3390 (const :tag "Full Table of Contents" t)
3391 (integer :tag "TOC to level")))
3393 (defcustom org-export-mark-todo-in-toc nil
3394 "Non-nil means, mark TOC lines that contain any open TODO items."
3395 :group 'org-export-general
3396 :type 'boolean)
3398 (defcustom org-export-preserve-breaks nil
3399 "Non-nil means, preserve all line breaks when exporting.
3400 Normally, in HTML output paragraphs will be reformatted. In ASCII
3401 export, line breaks will always be preserved, regardless of this variable.
3403 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3404 :group 'org-export-general
3405 :type 'boolean)
3407 (defcustom org-export-with-archived-trees 'headline
3408 "Whether subtrees with the ARCHIVE tag should be exported.
3409 This can have three different values
3410 nil Do not export, pretend this tree is not present
3411 t Do export the entire tree
3412 headline Only export the headline, but skip the tree below it."
3413 :group 'org-export-general
3414 :group 'org-archive
3415 :type '(choice
3416 (const :tag "not at all" nil)
3417 (const :tag "headline only" 'headline)
3418 (const :tag "entirely" t)))
3420 (defcustom org-export-author-info t
3421 "Non-nil means, insert author name and email into the exported file.
3423 This option can also be set with the +OPTIONS line,
3424 e.g. \"author-info:nil\"."
3425 :group 'org-export-general
3426 :type 'boolean)
3428 (defcustom org-export-time-stamp-file t
3429 "Non-nil means, insert a time stamp into the exported file.
3430 The time stamp shows when the file was created.
3432 This option can also be set with the +OPTIONS line,
3433 e.g. \"timestamp:nil\"."
3434 :group 'org-export-general
3435 :type 'boolean)
3437 (defcustom org-export-with-timestamps t
3438 "If nil, do not export time stamps and associated keywords."
3439 :group 'org-export-general
3440 :type 'boolean)
3442 (defcustom org-export-remove-timestamps-from-toc t
3443 "If nil, remove timestamps from the table of contents entries."
3444 :group 'org-export-general
3445 :type 'boolean)
3447 (defcustom org-export-with-tags 'not-in-toc
3448 "If nil, do not export tags, just remove them from headlines.
3449 If this is the symbol `not-in-toc', tags will be removed from table of
3450 contents entries, but still be shown in the headlines of the document.
3452 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3453 :group 'org-export-general
3454 :type '(choice
3455 (const :tag "Off" nil)
3456 (const :tag "Not in TOC" not-in-toc)
3457 (const :tag "On" t)))
3459 (defcustom org-export-with-drawers nil
3460 "Non-nil means, export with drawers like the property drawer.
3461 When t, all drawers are exported. This may also be a list of
3462 drawer names to export."
3463 :group 'org-export-general
3464 :type '(choice
3465 (const :tag "All drawers" t)
3466 (const :tag "None" nil)
3467 (repeat :tag "Selected drawers"
3468 (string :tag "Drawer name"))))
3470 (defgroup org-export-translation nil
3471 "Options for translating special ascii sequences for the export backends."
3472 :tag "Org Export Translation"
3473 :group 'org-export)
3475 (defcustom org-export-with-emphasize t
3476 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3477 If the export target supports emphasizing text, the word will be
3478 typeset in bold, italic, or underlined, respectively. Works only for
3479 single words, but you can say: I *really* *mean* *this*.
3480 Not all export backends support this.
3482 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3483 :group 'org-export-translation
3484 :type 'boolean)
3486 (defcustom org-export-with-footnotes t
3487 "If nil, export [1] as a footnote marker.
3488 Lines starting with [1] will be formatted as footnotes.
3490 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3491 :group 'org-export-translation
3492 :type 'boolean)
3494 (defcustom org-export-with-sub-superscripts t
3495 "Non-nil means, interpret \"_\" and \"^\" for export.
3496 When this option is turned on, you can use TeX-like syntax for sub- and
3497 superscripts. Several characters after \"_\" or \"^\" will be
3498 considered as a single item - so grouping with {} is normally not
3499 needed. For example, the following things will be parsed as single
3500 sub- or superscripts.
3502 10^24 or 10^tau several digits will be considered 1 item.
3503 10^-12 or 10^-tau a leading sign with digits or a word
3504 x^2-y^3 will be read as x^2 - y^3, because items are
3505 terminated by almost any nonword/nondigit char.
3506 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3508 Still, ambiguity is possible - so when in doubt use {} to enclose the
3509 sub/superscript. If you set this variable to the symbol `{}',
3510 the braces are *required* in order to trigger interpretations as
3511 sub/superscript. This can be helpful in documents that need \"_\"
3512 frequently in plain text.
3514 Not all export backends support this, but HTML does.
3516 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3517 :group 'org-export-translation
3518 :type '(choice
3519 (const :tag "Always interpret" t)
3520 (const :tag "Only with braces" {})
3521 (const :tag "Never interpret" nil)))
3523 (defcustom org-export-with-special-strings t
3524 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3525 When this option is turned on, these strings will be exported as:
3527 \\- : &shy;
3528 -- : &ndash;
3529 --- : &mdash;
3531 Not all export backends support this, but HTML does.
3533 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3534 :group 'org-export-translation
3535 :type 'boolean)
3537 (defcustom org-export-with-TeX-macros t
3538 "Non-nil means, interpret simple TeX-like macros when exporting.
3539 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3540 No only real TeX macros will work here, but the standard HTML entities
3541 for math can be used as macro names as well. For a list of supported
3542 names in HTML export, see the constant `org-html-entities'.
3543 Not all export backends support this.
3545 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3546 :group 'org-export-translation
3547 :group 'org-export-latex
3548 :type 'boolean)
3550 (defcustom org-export-with-LaTeX-fragments nil
3551 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3552 When set, the exporter will find LaTeX environments if the \\begin line is
3553 the first non-white thing on a line. It will also find the math delimiters
3554 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3555 display math.
3557 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3558 :group 'org-export-translation
3559 :group 'org-export-latex
3560 :type 'boolean)
3562 (defcustom org-export-with-fixed-width t
3563 "Non-nil means, lines starting with \":\" will be in fixed width font.
3564 This can be used to have pre-formatted text, fragments of code etc. For
3565 example:
3566 : ;; Some Lisp examples
3567 : (while (defc cnt)
3568 : (ding))
3569 will be looking just like this in also HTML. See also the QUOTE keyword.
3570 Not all export backends support this.
3572 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3573 :group 'org-export-translation
3574 :type 'boolean)
3576 (defcustom org-match-sexp-depth 3
3577 "Number of stacked braces for sub/superscript matching.
3578 This has to be set before loading org.el to be effective."
3579 :group 'org-export-translation
3580 :type 'integer)
3582 (defgroup org-export-tables nil
3583 "Options for exporting tables in Org-mode."
3584 :tag "Org Export Tables"
3585 :group 'org-export)
3587 (defcustom org-export-with-tables t
3588 "If non-nil, lines starting with \"|\" define a table.
3589 For example:
3591 | Name | Address | Birthday |
3592 |-------------+----------+-----------|
3593 | Arthur Dent | England | 29.2.2100 |
3595 Not all export backends support this.
3597 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3598 :group 'org-export-tables
3599 :type 'boolean)
3601 (defcustom org-export-highlight-first-table-line t
3602 "Non-nil means, highlight the first table line.
3603 In HTML export, this means use <th> instead of <td>.
3604 In tables created with table.el, this applies to the first table line.
3605 In Org-mode tables, all lines before the first horizontal separator
3606 line will be formatted with <th> tags."
3607 :group 'org-export-tables
3608 :type 'boolean)
3610 (defcustom org-export-table-remove-special-lines t
3611 "Remove special lines and marking characters in calculating tables.
3612 This removes the special marking character column from tables that are set
3613 up for spreadsheet calculations. It also removes the entire lines
3614 marked with `!', `_', or `^'. The lines with `$' are kept, because
3615 the values of constants may be useful to have."
3616 :group 'org-export-tables
3617 :type 'boolean)
3619 (defcustom org-export-prefer-native-exporter-for-tables nil
3620 "Non-nil means, always export tables created with table.el natively.
3621 Natively means, use the HTML code generator in table.el.
3622 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3623 the table does not use row- or column-spanning). This has the
3624 advantage, that the automatic HTML conversions for math symbols and
3625 sub/superscripts can be applied. Org-mode's HTML generator is also
3626 much faster."
3627 :group 'org-export-tables
3628 :type 'boolean)
3630 (defgroup org-export-ascii nil
3631 "Options specific for ASCII export of Org-mode files."
3632 :tag "Org Export ASCII"
3633 :group 'org-export)
3635 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3636 "Characters for underlining headings in ASCII export.
3637 In the given sequence, these characters will be used for level 1, 2, ..."
3638 :group 'org-export-ascii
3639 :type '(repeat character))
3641 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3642 "Bullet characters for headlines converted to lists in ASCII export.
3643 The first character is used for the first lest level generated in this
3644 way, and so on. If there are more levels than characters given here,
3645 the list will be repeated.
3646 Note that plain lists will keep the same bullets as the have in the
3647 Org-mode file."
3648 :group 'org-export-ascii
3649 :type '(repeat character))
3651 (defgroup org-export-xml nil
3652 "Options specific for XML export of Org-mode files."
3653 :tag "Org Export XML"
3654 :group 'org-export)
3656 (defgroup org-export-html nil
3657 "Options specific for HTML export of Org-mode files."
3658 :tag "Org Export HTML"
3659 :group 'org-export)
3661 (defcustom org-export-html-coding-system nil
3663 :group 'org-export-html
3664 :type 'coding-system)
3666 (defcustom org-export-html-extension "html"
3667 "The extension for exported HTML files."
3668 :group 'org-export-html
3669 :type 'string)
3671 (defcustom org-export-html-style
3672 "<style type=\"text/css\">
3673 html {
3674 font-family: Times, serif;
3675 font-size: 12pt;
3677 .title { text-align: center; }
3678 .todo { color: red; }
3679 .done { color: green; }
3680 .timestamp { color: grey }
3681 .timestamp-kwd { color: CadetBlue }
3682 .tag { background-color:lightblue; font-weight:normal }
3683 .target { background-color: lavender; }
3684 pre {
3685 border: 1pt solid #AEBDCC;
3686 background-color: #F3F5F7;
3687 padding: 5pt;
3688 font-family: courier, monospace;
3690 table { border-collapse: collapse; }
3691 td, th {
3692 vertical-align: top;
3693 <!--border: 1pt solid #ADB9CC;-->
3695 </style>"
3696 "The default style specification for exported HTML files.
3697 Since there are different ways of setting style information, this variable
3698 needs to contain the full HTML structure to provide a style, including the
3699 surrounding HTML tags. The style specifications should include definitions
3700 for new classes todo, done, title, and deadline. For example, valid values
3701 would be:
3703 <style type=\"text/css\">
3704 p { font-weight: normal; color: gray; }
3705 h1 { color: black; }
3706 .title { text-align: center; }
3707 .todo, .deadline { color: red; }
3708 .done { color: green; }
3709 </style>
3711 or, if you want to keep the style in a file,
3713 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3715 As the value of this option simply gets inserted into the HTML <head> header,
3716 you can \"misuse\" it to add arbitrary text to the header."
3717 :group 'org-export-html
3718 :type 'string)
3721 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3722 "Format for typesetting the document title in HTML export."
3723 :group 'org-export-html
3724 :type 'string)
3726 (defcustom org-export-html-toplevel-hlevel 2
3727 "The <H> level for level 1 headings in HTML export."
3728 :group 'org-export-html
3729 :type 'string)
3731 (defcustom org-export-html-link-org-files-as-html t
3732 "Non-nil means, make file links to `file.org' point to `file.html'.
3733 When org-mode is exporting an org-mode file to HTML, links to
3734 non-html files are directly put into a href tag in HTML.
3735 However, links to other Org-mode files (recognized by the
3736 extension `.org.) should become links to the corresponding html
3737 file, assuming that the linked org-mode file will also be
3738 converted to HTML.
3739 When nil, the links still point to the plain `.org' file."
3740 :group 'org-export-html
3741 :type 'boolean)
3743 (defcustom org-export-html-inline-images 'maybe
3744 "Non-nil means, inline images into exported HTML pages.
3745 This is done using an <img> tag. When nil, an anchor with href is used to
3746 link to the image. If this option is `maybe', then images in links with
3747 an empty description will be inlined, while images with a description will
3748 be linked only."
3749 :group 'org-export-html
3750 :type '(choice (const :tag "Never" nil)
3751 (const :tag "Always" t)
3752 (const :tag "When there is no description" maybe)))
3754 ;; FIXME: rename
3755 (defcustom org-export-html-expand t
3756 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3757 When nil, these tags will be exported as plain text and therefore
3758 not be interpreted by a browser.
3760 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3761 :group 'org-export-html
3762 :type 'boolean)
3764 (defcustom org-export-html-table-tag
3765 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3766 "The HTML tag that is used to start a table.
3767 This must be a <table> tag, but you may change the options like
3768 borders and spacing."
3769 :group 'org-export-html
3770 :type 'string)
3772 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3773 "The opening tag for table header fields.
3774 This is customizable so that alignment options can be specified."
3775 :group 'org-export-tables
3776 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3778 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3779 "The opening tag for table data fields.
3780 This is customizable so that alignment options can be specified."
3781 :group 'org-export-tables
3782 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3784 (defcustom org-export-html-with-timestamp nil
3785 "If non-nil, write `org-export-html-html-helper-timestamp'
3786 into the exported HTML text. Otherwise, the buffer will just be saved
3787 to a file."
3788 :group 'org-export-html
3789 :type 'boolean)
3791 (defcustom org-export-html-html-helper-timestamp
3792 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3793 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3794 :group 'org-export-html
3795 :type 'string)
3797 (defgroup org-export-icalendar nil
3798 "Options specific for iCalendar export of Org-mode files."
3799 :tag "Org Export iCalendar"
3800 :group 'org-export)
3802 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3803 "The file name for the iCalendar file covering all agenda files.
3804 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3805 The file name should be absolute, the file will be overwritten without warning."
3806 :group 'org-export-icalendar
3807 :type 'file)
3809 (defcustom org-icalendar-include-todo nil
3810 "Non-nil means, export to iCalendar files should also cover TODO items."
3811 :group 'org-export-icalendar
3812 :type '(choice
3813 (const :tag "None" nil)
3814 (const :tag "Unfinished" t)
3815 (const :tag "All" all)))
3817 (defcustom org-icalendar-include-sexps t
3818 "Non-nil means, export to iCalendar files should also cover sexp entries.
3819 These are entries like in the diary, but directly in an Org-mode file."
3820 :group 'org-export-icalendar
3821 :type 'boolean)
3823 (defcustom org-icalendar-include-body 100
3824 "Amount of text below headline to be included in iCalendar export.
3825 This is a number of characters that should maximally be included.
3826 Properties, scheduling and clocking lines will always be removed.
3827 The text will be inserted into the DESCRIPTION field."
3828 :group 'org-export-icalendar
3829 :type '(choice
3830 (const :tag "Nothing" nil)
3831 (const :tag "Everything" t)
3832 (integer :tag "Max characters")))
3834 (defcustom org-icalendar-combined-name "OrgMode"
3835 "Calendar name for the combined iCalendar representing all agenda files."
3836 :group 'org-export-icalendar
3837 :type 'string)
3839 (defgroup org-font-lock nil
3840 "Font-lock settings for highlighting in Org-mode."
3841 :tag "Org Font Lock"
3842 :group 'org)
3844 (defcustom org-level-color-stars-only nil
3845 "Non-nil means fontify only the stars in each headline.
3846 When nil, the entire headline is fontified.
3847 Changing it requires restart of `font-lock-mode' to become effective
3848 also in regions already fontified."
3849 :group 'org-font-lock
3850 :type 'boolean)
3852 (defcustom org-hide-leading-stars nil
3853 "Non-nil means, hide the first N-1 stars in a headline.
3854 This works by using the face `org-hide' for these stars. This
3855 face is white for a light background, and black for a dark
3856 background. You may have to customize the face `org-hide' to
3857 make this work.
3858 Changing it requires restart of `font-lock-mode' to become effective
3859 also in regions already fontified.
3860 You may also set this on a per-file basis by adding one of the following
3861 lines to the buffer:
3863 #+STARTUP: hidestars
3864 #+STARTUP: showstars"
3865 :group 'org-font-lock
3866 :type 'boolean)
3868 (defcustom org-fontify-done-headline nil
3869 "Non-nil means, change the face of a headline if it is marked DONE.
3870 Normally, only the TODO/DONE keyword indicates the state of a headline.
3871 When this is non-nil, the headline after the keyword is set to the
3872 `org-headline-done' as an additional indication."
3873 :group 'org-font-lock
3874 :type 'boolean)
3876 (defcustom org-fontify-emphasized-text t
3877 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3878 Changing this variable requires a restart of Emacs to take effect."
3879 :group 'org-font-lock
3880 :type 'boolean)
3882 (defcustom org-highlight-latex-fragments-and-specials nil
3883 "Non-nil means, fontify what is treated specially by the exporters."
3884 :group 'org-font-lock
3885 :type 'boolean)
3887 (defcustom org-hide-emphasis-markers nil
3888 "Non-nil mean font-lock should hide the emphasis marker characters."
3889 :group 'org-font-lock
3890 :type 'boolean)
3892 (defvar org-emph-re nil
3893 "Regular expression for matching emphasis.")
3894 (defvar org-verbatim-re nil
3895 "Regular expression for matching verbatim text.")
3896 (defvar org-emphasis-regexp-components) ; defined just below
3897 (defvar org-emphasis-alist) ; defined just below
3898 (defun org-set-emph-re (var val)
3899 "Set variable and compute the emphasis regular expression."
3900 (set var val)
3901 (when (and (boundp 'org-emphasis-alist)
3902 (boundp 'org-emphasis-regexp-components)
3903 org-emphasis-alist org-emphasis-regexp-components)
3904 (let* ((e org-emphasis-regexp-components)
3905 (pre (car e))
3906 (post (nth 1 e))
3907 (border (nth 2 e))
3908 (body (nth 3 e))
3909 (nl (nth 4 e))
3910 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3911 (body1 (concat body "*?"))
3912 (markers (mapconcat 'car org-emphasis-alist ""))
3913 (vmarkers (mapconcat
3914 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3915 org-emphasis-alist "")))
3916 ;; make sure special characters appear at the right position in the class
3917 (if (string-match "\\^" markers)
3918 (setq markers (concat (replace-match "" t t markers) "^")))
3919 (if (string-match "-" markers)
3920 (setq markers (concat (replace-match "" t t markers) "-")))
3921 (if (string-match "\\^" vmarkers)
3922 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3923 (if (string-match "-" vmarkers)
3924 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3925 (if (> nl 0)
3926 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3927 (int-to-string nl) "\\}")))
3928 ;; Make the regexp
3929 (setq org-emph-re
3930 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3931 "\\("
3932 "\\([" markers "]\\)"
3933 "\\("
3934 "[^" border "]\\|"
3935 "[^" border (if (and nil stacked) markers) "]"
3936 body1
3937 "[^" border (if (and nil stacked) markers) "]"
3938 "\\)"
3939 "\\3\\)"
3940 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3941 (setq org-verbatim-re
3942 (concat "\\([" pre "]\\|^\\)"
3943 "\\("
3944 "\\([" vmarkers "]\\)"
3945 "\\("
3946 "[^" border "]\\|"
3947 "[^" border "]"
3948 body1
3949 "[^" border "]"
3950 "\\)"
3951 "\\3\\)"
3952 "\\([" post "]\\|$\\)")))))
3954 (defcustom org-emphasis-regexp-components
3955 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3956 "Components used to build the regular expression for emphasis.
3957 This is a list with 6 entries. Terminology: In an emphasis string
3958 like \" *strong word* \", we call the initial space PREMATCH, the final
3959 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3960 and \"trong wor\" is the body. The different components in this variable
3961 specify what is allowed/forbidden in each part:
3963 pre Chars allowed as prematch. Beginning of line will be allowed too.
3964 post Chars allowed as postmatch. End of line will be allowed too.
3965 border The chars *forbidden* as border characters.
3966 body-regexp A regexp like \".\" to match a body character. Don't use
3967 non-shy groups here, and don't allow newline here.
3968 newline The maximum number of newlines allowed in an emphasis exp.
3970 Use customize to modify this, or restart Emacs after changing it."
3971 :group 'org-font-lock
3972 :set 'org-set-emph-re
3973 :type '(list
3974 (sexp :tag "Allowed chars in pre ")
3975 (sexp :tag "Allowed chars in post ")
3976 (sexp :tag "Forbidden chars in border ")
3977 (sexp :tag "Regexp for body ")
3978 (integer :tag "number of newlines allowed")
3979 (option (boolean :tag "Stacking (DISABLED) "))))
3981 (defcustom org-emphasis-alist
3982 '(("*" bold "<b>" "</b>")
3983 ("/" italic "<i>" "</i>")
3984 ("_" underline "<u>" "</u>")
3985 ("=" org-code "<code>" "</code>" verbatim)
3986 ("~" org-verbatim "" "" verbatim)
3987 ("+" (:strike-through t) "<del>" "</del>")
3989 "Special syntax for emphasized text.
3990 Text starting and ending with a special character will be emphasized, for
3991 example *bold*, _underlined_ and /italic/. This variable sets the marker
3992 characters, the face to be used by font-lock for highlighting in Org-mode
3993 Emacs buffers, and the HTML tags to be used for this.
3994 Use customize to modify this, or restart Emacs after changing it."
3995 :group 'org-font-lock
3996 :set 'org-set-emph-re
3997 :type '(repeat
3998 (list
3999 (string :tag "Marker character")
4000 (choice
4001 (face :tag "Font-lock-face")
4002 (plist :tag "Face property list"))
4003 (string :tag "HTML start tag")
4004 (string :tag "HTML end tag")
4005 (option (const verbatim)))))
4007 ;;; The faces
4009 (defgroup org-faces nil
4010 "Faces in Org-mode."
4011 :tag "Org Faces"
4012 :group 'org-font-lock)
4014 (defun org-compatible-face (inherits specs)
4015 "Make a compatible face specification.
4016 If INHERITS is an existing face and if the Emacs version supports it,
4017 just inherit the face. If not, use SPECS to define the face.
4018 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
4019 For them we convert a (min-colors 8) entry to a `tty' entry and move it
4020 to the top of the list. The `min-colors' attribute will be removed from
4021 any other entries, and any resulting duplicates will be removed entirely."
4022 (cond
4023 ((and inherits (facep inherits)
4024 (not (featurep 'xemacs)) (> emacs-major-version 22))
4025 ;; In Emacs 23, we use inheritance where possible.
4026 ;; We only do this in Emacs 23, because only there the outline
4027 ;; faces have been changed to the original org-mode-level-faces.
4028 (list (list t :inherit inherits)))
4029 ((or (featurep 'xemacs) (< emacs-major-version 22))
4030 ;; These do not understand the `min-colors' attribute.
4031 (let (r e a)
4032 (while (setq e (pop specs))
4033 (cond
4034 ((memq (car e) '(t default)) (push e r))
4035 ((setq a (member '(min-colors 8) (car e)))
4036 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
4037 (cdr e)))))
4038 ((setq a (assq 'min-colors (car e)))
4039 (setq e (cons (delq a (car e)) (cdr e)))
4040 (or (assoc (car e) r) (push e r)))
4041 (t (or (assoc (car e) r) (push e r)))))
4042 (nreverse r)))
4043 (t specs)))
4044 (put 'org-compatible-face 'lisp-indent-function 1)
4046 (defface org-hide
4047 '((((background light)) (:foreground "white"))
4048 (((background dark)) (:foreground "black")))
4049 "Face used to hide leading stars in headlines.
4050 The forground color of this face should be equal to the background
4051 color of the frame."
4052 :group 'org-faces)
4054 (defface org-level-1 ;; font-lock-function-name-face
4055 (org-compatible-face 'outline-1
4056 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4057 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4058 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4059 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4060 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4061 (t (:bold t))))
4062 "Face used for level 1 headlines."
4063 :group 'org-faces)
4065 (defface org-level-2 ;; font-lock-variable-name-face
4066 (org-compatible-face 'outline-2
4067 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4068 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4069 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
4070 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
4071 (t (:bold t))))
4072 "Face used for level 2 headlines."
4073 :group 'org-faces)
4075 (defface org-level-3 ;; font-lock-keyword-face
4076 (org-compatible-face 'outline-3
4077 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
4078 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
4079 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4080 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4081 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4082 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4083 (t (:bold t))))
4084 "Face used for level 3 headlines."
4085 :group 'org-faces)
4087 (defface org-level-4 ;; font-lock-comment-face
4088 (org-compatible-face 'outline-4
4089 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4090 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4091 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4092 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4093 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4094 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4095 (t (:bold t))))
4096 "Face used for level 4 headlines."
4097 :group 'org-faces)
4099 (defface org-level-5 ;; font-lock-type-face
4100 (org-compatible-face 'outline-5
4101 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4102 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4103 (((class color) (min-colors 8)) (:foreground "green"))))
4104 "Face used for level 5 headlines."
4105 :group 'org-faces)
4107 (defface org-level-6 ;; font-lock-constant-face
4108 (org-compatible-face 'outline-6
4109 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4110 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4111 (((class color) (min-colors 8)) (:foreground "magenta"))))
4112 "Face used for level 6 headlines."
4113 :group 'org-faces)
4115 (defface org-level-7 ;; font-lock-builtin-face
4116 (org-compatible-face 'outline-7
4117 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4118 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4119 (((class color) (min-colors 8)) (:foreground "blue"))))
4120 "Face used for level 7 headlines."
4121 :group 'org-faces)
4123 (defface org-level-8 ;; font-lock-string-face
4124 (org-compatible-face 'outline-8
4125 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4126 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4127 (((class color) (min-colors 8)) (:foreground "green"))))
4128 "Face used for level 8 headlines."
4129 :group 'org-faces)
4131 (defface org-special-keyword ;; font-lock-string-face
4132 (org-compatible-face nil
4133 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4134 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4135 (t (:italic t))))
4136 "Face used for special keywords."
4137 :group 'org-faces)
4139 (defface org-drawer ;; font-lock-function-name-face
4140 (org-compatible-face nil
4141 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4142 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4143 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4144 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4145 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4146 (t (:bold t))))
4147 "Face used for drawers."
4148 :group 'org-faces)
4150 (defface org-property-value nil
4151 "Face used for the value of a property."
4152 :group 'org-faces)
4154 (defface org-column
4155 (org-compatible-face nil
4156 '((((class color) (min-colors 16) (background light))
4157 (:background "grey90"))
4158 (((class color) (min-colors 16) (background dark))
4159 (:background "grey30"))
4160 (((class color) (min-colors 8))
4161 (:background "cyan" :foreground "black"))
4162 (t (:inverse-video t))))
4163 "Face for column display of entry properties."
4164 :group 'org-faces)
4166 (when (fboundp 'set-face-attribute)
4167 ;; Make sure that a fixed-width face is used when we have a column table.
4168 (set-face-attribute 'org-column nil
4169 :height (face-attribute 'default :height)
4170 :family (face-attribute 'default :family)))
4172 (defface org-warning
4173 (org-compatible-face 'font-lock-warning-face
4174 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4175 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4176 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4177 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4178 (t (:bold t))))
4179 "Face for deadlines and TODO keywords."
4180 :group 'org-faces)
4182 (defface org-archived ; similar to shadow
4183 (org-compatible-face 'shadow
4184 '((((class color grayscale) (min-colors 88) (background light))
4185 (:foreground "grey50"))
4186 (((class color grayscale) (min-colors 88) (background dark))
4187 (:foreground "grey70"))
4188 (((class color) (min-colors 8) (background light))
4189 (:foreground "green"))
4190 (((class color) (min-colors 8) (background dark))
4191 (:foreground "yellow"))))
4192 "Face for headline with the ARCHIVE tag."
4193 :group 'org-faces)
4195 (defface org-link
4196 '((((class color) (background light)) (:foreground "Purple" :underline t))
4197 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4198 (t (:underline t)))
4199 "Face for links."
4200 :group 'org-faces)
4202 (defface org-ellipsis
4203 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4204 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4205 (t (:strike-through t)))
4206 "Face for the ellipsis in folded text."
4207 :group 'org-faces)
4209 (defface org-target
4210 '((((class color) (background light)) (:underline t))
4211 (((class color) (background dark)) (:underline t))
4212 (t (:underline t)))
4213 "Face for links."
4214 :group 'org-faces)
4216 (defface org-date
4217 '((((class color) (background light)) (:foreground "Purple" :underline t))
4218 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4219 (t (:underline t)))
4220 "Face for links."
4221 :group 'org-faces)
4223 (defface org-sexp-date
4224 '((((class color) (background light)) (:foreground "Purple"))
4225 (((class color) (background dark)) (:foreground "Cyan"))
4226 (t (:underline t)))
4227 "Face for links."
4228 :group 'org-faces)
4230 (defface org-tag
4231 '((t (:bold t)))
4232 "Face for tags."
4233 :group 'org-faces)
4235 (defface org-todo ; font-lock-warning-face
4236 (org-compatible-face nil
4237 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4238 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4239 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4240 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4241 (t (:inverse-video t :bold t))))
4242 "Face for TODO keywords."
4243 :group 'org-faces)
4245 (defface org-done ;; font-lock-type-face
4246 (org-compatible-face nil
4247 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4248 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4249 (((class color) (min-colors 8)) (:foreground "green"))
4250 (t (:bold t))))
4251 "Face used for todo keywords that indicate DONE items."
4252 :group 'org-faces)
4254 (defface org-headline-done ;; font-lock-string-face
4255 (org-compatible-face nil
4256 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4257 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4258 (((class color) (min-colors 8) (background light)) (:bold nil))))
4259 "Face used to indicate that a headline is DONE.
4260 This face is only used if `org-fontify-done-headline' is set. If applies
4261 to the part of the headline after the DONE keyword."
4262 :group 'org-faces)
4264 (defcustom org-todo-keyword-faces nil
4265 "Faces for specific TODO keywords.
4266 This is a list of cons cells, with TODO keywords in the car
4267 and faces in the cdr. The face can be a symbol, or a property
4268 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4269 :group 'org-faces
4270 :group 'org-todo
4271 :type '(repeat
4272 (cons
4273 (string :tag "keyword")
4274 (sexp :tag "face"))))
4276 (defface org-table ;; font-lock-function-name-face
4277 (org-compatible-face nil
4278 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4279 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4280 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4281 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4282 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4283 (((class color) (min-colors 8) (background dark)))))
4284 "Face used for tables."
4285 :group 'org-faces)
4287 (defface org-formula
4288 (org-compatible-face nil
4289 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4290 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4291 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4292 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4293 (t (:bold t :italic t))))
4294 "Face for formulas."
4295 :group 'org-faces)
4297 (defface org-code
4298 (org-compatible-face nil
4299 '((((class color grayscale) (min-colors 88) (background light))
4300 (:foreground "grey50"))
4301 (((class color grayscale) (min-colors 88) (background dark))
4302 (:foreground "grey70"))
4303 (((class color) (min-colors 8) (background light))
4304 (:foreground "green"))
4305 (((class color) (min-colors 8) (background dark))
4306 (:foreground "yellow"))))
4307 "Face for fixed-with text like code snippets."
4308 :group 'org-faces
4309 :version "22.1")
4311 (defface org-verbatim
4312 (org-compatible-face nil
4313 '((((class color grayscale) (min-colors 88) (background light))
4314 (:foreground "grey50" :underline t))
4315 (((class color grayscale) (min-colors 88) (background dark))
4316 (:foreground "grey70" :underline t))
4317 (((class color) (min-colors 8) (background light))
4318 (:foreground "green" :underline t))
4319 (((class color) (min-colors 8) (background dark))
4320 (:foreground "yellow" :underline t))))
4321 "Face for fixed-with text like code snippets."
4322 :group 'org-faces
4323 :version "22.1")
4325 (defface org-agenda-structure ;; font-lock-function-name-face
4326 (org-compatible-face nil
4327 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4328 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4329 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4330 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4331 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4332 (t (:bold t))))
4333 "Face used in agenda for captions and dates."
4334 :group 'org-faces)
4336 (defface org-scheduled-today
4337 (org-compatible-face nil
4338 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4339 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4340 (((class color) (min-colors 8)) (:foreground "green"))
4341 (t (:bold t :italic t))))
4342 "Face for items scheduled for a certain day."
4343 :group 'org-faces)
4345 (defface org-scheduled-previously
4346 (org-compatible-face nil
4347 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4348 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4349 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4350 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4351 (t (:bold t))))
4352 "Face for items scheduled previously, and not yet done."
4353 :group 'org-faces)
4355 (defface org-upcoming-deadline
4356 (org-compatible-face nil
4357 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4358 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4359 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4360 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4361 (t (:bold t))))
4362 "Face for items scheduled previously, and not yet done."
4363 :group 'org-faces)
4365 (defcustom org-agenda-deadline-faces
4366 '((1.0 . org-warning)
4367 (0.5 . org-upcoming-deadline)
4368 (0.0 . default))
4369 "Faces for showing deadlines in the agenda.
4370 This is a list of cons cells. The cdr of each cell is a face to be used,
4371 and it can also just be like '(:foreground \"yellow\").
4372 Each car is a fraction of the head-warning time that must have passed for
4373 this the face in the cdr to be used for display. The numbers must be
4374 given in descending order. The head-warning time is normally taken
4375 from `org-deadline-warning-days', but can also be specified in the deadline
4376 timestamp itself, like this:
4378 DEADLINE: <2007-08-13 Mon -8d>
4380 You may use d for days, w for weeks, m for months and y for years. Months
4381 and years will only be treated in an approximate fashion (30.4 days for a
4382 month and 365.24 days for a year)."
4383 :group 'org-faces
4384 :group 'org-agenda-daily/weekly
4385 :type '(repeat
4386 (cons
4387 (number :tag "Fraction of head-warning time passed")
4388 (sexp :tag "Face"))))
4390 ;; FIXME: this is not a good face yet.
4391 (defface org-agenda-restriction-lock
4392 (org-compatible-face nil
4393 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4394 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4395 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4396 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4397 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4398 (t (:inverse-video t))))
4399 "Face for showing the agenda restriction lock."
4400 :group 'org-faces)
4402 (defface org-time-grid ;; font-lock-variable-name-face
4403 (org-compatible-face nil
4404 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4405 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4406 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4407 "Face used for time grids."
4408 :group 'org-faces)
4410 (defconst org-level-faces
4411 '(org-level-1 org-level-2 org-level-3 org-level-4
4412 org-level-5 org-level-6 org-level-7 org-level-8
4415 (defcustom org-n-level-faces (length org-level-faces)
4416 "The number of different faces to be used for headlines.
4417 Org-mode defines 8 different headline faces, so this can be at most 8.
4418 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4419 :type 'number
4420 :group 'org-faces)
4422 ;;; Functions and variables from ther packages
4423 ;; Declared here to avoid compiler warnings
4425 (eval-and-compile
4426 (unless (fboundp 'declare-function)
4427 (defmacro declare-function (fn file &optional arglist fileonly))))
4429 ;; XEmacs only
4430 (defvar outline-mode-menu-heading)
4431 (defvar outline-mode-menu-show)
4432 (defvar outline-mode-menu-hide)
4433 (defvar zmacs-regions) ; XEmacs regions
4435 ;; Emacs only
4436 (defvar mark-active)
4438 ;; Various packages
4439 ;; FIXME: get the argument lists for the UNKNOWN stuff
4440 (declare-function add-to-diary-list "diary-lib"
4441 (date string specifier &optional marker globcolor literal))
4442 (declare-function table--at-cell-p "table" (position &optional object at-column))
4443 (declare-function bibtex-beginning-of-entry "bibtex" ())
4444 (declare-function bibtex-generate-autokey "bibtex" ())
4445 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4446 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4447 (defvar calc-embedded-close-formula)
4448 (defvar calc-embedded-open-formula)
4449 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4450 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4451 (declare-function calendar-check-holidays "holidays" (date))
4452 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4453 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4454 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4455 (declare-function calendar-forward-day "cal-move" (arg))
4456 (declare-function calendar-french-date-string "cal-french" (&optional date))
4457 (declare-function calendar-goto-date "cal-move" (date))
4458 (declare-function calendar-goto-today "cal-move" ())
4459 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4460 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4461 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4462 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
4463 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
4464 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4465 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4466 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4467 (defvar calendar-mode-map)
4468 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4469 (declare-function cdlatex-tab "ext:cdlatex" ())
4470 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4471 (defvar font-lock-unfontify-region-function)
4472 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4473 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4474 (declare-function parse-time-string "parse-time" (string))
4475 (declare-function remember "remember" (&optional initial))
4476 (declare-function remember-buffer-desc "remember" ())
4477 (declare-function remember-finalize "remember" ())
4478 (defvar remember-save-after-remembering)
4479 (defvar remember-data-file)
4480 (defvar remember-register)
4481 (defvar remember-buffer)
4482 (defvar remember-handler-functions)
4483 (defvar remember-annotation-functions)
4484 (defvar texmathp-why)
4485 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4487 (defvar w3m-current-url)
4488 (defvar w3m-current-title)
4490 (defvar org-latex-regexps)
4491 (defvar constants-unit-system)
4493 ;;; Variables for pre-computed regular expressions, all buffer local
4495 (defvar org-drawer-regexp nil
4496 "Matches first line of a hidden block.")
4497 (make-variable-buffer-local 'org-drawer-regexp)
4498 (defvar org-todo-regexp nil
4499 "Matches any of the TODO state keywords.")
4500 (make-variable-buffer-local 'org-todo-regexp)
4501 (defvar org-not-done-regexp nil
4502 "Matches any of the TODO state keywords except the last one.")
4503 (make-variable-buffer-local 'org-not-done-regexp)
4504 (defvar org-todo-line-regexp nil
4505 "Matches a headline and puts TODO state into group 2 if present.")
4506 (make-variable-buffer-local 'org-todo-line-regexp)
4507 (defvar org-complex-heading-regexp nil
4508 "Matches a headline and puts everything into groups:
4509 group 1: the stars
4510 group 2: The todo keyword, maybe
4511 group 3: Priority cookie
4512 group 4: True headline
4513 group 5: Tags")
4514 (make-variable-buffer-local 'org-complex-heading-regexp)
4515 (defvar org-todo-line-tags-regexp nil
4516 "Matches a headline and puts TODO state into group 2 if present.
4517 Also put tags into group 4 if tags are present.")
4518 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4519 (defvar org-nl-done-regexp nil
4520 "Matches newline followed by a headline with the DONE keyword.")
4521 (make-variable-buffer-local 'org-nl-done-regexp)
4522 (defvar org-looking-at-done-regexp nil
4523 "Matches the DONE keyword a point.")
4524 (make-variable-buffer-local 'org-looking-at-done-regexp)
4525 (defvar org-ds-keyword-length 12
4526 "Maximum length of the Deadline and SCHEDULED keywords.")
4527 (make-variable-buffer-local 'org-ds-keyword-length)
4528 (defvar org-deadline-regexp nil
4529 "Matches the DEADLINE keyword.")
4530 (make-variable-buffer-local 'org-deadline-regexp)
4531 (defvar org-deadline-time-regexp nil
4532 "Matches the DEADLINE keyword together with a time stamp.")
4533 (make-variable-buffer-local 'org-deadline-time-regexp)
4534 (defvar org-deadline-line-regexp nil
4535 "Matches the DEADLINE keyword and the rest of the line.")
4536 (make-variable-buffer-local 'org-deadline-line-regexp)
4537 (defvar org-scheduled-regexp nil
4538 "Matches the SCHEDULED keyword.")
4539 (make-variable-buffer-local 'org-scheduled-regexp)
4540 (defvar org-scheduled-time-regexp nil
4541 "Matches the SCHEDULED keyword together with a time stamp.")
4542 (make-variable-buffer-local 'org-scheduled-time-regexp)
4543 (defvar org-closed-time-regexp nil
4544 "Matches the CLOSED keyword together with a time stamp.")
4545 (make-variable-buffer-local 'org-closed-time-regexp)
4547 (defvar org-keyword-time-regexp nil
4548 "Matches any of the 4 keywords, together with the time stamp.")
4549 (make-variable-buffer-local 'org-keyword-time-regexp)
4550 (defvar org-keyword-time-not-clock-regexp nil
4551 "Matches any of the 3 keywords, together with the time stamp.")
4552 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4553 (defvar org-maybe-keyword-time-regexp nil
4554 "Matches a timestamp, possibly preceeded by a keyword.")
4555 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4556 (defvar org-planning-or-clock-line-re nil
4557 "Matches a line with planning or clock info.")
4558 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4560 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4561 rear-nonsticky t mouse-map t fontified t)
4562 "Properties to remove when a string without properties is wanted.")
4564 (defsubst org-match-string-no-properties (num &optional string)
4565 (if (featurep 'xemacs)
4566 (let ((s (match-string num string)))
4567 (remove-text-properties 0 (length s) org-rm-props s)
4569 (match-string-no-properties num string)))
4571 (defsubst org-no-properties (s)
4572 (if (fboundp 'set-text-properties)
4573 (set-text-properties 0 (length s) nil s)
4574 (remove-text-properties 0 (length s) org-rm-props s))
4577 (defsubst org-get-alist-option (option key)
4578 (cond ((eq key t) t)
4579 ((eq option t) t)
4580 ((assoc key option) (cdr (assoc key option)))
4581 (t (cdr (assq 'default option)))))
4583 (defsubst org-inhibit-invisibility ()
4584 "Modified `buffer-invisibility-spec' for Emacs 21.
4585 Some ops with invisible text do not work correctly on Emacs 21. For these
4586 we turn off invisibility temporarily. Use this in a `let' form."
4587 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4589 (defsubst org-set-local (var value)
4590 "Make VAR local in current buffer and set it to VALUE."
4591 (set (make-variable-buffer-local var) value))
4593 (defsubst org-mode-p ()
4594 "Check if the current buffer is in Org-mode."
4595 (eq major-mode 'org-mode))
4597 (defsubst org-last (list)
4598 "Return the last element of LIST."
4599 (car (last list)))
4601 (defun org-let (list &rest body)
4602 (eval (cons 'let (cons list body))))
4603 (put 'org-let 'lisp-indent-function 1)
4605 (defun org-let2 (list1 list2 &rest body)
4606 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4607 (put 'org-let2 'lisp-indent-function 2)
4608 (defconst org-startup-options
4609 '(("fold" org-startup-folded t)
4610 ("overview" org-startup-folded t)
4611 ("nofold" org-startup-folded nil)
4612 ("showall" org-startup-folded nil)
4613 ("content" org-startup-folded content)
4614 ("hidestars" org-hide-leading-stars t)
4615 ("showstars" org-hide-leading-stars nil)
4616 ("odd" org-odd-levels-only t)
4617 ("oddeven" org-odd-levels-only nil)
4618 ("align" org-startup-align-all-tables t)
4619 ("noalign" org-startup-align-all-tables nil)
4620 ("customtime" org-display-custom-times t)
4621 ("logdone" org-log-done time)
4622 ("lognotedone" org-log-done note)
4623 ("nologdone" org-log-done nil)
4624 ("lognoteclock-out" org-log-note-clock-out t)
4625 ("nolognoteclock-out" org-log-note-clock-out nil)
4626 ("logrepeat" org-log-repeat state)
4627 ("lognoterepeat" org-log-repeat note)
4628 ("nologrepeat" org-log-repeat nil)
4629 ("constcgs" constants-unit-system cgs)
4630 ("constSI" constants-unit-system SI))
4631 "Variable associated with STARTUP options for org-mode.
4632 Each element is a list of three items: The startup options as written
4633 in the #+STARTUP line, the corresponding variable, and the value to
4634 set this variable to if the option is found. An optional forth element PUSH
4635 means to push this value onto the list in the variable.")
4637 (defun org-set-regexps-and-options ()
4638 "Precompute regular expressions for current buffer."
4639 (when (org-mode-p)
4640 (org-set-local 'org-todo-kwd-alist nil)
4641 (org-set-local 'org-todo-key-alist nil)
4642 (org-set-local 'org-todo-key-trigger nil)
4643 (org-set-local 'org-todo-keywords-1 nil)
4644 (org-set-local 'org-done-keywords nil)
4645 (org-set-local 'org-todo-heads nil)
4646 (org-set-local 'org-todo-sets nil)
4647 (org-set-local 'org-todo-log-states nil)
4648 (let ((re (org-make-options-regexp
4649 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4650 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4651 "CONSTANTS" "PROPERTY" "DRAWERS")))
4652 (splitre "[ \t]+")
4653 kwds kws0 kwsa key log value cat arch tags const links hw dws
4654 tail sep kws1 prio props drawers)
4655 (save-excursion
4656 (save-restriction
4657 (widen)
4658 (goto-char (point-min))
4659 (while (re-search-forward re nil t)
4660 (setq key (match-string 1) value (org-match-string-no-properties 2))
4661 (cond
4662 ((equal key "CATEGORY")
4663 (if (string-match "[ \t]+$" value)
4664 (setq value (replace-match "" t t value)))
4665 (setq cat value))
4666 ((member key '("SEQ_TODO" "TODO"))
4667 (push (cons 'sequence (org-split-string value splitre)) kwds))
4668 ((equal key "TYP_TODO")
4669 (push (cons 'type (org-split-string value splitre)) kwds))
4670 ((equal key "TAGS")
4671 (setq tags (append tags (org-split-string value splitre))))
4672 ((equal key "COLUMNS")
4673 (org-set-local 'org-columns-default-format value))
4674 ((equal key "LINK")
4675 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4676 (push (cons (match-string 1 value)
4677 (org-trim (match-string 2 value)))
4678 links)))
4679 ((equal key "PRIORITIES")
4680 (setq prio (org-split-string value " +")))
4681 ((equal key "PROPERTY")
4682 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4683 (push (cons (match-string 1 value) (match-string 2 value))
4684 props)))
4685 ((equal key "DRAWERS")
4686 (setq drawers (org-split-string value splitre)))
4687 ((equal key "CONSTANTS")
4688 (setq const (append const (org-split-string value splitre))))
4689 ((equal key "STARTUP")
4690 (let ((opts (org-split-string value splitre))
4691 l var val)
4692 (while (setq l (pop opts))
4693 (when (setq l (assoc l org-startup-options))
4694 (setq var (nth 1 l) val (nth 2 l))
4695 (if (not (nth 3 l))
4696 (set (make-local-variable var) val)
4697 (if (not (listp (symbol-value var)))
4698 (set (make-local-variable var) nil))
4699 (set (make-local-variable var) (symbol-value var))
4700 (add-to-list var val))))))
4701 ((equal key "ARCHIVE")
4702 (string-match " *$" value)
4703 (setq arch (replace-match "" t t value))
4704 (remove-text-properties 0 (length arch)
4705 '(face t fontified t) arch)))
4707 (when cat
4708 (org-set-local 'org-category (intern cat))
4709 (push (cons "CATEGORY" cat) props))
4710 (when prio
4711 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4712 (setq prio (mapcar 'string-to-char prio))
4713 (org-set-local 'org-highest-priority (nth 0 prio))
4714 (org-set-local 'org-lowest-priority (nth 1 prio))
4715 (org-set-local 'org-default-priority (nth 2 prio)))
4716 (and props (org-set-local 'org-local-properties (nreverse props)))
4717 (and drawers (org-set-local 'org-drawers drawers))
4718 (and arch (org-set-local 'org-archive-location arch))
4719 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4720 ;; Process the TODO keywords
4721 (unless kwds
4722 ;; Use the global values as if they had been given locally.
4723 (setq kwds (default-value 'org-todo-keywords))
4724 (if (stringp (car kwds))
4725 (setq kwds (list (cons org-todo-interpretation
4726 (default-value 'org-todo-keywords)))))
4727 (setq kwds (reverse kwds)))
4728 (setq kwds (nreverse kwds))
4729 (let (inter kws kw)
4730 (while (setq kws (pop kwds))
4731 (setq inter (pop kws) sep (member "|" kws)
4732 kws0 (delete "|" (copy-sequence kws))
4733 kwsa nil
4734 kws1 (mapcar
4735 (lambda (x)
4736 ;; 1 2
4737 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4738 (progn
4739 (setq kw (match-string 1 x)
4740 key (and (match-end 2) (match-string 2 x))
4741 log (org-extract-log-state-settings x))
4742 (push (cons kw (and key (string-to-char key))) kwsa)
4743 (and log (push log org-todo-log-states))
4745 (error "Invalid TODO keyword %s" x)))
4746 kws0)
4747 kwsa (if kwsa (append '((:startgroup))
4748 (nreverse kwsa)
4749 '((:endgroup))))
4750 hw (car kws1)
4751 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4752 tail (list inter hw (car dws) (org-last dws)))
4753 (add-to-list 'org-todo-heads hw 'append)
4754 (push kws1 org-todo-sets)
4755 (setq org-done-keywords (append org-done-keywords dws nil))
4756 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4757 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4758 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4759 (setq org-todo-sets (nreverse org-todo-sets)
4760 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4761 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4762 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4763 ;; Process the constants
4764 (when const
4765 (let (e cst)
4766 (while (setq e (pop const))
4767 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4768 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4769 (setq org-table-formula-constants-local cst)))
4771 ;; Process the tags.
4772 (when tags
4773 (let (e tgs)
4774 (while (setq e (pop tags))
4775 (cond
4776 ((equal e "{") (push '(:startgroup) tgs))
4777 ((equal e "}") (push '(:endgroup) tgs))
4778 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4779 (push (cons (match-string 1 e)
4780 (string-to-char (match-string 2 e)))
4781 tgs))
4782 (t (push (list e) tgs))))
4783 (org-set-local 'org-tag-alist nil)
4784 (while (setq e (pop tgs))
4785 (or (and (stringp (car e))
4786 (assoc (car e) org-tag-alist))
4787 (push e org-tag-alist))))))
4789 ;; Compute the regular expressions and other local variables
4790 (if (not org-done-keywords)
4791 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4792 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4793 (length org-scheduled-string)))
4794 org-drawer-regexp
4795 (concat "^[ \t]*:\\("
4796 (mapconcat 'regexp-quote org-drawers "\\|")
4797 "\\):[ \t]*$")
4798 org-not-done-keywords
4799 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4800 org-todo-regexp
4801 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4802 "\\|") "\\)\\>")
4803 org-not-done-regexp
4804 (concat "\\<\\("
4805 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4806 "\\)\\>")
4807 org-todo-line-regexp
4808 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4809 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4810 "\\)\\>\\)?[ \t]*\\(.*\\)")
4811 org-complex-heading-regexp
4812 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4813 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4814 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4815 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4816 org-nl-done-regexp
4817 (concat "\n\\*+[ \t]+"
4818 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4819 "\\)" "\\>")
4820 org-todo-line-tags-regexp
4821 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4822 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4823 (org-re
4824 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4825 org-looking-at-done-regexp
4826 (concat "^" "\\(?:"
4827 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4828 "\\>")
4829 org-deadline-regexp (concat "\\<" org-deadline-string)
4830 org-deadline-time-regexp
4831 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4832 org-deadline-line-regexp
4833 (concat "\\<\\(" org-deadline-string "\\).*")
4834 org-scheduled-regexp
4835 (concat "\\<" org-scheduled-string)
4836 org-scheduled-time-regexp
4837 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4838 org-closed-time-regexp
4839 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4840 org-keyword-time-regexp
4841 (concat "\\<\\(" org-scheduled-string
4842 "\\|" org-deadline-string
4843 "\\|" org-closed-string
4844 "\\|" org-clock-string "\\)"
4845 " *[[<]\\([^]>]+\\)[]>]")
4846 org-keyword-time-not-clock-regexp
4847 (concat "\\<\\(" org-scheduled-string
4848 "\\|" org-deadline-string
4849 "\\|" org-closed-string
4850 "\\)"
4851 " *[[<]\\([^]>]+\\)[]>]")
4852 org-maybe-keyword-time-regexp
4853 (concat "\\(\\<\\(" org-scheduled-string
4854 "\\|" org-deadline-string
4855 "\\|" org-closed-string
4856 "\\|" org-clock-string "\\)\\)?"
4857 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4858 org-planning-or-clock-line-re
4859 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4860 "\\|" org-deadline-string
4861 "\\|" org-closed-string "\\|" org-clock-string
4862 "\\)\\>\\)")
4864 (org-compute-latex-and-specials-regexp)
4865 (org-set-font-lock-defaults)))
4867 (defun org-extract-log-state-settings (x)
4868 "Extract the log state setting from a TODO keyword string.
4869 This will extract info from a string like \"WAIT(w@/!)\"."
4870 (let (kw key log1 log2)
4871 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4872 (setq kw (match-string 1 x)
4873 key (and (match-end 2) (match-string 2 x))
4874 log1 (and (match-end 3) (match-string 3 x))
4875 log2 (and (match-end 4) (match-string 4 x)))
4876 (and (or log1 log2)
4877 (list kw
4878 (and log1 (if (equal log1 "!") 'time 'note))
4879 (and log2 (if (equal log2 "!") 'time 'note)))))))
4881 (defun org-remove-keyword-keys (list)
4882 "Remove a pair of parenthesis at the end of each string in LIST."
4883 (mapcar (lambda (x)
4884 (if (string-match "(.*)$" x)
4885 (substring x 0 (match-beginning 0))
4887 list))
4889 ;; FIXME: this could be done much better, using second characters etc.
4890 (defun org-assign-fast-keys (alist)
4891 "Assign fast keys to a keyword-key alist.
4892 Respect keys that are already there."
4893 (let (new e k c c1 c2 (char ?a))
4894 (while (setq e (pop alist))
4895 (cond
4896 ((equal e '(:startgroup)) (push e new))
4897 ((equal e '(:endgroup)) (push e new))
4899 (setq k (car e) c2 nil)
4900 (if (cdr e)
4901 (setq c (cdr e))
4902 ;; automatically assign a character.
4903 (setq c1 (string-to-char
4904 (downcase (substring
4905 k (if (= (string-to-char k) ?@) 1 0)))))
4906 (if (or (rassoc c1 new) (rassoc c1 alist))
4907 (while (or (rassoc char new) (rassoc char alist))
4908 (setq char (1+ char)))
4909 (setq c2 c1))
4910 (setq c (or c2 char)))
4911 (push (cons k c) new))))
4912 (nreverse new)))
4914 ;;; Some variables ujsed in various places
4916 (defvar org-window-configuration nil
4917 "Used in various places to store a window configuration.")
4918 (defvar org-finish-function nil
4919 "Function to be called when `C-c C-c' is used.
4920 This is for getting out of special buffers like remember.")
4923 ;; FIXME: Occasionally check by commenting these, to make sure
4924 ;; no other functions uses these, forgetting to let-bind them.
4925 (defvar entry)
4926 (defvar state)
4927 (defvar last-state)
4928 (defvar date)
4929 (defvar description)
4931 ;; Defined somewhere in this file, but used before definition.
4932 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4933 (defvar org-agenda-buffer-name)
4934 (defvar org-agenda-undo-list)
4935 (defvar org-agenda-pending-undo-list)
4936 (defvar org-agenda-overriding-header)
4937 (defvar orgtbl-mode)
4938 (defvar org-html-entities)
4939 (defvar org-struct-menu)
4940 (defvar org-org-menu)
4941 (defvar org-tbl-menu)
4942 (defvar org-agenda-keymap)
4944 ;;;; Emacs/XEmacs compatibility
4946 ;; Overlay compatibility functions
4947 (defun org-make-overlay (beg end &optional buffer)
4948 (if (featurep 'xemacs)
4949 (make-extent beg end buffer)
4950 (make-overlay beg end buffer)))
4951 (defun org-delete-overlay (ovl)
4952 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4953 (defun org-detach-overlay (ovl)
4954 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4955 (defun org-move-overlay (ovl beg end &optional buffer)
4956 (if (featurep 'xemacs)
4957 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4958 (move-overlay ovl beg end buffer)))
4959 (defun org-overlay-put (ovl prop value)
4960 (if (featurep 'xemacs)
4961 (set-extent-property ovl prop value)
4962 (overlay-put ovl prop value)))
4963 (defun org-overlay-display (ovl text &optional face evap)
4964 "Make overlay OVL display TEXT with face FACE."
4965 (if (featurep 'xemacs)
4966 (let ((gl (make-glyph text)))
4967 (and face (set-glyph-face gl face))
4968 (set-extent-property ovl 'invisible t)
4969 (set-extent-property ovl 'end-glyph gl))
4970 (overlay-put ovl 'display text)
4971 (if face (overlay-put ovl 'face face))
4972 (if evap (overlay-put ovl 'evaporate t))))
4973 (defun org-overlay-before-string (ovl text &optional face evap)
4974 "Make overlay OVL display TEXT with face FACE."
4975 (if (featurep 'xemacs)
4976 (let ((gl (make-glyph text)))
4977 (and face (set-glyph-face gl face))
4978 (set-extent-property ovl 'begin-glyph gl))
4979 (if face (org-add-props text nil 'face face))
4980 (overlay-put ovl 'before-string text)
4981 (if evap (overlay-put ovl 'evaporate t))))
4982 (defun org-overlay-get (ovl prop)
4983 (if (featurep 'xemacs)
4984 (extent-property ovl prop)
4985 (overlay-get ovl prop)))
4986 (defun org-overlays-at (pos)
4987 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4988 (defun org-overlays-in (&optional start end)
4989 (if (featurep 'xemacs)
4990 (extent-list nil start end)
4991 (overlays-in start end)))
4992 (defun org-overlay-start (o)
4993 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4994 (defun org-overlay-end (o)
4995 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4996 (defun org-find-overlays (prop &optional pos delete)
4997 "Find all overlays specifying PROP at POS or point.
4998 If DELETE is non-nil, delete all those overlays."
4999 (let ((overlays (org-overlays-at (or pos (point))))
5000 ov found)
5001 (while (setq ov (pop overlays))
5002 (if (org-overlay-get ov prop)
5003 (if delete (org-delete-overlay ov) (push ov found))))
5004 found))
5006 ;; Region compatibility
5008 (defun org-add-hook (hook function &optional append local)
5009 "Add-hook, compatible with both Emacsen."
5010 (if (and local (featurep 'xemacs))
5011 (add-local-hook hook function append)
5012 (add-hook hook function append local)))
5014 (defvar org-ignore-region nil
5015 "To temporarily disable the active region.")
5017 (defun org-region-active-p ()
5018 "Is `transient-mark-mode' on and the region active?
5019 Works on both Emacs and XEmacs."
5020 (if org-ignore-region
5022 (if (featurep 'xemacs)
5023 (and zmacs-regions (region-active-p))
5024 (if (fboundp 'use-region-p)
5025 (use-region-p)
5026 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5028 ;; Invisibility compatibility
5030 (defun org-add-to-invisibility-spec (arg)
5031 "Add elements to `buffer-invisibility-spec'.
5032 See documentation for `buffer-invisibility-spec' for the kind of elements
5033 that can be added."
5034 (cond
5035 ((fboundp 'add-to-invisibility-spec)
5036 (add-to-invisibility-spec arg))
5037 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5038 (setq buffer-invisibility-spec (list arg)))
5040 (setq buffer-invisibility-spec
5041 (cons arg buffer-invisibility-spec)))))
5043 (defun org-remove-from-invisibility-spec (arg)
5044 "Remove elements from `buffer-invisibility-spec'."
5045 (if (fboundp 'remove-from-invisibility-spec)
5046 (remove-from-invisibility-spec arg)
5047 (if (consp buffer-invisibility-spec)
5048 (setq buffer-invisibility-spec
5049 (delete arg buffer-invisibility-spec)))))
5051 (defun org-in-invisibility-spec-p (arg)
5052 "Is ARG a member of `buffer-invisibility-spec'?"
5053 (if (consp buffer-invisibility-spec)
5054 (member arg buffer-invisibility-spec)
5055 nil))
5057 ;;;; Define the Org-mode
5059 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5060 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
5063 ;; We use a before-change function to check if a table might need
5064 ;; an update.
5065 (defvar org-table-may-need-update t
5066 "Indicates that a table might need an update.
5067 This variable is set by `org-before-change-function'.
5068 `org-table-align' sets it back to nil.")
5069 (defvar org-mode-map)
5070 (defvar org-mode-hook nil)
5071 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5072 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5073 (defvar org-table-buffer-is-an nil)
5074 (defconst org-outline-regexp "\\*+ ")
5076 ;;;###autoload
5077 (define-derived-mode org-mode outline-mode "Org"
5078 "Outline-based notes management and organizer, alias
5079 \"Carsten's outline-mode for keeping track of everything.\"
5081 Org-mode develops organizational tasks around a NOTES file which
5082 contains information about projects as plain text. Org-mode is
5083 implemented on top of outline-mode, which is ideal to keep the content
5084 of large files well structured. It supports ToDo items, deadlines and
5085 time stamps, which magically appear in the diary listing of the Emacs
5086 calendar. Tables are easily created with a built-in table editor.
5087 Plain text URL-like links connect to websites, emails (VM), Usenet
5088 messages (Gnus), BBDB entries, and any files related to the project.
5089 For printing and sharing of notes, an Org-mode file (or a part of it)
5090 can be exported as a structured ASCII or HTML file.
5092 The following commands are available:
5094 \\{org-mode-map}"
5096 ;; Get rid of Outline menus, they are not needed
5097 ;; Need to do this here because define-derived-mode sets up
5098 ;; the keymap so late. Still, it is a waste to call this each time
5099 ;; we switch another buffer into org-mode.
5100 (if (featurep 'xemacs)
5101 (when (boundp 'outline-mode-menu-heading)
5102 ;; Assume this is Greg's port, it used easymenu
5103 (easy-menu-remove outline-mode-menu-heading)
5104 (easy-menu-remove outline-mode-menu-show)
5105 (easy-menu-remove outline-mode-menu-hide))
5106 (define-key org-mode-map [menu-bar headings] 'undefined)
5107 (define-key org-mode-map [menu-bar hide] 'undefined)
5108 (define-key org-mode-map [menu-bar show] 'undefined))
5110 (org-load-modules-maybe)
5111 (easy-menu-add org-org-menu)
5112 (easy-menu-add org-tbl-menu)
5113 (org-install-agenda-files-menu)
5114 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5115 (org-add-to-invisibility-spec '(org-cwidth))
5116 (when (featurep 'xemacs)
5117 (org-set-local 'line-move-ignore-invisible t))
5118 (org-set-local 'outline-regexp org-outline-regexp)
5119 (org-set-local 'outline-level 'org-outline-level)
5120 (when (and org-ellipsis
5121 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5122 (fboundp 'make-glyph-code))
5123 (unless org-display-table
5124 (setq org-display-table (make-display-table)))
5125 (set-display-table-slot
5126 org-display-table 4
5127 (vconcat (mapcar
5128 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5129 org-ellipsis)))
5130 (if (stringp org-ellipsis) org-ellipsis "..."))))
5131 (setq buffer-display-table org-display-table))
5132 (org-set-regexps-and-options)
5133 ;; Calc embedded
5134 (org-set-local 'calc-embedded-open-mode "# ")
5135 (modify-syntax-entry ?# "<")
5136 (modify-syntax-entry ?@ "w")
5137 (if org-startup-truncated (setq truncate-lines t))
5138 (org-set-local 'font-lock-unfontify-region-function
5139 'org-unfontify-region)
5140 ;; Activate before-change-function
5141 (org-set-local 'org-table-may-need-update t)
5142 (org-add-hook 'before-change-functions 'org-before-change-function nil
5143 'local)
5144 ;; Check for running clock before killing a buffer
5145 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5146 ;; Paragraphs and auto-filling
5147 (org-set-autofill-regexps)
5148 (setq indent-line-function 'org-indent-line-function)
5149 (org-update-radio-target-regexp)
5151 ;; Comment characters
5152 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5153 (org-set-local 'comment-padding " ")
5155 ;; Align options lines
5156 (org-set-local
5157 'align-mode-rules-list
5158 '((org-in-buffer-settings
5159 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5160 (modes . '(org-mode)))))
5162 ;; Imenu
5163 (org-set-local 'imenu-create-index-function
5164 'org-imenu-get-tree)
5166 ;; Make isearch reveal context
5167 (if (or (featurep 'xemacs)
5168 (not (boundp 'outline-isearch-open-invisible-function)))
5169 ;; Emacs 21 and XEmacs make use of the hook
5170 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5171 ;; Emacs 22 deals with this through a special variable
5172 (org-set-local 'outline-isearch-open-invisible-function
5173 (lambda (&rest ignore) (org-show-context 'isearch))))
5175 ;; If empty file that did not turn on org-mode automatically, make it to.
5176 (if (and org-insert-mode-line-in-empty-file
5177 (interactive-p)
5178 (= (point-min) (point-max)))
5179 (insert "# -*- mode: org -*-\n\n"))
5181 (unless org-inhibit-startup
5182 (when org-startup-align-all-tables
5183 (let ((bmp (buffer-modified-p)))
5184 (org-table-map-tables 'org-table-align)
5185 (set-buffer-modified-p bmp)))
5186 (org-cycle-hide-drawers 'all)
5187 (cond
5188 ((eq org-startup-folded t)
5189 (org-cycle '(4)))
5190 ((eq org-startup-folded 'content)
5191 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5192 (org-cycle '(4)) (org-cycle '(4)))))))
5194 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5196 (defsubst org-call-with-arg (command arg)
5197 "Call COMMAND interactively, but pretend prefix are was ARG."
5198 (let ((current-prefix-arg arg)) (call-interactively command)))
5200 (defsubst org-current-line (&optional pos)
5201 (save-excursion
5202 (and pos (goto-char pos))
5203 ;; works also in narrowed buffer, because we start at 1, not point-min
5204 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5206 (defun org-current-time ()
5207 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5208 (if (> (car org-time-stamp-rounding-minutes) 1)
5209 (let ((r (car org-time-stamp-rounding-minutes))
5210 (time (decode-time)))
5211 (apply 'encode-time
5212 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5213 (nthcdr 2 time))))
5214 (current-time)))
5216 (defun org-add-props (string plist &rest props)
5217 "Add text properties to entire string, from beginning to end.
5218 PLIST may be a list of properties, PROPS are individual properties and values
5219 that will be added to PLIST. Returns the string that was modified."
5220 (add-text-properties
5221 0 (length string) (if props (append plist props) plist) string)
5222 string)
5223 (put 'org-add-props 'lisp-indent-function 2)
5226 ;;;; Font-Lock stuff, including the activators
5228 (defvar org-mouse-map (make-sparse-keymap))
5229 (org-defkey org-mouse-map
5230 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5231 (org-defkey org-mouse-map
5232 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5233 (when org-mouse-1-follows-link
5234 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5235 (when org-tab-follows-link
5236 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5237 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5238 (when org-return-follows-link
5239 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5240 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5242 (require 'font-lock)
5244 (defconst org-non-link-chars "]\t\n\r<>")
5245 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5246 "shell" "elisp"))
5247 (defvar org-link-re-with-space nil
5248 "Matches a link with spaces, optional angular brackets around it.")
5249 (defvar org-link-re-with-space2 nil
5250 "Matches a link with spaces, optional angular brackets around it.")
5251 (defvar org-angle-link-re nil
5252 "Matches link with angular brackets, spaces are allowed.")
5253 (defvar org-plain-link-re nil
5254 "Matches plain link, without spaces.")
5255 (defvar org-bracket-link-regexp nil
5256 "Matches a link in double brackets.")
5257 (defvar org-bracket-link-analytic-regexp nil
5258 "Regular expression used to analyze links.
5259 Here is what the match groups contain after a match:
5260 1: http:
5261 2: http
5262 3: path
5263 4: [desc]
5264 5: desc")
5265 (defvar org-any-link-re nil
5266 "Regular expression matching any link.")
5268 (defun org-make-link-regexps ()
5269 "Update the link regular expressions.
5270 This should be called after the variable `org-link-types' has changed."
5271 (setq org-link-re-with-space
5272 (concat
5273 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5274 "\\([^" org-non-link-chars " ]"
5275 "[^" org-non-link-chars "]*"
5276 "[^" org-non-link-chars " ]\\)>?")
5277 org-link-re-with-space2
5278 (concat
5279 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5280 "\\([^" org-non-link-chars " ]"
5281 "[^]\t\n\r]*"
5282 "[^" org-non-link-chars " ]\\)>?")
5283 org-angle-link-re
5284 (concat
5285 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5286 "\\([^" org-non-link-chars " ]"
5287 "[^" org-non-link-chars "]*"
5288 "\\)>")
5289 org-plain-link-re
5290 (concat
5291 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5292 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5293 org-bracket-link-regexp
5294 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5295 org-bracket-link-analytic-regexp
5296 (concat
5297 "\\[\\["
5298 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5299 "\\([^]]+\\)"
5300 "\\]"
5301 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5302 "\\]")
5303 org-any-link-re
5304 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5305 org-angle-link-re "\\)\\|\\("
5306 org-plain-link-re "\\)")))
5308 (org-make-link-regexps)
5310 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5311 "Regular expression for fast time stamp matching.")
5312 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5313 "Regular expression for fast time stamp matching.")
5314 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5315 "Regular expression matching time strings for analysis.
5316 This one does not require the space after the date, so it can be used
5317 on a string that terminates immediately after the date.")
5318 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5319 "Regular expression matching time strings for analysis.")
5320 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5321 "Regular expression matching time stamps, with groups.")
5322 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5323 "Regular expression matching time stamps (also [..]), with groups.")
5324 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5325 "Regular expression matching a time stamp range.")
5326 (defconst org-tr-regexp-both
5327 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5328 "Regular expression matching a time stamp range.")
5329 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5330 org-ts-regexp "\\)?")
5331 "Regular expression matching a time stamp or time stamp range.")
5332 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5333 org-ts-regexp-both "\\)?")
5334 "Regular expression matching a time stamp or time stamp range.
5335 The time stamps may be either active or inactive.")
5337 (defvar org-emph-face nil)
5339 (defun org-do-emphasis-faces (limit)
5340 "Run through the buffer and add overlays to links."
5341 (let (rtn)
5342 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5343 (if (not (= (char-after (match-beginning 3))
5344 (char-after (match-beginning 4))))
5345 (progn
5346 (setq rtn t)
5347 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5348 'face
5349 (nth 1 (assoc (match-string 3)
5350 org-emphasis-alist)))
5351 (add-text-properties (match-beginning 2) (match-end 2)
5352 '(font-lock-multiline t))
5353 (when org-hide-emphasis-markers
5354 (add-text-properties (match-end 4) (match-beginning 5)
5355 '(invisible org-link))
5356 (add-text-properties (match-beginning 3) (match-end 3)
5357 '(invisible org-link)))))
5358 (backward-char 1))
5359 rtn))
5361 (defun org-emphasize (&optional char)
5362 "Insert or change an emphasis, i.e. a font like bold or italic.
5363 If there is an active region, change that region to a new emphasis.
5364 If there is no region, just insert the marker characters and position
5365 the cursor between them.
5366 CHAR should be either the marker character, or the first character of the
5367 HTML tag associated with that emphasis. If CHAR is a space, the means
5368 to remove the emphasis of the selected region.
5369 If char is not given (for example in an interactive call) it
5370 will be prompted for."
5371 (interactive)
5372 (let ((eal org-emphasis-alist) e det
5373 (erc org-emphasis-regexp-components)
5374 (prompt "")
5375 (string "") beg end move tag c s)
5376 (if (org-region-active-p)
5377 (setq beg (region-beginning) end (region-end)
5378 string (buffer-substring beg end))
5379 (setq move t))
5381 (while (setq e (pop eal))
5382 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5383 c (aref tag 0))
5384 (push (cons c (string-to-char (car e))) det)
5385 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5386 (substring tag 1)))))
5387 (unless char
5388 (message "%s" (concat "Emphasis marker or tag:" prompt))
5389 (setq char (read-char-exclusive)))
5390 (setq char (or (cdr (assoc char det)) char))
5391 (if (equal char ?\ )
5392 (setq s "" move nil)
5393 (unless (assoc (char-to-string char) org-emphasis-alist)
5394 (error "No such emphasis marker: \"%c\"" char))
5395 (setq s (char-to-string char)))
5396 (while (and (> (length string) 1)
5397 (equal (substring string 0 1) (substring string -1))
5398 (assoc (substring string 0 1) org-emphasis-alist))
5399 (setq string (substring string 1 -1)))
5400 (setq string (concat s string s))
5401 (if beg (delete-region beg end))
5402 (unless (or (bolp)
5403 (string-match (concat "[" (nth 0 erc) "\n]")
5404 (char-to-string (char-before (point)))))
5405 (insert " "))
5406 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5407 (char-to-string (char-after (point))))
5408 (insert " ") (backward-char 1))
5409 (insert string)
5410 (and move (backward-char 1))))
5412 (defconst org-nonsticky-props
5413 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5416 (defun org-activate-plain-links (limit)
5417 "Run through the buffer and add overlays to links."
5418 (catch 'exit
5419 (let (f)
5420 (while (re-search-forward org-plain-link-re limit t)
5421 (setq f (get-text-property (match-beginning 0) 'face))
5422 (if (or (eq f 'org-tag)
5423 (and (listp f) (memq 'org-tag f)))
5425 (add-text-properties (match-beginning 0) (match-end 0)
5426 (list 'mouse-face 'highlight
5427 'rear-nonsticky org-nonsticky-props
5428 'keymap org-mouse-map
5430 (throw 'exit t))))))
5432 (defun org-activate-code (limit)
5433 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5434 (unless (get-text-property (match-beginning 1) 'face)
5435 (remove-text-properties (match-beginning 0) (match-end 0)
5436 '(display t invisible t intangible t))
5437 t)))
5439 (defun org-activate-angle-links (limit)
5440 "Run through the buffer and add overlays to links."
5441 (if (re-search-forward org-angle-link-re limit t)
5442 (progn
5443 (add-text-properties (match-beginning 0) (match-end 0)
5444 (list 'mouse-face 'highlight
5445 'rear-nonsticky org-nonsticky-props
5446 'keymap org-mouse-map
5448 t)))
5450 (defmacro org-maybe-intangible (props)
5451 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5452 In emacs 21, invisible text is not avoided by the command loop, so the
5453 intangible property is needed to make sure point skips this text.
5454 In Emacs 22, this is not necessary. The intangible text property has
5455 led to problems with flyspell. These problems are fixed in flyspell.el,
5456 but we still avoid setting the property in Emacs 22 and later.
5457 We use a macro so that the test can happen at compilation time."
5458 (if (< emacs-major-version 22)
5459 `(append '(intangible t) ,props)
5460 props))
5462 (defun org-activate-bracket-links (limit)
5463 "Run through the buffer and add overlays to bracketed links."
5464 (if (re-search-forward org-bracket-link-regexp limit t)
5465 (let* ((help (concat "LINK: "
5466 (org-match-string-no-properties 1)))
5467 ;; FIXME: above we should remove the escapes.
5468 ;; but that requires another match, protecting match data,
5469 ;; a lot of overhead for font-lock.
5470 (ip (org-maybe-intangible
5471 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5472 'keymap org-mouse-map 'mouse-face 'highlight
5473 'font-lock-multiline t 'help-echo help)))
5474 (vp (list 'rear-nonsticky org-nonsticky-props
5475 'keymap org-mouse-map 'mouse-face 'highlight
5476 ' font-lock-multiline t 'help-echo help)))
5477 ;; We need to remove the invisible property here. Table narrowing
5478 ;; may have made some of this invisible.
5479 (remove-text-properties (match-beginning 0) (match-end 0)
5480 '(invisible nil))
5481 (if (match-end 3)
5482 (progn
5483 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5484 (add-text-properties (match-beginning 3) (match-end 3) vp)
5485 (add-text-properties (match-end 3) (match-end 0) ip))
5486 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5487 (add-text-properties (match-beginning 1) (match-end 1) vp)
5488 (add-text-properties (match-end 1) (match-end 0) ip))
5489 t)))
5491 (defun org-activate-dates (limit)
5492 "Run through the buffer and add overlays to dates."
5493 (if (re-search-forward org-tsr-regexp-both limit t)
5494 (progn
5495 (add-text-properties (match-beginning 0) (match-end 0)
5496 (list 'mouse-face 'highlight
5497 'rear-nonsticky org-nonsticky-props
5498 'keymap org-mouse-map))
5499 (when org-display-custom-times
5500 (if (match-end 3)
5501 (org-display-custom-time (match-beginning 3) (match-end 3)))
5502 (org-display-custom-time (match-beginning 1) (match-end 1)))
5503 t)))
5505 (defvar org-target-link-regexp nil
5506 "Regular expression matching radio targets in plain text.")
5507 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5508 "Regular expression matching a link target.")
5509 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5510 "Regular expression matching a radio target.")
5511 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5512 "Regular expression matching any target.")
5514 (defun org-activate-target-links (limit)
5515 "Run through the buffer and add overlays to target matches."
5516 (when org-target-link-regexp
5517 (let ((case-fold-search t))
5518 (if (re-search-forward org-target-link-regexp limit t)
5519 (progn
5520 (add-text-properties (match-beginning 0) (match-end 0)
5521 (list 'mouse-face 'highlight
5522 'rear-nonsticky org-nonsticky-props
5523 'keymap org-mouse-map
5524 'help-echo "Radio target link"
5525 'org-linked-text t))
5526 t)))))
5528 (defun org-update-radio-target-regexp ()
5529 "Find all radio targets in this file and update the regular expression."
5530 (interactive)
5531 (when (memq 'radio org-activate-links)
5532 (setq org-target-link-regexp
5533 (org-make-target-link-regexp (org-all-targets 'radio)))
5534 (org-restart-font-lock)))
5536 (defun org-hide-wide-columns (limit)
5537 (let (s e)
5538 (setq s (text-property-any (point) (or limit (point-max))
5539 'org-cwidth t))
5540 (when s
5541 (setq e (next-single-property-change s 'org-cwidth))
5542 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5543 (goto-char e)
5544 t)))
5546 (defvar org-latex-and-specials-regexp nil
5547 "Regular expression for highlighting export special stuff.")
5548 (defvar org-match-substring-regexp)
5549 (defvar org-match-substring-with-braces-regexp)
5550 (defvar org-export-html-special-string-regexps)
5552 (defun org-compute-latex-and-specials-regexp ()
5553 "Compute regular expression for stuff treated specially by exporters."
5554 (if (not org-highlight-latex-fragments-and-specials)
5555 (org-set-local 'org-latex-and-specials-regexp nil)
5556 (let*
5557 ((matchers (plist-get org-format-latex-options :matchers))
5558 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5559 org-latex-regexps)))
5560 (options (org-combine-plists (org-default-export-plist)
5561 (org-infile-export-plist)))
5562 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5563 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5564 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5565 (org-export-html-expand (plist-get options :expand-quoted-html))
5566 (org-export-with-special-strings (plist-get options :special-strings))
5567 (re-sub
5568 (cond
5569 ((equal org-export-with-sub-superscripts '{})
5570 (list org-match-substring-with-braces-regexp))
5571 (org-export-with-sub-superscripts
5572 (list org-match-substring-regexp))
5573 (t nil)))
5574 (re-latex
5575 (if org-export-with-LaTeX-fragments
5576 (mapcar (lambda (x) (nth 1 x)) latexs)))
5577 (re-macros
5578 (if org-export-with-TeX-macros
5579 (list (concat "\\\\"
5580 (regexp-opt
5581 (append (mapcar 'car org-html-entities)
5582 (if (boundp 'org-latex-entities)
5583 org-latex-entities nil))
5584 'words))) ; FIXME
5586 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5587 (re-special (if org-export-with-special-strings
5588 (mapcar (lambda (x) (car x))
5589 org-export-html-special-string-regexps)))
5590 (re-rest
5591 (delq nil
5592 (list
5593 (if org-export-html-expand "@<[^>\n]+>")
5594 ))))
5595 (org-set-local
5596 'org-latex-and-specials-regexp
5597 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5598 re-rest) "\\|")))))
5600 (defface org-latex-and-export-specials
5601 (let ((font (cond ((assq :inherit custom-face-attributes)
5602 '(:inherit underline))
5603 (t '(:underline t)))))
5604 `((((class grayscale) (background light))
5605 (:foreground "DimGray" ,@font))
5606 (((class grayscale) (background dark))
5607 (:foreground "LightGray" ,@font))
5608 (((class color) (background light))
5609 (:foreground "SaddleBrown"))
5610 (((class color) (background dark))
5611 (:foreground "burlywood"))
5612 (t (,@font))))
5613 "Face used to highlight math latex and other special exporter stuff."
5614 :group 'org-faces)
5616 (defun org-do-latex-and-special-faces (limit)
5617 "Run through the buffer and add overlays to links."
5618 (when org-latex-and-specials-regexp
5619 (let (rtn d)
5620 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5621 limit t))
5622 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5623 'face))
5624 '(org-code org-verbatim underline)))
5625 (progn
5626 (setq rtn t
5627 d (cond ((member (char-after (1+ (match-beginning 0)))
5628 '(?_ ?^)) 1)
5629 (t 0)))
5630 (font-lock-prepend-text-property
5631 (+ d (match-beginning 0)) (match-end 0)
5632 'face 'org-latex-and-export-specials)
5633 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5634 '(font-lock-multiline t)))))
5635 rtn)))
5637 (defun org-restart-font-lock ()
5638 "Restart font-lock-mode, to force refontification."
5639 (when (and (boundp 'font-lock-mode) font-lock-mode)
5640 (font-lock-mode -1)
5641 (font-lock-mode 1)))
5643 (defun org-all-targets (&optional radio)
5644 "Return a list of all targets in this file.
5645 With optional argument RADIO, only find radio targets."
5646 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5647 rtn)
5648 (save-excursion
5649 (goto-char (point-min))
5650 (while (re-search-forward re nil t)
5651 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5652 rtn)))
5654 (defun org-make-target-link-regexp (targets)
5655 "Make regular expression matching all strings in TARGETS.
5656 The regular expression finds the targets also if there is a line break
5657 between words."
5658 (and targets
5659 (concat
5660 "\\<\\("
5661 (mapconcat
5662 (lambda (x)
5663 (while (string-match " +" x)
5664 (setq x (replace-match "\\s-+" t t x)))
5666 targets
5667 "\\|")
5668 "\\)\\>")))
5670 (defun org-activate-tags (limit)
5671 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5672 (progn
5673 (add-text-properties (match-beginning 1) (match-end 1)
5674 (list 'mouse-face 'highlight
5675 'rear-nonsticky org-nonsticky-props
5676 'keymap org-mouse-map))
5677 t)))
5679 (defun org-outline-level ()
5680 (save-excursion
5681 (looking-at outline-regexp)
5682 (if (match-beginning 1)
5683 (+ (org-get-string-indentation (match-string 1)) 1000)
5684 (1- (- (match-end 0) (match-beginning 0))))))
5686 (defvar org-font-lock-keywords nil)
5688 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5689 "Regular expression matching a property line.")
5691 (defun org-set-font-lock-defaults ()
5692 (let* ((em org-fontify-emphasized-text)
5693 (lk org-activate-links)
5694 (org-font-lock-extra-keywords
5695 (list
5696 ;; Headlines
5697 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5698 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5699 ;; Table lines
5700 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5701 (1 'org-table t))
5702 ;; Table internals
5703 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5704 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5705 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5706 ;; Drawers
5707 (list org-drawer-regexp '(0 'org-special-keyword t))
5708 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5709 ;; Properties
5710 (list org-property-re
5711 '(1 'org-special-keyword t)
5712 '(3 'org-property-value t))
5713 (if org-format-transports-properties-p
5714 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5715 ;; Links
5716 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5717 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5718 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5719 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5720 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5721 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5722 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5723 '(org-hide-wide-columns (0 nil append))
5724 ;; TODO lines
5725 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5726 '(1 (org-get-todo-face 1) t))
5727 ;; DONE
5728 (if org-fontify-done-headline
5729 (list (concat "^[*]+ +\\<\\("
5730 (mapconcat 'regexp-quote org-done-keywords "\\|")
5731 "\\)\\(.*\\)")
5732 '(2 'org-headline-done t))
5733 nil)
5734 ;; Priorities
5735 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5736 ;; Special keywords
5737 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5738 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5739 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5740 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5741 ;; Emphasis
5742 (if em
5743 (if (featurep 'xemacs)
5744 '(org-do-emphasis-faces (0 nil append))
5745 '(org-do-emphasis-faces)))
5746 ;; Checkboxes
5747 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5748 2 'bold prepend)
5749 (if org-provide-checkbox-statistics
5750 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5751 (0 (org-get-checkbox-statistics-face) t)))
5752 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5753 '(1 'org-archived prepend))
5754 ;; Specials
5755 '(org-do-latex-and-special-faces)
5756 ;; Code
5757 '(org-activate-code (1 'org-code t))
5758 ;; COMMENT
5759 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5760 "\\|" org-quote-string "\\)\\>")
5761 '(1 'org-special-keyword t))
5762 '("^#.*" (0 'font-lock-comment-face t))
5764 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5765 ;; Now set the full font-lock-keywords
5766 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5767 (org-set-local 'font-lock-defaults
5768 '(org-font-lock-keywords t nil nil backward-paragraph))
5769 (kill-local-variable 'font-lock-keywords) nil))
5771 (defvar org-m nil)
5772 (defvar org-l nil)
5773 (defvar org-f nil)
5774 (defun org-get-level-face (n)
5775 "Get the right face for match N in font-lock matching of healdines."
5776 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5777 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5778 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5779 (cond
5780 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5781 ((eq n 2) org-f)
5782 (t (if org-level-color-stars-only nil org-f))))
5784 (defun org-get-todo-face (kwd)
5785 "Get the right face for a TODO keyword KWD.
5786 If KWD is a number, get the corresponding match group."
5787 (if (numberp kwd) (setq kwd (match-string kwd)))
5788 (or (cdr (assoc kwd org-todo-keyword-faces))
5789 (and (member kwd org-done-keywords) 'org-done)
5790 'org-todo))
5792 (defun org-unfontify-region (beg end &optional maybe_loudly)
5793 "Remove fontification and activation overlays from links."
5794 (font-lock-default-unfontify-region beg end)
5795 (let* ((buffer-undo-list t)
5796 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5797 (inhibit-modification-hooks t)
5798 deactivate-mark buffer-file-name buffer-file-truename)
5799 (remove-text-properties beg end
5800 '(mouse-face t keymap t org-linked-text t
5801 invisible t intangible t))))
5803 ;;;; Visibility cycling, including org-goto and indirect buffer
5805 ;;; Cycling
5807 (defvar org-cycle-global-status nil)
5808 (make-variable-buffer-local 'org-cycle-global-status)
5809 (defvar org-cycle-subtree-status nil)
5810 (make-variable-buffer-local 'org-cycle-subtree-status)
5812 ;;;###autoload
5813 (defun org-cycle (&optional arg)
5814 "Visibility cycling for Org-mode.
5816 - When this function is called with a prefix argument, rotate the entire
5817 buffer through 3 states (global cycling)
5818 1. OVERVIEW: Show only top-level headlines.
5819 2. CONTENTS: Show all headlines of all levels, but no body text.
5820 3. SHOW ALL: Show everything.
5822 - When point is at the beginning of a headline, rotate the subtree started
5823 by this line through 3 different states (local cycling)
5824 1. FOLDED: Only the main headline is shown.
5825 2. CHILDREN: The main headline and the direct children are shown.
5826 From this state, you can move to one of the children
5827 and zoom in further.
5828 3. SUBTREE: Show the entire subtree, including body text.
5830 - When there is a numeric prefix, go up to a heading with level ARG, do
5831 a `show-subtree' and return to the previous cursor position. If ARG
5832 is negative, go up that many levels.
5834 - When point is not at the beginning of a headline, execute
5835 `indent-relative', like TAB normally does. See the option
5836 `org-cycle-emulate-tab' for details.
5838 - Special case: if point is at the beginning of the buffer and there is
5839 no headline in line 1, this function will act as if called with prefix arg.
5840 But only if also the variable `org-cycle-global-at-bob' is t."
5841 (interactive "P")
5842 (org-load-modules-maybe)
5843 (let* ((outline-regexp
5844 (if (and (org-mode-p) org-cycle-include-plain-lists)
5845 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5846 outline-regexp))
5847 (bob-special (and org-cycle-global-at-bob (bobp)
5848 (not (looking-at outline-regexp))))
5849 (org-cycle-hook
5850 (if bob-special
5851 (delq 'org-optimize-window-after-visibility-change
5852 (copy-sequence org-cycle-hook))
5853 org-cycle-hook))
5854 (pos (point)))
5856 (if (or bob-special (equal arg '(4)))
5857 ;; special case: use global cycling
5858 (setq arg t))
5860 (cond
5862 ((org-at-table-p 'any)
5863 ;; Enter the table or move to the next field in the table
5864 (or (org-table-recognize-table.el)
5865 (progn
5866 (if arg (org-table-edit-field t)
5867 (org-table-justify-field-maybe)
5868 (call-interactively 'org-table-next-field)))))
5870 ((eq arg t) ;; Global cycling
5872 (cond
5873 ((and (eq last-command this-command)
5874 (eq org-cycle-global-status 'overview))
5875 ;; We just created the overview - now do table of contents
5876 ;; This can be slow in very large buffers, so indicate action
5877 (message "CONTENTS...")
5878 (org-content)
5879 (message "CONTENTS...done")
5880 (setq org-cycle-global-status 'contents)
5881 (run-hook-with-args 'org-cycle-hook 'contents))
5883 ((and (eq last-command this-command)
5884 (eq org-cycle-global-status 'contents))
5885 ;; We just showed the table of contents - now show everything
5886 (show-all)
5887 (message "SHOW ALL")
5888 (setq org-cycle-global-status 'all)
5889 (run-hook-with-args 'org-cycle-hook 'all))
5892 ;; Default action: go to overview
5893 (org-overview)
5894 (message "OVERVIEW")
5895 (setq org-cycle-global-status 'overview)
5896 (run-hook-with-args 'org-cycle-hook 'overview))))
5898 ((and org-drawers org-drawer-regexp
5899 (save-excursion
5900 (beginning-of-line 1)
5901 (looking-at org-drawer-regexp)))
5902 ;; Toggle block visibility
5903 (org-flag-drawer
5904 (not (get-char-property (match-end 0) 'invisible))))
5906 ((integerp arg)
5907 ;; Show-subtree, ARG levels up from here.
5908 (save-excursion
5909 (org-back-to-heading)
5910 (outline-up-heading (if (< arg 0) (- arg)
5911 (- (funcall outline-level) arg)))
5912 (org-show-subtree)))
5914 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5915 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5916 ;; At a heading: rotate between three different views
5917 (org-back-to-heading)
5918 (let ((goal-column 0) eoh eol eos)
5919 ;; First, some boundaries
5920 (save-excursion
5921 (org-back-to-heading)
5922 (save-excursion
5923 (beginning-of-line 2)
5924 (while (and (not (eobp)) ;; this is like `next-line'
5925 (get-char-property (1- (point)) 'invisible))
5926 (beginning-of-line 2)) (setq eol (point)))
5927 (outline-end-of-heading) (setq eoh (point))
5928 (org-end-of-subtree t)
5929 (unless (eobp)
5930 (skip-chars-forward " \t\n")
5931 (beginning-of-line 1) ; in case this is an item
5933 (setq eos (1- (point))))
5934 ;; Find out what to do next and set `this-command'
5935 (cond
5936 ((= eos eoh)
5937 ;; Nothing is hidden behind this heading
5938 (message "EMPTY ENTRY")
5939 (setq org-cycle-subtree-status nil)
5940 (save-excursion
5941 (goto-char eos)
5942 (outline-next-heading)
5943 (if (org-invisible-p) (org-flag-heading nil))))
5944 ((or (>= eol eos)
5945 (not (string-match "\\S-" (buffer-substring eol eos))))
5946 ;; Entire subtree is hidden in one line: open it
5947 (org-show-entry)
5948 (show-children)
5949 (message "CHILDREN")
5950 (save-excursion
5951 (goto-char eos)
5952 (outline-next-heading)
5953 (if (org-invisible-p) (org-flag-heading nil)))
5954 (setq org-cycle-subtree-status 'children)
5955 (run-hook-with-args 'org-cycle-hook 'children))
5956 ((and (eq last-command this-command)
5957 (eq org-cycle-subtree-status 'children))
5958 ;; We just showed the children, now show everything.
5959 (org-show-subtree)
5960 (message "SUBTREE")
5961 (setq org-cycle-subtree-status 'subtree)
5962 (run-hook-with-args 'org-cycle-hook 'subtree))
5964 ;; Default action: hide the subtree.
5965 (hide-subtree)
5966 (message "FOLDED")
5967 (setq org-cycle-subtree-status 'folded)
5968 (run-hook-with-args 'org-cycle-hook 'folded)))))
5970 ;; TAB emulation
5971 (buffer-read-only (org-back-to-heading))
5973 ((org-try-cdlatex-tab))
5975 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5976 (or (not (bolp))
5977 (not (looking-at outline-regexp))))
5978 (call-interactively (global-key-binding "\t")))
5980 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5981 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5982 (or (and (eq org-cycle-emulate-tab 'white)
5983 (= (match-end 0) (point-at-eol)))
5984 (and (eq org-cycle-emulate-tab 'whitestart)
5985 (>= (match-end 0) pos))))
5987 (eq org-cycle-emulate-tab t))
5988 ; (if (and (looking-at "[ \n\r\t]")
5989 ; (string-match "^[ \t]*$" (buffer-substring
5990 ; (point-at-bol) (point))))
5991 ; (progn
5992 ; (beginning-of-line 1)
5993 ; (and (looking-at "[ \t]+") (replace-match ""))))
5994 (call-interactively (global-key-binding "\t")))
5996 (t (save-excursion
5997 (org-back-to-heading)
5998 (org-cycle))))))
6000 ;;;###autoload
6001 (defun org-global-cycle (&optional arg)
6002 "Cycle the global visibility. For details see `org-cycle'."
6003 (interactive "P")
6004 (let ((org-cycle-include-plain-lists
6005 (if (org-mode-p) org-cycle-include-plain-lists nil)))
6006 (if (integerp arg)
6007 (progn
6008 (show-all)
6009 (hide-sublevels arg)
6010 (setq org-cycle-global-status 'contents))
6011 (org-cycle '(4)))))
6013 (defun org-overview ()
6014 "Switch to overview mode, shoing only top-level headlines.
6015 Really, this shows all headlines with level equal or greater than the level
6016 of the first headline in the buffer. This is important, because if the
6017 first headline is not level one, then (hide-sublevels 1) gives confusing
6018 results."
6019 (interactive)
6020 (let ((level (save-excursion
6021 (goto-char (point-min))
6022 (if (re-search-forward (concat "^" outline-regexp) nil t)
6023 (progn
6024 (goto-char (match-beginning 0))
6025 (funcall outline-level))))))
6026 (and level (hide-sublevels level))))
6028 (defun org-content (&optional arg)
6029 "Show all headlines in the buffer, like a table of contents.
6030 With numerical argument N, show content up to level N."
6031 (interactive "P")
6032 (save-excursion
6033 ;; Visit all headings and show their offspring
6034 (and (integerp arg) (org-overview))
6035 (goto-char (point-max))
6036 (catch 'exit
6037 (while (and (progn (condition-case nil
6038 (outline-previous-visible-heading 1)
6039 (error (goto-char (point-min))))
6041 (looking-at outline-regexp))
6042 (if (integerp arg)
6043 (show-children (1- arg))
6044 (show-branches))
6045 (if (bobp) (throw 'exit nil))))))
6048 (defun org-optimize-window-after-visibility-change (state)
6049 "Adjust the window after a change in outline visibility.
6050 This function is the default value of the hook `org-cycle-hook'."
6051 (when (get-buffer-window (current-buffer))
6052 (cond
6053 ; ((eq state 'overview) (org-first-headline-recenter 1))
6054 ; ((eq state 'overview) (org-beginning-of-line))
6055 ((eq state 'content) nil)
6056 ((eq state 'all) nil)
6057 ((eq state 'folded) nil)
6058 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6059 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6061 (defun org-compact-display-after-subtree-move ()
6062 (let (beg end)
6063 (save-excursion
6064 (if (org-up-heading-safe)
6065 (progn
6066 (hide-subtree)
6067 (show-entry)
6068 (show-children)
6069 (org-cycle-show-empty-lines 'children)
6070 (org-cycle-hide-drawers 'children))
6071 (org-overview)))))
6073 (defun org-cycle-show-empty-lines (state)
6074 "Show empty lines above all visible headlines.
6075 The region to be covered depends on STATE when called through
6076 `org-cycle-hook'. Lisp program can use t for STATE to get the
6077 entire buffer covered. Note that an empty line is only shown if there
6078 are at least `org-cycle-separator-lines' empty lines before the headeline."
6079 (when (> org-cycle-separator-lines 0)
6080 (save-excursion
6081 (let* ((n org-cycle-separator-lines)
6082 (re (cond
6083 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6084 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6085 (t (let ((ns (number-to-string (- n 2))))
6086 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6087 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6088 beg end)
6089 (cond
6090 ((memq state '(overview contents t))
6091 (setq beg (point-min) end (point-max)))
6092 ((memq state '(children folded))
6093 (setq beg (point) end (progn (org-end-of-subtree t t)
6094 (beginning-of-line 2)
6095 (point)))))
6096 (when beg
6097 (goto-char beg)
6098 (while (re-search-forward re end t)
6099 (if (not (get-char-property (match-end 1) 'invisible))
6100 (outline-flag-region
6101 (match-beginning 1) (match-end 1) nil)))))))
6102 ;; Never hide empty lines at the end of the file.
6103 (save-excursion
6104 (goto-char (point-max))
6105 (outline-previous-heading)
6106 (outline-end-of-heading)
6107 (if (and (looking-at "[ \t\n]+")
6108 (= (match-end 0) (point-max)))
6109 (outline-flag-region (point) (match-end 0) nil))))
6111 (defun org-subtree-end-visible-p ()
6112 "Is the end of the current subtree visible?"
6113 (pos-visible-in-window-p
6114 (save-excursion (org-end-of-subtree t) (point))))
6116 (defun org-first-headline-recenter (&optional N)
6117 "Move cursor to the first headline and recenter the headline.
6118 Optional argument N means, put the headline into the Nth line of the window."
6119 (goto-char (point-min))
6120 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6121 (beginning-of-line)
6122 (recenter (prefix-numeric-value N))))
6124 ;;; Org-goto
6126 (defvar org-goto-window-configuration nil)
6127 (defvar org-goto-marker nil)
6128 (defvar org-goto-map
6129 (let ((map (make-sparse-keymap)))
6130 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6131 (while (setq cmd (pop cmds))
6132 (substitute-key-definition cmd cmd map global-map)))
6133 (suppress-keymap map)
6134 (org-defkey map "\C-m" 'org-goto-ret)
6135 (org-defkey map [(return)] 'org-goto-ret)
6136 (org-defkey map [(left)] 'org-goto-left)
6137 (org-defkey map [(right)] 'org-goto-right)
6138 (org-defkey map [(control ?g)] 'org-goto-quit)
6139 (org-defkey map "\C-i" 'org-cycle)
6140 (org-defkey map [(tab)] 'org-cycle)
6141 (org-defkey map [(down)] 'outline-next-visible-heading)
6142 (org-defkey map [(up)] 'outline-previous-visible-heading)
6143 (if org-goto-auto-isearch
6144 (if (fboundp 'define-key-after)
6145 (define-key-after map [t] 'org-goto-local-auto-isearch)
6146 nil)
6147 (org-defkey map "q" 'org-goto-quit)
6148 (org-defkey map "n" 'outline-next-visible-heading)
6149 (org-defkey map "p" 'outline-previous-visible-heading)
6150 (org-defkey map "f" 'outline-forward-same-level)
6151 (org-defkey map "b" 'outline-backward-same-level)
6152 (org-defkey map "u" 'outline-up-heading))
6153 (org-defkey map "/" 'org-occur)
6154 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6155 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6156 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6157 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6158 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6159 map))
6161 (defconst org-goto-help
6162 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6163 RET=jump to location [Q]uit and return to previous location
6164 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6166 (defvar org-goto-start-pos) ; dynamically scoped parameter
6168 (defun org-goto (&optional alternative-interface)
6169 "Look up a different location in the current file, keeping current visibility.
6171 When you want look-up or go to a different location in a document, the
6172 fastest way is often to fold the entire buffer and then dive into the tree.
6173 This method has the disadvantage, that the previous location will be folded,
6174 which may not be what you want.
6176 This command works around this by showing a copy of the current buffer
6177 in an indirect buffer, in overview mode. You can dive into the tree in
6178 that copy, use org-occur and incremental search to find a location.
6179 When pressing RET or `Q', the command returns to the original buffer in
6180 which the visibility is still unchanged. After RET is will also jump to
6181 the location selected in the indirect buffer and expose the
6182 the headline hierarchy above."
6183 (interactive "P")
6184 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6185 (org-refile-use-outline-path t)
6186 (interface
6187 (if (not alternative-interface)
6188 org-goto-interface
6189 (if (eq org-goto-interface 'outline)
6190 'outline-path-completion
6191 'outline)))
6192 (org-goto-start-pos (point))
6193 (selected-point
6194 (if (eq interface 'outline)
6195 (car (org-get-location (current-buffer) org-goto-help))
6196 (nth 3 (org-refile-get-location "Goto: ")))))
6197 (if selected-point
6198 (progn
6199 (org-mark-ring-push org-goto-start-pos)
6200 (goto-char selected-point)
6201 (if (or (org-invisible-p) (org-invisible-p2))
6202 (org-show-context 'org-goto)))
6203 (message "Quit"))))
6205 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6206 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6207 (defvar org-goto-local-auto-isearch-map) ; defined below
6209 (defun org-get-location (buf help)
6210 "Let the user select a location in the Org-mode buffer BUF.
6211 This function uses a recursive edit. It returns the selected position
6212 or nil."
6213 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6214 (isearch-hide-immediately nil)
6215 (isearch-search-fun-function
6216 (lambda () 'org-goto-local-search-forward-headings))
6217 (org-goto-selected-point org-goto-exit-command))
6218 (save-excursion
6219 (save-window-excursion
6220 (delete-other-windows)
6221 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6222 (switch-to-buffer
6223 (condition-case nil
6224 (make-indirect-buffer (current-buffer) "*org-goto*")
6225 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6226 (with-output-to-temp-buffer "*Help*"
6227 (princ help))
6228 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6229 (setq buffer-read-only nil)
6230 (let ((org-startup-truncated t)
6231 (org-startup-folded nil)
6232 (org-startup-align-all-tables nil))
6233 (org-mode)
6234 (org-overview))
6235 (setq buffer-read-only t)
6236 (if (and (boundp 'org-goto-start-pos)
6237 (integer-or-marker-p org-goto-start-pos))
6238 (let ((org-show-hierarchy-above t)
6239 (org-show-siblings t)
6240 (org-show-following-heading t))
6241 (goto-char org-goto-start-pos)
6242 (and (org-invisible-p) (org-show-context)))
6243 (goto-char (point-min)))
6244 (org-beginning-of-line)
6245 (message "Select location and press RET")
6246 (use-local-map org-goto-map)
6247 (recursive-edit)
6249 (kill-buffer "*org-goto*")
6250 (cons org-goto-selected-point org-goto-exit-command)))
6252 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6253 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6254 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6255 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6257 (defun org-goto-local-search-forward-headings (string bound noerror)
6258 "Search and make sure that anu matches are in headlines."
6259 (catch 'return
6260 (while (search-forward string bound noerror)
6261 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6262 (and (member :headline context)
6263 (not (member :tags context))))
6264 (throw 'return (point))))))
6266 (defun org-goto-local-auto-isearch ()
6267 "Start isearch."
6268 (interactive)
6269 (goto-char (point-min))
6270 (let ((keys (this-command-keys)))
6271 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6272 (isearch-mode t)
6273 (isearch-process-search-char (string-to-char keys)))))
6275 (defun org-goto-ret (&optional arg)
6276 "Finish `org-goto' by going to the new location."
6277 (interactive "P")
6278 (setq org-goto-selected-point (point)
6279 org-goto-exit-command 'return)
6280 (throw 'exit nil))
6282 (defun org-goto-left ()
6283 "Finish `org-goto' by going to the new location."
6284 (interactive)
6285 (if (org-on-heading-p)
6286 (progn
6287 (beginning-of-line 1)
6288 (setq org-goto-selected-point (point)
6289 org-goto-exit-command 'left)
6290 (throw 'exit nil))
6291 (error "Not on a heading")))
6293 (defun org-goto-right ()
6294 "Finish `org-goto' by going to the new location."
6295 (interactive)
6296 (if (org-on-heading-p)
6297 (progn
6298 (setq org-goto-selected-point (point)
6299 org-goto-exit-command 'right)
6300 (throw 'exit nil))
6301 (error "Not on a heading")))
6303 (defun org-goto-quit ()
6304 "Finish `org-goto' without cursor motion."
6305 (interactive)
6306 (setq org-goto-selected-point nil)
6307 (setq org-goto-exit-command 'quit)
6308 (throw 'exit nil))
6310 ;;; Indirect buffer display of subtrees
6312 (defvar org-indirect-dedicated-frame nil
6313 "This is the frame being used for indirect tree display.")
6314 (defvar org-last-indirect-buffer nil)
6316 (defun org-tree-to-indirect-buffer (&optional arg)
6317 "Create indirect buffer and narrow it to current subtree.
6318 With numerical prefix ARG, go up to this level and then take that tree.
6319 If ARG is negative, go up that many levels.
6320 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6321 indirect buffer previously made with this command, to avoid proliferation of
6322 indirect buffers. However, when you call the command with a `C-u' prefix, or
6323 when `org-indirect-buffer-display' is `new-frame', the last buffer
6324 is kept so that you can work with several indirect buffers at the same time.
6325 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6326 requests that a new frame be made for the new buffer, so that the dedicated
6327 frame is not changed."
6328 (interactive "P")
6329 (let ((cbuf (current-buffer))
6330 (cwin (selected-window))
6331 (pos (point))
6332 beg end level heading ibuf)
6333 (save-excursion
6334 (org-back-to-heading t)
6335 (when (numberp arg)
6336 (setq level (org-outline-level))
6337 (if (< arg 0) (setq arg (+ level arg)))
6338 (while (> (setq level (org-outline-level)) arg)
6339 (outline-up-heading 1 t)))
6340 (setq beg (point)
6341 heading (org-get-heading))
6342 (org-end-of-subtree t) (setq end (point)))
6343 (if (and (buffer-live-p org-last-indirect-buffer)
6344 (not (eq org-indirect-buffer-display 'new-frame))
6345 (not arg))
6346 (kill-buffer org-last-indirect-buffer))
6347 (setq ibuf (org-get-indirect-buffer cbuf)
6348 org-last-indirect-buffer ibuf)
6349 (cond
6350 ((or (eq org-indirect-buffer-display 'new-frame)
6351 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6352 (select-frame (make-frame))
6353 (delete-other-windows)
6354 (switch-to-buffer ibuf)
6355 (org-set-frame-title heading))
6356 ((eq org-indirect-buffer-display 'dedicated-frame)
6357 (raise-frame
6358 (select-frame (or (and org-indirect-dedicated-frame
6359 (frame-live-p org-indirect-dedicated-frame)
6360 org-indirect-dedicated-frame)
6361 (setq org-indirect-dedicated-frame (make-frame)))))
6362 (delete-other-windows)
6363 (switch-to-buffer ibuf)
6364 (org-set-frame-title (concat "Indirect: " heading)))
6365 ((eq org-indirect-buffer-display 'current-window)
6366 (switch-to-buffer ibuf))
6367 ((eq org-indirect-buffer-display 'other-window)
6368 (pop-to-buffer ibuf))
6369 (t (error "Invalid value.")))
6370 (if (featurep 'xemacs)
6371 (save-excursion (org-mode) (turn-on-font-lock)))
6372 (narrow-to-region beg end)
6373 (show-all)
6374 (goto-char pos)
6375 (and (window-live-p cwin) (select-window cwin))))
6377 (defun org-get-indirect-buffer (&optional buffer)
6378 (setq buffer (or buffer (current-buffer)))
6379 (let ((n 1) (base (buffer-name buffer)) bname)
6380 (while (buffer-live-p
6381 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6382 (setq n (1+ n)))
6383 (condition-case nil
6384 (make-indirect-buffer buffer bname 'clone)
6385 (error (make-indirect-buffer buffer bname)))))
6387 (defun org-set-frame-title (title)
6388 "Set the title of the current frame to the string TITLE."
6389 ;; FIXME: how to name a single frame in XEmacs???
6390 (unless (featurep 'xemacs)
6391 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6393 ;;;; Structure editing
6395 ;;; Inserting headlines
6397 (defun org-insert-heading (&optional force-heading)
6398 "Insert a new heading or item with same depth at point.
6399 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6400 If point is at the beginning of a headline, insert a sibling before the
6401 current headline. If point is not at the beginning, do not split the line,
6402 but create the new hedline after the current line."
6403 (interactive "P")
6404 (if (= (buffer-size) 0)
6405 (insert "\n* ")
6406 (when (or force-heading (not (org-insert-item)))
6407 (let* ((head (save-excursion
6408 (condition-case nil
6409 (progn
6410 (org-back-to-heading)
6411 (match-string 0))
6412 (error "*"))))
6413 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6414 pos)
6415 (cond
6416 ((and (org-on-heading-p) (bolp)
6417 (or (bobp)
6418 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6419 ;; insert before the current line
6420 (open-line (if blank 2 1)))
6421 ((and (bolp)
6422 (or (bobp)
6423 (save-excursion
6424 (backward-char 1) (not (org-invisible-p)))))
6425 ;; insert right here
6426 nil)
6428 ; ;; in the middle of the line
6429 ; (org-show-entry)
6430 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6431 ; (if (and
6432 ; (org-on-heading-p)
6433 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6434 ; ;; protect the tags
6435 ;; (let ((tags (match-string 2)) pos)
6436 ; (delete-region (match-beginning 1) (match-end 1))
6437 ; (setq pos (point-at-bol))
6438 ; (newline (if blank 2 1))
6439 ; (save-excursion
6440 ; (goto-char pos)
6441 ; (end-of-line 1)
6442 ; (insert " " tags)
6443 ; (org-set-tags nil 'align)))
6444 ; (newline (if blank 2 1)))
6445 ; (newline (if blank 2 1))))
6448 ;; in the middle of the line
6449 (org-show-entry)
6450 (let ((split
6451 (org-get-alist-option org-M-RET-may-split-line 'headline))
6452 tags pos)
6453 (if (org-on-heading-p)
6454 (progn
6455 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6456 (setq tags (and (match-end 2) (match-string 2)))
6457 (and (match-end 1)
6458 (delete-region (match-beginning 1) (match-end 1)))
6459 (setq pos (point-at-bol))
6460 (or split (end-of-line 1))
6461 (delete-horizontal-space)
6462 (newline (if blank 2 1))
6463 (when tags
6464 (save-excursion
6465 (goto-char pos)
6466 (end-of-line 1)
6467 (insert " " tags)
6468 (org-set-tags nil 'align))))
6469 (or split (end-of-line 1))
6470 (newline (if blank 2 1))))))
6471 (insert head) (just-one-space)
6472 (setq pos (point))
6473 (end-of-line 1)
6474 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6475 (run-hooks 'org-insert-heading-hook)))))
6477 (defun org-insert-heading-after-current ()
6478 "Insert a new heading with same level as current, after current subtree."
6479 (interactive)
6480 (org-back-to-heading)
6481 (org-insert-heading)
6482 (org-move-subtree-down)
6483 (end-of-line 1))
6485 (defun org-insert-todo-heading (arg)
6486 "Insert a new heading with the same level and TODO state as current heading.
6487 If the heading has no TODO state, or if the state is DONE, use the first
6488 state (TODO by default). Also with prefix arg, force first state."
6489 (interactive "P")
6490 (when (not (org-insert-item 'checkbox))
6491 (org-insert-heading)
6492 (save-excursion
6493 (org-back-to-heading)
6494 (outline-previous-heading)
6495 (looking-at org-todo-line-regexp))
6496 (if (or arg
6497 (not (match-beginning 2))
6498 (member (match-string 2) org-done-keywords))
6499 (insert (car org-todo-keywords-1) " ")
6500 (insert (match-string 2) " "))))
6502 (defun org-insert-subheading (arg)
6503 "Insert a new subheading and demote it.
6504 Works for outline headings and for plain lists alike."
6505 (interactive "P")
6506 (org-insert-heading arg)
6507 (cond
6508 ((org-on-heading-p) (org-do-demote))
6509 ((org-at-item-p) (org-indent-item 1))))
6511 (defun org-insert-todo-subheading (arg)
6512 "Insert a new subheading with TODO keyword or checkbox and demote it.
6513 Works for outline headings and for plain lists alike."
6514 (interactive "P")
6515 (org-insert-todo-heading arg)
6516 (cond
6517 ((org-on-heading-p) (org-do-demote))
6518 ((org-at-item-p) (org-indent-item 1))))
6520 ;;; Promotion and Demotion
6522 (defun org-promote-subtree ()
6523 "Promote the entire subtree.
6524 See also `org-promote'."
6525 (interactive)
6526 (save-excursion
6527 (org-map-tree 'org-promote))
6528 (org-fix-position-after-promote))
6530 (defun org-demote-subtree ()
6531 "Demote the entire subtree. See `org-demote'.
6532 See also `org-promote'."
6533 (interactive)
6534 (save-excursion
6535 (org-map-tree 'org-demote))
6536 (org-fix-position-after-promote))
6539 (defun org-do-promote ()
6540 "Promote the current heading higher up the tree.
6541 If the region is active in `transient-mark-mode', promote all headings
6542 in the region."
6543 (interactive)
6544 (save-excursion
6545 (if (org-region-active-p)
6546 (org-map-region 'org-promote (region-beginning) (region-end))
6547 (org-promote)))
6548 (org-fix-position-after-promote))
6550 (defun org-do-demote ()
6551 "Demote the current heading lower down the tree.
6552 If the region is active in `transient-mark-mode', demote all headings
6553 in the region."
6554 (interactive)
6555 (save-excursion
6556 (if (org-region-active-p)
6557 (org-map-region 'org-demote (region-beginning) (region-end))
6558 (org-demote)))
6559 (org-fix-position-after-promote))
6561 (defun org-fix-position-after-promote ()
6562 "Make sure that after pro/demotion cursor position is right."
6563 (let ((pos (point)))
6564 (when (save-excursion
6565 (beginning-of-line 1)
6566 (looking-at org-todo-line-regexp)
6567 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6568 (cond ((eobp) (insert " "))
6569 ((eolp) (insert " "))
6570 ((equal (char-after) ?\ ) (forward-char 1))))))
6572 (defun org-reduced-level (l)
6573 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6575 (defun org-get-valid-level (level &optional change)
6576 "Rectify a level change under the influence of `org-odd-levels-only'
6577 LEVEL is a current level, CHANGE is by how much the level should be
6578 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6579 even level numbers will become the next higher odd number."
6580 (if org-odd-levels-only
6581 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6582 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6583 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6584 (max 1 (+ level change))))
6586 (if (featurep 'xemacs)
6587 (define-obsolete-function-alias 'org-get-legal-level
6588 'org-get-valid-level)
6589 (define-obsolete-function-alias 'org-get-legal-level
6590 'org-get-valid-level "23.1"))
6592 (defun org-promote ()
6593 "Promote the current heading higher up the tree.
6594 If the region is active in `transient-mark-mode', promote all headings
6595 in the region."
6596 (org-back-to-heading t)
6597 (let* ((level (save-match-data (funcall outline-level)))
6598 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6599 (diff (abs (- level (length up-head) -1))))
6600 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6601 (replace-match up-head nil t)
6602 ;; Fixup tag positioning
6603 (and org-auto-align-tags (org-set-tags nil t))
6604 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6606 (defun org-demote ()
6607 "Demote the current heading lower down the tree.
6608 If the region is active in `transient-mark-mode', demote all headings
6609 in the region."
6610 (org-back-to-heading t)
6611 (let* ((level (save-match-data (funcall outline-level)))
6612 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6613 (diff (abs (- level (length down-head) -1))))
6614 (replace-match down-head nil t)
6615 ;; Fixup tag positioning
6616 (and org-auto-align-tags (org-set-tags nil t))
6617 (if org-adapt-indentation (org-fixup-indentation diff))))
6619 (defun org-map-tree (fun)
6620 "Call FUN for every heading underneath the current one."
6621 (org-back-to-heading)
6622 (let ((level (funcall outline-level)))
6623 (save-excursion
6624 (funcall fun)
6625 (while (and (progn
6626 (outline-next-heading)
6627 (> (funcall outline-level) level))
6628 (not (eobp)))
6629 (funcall fun)))))
6631 (defun org-map-region (fun beg end)
6632 "Call FUN for every heading between BEG and END."
6633 (let ((org-ignore-region t))
6634 (save-excursion
6635 (setq end (copy-marker end))
6636 (goto-char beg)
6637 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6638 (< (point) end))
6639 (funcall fun))
6640 (while (and (progn
6641 (outline-next-heading)
6642 (< (point) end))
6643 (not (eobp)))
6644 (funcall fun)))))
6646 (defun org-fixup-indentation (diff)
6647 "Change the indentation in the current entry by DIFF
6648 However, if any line in the current entry has no indentation, or if it
6649 would end up with no indentation after the change, nothing at all is done."
6650 (save-excursion
6651 (let ((end (save-excursion (outline-next-heading)
6652 (point-marker)))
6653 (prohibit (if (> diff 0)
6654 "^\\S-"
6655 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6656 col)
6657 (unless (save-excursion (end-of-line 1)
6658 (re-search-forward prohibit end t))
6659 (while (and (< (point) end)
6660 (re-search-forward "^[ \t]+" end t))
6661 (goto-char (match-end 0))
6662 (setq col (current-column))
6663 (if (< diff 0) (replace-match ""))
6664 (indent-to (+ diff col))))
6665 (move-marker end nil))))
6667 (defun org-convert-to-odd-levels ()
6668 "Convert an org-mode file with all levels allowed to one with odd levels.
6669 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6670 level 5 etc."
6671 (interactive)
6672 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6673 (let ((org-odd-levels-only nil) n)
6674 (save-excursion
6675 (goto-char (point-min))
6676 (while (re-search-forward "^\\*\\*+ " nil t)
6677 (setq n (- (length (match-string 0)) 2))
6678 (while (>= (setq n (1- n)) 0)
6679 (org-demote))
6680 (end-of-line 1))))))
6683 (defun org-convert-to-oddeven-levels ()
6684 "Convert an org-mode file with only odd levels to one with odd and even levels.
6685 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6686 section with an even level, conversion would destroy the structure of the file. An error
6687 is signaled in this case."
6688 (interactive)
6689 (goto-char (point-min))
6690 ;; First check if there are no even levels
6691 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6692 (org-show-context t)
6693 (error "Not all levels are odd in this file. Conversion not possible."))
6694 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6695 (let ((org-odd-levels-only nil) n)
6696 (save-excursion
6697 (goto-char (point-min))
6698 (while (re-search-forward "^\\*\\*+ " nil t)
6699 (setq n (/ (1- (length (match-string 0))) 2))
6700 (while (>= (setq n (1- n)) 0)
6701 (org-promote))
6702 (end-of-line 1))))))
6704 (defun org-tr-level (n)
6705 "Make N odd if required."
6706 (if org-odd-levels-only (1+ (/ n 2)) n))
6708 ;;; Vertical tree motion, cutting and pasting of subtrees
6710 (defun org-move-subtree-up (&optional arg)
6711 "Move the current subtree up past ARG headlines of the same level."
6712 (interactive "p")
6713 (org-move-subtree-down (- (prefix-numeric-value arg))))
6715 (defun org-move-subtree-down (&optional arg)
6716 "Move the current subtree down past ARG headlines of the same level."
6717 (interactive "p")
6718 (setq arg (prefix-numeric-value arg))
6719 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6720 'outline-get-last-sibling))
6721 (ins-point (make-marker))
6722 (cnt (abs arg))
6723 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6724 ;; Select the tree
6725 (org-back-to-heading)
6726 (setq beg0 (point))
6727 (save-excursion
6728 (setq ne-beg (org-back-over-empty-lines))
6729 (setq beg (point)))
6730 (save-match-data
6731 (save-excursion (outline-end-of-heading)
6732 (setq folded (org-invisible-p)))
6733 (outline-end-of-subtree))
6734 (outline-next-heading)
6735 (setq ne-end (org-back-over-empty-lines))
6736 (setq end (point))
6737 (goto-char beg0)
6738 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6739 ;; include less whitespace
6740 (save-excursion
6741 (goto-char beg)
6742 (forward-line (- ne-beg ne-end))
6743 (setq beg (point))))
6744 ;; Find insertion point, with error handling
6745 (while (> cnt 0)
6746 (or (and (funcall movfunc) (looking-at outline-regexp))
6747 (progn (goto-char beg0)
6748 (error "Cannot move past superior level or buffer limit")))
6749 (setq cnt (1- cnt)))
6750 (if (> arg 0)
6751 ;; Moving forward - still need to move over subtree
6752 (progn (org-end-of-subtree t t)
6753 (save-excursion
6754 (org-back-over-empty-lines)
6755 (or (bolp) (newline)))))
6756 (setq ne-ins (org-back-over-empty-lines))
6757 (move-marker ins-point (point))
6758 (setq txt (buffer-substring beg end))
6759 (delete-region beg end)
6760 (outline-flag-region (1- beg) beg nil)
6761 (outline-flag-region (1- (point)) (point) nil)
6762 (insert txt)
6763 (or (bolp) (insert "\n"))
6764 (setq ins-end (point))
6765 (goto-char ins-point)
6766 (org-skip-whitespace)
6767 (when (and (< arg 0)
6768 (org-first-sibling-p)
6769 (> ne-ins ne-beg))
6770 ;; Move whitespace back to beginning
6771 (save-excursion
6772 (goto-char ins-end)
6773 (let ((kill-whole-line t))
6774 (kill-line (- ne-ins ne-beg)) (point)))
6775 (insert (make-string (- ne-ins ne-beg) ?\n)))
6776 (move-marker ins-point nil)
6777 (org-compact-display-after-subtree-move)
6778 (unless folded
6779 (org-show-entry)
6780 (show-children)
6781 (org-cycle-hide-drawers 'children))))
6783 (defvar org-subtree-clip ""
6784 "Clipboard for cut and paste of subtrees.
6785 This is actually only a copy of the kill, because we use the normal kill
6786 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6788 (defvar org-subtree-clip-folded nil
6789 "Was the last copied subtree folded?
6790 This is used to fold the tree back after pasting.")
6792 (defun org-cut-subtree (&optional n)
6793 "Cut the current subtree into the clipboard.
6794 With prefix arg N, cut this many sequential subtrees.
6795 This is a short-hand for marking the subtree and then cutting it."
6796 (interactive "p")
6797 (org-copy-subtree n 'cut))
6799 (defun org-copy-subtree (&optional n cut)
6800 "Cut the current subtree into the clipboard.
6801 With prefix arg N, cut this many sequential subtrees.
6802 This is a short-hand for marking the subtree and then copying it.
6803 If CUT is non-nil, actually cut the subtree."
6804 (interactive "p")
6805 (let (beg end folded (beg0 (point)))
6806 (if (interactive-p)
6807 (org-back-to-heading nil) ; take what looks like a subtree
6808 (org-back-to-heading t)) ; take what is really there
6809 (org-back-over-empty-lines)
6810 (setq beg (point))
6811 (skip-chars-forward " \t\r\n")
6812 (save-match-data
6813 (save-excursion (outline-end-of-heading)
6814 (setq folded (org-invisible-p)))
6815 (condition-case nil
6816 (outline-forward-same-level (1- n))
6817 (error nil))
6818 (org-end-of-subtree t t))
6819 (org-back-over-empty-lines)
6820 (setq end (point))
6821 (goto-char beg0)
6822 (when (> end beg)
6823 (setq org-subtree-clip-folded folded)
6824 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6825 (setq org-subtree-clip (current-kill 0))
6826 (message "%s: Subtree(s) with %d characters"
6827 (if cut "Cut" "Copied")
6828 (length org-subtree-clip)))))
6830 (defun org-paste-subtree (&optional level tree)
6831 "Paste the clipboard as a subtree, with modification of headline level.
6832 The entire subtree is promoted or demoted in order to match a new headline
6833 level. By default, the new level is derived from the visible headings
6834 before and after the insertion point, and taken to be the inferior headline
6835 level of the two. So if the previous visible heading is level 3 and the
6836 next is level 4 (or vice versa), level 4 will be used for insertion.
6837 This makes sure that the subtree remains an independent subtree and does
6838 not swallow low level entries.
6840 You can also force a different level, either by using a numeric prefix
6841 argument, or by inserting the heading marker by hand. For example, if the
6842 cursor is after \"*****\", then the tree will be shifted to level 5.
6844 If you want to insert the tree as is, just use \\[yank].
6846 If optional TREE is given, use this text instead of the kill ring."
6847 (interactive "P")
6848 (unless (org-kill-is-subtree-p tree)
6849 (error "%s"
6850 (substitute-command-keys
6851 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6852 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6853 (^re (concat "^\\(" outline-regexp "\\)"))
6854 (re (concat "\\(" outline-regexp "\\)"))
6855 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6857 (old-level (if (string-match ^re txt)
6858 (- (match-end 0) (match-beginning 0) 1)
6859 -1))
6860 (force-level (cond (level (prefix-numeric-value level))
6861 ((string-match
6862 ^re_ (buffer-substring (point-at-bol) (point)))
6863 (- (match-end 1) (match-beginning 1)))
6864 (t nil)))
6865 (previous-level (save-excursion
6866 (condition-case nil
6867 (progn
6868 (outline-previous-visible-heading 1)
6869 (if (looking-at re)
6870 (- (match-end 0) (match-beginning 0) 1)
6872 (error 1))))
6873 (next-level (save-excursion
6874 (condition-case nil
6875 (progn
6876 (or (looking-at outline-regexp)
6877 (outline-next-visible-heading 1))
6878 (if (looking-at re)
6879 (- (match-end 0) (match-beginning 0) 1)
6881 (error 1))))
6882 (new-level (or force-level (max previous-level next-level)))
6883 (shift (if (or (= old-level -1)
6884 (= new-level -1)
6885 (= old-level new-level))
6887 (- new-level old-level)))
6888 (delta (if (> shift 0) -1 1))
6889 (func (if (> shift 0) 'org-demote 'org-promote))
6890 (org-odd-levels-only nil)
6891 beg end)
6892 ;; Remove the forced level indicator
6893 (if force-level
6894 (delete-region (point-at-bol) (point)))
6895 ;; Paste
6896 (beginning-of-line 1)
6897 (org-back-over-empty-lines) ;; FIXME: correct fix????
6898 (setq beg (point))
6899 (insert-before-markers txt) ;; FIXME: correct fix????
6900 (unless (string-match "\n\\'" txt) (insert "\n"))
6901 (setq end (point))
6902 (goto-char beg)
6903 (skip-chars-forward " \t\n\r")
6904 (setq beg (point))
6905 ;; Shift if necessary
6906 (unless (= shift 0)
6907 (save-restriction
6908 (narrow-to-region beg end)
6909 (while (not (= shift 0))
6910 (org-map-region func (point-min) (point-max))
6911 (setq shift (+ delta shift)))
6912 (goto-char (point-min))))
6913 (when (interactive-p)
6914 (message "Clipboard pasted as level %d subtree" new-level))
6915 (if (and kill-ring
6916 (eq org-subtree-clip (current-kill 0))
6917 org-subtree-clip-folded)
6918 ;; The tree was folded before it was killed/copied
6919 (hide-subtree))))
6921 (defun org-kill-is-subtree-p (&optional txt)
6922 "Check if the current kill is an outline subtree, or a set of trees.
6923 Returns nil if kill does not start with a headline, or if the first
6924 headline level is not the largest headline level in the tree.
6925 So this will actually accept several entries of equal levels as well,
6926 which is OK for `org-paste-subtree'.
6927 If optional TXT is given, check this string instead of the current kill."
6928 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6929 (start-level (and kill
6930 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6931 org-outline-regexp "\\)")
6932 kill)
6933 (- (match-end 2) (match-beginning 2) 1)))
6934 (re (concat "^" org-outline-regexp))
6935 (start (1+ (match-beginning 2))))
6936 (if (not start-level)
6937 (progn
6938 nil) ;; does not even start with a heading
6939 (catch 'exit
6940 (while (setq start (string-match re kill (1+ start)))
6941 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6942 (throw 'exit nil)))
6943 t))))
6945 (defun org-narrow-to-subtree ()
6946 "Narrow buffer to the current subtree."
6947 (interactive)
6948 (save-excursion
6949 (save-match-data
6950 (narrow-to-region
6951 (progn (org-back-to-heading) (point))
6952 (progn (org-end-of-subtree t t) (point))))))
6955 ;;; Outline Sorting
6957 (defun org-sort (with-case)
6958 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6959 Optional argument WITH-CASE means sort case-sensitively."
6960 (interactive "P")
6961 (if (org-at-table-p)
6962 (org-call-with-arg 'org-table-sort-lines with-case)
6963 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6965 (defvar org-priority-regexp) ; defined later in the file
6967 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6968 "Sort entries on a certain level of an outline tree.
6969 If there is an active region, the entries in the region are sorted.
6970 Else, if the cursor is before the first entry, sort the top-level items.
6971 Else, the children of the entry at point are sorted.
6973 Sorting can be alphabetically, numerically, and by date/time as given by
6974 the first time stamp in the entry. The command prompts for the sorting
6975 type unless it has been given to the function through the SORTING-TYPE
6976 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6977 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6978 called with point at the beginning of the record. It must return either
6979 a string or a number that should serve as the sorting key for that record.
6981 Comparing entries ignores case by default. However, with an optional argument
6982 WITH-CASE, the sorting considers case as well."
6983 (interactive "P")
6984 (let ((case-func (if with-case 'identity 'downcase))
6985 start beg end stars re re2
6986 txt what tmp plain-list-p)
6987 ;; Find beginning and end of region to sort
6988 (cond
6989 ((org-region-active-p)
6990 ;; we will sort the region
6991 (setq end (region-end)
6992 what "region")
6993 (goto-char (region-beginning))
6994 (if (not (org-on-heading-p)) (outline-next-heading))
6995 (setq start (point)))
6996 ((org-at-item-p)
6997 ;; we will sort this plain list
6998 (org-beginning-of-item-list) (setq start (point))
6999 (org-end-of-item-list) (setq end (point))
7000 (goto-char start)
7001 (setq plain-list-p t
7002 what "plain list"))
7003 ((or (org-on-heading-p)
7004 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7005 ;; we will sort the children of the current headline
7006 (org-back-to-heading)
7007 (setq start (point)
7008 end (progn (org-end-of-subtree t t)
7009 (org-back-over-empty-lines)
7010 (point))
7011 what "children")
7012 (goto-char start)
7013 (show-subtree)
7014 (outline-next-heading))
7016 ;; we will sort the top-level entries in this file
7017 (goto-char (point-min))
7018 (or (org-on-heading-p) (outline-next-heading))
7019 (setq start (point) end (point-max) what "top-level")
7020 (goto-char start)
7021 (show-all)))
7023 (setq beg (point))
7024 (if (>= beg end) (error "Nothing to sort"))
7026 (unless plain-list-p
7027 (looking-at "\\(\\*+\\)")
7028 (setq stars (match-string 1)
7029 re (concat "^" (regexp-quote stars) " +")
7030 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7031 txt (buffer-substring beg end))
7032 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7033 (if (and (not (equal stars "*")) (string-match re2 txt))
7034 (error "Region to sort contains a level above the first entry")))
7036 (unless sorting-type
7037 (message
7038 (if plain-list-p
7039 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7040 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7041 what)
7042 (setq sorting-type (read-char-exclusive))
7044 (and (= (downcase sorting-type) ?f)
7045 (setq getkey-func
7046 (completing-read "Sort using function: "
7047 obarray 'fboundp t nil nil))
7048 (setq getkey-func (intern getkey-func)))
7050 (and (= (downcase sorting-type) ?r)
7051 (setq property
7052 (completing-read "Property: "
7053 (mapcar 'list (org-buffer-property-keys t))
7054 nil t))))
7056 (message "Sorting entries...")
7058 (save-restriction
7059 (narrow-to-region start end)
7061 (let ((dcst (downcase sorting-type))
7062 (now (current-time)))
7063 (sort-subr
7064 (/= dcst sorting-type)
7065 ;; This function moves to the beginning character of the "record" to
7066 ;; be sorted.
7067 (if plain-list-p
7068 (lambda nil
7069 (if (org-at-item-p) t (goto-char (point-max))))
7070 (lambda nil
7071 (if (re-search-forward re nil t)
7072 (goto-char (match-beginning 0))
7073 (goto-char (point-max)))))
7074 ;; This function moves to the last character of the "record" being
7075 ;; sorted.
7076 (if plain-list-p
7077 'org-end-of-item
7078 (lambda nil
7079 (save-match-data
7080 (condition-case nil
7081 (outline-forward-same-level 1)
7082 (error
7083 (goto-char (point-max)))))))
7085 ;; This function returns the value that gets sorted against.
7086 (if plain-list-p
7087 (lambda nil
7088 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7089 (cond
7090 ((= dcst ?n)
7091 (string-to-number (buffer-substring (match-end 0)
7092 (point-at-eol))))
7093 ((= dcst ?a)
7094 (buffer-substring (match-end 0) (point-at-eol)))
7095 ((= dcst ?t)
7096 (if (re-search-forward org-ts-regexp
7097 (point-at-eol) t)
7098 (org-time-string-to-time (match-string 0))
7099 now))
7100 ((= dcst ?f)
7101 (if getkey-func
7102 (progn
7103 (setq tmp (funcall getkey-func))
7104 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7105 tmp)
7106 (error "Invalid key function `%s'" getkey-func)))
7107 (t (error "Invalid sorting type `%c'" sorting-type)))))
7108 (lambda nil
7109 (cond
7110 ((= dcst ?n)
7111 (if (looking-at outline-regexp)
7112 (string-to-number (buffer-substring (match-end 0)
7113 (point-at-eol)))
7114 nil))
7115 ((= dcst ?a)
7116 (funcall case-func (buffer-substring (point-at-bol)
7117 (point-at-eol))))
7118 ((= dcst ?t)
7119 (if (re-search-forward org-ts-regexp
7120 (save-excursion
7121 (forward-line 2)
7122 (point)) t)
7123 (org-time-string-to-time (match-string 0))
7124 now))
7125 ((= dcst ?p)
7126 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7127 (string-to-char (match-string 2))
7128 org-default-priority))
7129 ((= dcst ?r)
7130 (or (org-entry-get nil property) ""))
7131 ((= dcst ?f)
7132 (if getkey-func
7133 (progn
7134 (setq tmp (funcall getkey-func))
7135 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7136 tmp)
7137 (error "Invalid key function `%s'" getkey-func)))
7138 (t (error "Invalid sorting type `%c'" sorting-type)))))
7140 (cond
7141 ((= dcst ?a) 'string<)
7142 ((= dcst ?t) 'time-less-p)
7143 (t nil)))))
7144 (message "Sorting entries...done")))
7146 (defun org-do-sort (table what &optional with-case sorting-type)
7147 "Sort TABLE of WHAT according to SORTING-TYPE.
7148 The user will be prompted for the SORTING-TYPE if the call to this
7149 function does not specify it. WHAT is only for the prompt, to indicate
7150 what is being sorted. The sorting key will be extracted from
7151 the car of the elements of the table.
7152 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7153 (unless sorting-type
7154 (message
7155 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7156 what)
7157 (setq sorting-type (read-char-exclusive)))
7158 (let ((dcst (downcase sorting-type))
7159 extractfun comparefun)
7160 ;; Define the appropriate functions
7161 (cond
7162 ((= dcst ?n)
7163 (setq extractfun 'string-to-number
7164 comparefun (if (= dcst sorting-type) '< '>)))
7165 ((= dcst ?a)
7166 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7167 (lambda(x) (downcase (org-sort-remove-invisible x))))
7168 comparefun (if (= dcst sorting-type)
7169 'string<
7170 (lambda (a b) (and (not (string< a b))
7171 (not (string= a b)))))))
7172 ((= dcst ?t)
7173 (setq extractfun
7174 (lambda (x)
7175 (if (string-match org-ts-regexp x)
7176 (time-to-seconds
7177 (org-time-string-to-time (match-string 0 x)))
7179 comparefun (if (= dcst sorting-type) '< '>)))
7180 (t (error "Invalid sorting type `%c'" sorting-type)))
7182 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7183 table)
7184 (lambda (a b) (funcall comparefun (car a) (car b))))))
7186 ;;;; Plain list items, including checkboxes
7188 ;;; Plain list items
7190 (defun org-at-item-p ()
7191 "Is point in a line starting a hand-formatted item?"
7192 (let ((llt org-plain-list-ordered-item-terminator))
7193 (save-excursion
7194 (goto-char (point-at-bol))
7195 (looking-at
7196 (cond
7197 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7198 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7199 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7200 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7202 (defun org-in-item-p ()
7203 "It the cursor inside a plain list item.
7204 Does not have to be the first line."
7205 (save-excursion
7206 (condition-case nil
7207 (progn
7208 (org-beginning-of-item)
7209 (org-at-item-p)
7211 (error nil))))
7213 (defun org-insert-item (&optional checkbox)
7214 "Insert a new item at the current level.
7215 Return t when things worked, nil when we are not in an item."
7216 (when (save-excursion
7217 (condition-case nil
7218 (progn
7219 (org-beginning-of-item)
7220 (org-at-item-p)
7221 (if (org-invisible-p) (error "Invisible item"))
7223 (error nil)))
7224 (let* ((bul (match-string 0))
7225 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7226 (match-end 0)))
7227 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7228 pos)
7229 (cond
7230 ((and (org-at-item-p) (<= (point) eow))
7231 ;; before the bullet
7232 (beginning-of-line 1)
7233 (open-line (if blank 2 1)))
7234 ((<= (point) eow)
7235 (beginning-of-line 1))
7237 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7238 (end-of-line 1)
7239 (delete-horizontal-space))
7240 (newline (if blank 2 1))))
7241 (insert bul (if checkbox "[ ]" ""))
7242 (just-one-space)
7243 (setq pos (point))
7244 (end-of-line 1)
7245 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7246 (org-maybe-renumber-ordered-list)
7247 (and checkbox (org-update-checkbox-count-maybe))
7250 ;;; Checkboxes
7252 (defun org-at-item-checkbox-p ()
7253 "Is point at a line starting a plain-list item with a checklet?"
7254 (and (org-at-item-p)
7255 (save-excursion
7256 (goto-char (match-end 0))
7257 (skip-chars-forward " \t")
7258 (looking-at "\\[[- X]\\]"))))
7260 (defun org-toggle-checkbox (&optional arg)
7261 "Toggle the checkbox in the current line."
7262 (interactive "P")
7263 (catch 'exit
7264 (let (beg end status (firstnew 'unknown))
7265 (cond
7266 ((org-region-active-p)
7267 (setq beg (region-beginning) end (region-end)))
7268 ((org-on-heading-p)
7269 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7270 ((org-at-item-checkbox-p)
7271 (let ((pos (point)))
7272 (replace-match
7273 (cond (arg "[-]")
7274 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7275 (t "[ ]"))
7276 t t)
7277 (goto-char pos))
7278 (throw 'exit t))
7279 (t (error "Not at a checkbox or heading, and no active region")))
7280 (save-excursion
7281 (goto-char beg)
7282 (while (< (point) end)
7283 (when (org-at-item-checkbox-p)
7284 (setq status (equal (match-string 0) "[X]"))
7285 (when (eq firstnew 'unknown)
7286 (setq firstnew (not status)))
7287 (replace-match
7288 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7289 (beginning-of-line 2)))))
7290 (org-update-checkbox-count-maybe))
7292 (defun org-update-checkbox-count-maybe ()
7293 "Update checkbox statistics unless turned off by user."
7294 (when org-provide-checkbox-statistics
7295 (org-update-checkbox-count)))
7297 (defun org-update-checkbox-count (&optional all)
7298 "Update the checkbox statistics in the current section.
7299 This will find all statistic cookies like [57%] and [6/12] and update them
7300 with the current numbers. With optional prefix argument ALL, do this for
7301 the whole buffer."
7302 (interactive "P")
7303 (save-excursion
7304 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7305 (beg (condition-case nil
7306 (progn (outline-back-to-heading) (point))
7307 (error (point-min))))
7308 (end (move-marker (make-marker)
7309 (progn (outline-next-heading) (point))))
7310 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7311 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7312 (re-find (concat re "\\|" re-box))
7313 beg-cookie end-cookie is-percent c-on c-off lim
7314 eline curr-ind next-ind continue-from startsearch
7315 (cstat 0)
7317 (when all
7318 (goto-char (point-min))
7319 (outline-next-heading)
7320 (setq beg (point) end (point-max)))
7321 (goto-char end)
7322 ;; find each statistic cookie
7323 (while (re-search-backward re-find beg t)
7324 (setq beg-cookie (match-beginning 1)
7325 end-cookie (match-end 1)
7326 cstat (+ cstat (if end-cookie 1 0))
7327 startsearch (point-at-eol)
7328 continue-from (point-at-bol)
7329 is-percent (match-beginning 2)
7330 lim (cond
7331 ((org-on-heading-p) (outline-next-heading) (point))
7332 ((org-at-item-p) (org-end-of-item) (point))
7333 (t nil))
7334 c-on 0
7335 c-off 0)
7336 (when lim
7337 ;; find first checkbox for this cookie and gather
7338 ;; statistics from all that are at this indentation level
7339 (goto-char startsearch)
7340 (if (re-search-forward re-box lim t)
7341 (progn
7342 (org-beginning-of-item)
7343 (setq curr-ind (org-get-indentation))
7344 (setq next-ind curr-ind)
7345 (while (= curr-ind next-ind)
7346 (save-excursion (end-of-line) (setq eline (point)))
7347 (if (re-search-forward re-box eline t)
7348 (if (member (match-string 2) '("[ ]" "[-]"))
7349 (setq c-off (1+ c-off))
7350 (setq c-on (1+ c-on))
7353 (org-end-of-item)
7354 (setq next-ind (org-get-indentation))
7356 (goto-char continue-from)
7357 ;; update cookie
7358 (when end-cookie
7359 (delete-region beg-cookie end-cookie)
7360 (goto-char beg-cookie)
7361 (insert
7362 (if is-percent
7363 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7364 (format "[%d/%d]" c-on (+ c-on c-off)))))
7365 ;; update items checkbox if it has one
7366 (when (org-at-item-p)
7367 (org-beginning-of-item)
7368 (when (and (> (+ c-on c-off) 0)
7369 (re-search-forward re-box (point-at-eol) t))
7370 (setq beg-cookie (match-beginning 2)
7371 end-cookie (match-end 2))
7372 (delete-region beg-cookie end-cookie)
7373 (goto-char beg-cookie)
7374 (cond ((= c-off 0) (insert "[X]"))
7375 ((= c-on 0) (insert "[ ]"))
7376 (t (insert "[-]")))
7378 (goto-char continue-from))
7379 (when (interactive-p)
7380 (message "Checkbox satistics updated %s (%d places)"
7381 (if all "in entire file" "in current outline entry") cstat)))))
7383 (defun org-get-checkbox-statistics-face ()
7384 "Select the face for checkbox statistics.
7385 The face will be `org-done' when all relevant boxes are checked. Otherwise
7386 it will be `org-todo'."
7387 (if (match-end 1)
7388 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7389 (if (and (> (match-end 2) (match-beginning 2))
7390 (equal (match-string 2) (match-string 3)))
7391 'org-done
7392 'org-todo)))
7394 (defun org-get-indentation (&optional line)
7395 "Get the indentation of the current line, interpreting tabs.
7396 When LINE is given, assume it represents a line and compute its indentation."
7397 (if line
7398 (if (string-match "^ *" (org-remove-tabs line))
7399 (match-end 0))
7400 (save-excursion
7401 (beginning-of-line 1)
7402 (skip-chars-forward " \t")
7403 (current-column))))
7405 (defun org-remove-tabs (s &optional width)
7406 "Replace tabulators in S with spaces.
7407 Assumes that s is a single line, starting in column 0."
7408 (setq width (or width tab-width))
7409 (while (string-match "\t" s)
7410 (setq s (replace-match
7411 (make-string
7412 (- (* width (/ (+ (match-beginning 0) width) width))
7413 (match-beginning 0)) ?\ )
7414 t t s)))
7417 (defun org-fix-indentation (line ind)
7418 "Fix indentation in LINE.
7419 IND is a cons cell with target and minimum indentation.
7420 If the current indenation in LINE is smaller than the minimum,
7421 leave it alone. If it is larger than ind, set it to the target."
7422 (let* ((l (org-remove-tabs line))
7423 (i (org-get-indentation l))
7424 (i1 (car ind)) (i2 (cdr ind)))
7425 (if (>= i i2) (setq l (substring line i2)))
7426 (if (> i1 0)
7427 (concat (make-string i1 ?\ ) l)
7428 l)))
7430 (defcustom org-empty-line-terminates-plain-lists nil
7431 "Non-nil means, an empty line ends all plain list levels.
7432 When nil, empty lines are part of the preceeding item."
7433 :group 'org-plain-lists
7434 :type 'boolean)
7436 (defun org-beginning-of-item ()
7437 "Go to the beginning of the current hand-formatted item.
7438 If the cursor is not in an item, throw an error."
7439 (interactive)
7440 (let ((pos (point))
7441 (limit (save-excursion
7442 (condition-case nil
7443 (progn
7444 (org-back-to-heading)
7445 (beginning-of-line 2) (point))
7446 (error (point-min)))))
7447 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7448 ind ind1)
7449 (if (org-at-item-p)
7450 (beginning-of-line 1)
7451 (beginning-of-line 1)
7452 (skip-chars-forward " \t")
7453 (setq ind (current-column))
7454 (if (catch 'exit
7455 (while t
7456 (beginning-of-line 0)
7457 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7459 (if (looking-at "[ \t]*$")
7460 (setq ind1 ind-empty)
7461 (skip-chars-forward " \t")
7462 (setq ind1 (current-column)))
7463 (if (< ind1 ind)
7464 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7466 (goto-char pos)
7467 (error "Not in an item")))))
7469 (defun org-end-of-item ()
7470 "Go to the end of the current hand-formatted item.
7471 If the cursor is not in an item, throw an error."
7472 (interactive)
7473 (let* ((pos (point))
7474 ind1
7475 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7476 (limit (save-excursion (outline-next-heading) (point)))
7477 (ind (save-excursion
7478 (org-beginning-of-item)
7479 (skip-chars-forward " \t")
7480 (current-column)))
7481 (end (catch 'exit
7482 (while t
7483 (beginning-of-line 2)
7484 (if (eobp) (throw 'exit (point)))
7485 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7486 (if (looking-at "[ \t]*$")
7487 (setq ind1 ind-empty)
7488 (skip-chars-forward " \t")
7489 (setq ind1 (current-column)))
7490 (if (<= ind1 ind)
7491 (throw 'exit (point-at-bol)))))))
7492 (if end
7493 (goto-char end)
7494 (goto-char pos)
7495 (error "Not in an item"))))
7497 (defun org-next-item ()
7498 "Move to the beginning of the next item in the current plain list.
7499 Error if not at a plain list, or if this is the last item in the list."
7500 (interactive)
7501 (let (ind ind1 (pos (point)))
7502 (org-beginning-of-item)
7503 (setq ind (org-get-indentation))
7504 (org-end-of-item)
7505 (setq ind1 (org-get-indentation))
7506 (unless (and (org-at-item-p) (= ind ind1))
7507 (goto-char pos)
7508 (error "On last item"))))
7510 (defun org-previous-item ()
7511 "Move to the beginning of the previous item in the current plain list.
7512 Error if not at a plain list, or if this is the first item in the list."
7513 (interactive)
7514 (let (beg ind ind1 (pos (point)))
7515 (org-beginning-of-item)
7516 (setq beg (point))
7517 (setq ind (org-get-indentation))
7518 (goto-char beg)
7519 (catch 'exit
7520 (while t
7521 (beginning-of-line 0)
7522 (if (looking-at "[ \t]*$")
7524 (if (<= (setq ind1 (org-get-indentation)) ind)
7525 (throw 'exit t)))))
7526 (condition-case nil
7527 (if (or (not (org-at-item-p))
7528 (< ind1 (1- ind)))
7529 (error "")
7530 (org-beginning-of-item))
7531 (error (goto-char pos)
7532 (error "On first item")))))
7534 (defun org-first-list-item-p ()
7535 "Is this heading the item in a plain list?"
7536 (unless (org-at-item-p)
7537 (error "Not at a plain list item"))
7538 (org-beginning-of-item)
7539 (= (point) (save-excursion (org-beginning-of-item-list))))
7541 (defun org-move-item-down ()
7542 "Move the plain list item at point down, i.e. swap with following item.
7543 Subitems (items with larger indentation) are considered part of the item,
7544 so this really moves item trees."
7545 (interactive)
7546 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7547 (org-beginning-of-item)
7548 (setq beg0 (point))
7549 (save-excursion
7550 (setq ne-beg (org-back-over-empty-lines))
7551 (setq beg (point)))
7552 (goto-char beg0)
7553 (setq ind (org-get-indentation))
7554 (org-end-of-item)
7555 (setq end0 (point))
7556 (setq ind1 (org-get-indentation))
7557 (setq ne-end (org-back-over-empty-lines))
7558 (setq end (point))
7559 (goto-char beg0)
7560 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7561 ;; include less whitespace
7562 (save-excursion
7563 (goto-char beg)
7564 (forward-line (- ne-beg ne-end))
7565 (setq beg (point))))
7566 (goto-char end0)
7567 (if (and (org-at-item-p) (= ind ind1))
7568 (progn
7569 (org-end-of-item)
7570 (org-back-over-empty-lines)
7571 (setq txt (buffer-substring beg end))
7572 (save-excursion
7573 (delete-region beg end))
7574 (setq pos (point))
7575 (insert txt)
7576 (goto-char pos) (org-skip-whitespace)
7577 (org-maybe-renumber-ordered-list))
7578 (goto-char pos)
7579 (error "Cannot move this item further down"))))
7581 (defun org-move-item-up (arg)
7582 "Move the plain list item at point up, i.e. swap with previous item.
7583 Subitems (items with larger indentation) are considered part of the item,
7584 so this really moves item trees."
7585 (interactive "p")
7586 (let (beg beg0 end ind ind1 (pos (point)) txt
7587 ne-beg ne-ins ins-end)
7588 (org-beginning-of-item)
7589 (setq beg0 (point))
7590 (setq ind (org-get-indentation))
7591 (save-excursion
7592 (setq ne-beg (org-back-over-empty-lines))
7593 (setq beg (point)))
7594 (goto-char beg0)
7595 (org-end-of-item)
7596 (setq end (point))
7597 (goto-char beg0)
7598 (catch 'exit
7599 (while t
7600 (beginning-of-line 0)
7601 (if (looking-at "[ \t]*$")
7602 (if org-empty-line-terminates-plain-lists
7603 (progn
7604 (goto-char pos)
7605 (error "Cannot move this item further up"))
7606 nil)
7607 (if (<= (setq ind1 (org-get-indentation)) ind)
7608 (throw 'exit t)))))
7609 (condition-case nil
7610 (org-beginning-of-item)
7611 (error (goto-char beg)
7612 (error "Cannot move this item further up")))
7613 (setq ind1 (org-get-indentation))
7614 (if (and (org-at-item-p) (= ind ind1))
7615 (progn
7616 (setq ne-ins (org-back-over-empty-lines))
7617 (setq txt (buffer-substring beg end))
7618 (save-excursion
7619 (delete-region beg end))
7620 (setq pos (point))
7621 (insert txt)
7622 (setq ins-end (point))
7623 (goto-char pos) (org-skip-whitespace)
7625 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7626 ;; Move whitespace back to beginning
7627 (save-excursion
7628 (goto-char ins-end)
7629 (let ((kill-whole-line t))
7630 (kill-line (- ne-ins ne-beg)) (point)))
7631 (insert (make-string (- ne-ins ne-beg) ?\n)))
7633 (org-maybe-renumber-ordered-list))
7634 (goto-char pos)
7635 (error "Cannot move this item further up"))))
7637 (defun org-maybe-renumber-ordered-list ()
7638 "Renumber the ordered list at point if setup allows it.
7639 This tests the user option `org-auto-renumber-ordered-lists' before
7640 doing the renumbering."
7641 (interactive)
7642 (when (and org-auto-renumber-ordered-lists
7643 (org-at-item-p))
7644 (if (match-beginning 3)
7645 (org-renumber-ordered-list 1)
7646 (org-fix-bullet-type))))
7648 (defun org-maybe-renumber-ordered-list-safe ()
7649 (condition-case nil
7650 (save-excursion
7651 (org-maybe-renumber-ordered-list))
7652 (error nil)))
7654 (defun org-cycle-list-bullet (&optional which)
7655 "Cycle through the different itemize/enumerate bullets.
7656 This cycle the entire list level through the sequence:
7658 `-' -> `+' -> `*' -> `1.' -> `1)'
7660 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7661 0 meand `-', 1 means `+' etc."
7662 (interactive "P")
7663 (org-preserve-lc
7664 (org-beginning-of-item-list)
7665 (org-at-item-p)
7666 (beginning-of-line 1)
7667 (let ((current (match-string 0))
7668 (prevp (eq which 'previous))
7669 new)
7670 (setq new (cond
7671 ((and (numberp which)
7672 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7673 ((string-match "-" current) (if prevp "1)" "+"))
7674 ((string-match "\\+" current)
7675 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7676 ((string-match "\\*" current) (if prevp "+" "1."))
7677 ((string-match "\\." current) (if prevp "*" "1)"))
7678 ((string-match ")" current) (if prevp "1." "-"))
7679 (t (error "This should not happen"))))
7680 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7681 (org-fix-bullet-type)
7682 (org-maybe-renumber-ordered-list))))
7684 (defun org-get-string-indentation (s)
7685 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7686 (let ((n -1) (i 0) (w tab-width) c)
7687 (catch 'exit
7688 (while (< (setq n (1+ n)) (length s))
7689 (setq c (aref s n))
7690 (cond ((= c ?\ ) (setq i (1+ i)))
7691 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7692 (t (throw 'exit t)))))
7695 (defun org-renumber-ordered-list (arg)
7696 "Renumber an ordered plain list.
7697 Cursor needs to be in the first line of an item, the line that starts
7698 with something like \"1.\" or \"2)\"."
7699 (interactive "p")
7700 (unless (and (org-at-item-p)
7701 (match-beginning 3))
7702 (error "This is not an ordered list"))
7703 (let ((line (org-current-line))
7704 (col (current-column))
7705 (ind (org-get-string-indentation
7706 (buffer-substring (point-at-bol) (match-beginning 3))))
7707 ;; (term (substring (match-string 3) -1))
7708 ind1 (n (1- arg))
7709 fmt)
7710 ;; find where this list begins
7711 (org-beginning-of-item-list)
7712 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7713 (setq fmt (concat "%d" (match-string 1)))
7714 (beginning-of-line 0)
7715 ;; walk forward and replace these numbers
7716 (catch 'exit
7717 (while t
7718 (catch 'next
7719 (beginning-of-line 2)
7720 (if (eobp) (throw 'exit nil))
7721 (if (looking-at "[ \t]*$") (throw 'next nil))
7722 (skip-chars-forward " \t") (setq ind1 (current-column))
7723 (if (> ind1 ind) (throw 'next t))
7724 (if (< ind1 ind) (throw 'exit t))
7725 (if (not (org-at-item-p)) (throw 'exit nil))
7726 (delete-region (match-beginning 2) (match-end 2))
7727 (goto-char (match-beginning 2))
7728 (insert (format fmt (setq n (1+ n)))))))
7729 (goto-line line)
7730 (move-to-column col)))
7732 (defun org-fix-bullet-type ()
7733 "Make sure all items in this list have the same bullet as the firsst item."
7734 (interactive)
7735 (unless (org-at-item-p) (error "This is not a list"))
7736 (let ((line (org-current-line))
7737 (col (current-column))
7738 (ind (current-indentation))
7739 ind1 bullet)
7740 ;; find where this list begins
7741 (org-beginning-of-item-list)
7742 (beginning-of-line 1)
7743 ;; find out what the bullet type is
7744 (looking-at "[ \t]*\\(\\S-+\\)")
7745 (setq bullet (match-string 1))
7746 ;; walk forward and replace these numbers
7747 (beginning-of-line 0)
7748 (catch 'exit
7749 (while t
7750 (catch 'next
7751 (beginning-of-line 2)
7752 (if (eobp) (throw 'exit nil))
7753 (if (looking-at "[ \t]*$") (throw 'next nil))
7754 (skip-chars-forward " \t") (setq ind1 (current-column))
7755 (if (> ind1 ind) (throw 'next t))
7756 (if (< ind1 ind) (throw 'exit t))
7757 (if (not (org-at-item-p)) (throw 'exit nil))
7758 (skip-chars-forward " \t")
7759 (looking-at "\\S-+")
7760 (replace-match bullet))))
7761 (goto-line line)
7762 (move-to-column col)
7763 (if (string-match "[0-9]" bullet)
7764 (org-renumber-ordered-list 1))))
7766 (defun org-beginning-of-item-list ()
7767 "Go to the beginning of the current item list.
7768 I.e. to the first item in this list."
7769 (interactive)
7770 (org-beginning-of-item)
7771 (let ((pos (point-at-bol))
7772 (ind (org-get-indentation))
7773 ind1)
7774 ;; find where this list begins
7775 (catch 'exit
7776 (while t
7777 (catch 'next
7778 (beginning-of-line 0)
7779 (if (looking-at "[ \t]*$")
7780 (throw (if (bobp) 'exit 'next) t))
7781 (skip-chars-forward " \t") (setq ind1 (current-column))
7782 (if (or (< ind1 ind)
7783 (and (= ind1 ind)
7784 (not (org-at-item-p)))
7785 (bobp))
7786 (throw 'exit t)
7787 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7788 (goto-char pos)))
7791 (defun org-end-of-item-list ()
7792 "Go to the end of the current item list.
7793 I.e. to the text after the last item."
7794 (interactive)
7795 (org-beginning-of-item)
7796 (let ((pos (point-at-bol))
7797 (ind (org-get-indentation))
7798 ind1)
7799 ;; find where this list begins
7800 (catch 'exit
7801 (while t
7802 (catch 'next
7803 (beginning-of-line 2)
7804 (if (looking-at "[ \t]*$")
7805 (throw (if (eobp) 'exit 'next) t))
7806 (skip-chars-forward " \t") (setq ind1 (current-column))
7807 (if (or (< ind1 ind)
7808 (and (= ind1 ind)
7809 (not (org-at-item-p)))
7810 (eobp))
7811 (progn
7812 (setq pos (point-at-bol))
7813 (throw 'exit t))))))
7814 (goto-char pos)))
7817 (defvar org-last-indent-begin-marker (make-marker))
7818 (defvar org-last-indent-end-marker (make-marker))
7820 (defun org-outdent-item (arg)
7821 "Outdent a local list item."
7822 (interactive "p")
7823 (org-indent-item (- arg)))
7825 (defun org-indent-item (arg)
7826 "Indent a local list item."
7827 (interactive "p")
7828 (unless (org-at-item-p)
7829 (error "Not on an item"))
7830 (save-excursion
7831 (let (beg end ind ind1 tmp delta ind-down ind-up)
7832 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7833 (setq beg org-last-indent-begin-marker
7834 end org-last-indent-end-marker)
7835 (org-beginning-of-item)
7836 (setq beg (move-marker org-last-indent-begin-marker (point)))
7837 (org-end-of-item)
7838 (setq end (move-marker org-last-indent-end-marker (point))))
7839 (goto-char beg)
7840 (setq tmp (org-item-indent-positions)
7841 ind (car tmp)
7842 ind-down (nth 2 tmp)
7843 ind-up (nth 1 tmp)
7844 delta (if (> arg 0)
7845 (if ind-down (- ind-down ind) 2)
7846 (if ind-up (- ind-up ind) -2)))
7847 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7848 (while (< (point) end)
7849 (beginning-of-line 1)
7850 (skip-chars-forward " \t") (setq ind1 (current-column))
7851 (delete-region (point-at-bol) (point))
7852 (or (eolp) (indent-to-column (+ ind1 delta)))
7853 (beginning-of-line 2))))
7854 (org-fix-bullet-type)
7855 (org-maybe-renumber-ordered-list-safe)
7856 (save-excursion
7857 (beginning-of-line 0)
7858 (condition-case nil (org-beginning-of-item) (error nil))
7859 (org-maybe-renumber-ordered-list-safe)))
7861 (defun org-item-indent-positions ()
7862 "Return indentation for plain list items.
7863 This returns a list with three values: The current indentation, the
7864 parent indentation and the indentation a child should habe.
7865 Assumes cursor in item line."
7866 (let* ((bolpos (point-at-bol))
7867 (ind (org-get-indentation))
7868 ind-down ind-up pos)
7869 (save-excursion
7870 (org-beginning-of-item-list)
7871 (skip-chars-backward "\n\r \t")
7872 (when (org-in-item-p)
7873 (org-beginning-of-item)
7874 (setq ind-up (org-get-indentation))))
7875 (setq pos (point))
7876 (save-excursion
7877 (cond
7878 ((and (condition-case nil (progn (org-previous-item) t)
7879 (error nil))
7880 (or (forward-char 1) t)
7881 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7882 (setq ind-down (org-get-indentation)))
7883 ((and (goto-char pos)
7884 (org-at-item-p))
7885 (goto-char (match-end 0))
7886 (skip-chars-forward " \t")
7887 (setq ind-down (current-column)))))
7888 (list ind ind-up ind-down)))
7890 ;;; The orgstruct minor mode
7892 ;; Define a minor mode which can be used in other modes in order to
7893 ;; integrate the org-mode structure editing commands.
7895 ;; This is really a hack, because the org-mode structure commands use
7896 ;; keys which normally belong to the major mode. Here is how it
7897 ;; works: The minor mode defines all the keys necessary to operate the
7898 ;; structure commands, but wraps the commands into a function which
7899 ;; tests if the cursor is currently at a headline or a plain list
7900 ;; item. If that is the case, the structure command is used,
7901 ;; temporarily setting many Org-mode variables like regular
7902 ;; expressions for filling etc. However, when any of those keys is
7903 ;; used at a different location, function uses `key-binding' to look
7904 ;; up if the key has an associated command in another currently active
7905 ;; keymap (minor modes, major mode, global), and executes that
7906 ;; command. There might be problems if any of the keys is otherwise
7907 ;; used as a prefix key.
7909 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7910 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7911 ;; addresses this by checking explicitly for both bindings.
7913 (defvar orgstruct-mode-map (make-sparse-keymap)
7914 "Keymap for the minor `orgstruct-mode'.")
7916 (defvar org-local-vars nil
7917 "List of local variables, for use by `orgstruct-mode'")
7919 ;;;###autoload
7920 (define-minor-mode orgstruct-mode
7921 "Toggle the minor more `orgstruct-mode'.
7922 This mode is for using Org-mode structure commands in other modes.
7923 The following key behave as if Org-mode was active, if the cursor
7924 is on a headline, or on a plain list item (both in the definition
7925 of Org-mode).
7927 M-up Move entry/item up
7928 M-down Move entry/item down
7929 M-left Promote
7930 M-right Demote
7931 M-S-up Move entry/item up
7932 M-S-down Move entry/item down
7933 M-S-left Promote subtree
7934 M-S-right Demote subtree
7935 M-q Fill paragraph and items like in Org-mode
7936 C-c ^ Sort entries
7937 C-c - Cycle list bullet
7938 TAB Cycle item visibility
7939 M-RET Insert new heading/item
7940 S-M-RET Insert new TODO heading / Chekbox item
7941 C-c C-c Set tags / toggle checkbox"
7942 nil " OrgStruct" nil
7943 (org-load-modules-maybe)
7944 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7946 ;;;###autoload
7947 (defun turn-on-orgstruct ()
7948 "Unconditionally turn on `orgstruct-mode'."
7949 (orgstruct-mode 1))
7951 ;;;###autoload
7952 (defun turn-on-orgstruct++ ()
7953 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7954 In addition to setting orgstruct-mode, this also exports all indentation and
7955 autofilling variables from org-mode into the buffer. Note that turning
7956 off orgstruct-mode will *not* remove these additional settings."
7957 (orgstruct-mode 1)
7958 (let (var val)
7959 (mapc
7960 (lambda (x)
7961 (when (string-match
7962 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7963 (symbol-name (car x)))
7964 (setq var (car x) val (nth 1 x))
7965 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7966 org-local-vars)))
7968 (defun orgstruct-error ()
7969 "Error when there is no default binding for a structure key."
7970 (interactive)
7971 (error "This key has no function outside structure elements"))
7973 (defun orgstruct-setup ()
7974 "Setup orgstruct keymaps."
7975 (let ((nfunc 0)
7976 (bindings
7977 (list
7978 '([(meta up)] org-metaup)
7979 '([(meta down)] org-metadown)
7980 '([(meta left)] org-metaleft)
7981 '([(meta right)] org-metaright)
7982 '([(meta shift up)] org-shiftmetaup)
7983 '([(meta shift down)] org-shiftmetadown)
7984 '([(meta shift left)] org-shiftmetaleft)
7985 '([(meta shift right)] org-shiftmetaright)
7986 '([(shift up)] org-shiftup)
7987 '([(shift down)] org-shiftdown)
7988 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7989 '("\M-q" fill-paragraph)
7990 '("\C-c^" org-sort)
7991 '("\C-c-" org-cycle-list-bullet)))
7992 elt key fun cmd)
7993 (while (setq elt (pop bindings))
7994 (setq nfunc (1+ nfunc))
7995 (setq key (org-key (car elt))
7996 fun (nth 1 elt)
7997 cmd (orgstruct-make-binding fun nfunc key))
7998 (org-defkey orgstruct-mode-map key cmd))
8000 ;; Special treatment needed for TAB and RET
8001 (org-defkey orgstruct-mode-map [(tab)]
8002 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
8003 (org-defkey orgstruct-mode-map "\C-i"
8004 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
8006 (org-defkey orgstruct-mode-map "\M-\C-m"
8007 (orgstruct-make-binding 'org-insert-heading 105
8008 "\M-\C-m" [(meta return)]))
8009 (org-defkey orgstruct-mode-map [(meta return)]
8010 (orgstruct-make-binding 'org-insert-heading 106
8011 [(meta return)] "\M-\C-m"))
8013 (org-defkey orgstruct-mode-map [(shift meta return)]
8014 (orgstruct-make-binding 'org-insert-todo-heading 107
8015 [(meta return)] "\M-\C-m"))
8017 (unless org-local-vars
8018 (setq org-local-vars (org-get-local-variables)))
8022 (defun orgstruct-make-binding (fun n &rest keys)
8023 "Create a function for binding in the structure minor mode.
8024 FUN is the command to call inside a table. N is used to create a unique
8025 command name. KEYS are keys that should be checked in for a command
8026 to execute outside of tables."
8027 (eval
8028 (list 'defun
8029 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8030 '(arg)
8031 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8032 "Outside of structure, run the binding of `"
8033 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8034 "'.")
8035 '(interactive "p")
8036 (list 'if
8037 '(org-context-p 'headline 'item)
8038 (list 'org-run-like-in-org-mode (list 'quote fun))
8039 (list 'let '(orgstruct-mode)
8040 (list 'call-interactively
8041 (append '(or)
8042 (mapcar (lambda (k)
8043 (list 'key-binding k))
8044 keys)
8045 '('orgstruct-error))))))))
8047 (defun org-context-p (&rest contexts)
8048 "Check if local context is and of CONTEXTS.
8049 Possible values in the list of contexts are `table', `headline', and `item'."
8050 (let ((pos (point)))
8051 (goto-char (point-at-bol))
8052 (prog1 (or (and (memq 'table contexts)
8053 (looking-at "[ \t]*|"))
8054 (and (memq 'headline contexts)
8055 (looking-at "\\*+"))
8056 (and (memq 'item contexts)
8057 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8058 (goto-char pos))))
8060 (defun org-get-local-variables ()
8061 "Return a list of all local variables in an org-mode buffer."
8062 (let (varlist)
8063 (with-current-buffer (get-buffer-create "*Org tmp*")
8064 (erase-buffer)
8065 (org-mode)
8066 (setq varlist (buffer-local-variables)))
8067 (kill-buffer "*Org tmp*")
8068 (delq nil
8069 (mapcar
8070 (lambda (x)
8071 (setq x
8072 (if (symbolp x)
8073 (list x)
8074 (list (car x) (list 'quote (cdr x)))))
8075 (if (string-match
8076 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8077 (symbol-name (car x)))
8078 x nil))
8079 varlist))))
8081 ;;;###autoload
8082 (defun org-run-like-in-org-mode (cmd)
8083 (org-load-modules-maybe)
8084 (unless org-local-vars
8085 (setq org-local-vars (org-get-local-variables)))
8086 (eval (list 'let org-local-vars
8087 (list 'call-interactively (list 'quote cmd)))))
8089 ;;;; Archiving
8091 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8093 (defun org-archive-subtree (&optional find-done)
8094 "Move the current subtree to the archive.
8095 The archive can be a certain top-level heading in the current file, or in
8096 a different file. The tree will be moved to that location, the subtree
8097 heading be marked DONE, and the current time will be added.
8099 When called with prefix argument FIND-DONE, find whole trees without any
8100 open TODO items and archive them (after getting confirmation from the user).
8101 If the cursor is not at a headline when this comand is called, try all level
8102 1 trees. If the cursor is on a headline, only try the direct children of
8103 this heading."
8104 (interactive "P")
8105 (if find-done
8106 (org-archive-all-done)
8107 ;; Save all relevant TODO keyword-relatex variables
8109 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8110 (tr-org-todo-keywords-1 org-todo-keywords-1)
8111 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8112 (tr-org-done-keywords org-done-keywords)
8113 (tr-org-todo-regexp org-todo-regexp)
8114 (tr-org-todo-line-regexp org-todo-line-regexp)
8115 (tr-org-odd-levels-only org-odd-levels-only)
8116 (this-buffer (current-buffer))
8117 (org-archive-location org-archive-location)
8118 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8119 ;; start of variables that will be used for saving context
8120 ;; The compiler complains about them - keep them anyway!
8121 (file (abbreviate-file-name (buffer-file-name)))
8122 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8123 (time (format-time-string
8124 (substring (cdr org-time-stamp-formats) 1 -1)
8125 (current-time)))
8126 afile heading buffer level newfile-p
8127 category todo priority
8128 ;; start of variables that will be used for savind context
8129 ltags itags prop)
8131 ;; Try to find a local archive location
8132 (save-excursion
8133 (save-restriction
8134 (widen)
8135 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8136 (if (and prop (string-match "\\S-" prop))
8137 (setq org-archive-location prop)
8138 (if (or (re-search-backward re nil t)
8139 (re-search-forward re nil t))
8140 (setq org-archive-location (match-string 1))))))
8142 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8143 (progn
8144 (setq afile (format (match-string 1 org-archive-location)
8145 (file-name-nondirectory buffer-file-name))
8146 heading (match-string 2 org-archive-location)))
8147 (error "Invalid `org-archive-location'"))
8148 (if (> (length afile) 0)
8149 (setq newfile-p (not (file-exists-p afile))
8150 buffer (find-file-noselect afile))
8151 (setq buffer (current-buffer)))
8152 (unless buffer
8153 (error "Cannot access file \"%s\"" afile))
8154 (if (and (> (length heading) 0)
8155 (string-match "^\\*+" heading))
8156 (setq level (match-end 0))
8157 (setq heading nil level 0))
8158 (save-excursion
8159 (org-back-to-heading t)
8160 ;; Get context information that will be lost by moving the tree
8161 (org-refresh-category-properties)
8162 (setq category (org-get-category)
8163 todo (and (looking-at org-todo-line-regexp)
8164 (match-string 2))
8165 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8166 ltags (org-get-tags)
8167 itags (org-delete-all ltags (org-get-tags-at)))
8168 (setq ltags (mapconcat 'identity ltags " ")
8169 itags (mapconcat 'identity itags " "))
8170 ;; We first only copy, in case something goes wrong
8171 ;; we need to protect this-command, to avoid kill-region sets it,
8172 ;; which would lead to duplication of subtrees
8173 (let (this-command) (org-copy-subtree))
8174 (set-buffer buffer)
8175 ;; Enforce org-mode for the archive buffer
8176 (if (not (org-mode-p))
8177 ;; Force the mode for future visits.
8178 (let ((org-insert-mode-line-in-empty-file t)
8179 (org-inhibit-startup t))
8180 (call-interactively 'org-mode)))
8181 (when newfile-p
8182 (goto-char (point-max))
8183 (insert (format "\nArchived entries from file %s\n\n"
8184 (buffer-file-name this-buffer))))
8185 ;; Force the TODO keywords of the original buffer
8186 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8187 (org-todo-keywords-1 tr-org-todo-keywords-1)
8188 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8189 (org-done-keywords tr-org-done-keywords)
8190 (org-todo-regexp tr-org-todo-regexp)
8191 (org-todo-line-regexp tr-org-todo-line-regexp)
8192 (org-odd-levels-only
8193 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8194 org-odd-levels-only
8195 tr-org-odd-levels-only)))
8196 (goto-char (point-min))
8197 (show-all)
8198 (if heading
8199 (progn
8200 (if (re-search-forward
8201 (concat "^" (regexp-quote heading)
8202 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8203 nil t)
8204 (goto-char (match-end 0))
8205 ;; Heading not found, just insert it at the end
8206 (goto-char (point-max))
8207 (or (bolp) (insert "\n"))
8208 (insert "\n" heading "\n")
8209 (end-of-line 0))
8210 ;; Make the subtree visible
8211 (show-subtree)
8212 (org-end-of-subtree t)
8213 (skip-chars-backward " \t\r\n")
8214 (and (looking-at "[ \t\r\n]*")
8215 (replace-match "\n\n")))
8216 ;; No specific heading, just go to end of file.
8217 (goto-char (point-max)) (insert "\n"))
8218 ;; Paste
8219 (org-paste-subtree (org-get-valid-level level 1))
8221 ;; Mark the entry as done
8222 (when (and org-archive-mark-done
8223 (looking-at org-todo-line-regexp)
8224 (or (not (match-end 2))
8225 (not (member (match-string 2) org-done-keywords))))
8226 (let (org-log-done org-todo-log-states)
8227 (org-todo
8228 (car (or (member org-archive-mark-done org-done-keywords)
8229 org-done-keywords)))))
8231 ;; Add the context info
8232 (when org-archive-save-context-info
8233 (let ((l org-archive-save-context-info) e n v)
8234 (while (setq e (pop l))
8235 (when (and (setq v (symbol-value e))
8236 (stringp v) (string-match "\\S-" v))
8237 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8238 (org-entry-put (point) n v)))))
8240 ;; Save and kill the buffer, if it is not the same buffer.
8241 (if (not (eq this-buffer buffer))
8242 (progn (save-buffer) (kill-buffer buffer)))))
8243 ;; Here we are back in the original buffer. Everything seems to have
8244 ;; worked. So now cut the tree and finish up.
8245 (let (this-command) (org-cut-subtree))
8246 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8247 (message "Subtree archived %s"
8248 (if (eq this-buffer buffer)
8249 (concat "under heading: " heading)
8250 (concat "in file: " (abbreviate-file-name afile)))))))
8252 (defun org-refresh-category-properties ()
8253 "Refresh category text properties in teh buffer."
8254 (let ((def-cat (cond
8255 ((null org-category)
8256 (if buffer-file-name
8257 (file-name-sans-extension
8258 (file-name-nondirectory buffer-file-name))
8259 "???"))
8260 ((symbolp org-category) (symbol-name org-category))
8261 (t org-category)))
8262 beg end cat pos optionp)
8263 (org-unmodified
8264 (save-excursion
8265 (save-restriction
8266 (widen)
8267 (goto-char (point-min))
8268 (put-text-property (point) (point-max) 'org-category def-cat)
8269 (while (re-search-forward
8270 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8271 (setq pos (match-end 0)
8272 optionp (equal (char-after (match-beginning 0)) ?#)
8273 cat (org-trim (match-string 2)))
8274 (if optionp
8275 (setq beg (point-at-bol) end (point-max))
8276 (org-back-to-heading t)
8277 (setq beg (point) end (org-end-of-subtree t t)))
8278 (put-text-property beg end 'org-category cat)
8279 (goto-char pos)))))))
8281 (defun org-archive-all-done (&optional tag)
8282 "Archive sublevels of the current tree without open TODO items.
8283 If the cursor is not on a headline, try all level 1 trees. If
8284 it is on a headline, try all direct children.
8285 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8286 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8287 (rea (concat ".*:" org-archive-tag ":"))
8288 (begm (make-marker))
8289 (endm (make-marker))
8290 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8291 "Move subtree to archive (no open TODO items)? "))
8292 beg end (cntarch 0))
8293 (if (org-on-heading-p)
8294 (progn
8295 (setq re1 (concat "^" (regexp-quote
8296 (make-string
8297 (1+ (- (match-end 0) (match-beginning 0) 1))
8298 ?*))
8299 " "))
8300 (move-marker begm (point))
8301 (move-marker endm (org-end-of-subtree t)))
8302 (setq re1 "^* ")
8303 (move-marker begm (point-min))
8304 (move-marker endm (point-max)))
8305 (save-excursion
8306 (goto-char begm)
8307 (while (re-search-forward re1 endm t)
8308 (setq beg (match-beginning 0)
8309 end (save-excursion (org-end-of-subtree t) (point)))
8310 (goto-char beg)
8311 (if (re-search-forward re end t)
8312 (goto-char end)
8313 (goto-char beg)
8314 (if (and (or (not tag) (not (looking-at rea)))
8315 (y-or-n-p question))
8316 (progn
8317 (if tag
8318 (org-toggle-tag org-archive-tag 'on)
8319 (org-archive-subtree))
8320 (setq cntarch (1+ cntarch)))
8321 (goto-char end)))))
8322 (message "%d trees archived" cntarch)))
8324 (defun org-cycle-hide-drawers (state)
8325 "Re-hide all drawers after a visibility state change."
8326 (when (and (org-mode-p)
8327 (not (memq state '(overview folded))))
8328 (save-excursion
8329 (let* ((globalp (memq state '(contents all)))
8330 (beg (if globalp (point-min) (point)))
8331 (end (if globalp (point-max) (org-end-of-subtree t))))
8332 (goto-char beg)
8333 (while (re-search-forward org-drawer-regexp end t)
8334 (org-flag-drawer t))))))
8336 (defun org-flag-drawer (flag)
8337 (save-excursion
8338 (beginning-of-line 1)
8339 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8340 (let ((b (match-end 0))
8341 (outline-regexp org-outline-regexp))
8342 (if (re-search-forward
8343 "^[ \t]*:END:"
8344 (save-excursion (outline-next-heading) (point)) t)
8345 (outline-flag-region b (point-at-eol) flag)
8346 (error ":END: line missing"))))))
8348 (defun org-cycle-hide-archived-subtrees (state)
8349 "Re-hide all archived subtrees after a visibility state change."
8350 (when (and (not org-cycle-open-archived-trees)
8351 (not (memq state '(overview folded))))
8352 (save-excursion
8353 (let* ((globalp (memq state '(contents all)))
8354 (beg (if globalp (point-min) (point)))
8355 (end (if globalp (point-max) (org-end-of-subtree t))))
8356 (org-hide-archived-subtrees beg end)
8357 (goto-char beg)
8358 (if (looking-at (concat ".*:" org-archive-tag ":"))
8359 (message "%s" (substitute-command-keys
8360 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8362 (defun org-force-cycle-archived ()
8363 "Cycle subtree even if it is archived."
8364 (interactive)
8365 (setq this-command 'org-cycle)
8366 (let ((org-cycle-open-archived-trees t))
8367 (call-interactively 'org-cycle)))
8369 (defun org-hide-archived-subtrees (beg end)
8370 "Re-hide all archived subtrees after a visibility state change."
8371 (save-excursion
8372 (let* ((re (concat ":" org-archive-tag ":")))
8373 (goto-char beg)
8374 (while (re-search-forward re end t)
8375 (and (org-on-heading-p) (hide-subtree))
8376 (org-end-of-subtree t)))))
8378 (defun org-toggle-tag (tag &optional onoff)
8379 "Toggle the tag TAG for the current line.
8380 If ONOFF is `on' or `off', don't toggle but set to this state."
8381 (unless (org-on-heading-p t) (error "Not on headling"))
8382 (let (res current)
8383 (save-excursion
8384 (beginning-of-line)
8385 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8386 (point-at-eol) t)
8387 (progn
8388 (setq current (match-string 1))
8389 (replace-match ""))
8390 (setq current ""))
8391 (setq current (nreverse (org-split-string current ":")))
8392 (cond
8393 ((eq onoff 'on)
8394 (setq res t)
8395 (or (member tag current) (push tag current)))
8396 ((eq onoff 'off)
8397 (or (not (member tag current)) (setq current (delete tag current))))
8398 (t (if (member tag current)
8399 (setq current (delete tag current))
8400 (setq res t)
8401 (push tag current))))
8402 (end-of-line 1)
8403 (if current
8404 (progn
8405 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8406 (org-set-tags nil t))
8407 (delete-horizontal-space))
8408 (run-hooks 'org-after-tags-change-hook))
8409 res))
8411 (defun org-toggle-archive-tag (&optional arg)
8412 "Toggle the archive tag for the current headline.
8413 With prefix ARG, check all children of current headline and offer tagging
8414 the children that do not contain any open TODO items."
8415 (interactive "P")
8416 (if arg
8417 (org-archive-all-done 'tag)
8418 (let (set)
8419 (save-excursion
8420 (org-back-to-heading t)
8421 (setq set (org-toggle-tag org-archive-tag))
8422 (when set (hide-subtree)))
8423 (and set (beginning-of-line 1))
8424 (message "Subtree %s" (if set "archived" "unarchived")))))
8427 ;;;; Tables
8429 ;;; The table editor
8431 ;; Watch out: Here we are talking about two different kind of tables.
8432 ;; Most of the code is for the tables created with the Org-mode table editor.
8433 ;; Sometimes, we talk about tables created and edited with the table.el
8434 ;; Emacs package. We call the former org-type tables, and the latter
8435 ;; table.el-type tables.
8437 (defun org-before-change-function (beg end)
8438 "Every change indicates that a table might need an update."
8439 (setq org-table-may-need-update t))
8441 (defconst org-table-line-regexp "^[ \t]*|"
8442 "Detects an org-type table line.")
8443 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8444 "Detects an org-type table line.")
8445 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8446 "Detects a table line marked for automatic recalculation.")
8447 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8448 "Detects a table line marked for automatic recalculation.")
8449 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8450 "Detects a table line marked for automatic recalculation.")
8451 (defconst org-table-hline-regexp "^[ \t]*|-"
8452 "Detects an org-type table hline.")
8453 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8454 "Detects a table-type table hline.")
8455 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8456 "Detects an org-type or table-type table.")
8457 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8458 "Searching from within a table (any type) this finds the first line
8459 outside the table.")
8460 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8461 "Searching from within a table (any type) this finds the first line
8462 outside the table.")
8464 (defvar org-table-last-highlighted-reference nil)
8465 (defvar org-table-formula-history nil)
8467 (defvar org-table-column-names nil
8468 "Alist with column names, derived from the `!' line.")
8469 (defvar org-table-column-name-regexp nil
8470 "Regular expression matching the current column names.")
8471 (defvar org-table-local-parameters nil
8472 "Alist with parameter names, derived from the `$' line.")
8473 (defvar org-table-named-field-locations nil
8474 "Alist with locations of named fields.")
8476 (defvar org-table-current-line-types nil
8477 "Table row types, non-nil only for the duration of a comand.")
8478 (defvar org-table-current-begin-line nil
8479 "Table begin line, non-nil only for the duration of a comand.")
8480 (defvar org-table-current-begin-pos nil
8481 "Table begin position, non-nil only for the duration of a comand.")
8482 (defvar org-table-dlines nil
8483 "Vector of data line line numbers in the current table.")
8484 (defvar org-table-hlines nil
8485 "Vector of hline line numbers in the current table.")
8487 (defconst org-table-range-regexp
8488 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8489 ;; 1 2 3 4 5
8490 "Regular expression for matching ranges in formulas.")
8492 (defconst org-table-range-regexp2
8493 (concat
8494 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8495 "\\.\\."
8496 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8497 "Match a range for reference display.")
8499 (defconst org-table-translate-regexp
8500 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8501 "Match a reference that needs translation, for reference display.")
8503 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8505 (defun org-table-create-with-table.el ()
8506 "Use the table.el package to insert a new table.
8507 If there is already a table at point, convert between Org-mode tables
8508 and table.el tables."
8509 (interactive)
8510 (require 'table)
8511 (cond
8512 ((org-at-table.el-p)
8513 (if (y-or-n-p "Convert table to Org-mode table? ")
8514 (org-table-convert)))
8515 ((org-at-table-p)
8516 (if (y-or-n-p "Convert table to table.el table? ")
8517 (org-table-convert)))
8518 (t (call-interactively 'table-insert))))
8520 (defun org-table-create-or-convert-from-region (arg)
8521 "Convert region to table, or create an empty table.
8522 If there is an active region, convert it to a table, using the function
8523 `org-table-convert-region'. See the documentation of that function
8524 to learn how the prefix argument is interpreted to determine the field
8525 separator.
8526 If there is no such region, create an empty table with `org-table-create'."
8527 (interactive "P")
8528 (if (org-region-active-p)
8529 (org-table-convert-region (region-beginning) (region-end) arg)
8530 (org-table-create arg)))
8532 (defun org-table-create (&optional size)
8533 "Query for a size and insert a table skeleton.
8534 SIZE is a string Columns x Rows like for example \"3x2\"."
8535 (interactive "P")
8536 (unless size
8537 (setq size (read-string
8538 (concat "Table size Columns x Rows [e.g. "
8539 org-table-default-size "]: ")
8540 "" nil org-table-default-size)))
8542 (let* ((pos (point))
8543 (indent (make-string (current-column) ?\ ))
8544 (split (org-split-string size " *x *"))
8545 (rows (string-to-number (nth 1 split)))
8546 (columns (string-to-number (car split)))
8547 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8548 "\n")))
8549 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8550 (point-at-bol) (point)))
8551 (beginning-of-line 1)
8552 (newline))
8553 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8554 (dotimes (i rows) (insert line))
8555 (goto-char pos)
8556 (if (> rows 1)
8557 ;; Insert a hline after the first row.
8558 (progn
8559 (end-of-line 1)
8560 (insert "\n|-")
8561 (goto-char pos)))
8562 (org-table-align)))
8564 (defun org-table-convert-region (beg0 end0 &optional separator)
8565 "Convert region to a table.
8566 The region goes from BEG0 to END0, but these borders will be moved
8567 slightly, to make sure a beginning of line in the first line is included.
8569 SEPARATOR specifies the field separator in the lines. It can have the
8570 following values:
8572 '(4) Use the comma as a field separator
8573 '(16) Use a TAB as field separator
8574 integer When a number, use that many spaces as field separator
8575 nil When nil, the command tries to be smart and figure out the
8576 separator in the following way:
8577 - when each line contains a TAB, assume TAB-separated material
8578 - when each line contains a comme, assume CSV material
8579 - else, assume one or more SPACE charcters as separator."
8580 (interactive "rP")
8581 (let* ((beg (min beg0 end0))
8582 (end (max beg0 end0))
8584 (goto-char beg)
8585 (beginning-of-line 1)
8586 (setq beg (move-marker (make-marker) (point)))
8587 (goto-char end)
8588 (if (bolp) (backward-char 1) (end-of-line 1))
8589 (setq end (move-marker (make-marker) (point)))
8590 ;; Get the right field separator
8591 (unless separator
8592 (goto-char beg)
8593 (setq separator
8594 (cond
8595 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8596 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8597 (t 1))))
8598 (setq re (cond
8599 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8600 ((equal separator '(16)) "^\\|\t")
8601 ((integerp separator)
8602 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8603 (t (error "This should not happen"))))
8604 (goto-char beg)
8605 (while (re-search-forward re end t)
8606 (replace-match "| " t t))
8607 (goto-char beg)
8608 (insert " ")
8609 (org-table-align)))
8611 (defun org-table-import (file arg)
8612 "Import FILE as a table.
8613 The file is assumed to be tab-separated. Such files can be produced by most
8614 spreadsheet and database applications. If no tabs (at least one per line)
8615 are found, lines will be split on whitespace into fields."
8616 (interactive "f\nP")
8617 (or (bolp) (newline))
8618 (let ((beg (point))
8619 (pm (point-max)))
8620 (insert-file-contents file)
8621 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8623 (defun org-table-export ()
8624 "Export table as a tab-separated file.
8625 Such a file can be imported into a spreadsheet program like Excel."
8626 (interactive)
8627 (let* ((beg (org-table-begin))
8628 (end (org-table-end))
8629 (table (buffer-substring beg end))
8630 (file (read-file-name "Export table to: "))
8631 buf)
8632 (unless (or (not (file-exists-p file))
8633 (y-or-n-p (format "Overwrite file %s? " file)))
8634 (error "Abort"))
8635 (with-current-buffer (find-file-noselect file)
8636 (setq buf (current-buffer))
8637 (erase-buffer)
8638 (fundamental-mode)
8639 (insert table)
8640 (goto-char (point-min))
8641 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8642 (replace-match "" t t)
8643 (end-of-line 1))
8644 (goto-char (point-min))
8645 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8646 (replace-match "" t t)
8647 (goto-char (min (1+ (point)) (point-max))))
8648 (goto-char (point-min))
8649 (while (re-search-forward "^-[-+]*$" nil t)
8650 (replace-match "")
8651 (if (looking-at "\n")
8652 (delete-char 1)))
8653 (goto-char (point-min))
8654 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8655 (replace-match "\t" t t))
8656 (save-buffer))
8657 (kill-buffer buf)))
8659 (defvar org-table-aligned-begin-marker (make-marker)
8660 "Marker at the beginning of the table last aligned.
8661 Used to check if cursor still is in that table, to minimize realignment.")
8662 (defvar org-table-aligned-end-marker (make-marker)
8663 "Marker at the end of the table last aligned.
8664 Used to check if cursor still is in that table, to minimize realignment.")
8665 (defvar org-table-last-alignment nil
8666 "List of flags for flushright alignment, from the last re-alignment.
8667 This is being used to correctly align a single field after TAB or RET.")
8668 (defvar org-table-last-column-widths nil
8669 "List of max width of fields in each column.
8670 This is being used to correctly align a single field after TAB or RET.")
8671 (defvar org-table-overlay-coordinates nil
8672 "Overlay coordinates after each align of a table.")
8673 (make-variable-buffer-local 'org-table-overlay-coordinates)
8675 (defvar org-last-recalc-line nil)
8676 (defconst org-narrow-column-arrow "=>"
8677 "Used as display property in narrowed table columns.")
8679 (defun org-table-align ()
8680 "Align the table at point by aligning all vertical bars."
8681 (interactive)
8682 (let* (
8683 ;; Limits of table
8684 (beg (org-table-begin))
8685 (end (org-table-end))
8686 ;; Current cursor position
8687 (linepos (org-current-line))
8688 (colpos (org-table-current-column))
8689 (winstart (window-start))
8690 (winstartline (org-current-line (min winstart (1- (point-max)))))
8691 lines (new "") lengths l typenums ty fields maxfields i
8692 column
8693 (indent "") cnt frac
8694 rfmt hfmt
8695 (spaces '(1 . 1))
8696 (sp1 (car spaces))
8697 (sp2 (cdr spaces))
8698 (rfmt1 (concat
8699 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8700 (hfmt1 (concat
8701 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8702 emptystrings links dates emph narrow fmax f1 len c e)
8703 (untabify beg end)
8704 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8705 ;; Check if we have links or dates
8706 (goto-char beg)
8707 (setq links (re-search-forward org-bracket-link-regexp end t))
8708 (goto-char beg)
8709 (setq emph (and org-hide-emphasis-markers
8710 (re-search-forward org-emph-re end t)))
8711 (goto-char beg)
8712 (setq dates (and org-display-custom-times
8713 (re-search-forward org-ts-regexp-both end t)))
8714 ;; Make sure the link properties are right
8715 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8716 ;; Make sure the date properties are right
8717 (when dates (goto-char beg) (while (org-activate-dates end)))
8718 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8720 ;; Check if we are narrowing any columns
8721 (goto-char beg)
8722 (setq narrow (and org-format-transports-properties-p
8723 (re-search-forward "<[0-9]+>" end t)))
8724 ;; Get the rows
8725 (setq lines (org-split-string
8726 (buffer-substring beg end) "\n"))
8727 ;; Store the indentation of the first line
8728 (if (string-match "^ *" (car lines))
8729 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8730 ;; Mark the hlines by setting the corresponding element to nil
8731 ;; At the same time, we remove trailing space.
8732 (setq lines (mapcar (lambda (l)
8733 (if (string-match "^ *|-" l)
8735 (if (string-match "[ \t]+$" l)
8736 (substring l 0 (match-beginning 0))
8737 l)))
8738 lines))
8739 ;; Get the data fields by splitting the lines.
8740 (setq fields (mapcar
8741 (lambda (l)
8742 (org-split-string l " *| *"))
8743 (delq nil (copy-sequence lines))))
8744 ;; How many fields in the longest line?
8745 (condition-case nil
8746 (setq maxfields (apply 'max (mapcar 'length fields)))
8747 (error
8748 (kill-region beg end)
8749 (org-table-create org-table-default-size)
8750 (error "Empty table - created default table")))
8751 ;; A list of empty strings to fill any short rows on output
8752 (setq emptystrings (make-list maxfields ""))
8753 ;; Check for special formatting.
8754 (setq i -1)
8755 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8756 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8757 ;; Check if there is an explicit width specified
8758 (when narrow
8759 (setq c column fmax nil)
8760 (while c
8761 (setq e (pop c))
8762 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8763 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8764 ;; Find fields that are wider than fmax, and shorten them
8765 (when fmax
8766 (loop for xx in column do
8767 (when (and (stringp xx)
8768 (> (org-string-width xx) fmax))
8769 (org-add-props xx nil
8770 'help-echo
8771 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8772 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8773 (unless (> f1 1)
8774 (error "Cannot narrow field starting with wide link \"%s\""
8775 (match-string 0 xx)))
8776 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8777 (add-text-properties (- f1 2) f1
8778 (list 'display org-narrow-column-arrow)
8779 xx)))))
8780 ;; Get the maximum width for each column
8781 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8782 ;; Get the fraction of numbers, to decide about alignment of the column
8783 (setq cnt 0 frac 0.0)
8784 (loop for x in column do
8785 (if (equal x "")
8787 (setq frac ( / (+ (* frac cnt)
8788 (if (string-match org-table-number-regexp x) 1 0))
8789 (setq cnt (1+ cnt))))))
8790 (push (>= frac org-table-number-fraction) typenums))
8791 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8793 ;; Store the alignment of this table, for later editing of single fields
8794 (setq org-table-last-alignment typenums
8795 org-table-last-column-widths lengths)
8797 ;; With invisible characters, `format' does not get the field width right
8798 ;; So we need to make these fields wide by hand.
8799 (when (or links emph)
8800 (loop for i from 0 upto (1- maxfields) do
8801 (setq len (nth i lengths))
8802 (loop for j from 0 upto (1- (length fields)) do
8803 (setq c (nthcdr i (car (nthcdr j fields))))
8804 (if (and (stringp (car c))
8805 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8806 ; (string-match org-bracket-link-regexp (car c))
8807 (< (org-string-width (car c)) len))
8808 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8810 ;; Compute the formats needed for output of the table
8811 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8812 (while (setq l (pop lengths))
8813 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8814 (setq rfmt (concat rfmt (format rfmt1 ty l))
8815 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8816 (setq rfmt (concat rfmt "\n")
8817 hfmt (concat (substring hfmt 0 -1) "|\n"))
8819 (setq new (mapconcat
8820 (lambda (l)
8821 (if l (apply 'format rfmt
8822 (append (pop fields) emptystrings))
8823 hfmt))
8824 lines ""))
8825 ;; Replace the old one
8826 (delete-region beg end)
8827 (move-marker end nil)
8828 (move-marker org-table-aligned-begin-marker (point))
8829 (insert new)
8830 (move-marker org-table-aligned-end-marker (point))
8831 (when (and orgtbl-mode (not (org-mode-p)))
8832 (goto-char org-table-aligned-begin-marker)
8833 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8834 ;; Try to move to the old location
8835 (goto-line winstartline)
8836 (setq winstart (point-at-bol))
8837 (goto-line linepos)
8838 (set-window-start (selected-window) winstart 'noforce)
8839 (org-table-goto-column colpos)
8840 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8841 (setq org-table-may-need-update nil)
8844 (defun org-string-width (s)
8845 "Compute width of string, ignoring invisible characters.
8846 This ignores character with invisibility property `org-link', and also
8847 characters with property `org-cwidth', because these will become invisible
8848 upon the next fontification round."
8849 (let (b l)
8850 (when (or (eq t buffer-invisibility-spec)
8851 (assq 'org-link buffer-invisibility-spec))
8852 (while (setq b (text-property-any 0 (length s)
8853 'invisible 'org-link s))
8854 (setq s (concat (substring s 0 b)
8855 (substring s (or (next-single-property-change
8856 b 'invisible s) (length s)))))))
8857 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8858 (setq s (concat (substring s 0 b)
8859 (substring s (or (next-single-property-change
8860 b 'org-cwidth s) (length s))))))
8861 (setq l (string-width s) b -1)
8862 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8863 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8866 (defun org-table-begin (&optional table-type)
8867 "Find the beginning of the table and return its position.
8868 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8869 (save-excursion
8870 (if (not (re-search-backward
8871 (if table-type org-table-any-border-regexp
8872 org-table-border-regexp)
8873 nil t))
8874 (progn (goto-char (point-min)) (point))
8875 (goto-char (match-beginning 0))
8876 (beginning-of-line 2)
8877 (point))))
8879 (defun org-table-end (&optional table-type)
8880 "Find the end of the table and return its position.
8881 With argument TABLE-TYPE, go to the end of a table.el-type table."
8882 (save-excursion
8883 (if (not (re-search-forward
8884 (if table-type org-table-any-border-regexp
8885 org-table-border-regexp)
8886 nil t))
8887 (goto-char (point-max))
8888 (goto-char (match-beginning 0)))
8889 (point-marker)))
8891 (defun org-table-justify-field-maybe (&optional new)
8892 "Justify the current field, text to left, number to right.
8893 Optional argument NEW may specify text to replace the current field content."
8894 (cond
8895 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8896 ((org-at-table-hline-p))
8897 ((and (not new)
8898 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8899 (current-buffer)))
8900 (< (point) org-table-aligned-begin-marker)
8901 (>= (point) org-table-aligned-end-marker)))
8902 ;; This is not the same table, force a full re-align
8903 (setq org-table-may-need-update t))
8904 (t ;; realign the current field, based on previous full realign
8905 (let* ((pos (point)) s
8906 (col (org-table-current-column))
8907 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8908 l f n o e)
8909 (when (> col 0)
8910 (skip-chars-backward "^|\n")
8911 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8912 (progn
8913 (setq s (match-string 1)
8914 o (match-string 0)
8915 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8916 e (not (= (match-beginning 2) (match-end 2))))
8917 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8918 l (if e "|" (setq org-table-may-need-update t) ""))
8919 n (format f s))
8920 (if new
8921 (if (<= (length new) l) ;; FIXME: length -> str-width?
8922 (setq n (format f new))
8923 (setq n (concat new "|") org-table-may-need-update t)))
8924 (or (equal n o)
8925 (let (org-table-may-need-update)
8926 (replace-match n t t))))
8927 (setq org-table-may-need-update t))
8928 (goto-char pos))))))
8930 (defun org-table-next-field ()
8931 "Go to the next field in the current table, creating new lines as needed.
8932 Before doing so, re-align the table if necessary."
8933 (interactive)
8934 (org-table-maybe-eval-formula)
8935 (org-table-maybe-recalculate-line)
8936 (if (and org-table-automatic-realign
8937 org-table-may-need-update)
8938 (org-table-align))
8939 (let ((end (org-table-end)))
8940 (if (org-at-table-hline-p)
8941 (end-of-line 1))
8942 (condition-case nil
8943 (progn
8944 (re-search-forward "|" end)
8945 (if (looking-at "[ \t]*$")
8946 (re-search-forward "|" end))
8947 (if (and (looking-at "-")
8948 org-table-tab-jumps-over-hlines
8949 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8950 (goto-char (match-beginning 1)))
8951 (if (looking-at "-")
8952 (progn
8953 (beginning-of-line 0)
8954 (org-table-insert-row 'below))
8955 (if (looking-at " ") (forward-char 1))))
8956 (error
8957 (org-table-insert-row 'below)))))
8959 (defun org-table-previous-field ()
8960 "Go to the previous field in the table.
8961 Before doing so, re-align the table if necessary."
8962 (interactive)
8963 (org-table-justify-field-maybe)
8964 (org-table-maybe-recalculate-line)
8965 (if (and org-table-automatic-realign
8966 org-table-may-need-update)
8967 (org-table-align))
8968 (if (org-at-table-hline-p)
8969 (end-of-line 1))
8970 (re-search-backward "|" (org-table-begin))
8971 (re-search-backward "|" (org-table-begin))
8972 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8973 (re-search-backward "|" (org-table-begin)))
8974 (if (looking-at "| ?")
8975 (goto-char (match-end 0))))
8977 (defun org-table-next-row ()
8978 "Go to the next row (same column) in the current table.
8979 Before doing so, re-align the table if necessary."
8980 (interactive)
8981 (org-table-maybe-eval-formula)
8982 (org-table-maybe-recalculate-line)
8983 (if (or (looking-at "[ \t]*$")
8984 (save-excursion (skip-chars-backward " \t") (bolp)))
8985 (newline)
8986 (if (and org-table-automatic-realign
8987 org-table-may-need-update)
8988 (org-table-align))
8989 (let ((col (org-table-current-column)))
8990 (beginning-of-line 2)
8991 (if (or (not (org-at-table-p))
8992 (org-at-table-hline-p))
8993 (progn
8994 (beginning-of-line 0)
8995 (org-table-insert-row 'below)))
8996 (org-table-goto-column col)
8997 (skip-chars-backward "^|\n\r")
8998 (if (looking-at " ") (forward-char 1)))))
9000 (defun org-table-copy-down (n)
9001 "Copy a field down in the current column.
9002 If the field at the cursor is empty, copy into it the content of the nearest
9003 non-empty field above. With argument N, use the Nth non-empty field.
9004 If the current field is not empty, it is copied down to the next row, and
9005 the cursor is moved with it. Therefore, repeating this command causes the
9006 column to be filled row-by-row.
9007 If the variable `org-table-copy-increment' is non-nil and the field is an
9008 integer or a timestamp, it will be incremented while copying. In the case of
9009 a timestamp, if the cursor is on the year, change the year. If it is on the
9010 month or the day, change that. Point will stay on the current date field
9011 in order to easily repeat the interval."
9012 (interactive "p")
9013 (let* ((colpos (org-table-current-column))
9014 (col (current-column))
9015 (field (org-table-get-field))
9016 (non-empty (string-match "[^ \t]" field))
9017 (beg (org-table-begin))
9018 txt)
9019 (org-table-check-inside-data-field)
9020 (if non-empty
9021 (progn
9022 (setq txt (org-trim field))
9023 (org-table-next-row)
9024 (org-table-blank-field))
9025 (save-excursion
9026 (setq txt
9027 (catch 'exit
9028 (while (progn (beginning-of-line 1)
9029 (re-search-backward org-table-dataline-regexp
9030 beg t))
9031 (org-table-goto-column colpos t)
9032 (if (and (looking-at
9033 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9034 (= (setq n (1- n)) 0))
9035 (throw 'exit (match-string 1))))))))
9036 (if txt
9037 (progn
9038 (if (and org-table-copy-increment
9039 (string-match "^[0-9]+$" txt))
9040 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9041 (insert txt)
9042 (move-to-column col)
9043 (if (and org-table-copy-increment (org-at-timestamp-p t))
9044 (org-timestamp-up 1)
9045 (org-table-maybe-recalculate-line))
9046 (org-table-align)
9047 (move-to-column col))
9048 (error "No non-empty field found"))))
9050 (defun org-table-check-inside-data-field ()
9051 "Is point inside a table data field?
9052 I.e. not on a hline or before the first or after the last column?
9053 This actually throws an error, so it aborts the current command."
9054 (if (or (not (org-at-table-p))
9055 (= (org-table-current-column) 0)
9056 (org-at-table-hline-p)
9057 (looking-at "[ \t]*$"))
9058 (error "Not in table data field")))
9060 (defvar org-table-clip nil
9061 "Clipboard for table regions.")
9063 (defun org-table-blank-field ()
9064 "Blank the current table field or active region."
9065 (interactive)
9066 (org-table-check-inside-data-field)
9067 (if (and (interactive-p) (org-region-active-p))
9068 (let (org-table-clip)
9069 (org-table-cut-region (region-beginning) (region-end)))
9070 (skip-chars-backward "^|")
9071 (backward-char 1)
9072 (if (looking-at "|[^|\n]+")
9073 (let* ((pos (match-beginning 0))
9074 (match (match-string 0))
9075 (len (org-string-width match)))
9076 (replace-match (concat "|" (make-string (1- len) ?\ )))
9077 (goto-char (+ 2 pos))
9078 (substring match 1)))))
9080 (defun org-table-get-field (&optional n replace)
9081 "Return the value of the field in column N of current row.
9082 N defaults to current field.
9083 If REPLACE is a string, replace field with this value. The return value
9084 is always the old value."
9085 (and n (org-table-goto-column n))
9086 (skip-chars-backward "^|\n")
9087 (backward-char 1)
9088 (if (looking-at "|[^|\r\n]*")
9089 (let* ((pos (match-beginning 0))
9090 (val (buffer-substring (1+ pos) (match-end 0))))
9091 (if replace
9092 (replace-match (concat "|" replace) t t))
9093 (goto-char (min (point-at-eol) (+ 2 pos)))
9094 val)
9095 (forward-char 1) ""))
9097 (defun org-table-field-info (arg)
9098 "Show info about the current field, and highlight any reference at point."
9099 (interactive "P")
9100 (org-table-get-specials)
9101 (save-excursion
9102 (let* ((pos (point))
9103 (col (org-table-current-column))
9104 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9105 (name (car (rassoc (list (org-current-line) col)
9106 org-table-named-field-locations)))
9107 (eql (org-table-get-stored-formulas))
9108 (dline (org-table-current-dline))
9109 (ref (format "@%d$%d" dline col))
9110 (ref1 (org-table-convert-refs-to-an ref))
9111 (fequation (or (assoc name eql) (assoc ref eql)))
9112 (cequation (assoc (int-to-string col) eql))
9113 (eqn (or fequation cequation)))
9114 (goto-char pos)
9115 (condition-case nil
9116 (org-table-show-reference 'local)
9117 (error nil))
9118 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9119 dline col
9120 (if cname (concat " or $" cname) "")
9121 dline col ref1
9122 (if name (concat " or $" name) "")
9123 ;; FIXME: formula info not correct if special table line
9124 (if eqn
9125 (concat ", formula: "
9126 (org-table-formula-to-user
9127 (concat
9128 (if (string-match "^[$@]"(car eqn)) "" "$")
9129 (car eqn) "=" (cdr eqn))))
9130 "")))))
9132 (defun org-table-current-column ()
9133 "Find out which column we are in.
9134 When called interactively, column is also displayed in echo area."
9135 (interactive)
9136 (if (interactive-p) (org-table-check-inside-data-field))
9137 (save-excursion
9138 (let ((cnt 0) (pos (point)))
9139 (beginning-of-line 1)
9140 (while (search-forward "|" pos t)
9141 (setq cnt (1+ cnt)))
9142 (if (interactive-p) (message "This is table column %d" cnt))
9143 cnt)))
9145 (defun org-table-current-dline ()
9146 "Find out what table data line we are in.
9147 Only datalins count for this."
9148 (interactive)
9149 (if (interactive-p) (org-table-check-inside-data-field))
9150 (save-excursion
9151 (let ((cnt 0) (pos (point)))
9152 (goto-char (org-table-begin))
9153 (while (<= (point) pos)
9154 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9155 (beginning-of-line 2))
9156 (if (interactive-p) (message "This is table line %d" cnt))
9157 cnt)))
9159 (defun org-table-goto-column (n &optional on-delim force)
9160 "Move the cursor to the Nth column in the current table line.
9161 With optional argument ON-DELIM, stop with point before the left delimiter
9162 of the field.
9163 If there are less than N fields, just go to after the last delimiter.
9164 However, when FORCE is non-nil, create new columns if necessary."
9165 (interactive "p")
9166 (let ((pos (point-at-eol)))
9167 (beginning-of-line 1)
9168 (when (> n 0)
9169 (while (and (> (setq n (1- n)) -1)
9170 (or (search-forward "|" pos t)
9171 (and force
9172 (progn (end-of-line 1)
9173 (skip-chars-backward "^|")
9174 (insert " | "))))))
9175 ; (backward-char 2) t)))))
9176 (when (and force (not (looking-at ".*|")))
9177 (save-excursion (end-of-line 1) (insert " | ")))
9178 (if on-delim
9179 (backward-char 1)
9180 (if (looking-at " ") (forward-char 1))))))
9182 (defun org-at-table-p (&optional table-type)
9183 "Return t if the cursor is inside an org-type table.
9184 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9185 (if org-enable-table-editor
9186 (save-excursion
9187 (beginning-of-line 1)
9188 (looking-at (if table-type org-table-any-line-regexp
9189 org-table-line-regexp)))
9190 nil))
9192 (defun org-at-table.el-p ()
9193 "Return t if and only if we are at a table.el table."
9194 (and (org-at-table-p 'any)
9195 (save-excursion
9196 (goto-char (org-table-begin 'any))
9197 (looking-at org-table1-hline-regexp))))
9199 (defun org-table-recognize-table.el ()
9200 "If there is a table.el table nearby, recognize it and move into it."
9201 (if org-table-tab-recognizes-table.el
9202 (if (org-at-table.el-p)
9203 (progn
9204 (beginning-of-line 1)
9205 (if (looking-at org-table-dataline-regexp)
9207 (if (looking-at org-table1-hline-regexp)
9208 (progn
9209 (beginning-of-line 2)
9210 (if (looking-at org-table-any-border-regexp)
9211 (beginning-of-line -1)))))
9212 (if (re-search-forward "|" (org-table-end t) t)
9213 (progn
9214 (require 'table)
9215 (if (table--at-cell-p (point))
9217 (message "recognizing table.el table...")
9218 (table-recognize-table)
9219 (message "recognizing table.el table...done")))
9220 (error "This should not happen..."))
9222 nil)
9223 nil))
9225 (defun org-at-table-hline-p ()
9226 "Return t if the cursor is inside a hline in a table."
9227 (if org-enable-table-editor
9228 (save-excursion
9229 (beginning-of-line 1)
9230 (looking-at org-table-hline-regexp))
9231 nil))
9233 (defun org-table-insert-column ()
9234 "Insert a new column into the table."
9235 (interactive)
9236 (if (not (org-at-table-p))
9237 (error "Not at a table"))
9238 (org-table-find-dataline)
9239 (let* ((col (max 1 (org-table-current-column)))
9240 (beg (org-table-begin))
9241 (end (org-table-end))
9242 ;; Current cursor position
9243 (linepos (org-current-line))
9244 (colpos col))
9245 (goto-char beg)
9246 (while (< (point) end)
9247 (if (org-at-table-hline-p)
9249 (org-table-goto-column col t)
9250 (insert "| "))
9251 (beginning-of-line 2))
9252 (move-marker end nil)
9253 (goto-line linepos)
9254 (org-table-goto-column colpos)
9255 (org-table-align)
9256 (org-table-fix-formulas "$" nil (1- col) 1)))
9258 (defun org-table-find-dataline ()
9259 "Find a dataline in the current table, which is needed for column commands."
9260 (if (and (org-at-table-p)
9261 (not (org-at-table-hline-p)))
9263 (let ((col (current-column))
9264 (end (org-table-end)))
9265 (move-to-column col)
9266 (while (and (< (point) end)
9267 (or (not (= (current-column) col))
9268 (org-at-table-hline-p)))
9269 (beginning-of-line 2)
9270 (move-to-column col))
9271 (if (and (org-at-table-p)
9272 (not (org-at-table-hline-p)))
9274 (error
9275 "Please position cursor in a data line for column operations")))))
9277 (defun org-table-delete-column ()
9278 "Delete a column from the table."
9279 (interactive)
9280 (if (not (org-at-table-p))
9281 (error "Not at a table"))
9282 (org-table-find-dataline)
9283 (org-table-check-inside-data-field)
9284 (let* ((col (org-table-current-column))
9285 (beg (org-table-begin))
9286 (end (org-table-end))
9287 ;; Current cursor position
9288 (linepos (org-current-line))
9289 (colpos col))
9290 (goto-char beg)
9291 (while (< (point) end)
9292 (if (org-at-table-hline-p)
9294 (org-table-goto-column col t)
9295 (and (looking-at "|[^|\n]+|")
9296 (replace-match "|")))
9297 (beginning-of-line 2))
9298 (move-marker end nil)
9299 (goto-line linepos)
9300 (org-table-goto-column colpos)
9301 (org-table-align)
9302 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9303 col -1 col)))
9305 (defun org-table-move-column-right ()
9306 "Move column to the right."
9307 (interactive)
9308 (org-table-move-column nil))
9309 (defun org-table-move-column-left ()
9310 "Move column to the left."
9311 (interactive)
9312 (org-table-move-column 'left))
9314 (defun org-table-move-column (&optional left)
9315 "Move the current column to the right. With arg LEFT, move to the left."
9316 (interactive "P")
9317 (if (not (org-at-table-p))
9318 (error "Not at a table"))
9319 (org-table-find-dataline)
9320 (org-table-check-inside-data-field)
9321 (let* ((col (org-table-current-column))
9322 (col1 (if left (1- col) col))
9323 (beg (org-table-begin))
9324 (end (org-table-end))
9325 ;; Current cursor position
9326 (linepos (org-current-line))
9327 (colpos (if left (1- col) (1+ col))))
9328 (if (and left (= col 1))
9329 (error "Cannot move column further left"))
9330 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9331 (error "Cannot move column further right"))
9332 (goto-char beg)
9333 (while (< (point) end)
9334 (if (org-at-table-hline-p)
9336 (org-table-goto-column col1 t)
9337 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9338 (replace-match "|\\2|\\1|")))
9339 (beginning-of-line 2))
9340 (move-marker end nil)
9341 (goto-line linepos)
9342 (org-table-goto-column colpos)
9343 (org-table-align)
9344 (org-table-fix-formulas
9345 "$" (list (cons (number-to-string col) (number-to-string colpos))
9346 (cons (number-to-string colpos) (number-to-string col))))))
9348 (defun org-table-move-row-down ()
9349 "Move table row down."
9350 (interactive)
9351 (org-table-move-row nil))
9352 (defun org-table-move-row-up ()
9353 "Move table row up."
9354 (interactive)
9355 (org-table-move-row 'up))
9357 (defun org-table-move-row (&optional up)
9358 "Move the current table line down. With arg UP, move it up."
9359 (interactive "P")
9360 (let* ((col (current-column))
9361 (pos (point))
9362 (hline1p (save-excursion (beginning-of-line 1)
9363 (looking-at org-table-hline-regexp)))
9364 (dline1 (org-table-current-dline))
9365 (dline2 (+ dline1 (if up -1 1)))
9366 (tonew (if up 0 2))
9367 txt hline2p)
9368 (beginning-of-line tonew)
9369 (unless (org-at-table-p)
9370 (goto-char pos)
9371 (error "Cannot move row further"))
9372 (setq hline2p (looking-at org-table-hline-regexp))
9373 (goto-char pos)
9374 (beginning-of-line 1)
9375 (setq pos (point))
9376 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9377 (delete-region (point) (1+ (point-at-eol)))
9378 (beginning-of-line tonew)
9379 (insert txt)
9380 (beginning-of-line 0)
9381 (move-to-column col)
9382 (unless (or hline1p hline2p)
9383 (org-table-fix-formulas
9384 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9385 (cons (number-to-string dline2) (number-to-string dline1)))))))
9387 (defun org-table-insert-row (&optional arg)
9388 "Insert a new row above the current line into the table.
9389 With prefix ARG, insert below the current line."
9390 (interactive "P")
9391 (if (not (org-at-table-p))
9392 (error "Not at a table"))
9393 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9394 (new (org-table-clean-line line)))
9395 ;; Fix the first field if necessary
9396 (if (string-match "^[ \t]*| *[#$] *|" line)
9397 (setq new (replace-match (match-string 0 line) t t new)))
9398 (beginning-of-line (if arg 2 1))
9399 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9400 (beginning-of-line 0)
9401 (re-search-forward "| ?" (point-at-eol) t)
9402 (and (or org-table-may-need-update org-table-overlay-coordinates)
9403 (org-table-align))
9404 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9406 (defun org-table-insert-hline (&optional above)
9407 "Insert a horizontal-line below the current line into the table.
9408 With prefix ABOVE, insert above the current line."
9409 (interactive "P")
9410 (if (not (org-at-table-p))
9411 (error "Not at a table"))
9412 (let ((line (org-table-clean-line
9413 (buffer-substring (point-at-bol) (point-at-eol))))
9414 (col (current-column)))
9415 (while (string-match "|\\( +\\)|" line)
9416 (setq line (replace-match
9417 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9418 ?-) "|") t t line)))
9419 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9420 (beginning-of-line (if above 1 2))
9421 (insert line "\n")
9422 (beginning-of-line (if above 1 -1))
9423 (move-to-column col)
9424 (and org-table-overlay-coordinates (org-table-align))))
9426 (defun org-table-hline-and-move (&optional same-column)
9427 "Insert a hline and move to the row below that line."
9428 (interactive "P")
9429 (let ((col (org-table-current-column)))
9430 (org-table-maybe-eval-formula)
9431 (org-table-maybe-recalculate-line)
9432 (org-table-insert-hline)
9433 (end-of-line 2)
9434 (if (looking-at "\n[ \t]*|-")
9435 (progn (insert "\n|") (org-table-align))
9436 (org-table-next-field))
9437 (if same-column (org-table-goto-column col))))
9439 (defun org-table-clean-line (s)
9440 "Convert a table line S into a string with only \"|\" and space.
9441 In particular, this does handle wide and invisible characters."
9442 (if (string-match "^[ \t]*|-" s)
9443 ;; It's a hline, just map the characters
9444 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9445 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9446 (setq s (replace-match
9447 (concat "|" (make-string (org-string-width (match-string 1 s))
9448 ?\ ) "|")
9449 t t s)))
9452 (defun org-table-kill-row ()
9453 "Delete the current row or horizontal line from the table."
9454 (interactive)
9455 (if (not (org-at-table-p))
9456 (error "Not at a table"))
9457 (let ((col (current-column))
9458 (dline (org-table-current-dline)))
9459 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9460 (if (not (org-at-table-p)) (beginning-of-line 0))
9461 (move-to-column col)
9462 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9463 dline -1 dline)))
9465 (defun org-table-sort-lines (with-case &optional sorting-type)
9466 "Sort table lines according to the column at point.
9468 The position of point indicates the column to be used for
9469 sorting, and the range of lines is the range between the nearest
9470 horizontal separator lines, or the entire table of no such lines
9471 exist. If point is before the first column, you will be prompted
9472 for the sorting column. If there is an active region, the mark
9473 specifies the first line and the sorting column, while point
9474 should be in the last line to be included into the sorting.
9476 The command then prompts for the sorting type which can be
9477 alphabetically, numerically, or by time (as given in a time stamp
9478 in the field). Sorting in reverse order is also possible.
9480 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9482 If SORTING-TYPE is specified when this function is called from a Lisp
9483 program, no prompting will take place. SORTING-TYPE must be a character,
9484 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9485 should be done in reverse order."
9486 (interactive "P")
9487 (let* ((thisline (org-current-line))
9488 (thiscol (org-table-current-column))
9489 beg end bcol ecol tend tbeg column lns pos)
9490 (when (equal thiscol 0)
9491 (if (interactive-p)
9492 (setq thiscol
9493 (string-to-number
9494 (read-string "Use column N for sorting: ")))
9495 (setq thiscol 1))
9496 (org-table-goto-column thiscol))
9497 (org-table-check-inside-data-field)
9498 (if (org-region-active-p)
9499 (progn
9500 (setq beg (region-beginning) end (region-end))
9501 (goto-char beg)
9502 (setq column (org-table-current-column)
9503 beg (point-at-bol))
9504 (goto-char end)
9505 (setq end (point-at-bol 2)))
9506 (setq column (org-table-current-column)
9507 pos (point)
9508 tbeg (org-table-begin)
9509 tend (org-table-end))
9510 (if (re-search-backward org-table-hline-regexp tbeg t)
9511 (setq beg (point-at-bol 2))
9512 (goto-char tbeg)
9513 (setq beg (point-at-bol 1)))
9514 (goto-char pos)
9515 (if (re-search-forward org-table-hline-regexp tend t)
9516 (setq end (point-at-bol 1))
9517 (goto-char tend)
9518 (setq end (point-at-bol))))
9519 (setq beg (move-marker (make-marker) beg)
9520 end (move-marker (make-marker) end))
9521 (untabify beg end)
9522 (goto-char beg)
9523 (org-table-goto-column column)
9524 (skip-chars-backward "^|")
9525 (setq bcol (current-column))
9526 (org-table-goto-column (1+ column))
9527 (skip-chars-backward "^|")
9528 (setq ecol (1- (current-column)))
9529 (org-table-goto-column column)
9530 (setq lns (mapcar (lambda(x) (cons
9531 (org-sort-remove-invisible
9532 (nth (1- column)
9533 (org-split-string x "[ \t]*|[ \t]*")))
9535 (org-split-string (buffer-substring beg end) "\n")))
9536 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9537 (delete-region beg end)
9538 (move-marker beg nil)
9539 (move-marker end nil)
9540 (insert (mapconcat 'cdr lns "\n") "\n")
9541 (goto-line thisline)
9542 (org-table-goto-column thiscol)
9543 (message "%d lines sorted, based on column %d" (length lns) column)))
9545 ;; FIXME: maybe we will not need this? Table sorting is broken....
9546 (defun org-sort-remove-invisible (s)
9547 (remove-text-properties 0 (length s) org-rm-props s)
9548 (while (string-match org-bracket-link-regexp s)
9549 (setq s (replace-match (if (match-end 2)
9550 (match-string 3 s)
9551 (match-string 1 s)) t t s)))
9554 (defun org-table-cut-region (beg end)
9555 "Copy region in table to the clipboard and blank all relevant fields."
9556 (interactive "r")
9557 (org-table-copy-region beg end 'cut))
9559 (defun org-table-copy-region (beg end &optional cut)
9560 "Copy rectangular region in table to clipboard.
9561 A special clipboard is used which can only be accessed
9562 with `org-table-paste-rectangle'."
9563 (interactive "rP")
9564 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9565 region cols
9566 (rpl (if cut " " nil)))
9567 (goto-char beg)
9568 (org-table-check-inside-data-field)
9569 (setq l01 (org-current-line)
9570 c01 (org-table-current-column))
9571 (goto-char end)
9572 (org-table-check-inside-data-field)
9573 (setq l02 (org-current-line)
9574 c02 (org-table-current-column))
9575 (setq l1 (min l01 l02) l2 (max l01 l02)
9576 c1 (min c01 c02) c2 (max c01 c02))
9577 (catch 'exit
9578 (while t
9579 (catch 'nextline
9580 (if (> l1 l2) (throw 'exit t))
9581 (goto-line l1)
9582 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9583 (setq cols nil ic1 c1 ic2 c2)
9584 (while (< ic1 (1+ ic2))
9585 (push (org-table-get-field ic1 rpl) cols)
9586 (setq ic1 (1+ ic1)))
9587 (push (nreverse cols) region)
9588 (setq l1 (1+ l1)))))
9589 (setq org-table-clip (nreverse region))
9590 (if cut (org-table-align))
9591 org-table-clip))
9593 (defun org-table-paste-rectangle ()
9594 "Paste a rectangular region into a table.
9595 The upper right corner ends up in the current field. All involved fields
9596 will be overwritten. If the rectangle does not fit into the present table,
9597 the table is enlarged as needed. The process ignores horizontal separator
9598 lines."
9599 (interactive)
9600 (unless (and org-table-clip (listp org-table-clip))
9601 (error "First cut/copy a region to paste!"))
9602 (org-table-check-inside-data-field)
9603 (let* ((clip org-table-clip)
9604 (line (org-current-line))
9605 (col (org-table-current-column))
9606 (org-enable-table-editor t)
9607 (org-table-automatic-realign nil)
9608 c cols field)
9609 (while (setq cols (pop clip))
9610 (while (org-at-table-hline-p) (beginning-of-line 2))
9611 (if (not (org-at-table-p))
9612 (progn (end-of-line 0) (org-table-next-field)))
9613 (setq c col)
9614 (while (setq field (pop cols))
9615 (org-table-goto-column c nil 'force)
9616 (org-table-get-field nil field)
9617 (setq c (1+ c)))
9618 (beginning-of-line 2))
9619 (goto-line line)
9620 (org-table-goto-column col)
9621 (org-table-align)))
9623 (defun org-table-convert ()
9624 "Convert from `org-mode' table to table.el and back.
9625 Obviously, this only works within limits. When an Org-mode table is
9626 converted to table.el, all horizontal separator lines get lost, because
9627 table.el uses these as cell boundaries and has no notion of horizontal lines.
9628 A table.el table can be converted to an Org-mode table only if it does not
9629 do row or column spanning. Multiline cells will become multiple cells.
9630 Beware, Org-mode does not test if the table can be successfully converted - it
9631 blindly applies a recipe that works for simple tables."
9632 (interactive)
9633 (require 'table)
9634 (if (org-at-table.el-p)
9635 ;; convert to Org-mode table
9636 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9637 (end (move-marker (make-marker) (org-table-end t))))
9638 (table-unrecognize-region beg end)
9639 (goto-char beg)
9640 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9641 (replace-match ""))
9642 (goto-char beg))
9643 (if (org-at-table-p)
9644 ;; convert to table.el table
9645 (let ((beg (move-marker (make-marker) (org-table-begin)))
9646 (end (move-marker (make-marker) (org-table-end))))
9647 ;; first, get rid of all horizontal lines
9648 (goto-char beg)
9649 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9650 (replace-match ""))
9651 ;; insert a hline before first
9652 (goto-char beg)
9653 (org-table-insert-hline 'above)
9654 (beginning-of-line -1)
9655 ;; insert a hline after each line
9656 (while (progn (beginning-of-line 3) (< (point) end))
9657 (org-table-insert-hline))
9658 (goto-char beg)
9659 (setq end (move-marker end (org-table-end)))
9660 ;; replace "+" at beginning and ending of hlines
9661 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9662 (replace-match "\\1+-"))
9663 (goto-char beg)
9664 (while (re-search-forward "-|[ \t]*$" end t)
9665 (replace-match "-+"))
9666 (goto-char beg)))))
9668 (defun org-table-wrap-region (arg)
9669 "Wrap several fields in a column like a paragraph.
9670 This is useful if you'd like to spread the contents of a field over several
9671 lines, in order to keep the table compact.
9673 If there is an active region, and both point and mark are in the same column,
9674 the text in the column is wrapped to minimum width for the given number of
9675 lines. Generally, this makes the table more compact. A prefix ARG may be
9676 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9677 formats the selected text to two lines. If the region was longer than two
9678 lines, the remaining lines remain empty. A negative prefix argument reduces
9679 the current number of lines by that amount. The wrapped text is pasted back
9680 into the table. If you formatted it to more lines than it was before, fields
9681 further down in the table get overwritten - so you might need to make space in
9682 the table first.
9684 If there is no region, the current field is split at the cursor position and
9685 the text fragment to the right of the cursor is prepended to the field one
9686 line down.
9688 If there is no region, but you specify a prefix ARG, the current field gets
9689 blank, and the content is appended to the field above."
9690 (interactive "P")
9691 (org-table-check-inside-data-field)
9692 (if (org-region-active-p)
9693 ;; There is a region: fill as a paragraph
9694 (let* ((beg (region-beginning))
9695 (cline (save-excursion (goto-char beg) (org-current-line)))
9696 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9697 nlines)
9698 (org-table-cut-region (region-beginning) (region-end))
9699 (if (> (length (car org-table-clip)) 1)
9700 (error "Region must be limited to single column"))
9701 (setq nlines (if arg
9702 (if (< arg 1)
9703 (+ (length org-table-clip) arg)
9704 arg)
9705 (length org-table-clip)))
9706 (setq org-table-clip
9707 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9708 nil nlines)))
9709 (goto-line cline)
9710 (org-table-goto-column ccol)
9711 (org-table-paste-rectangle))
9712 ;; No region, split the current field at point
9713 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9714 (skip-chars-forward "^\r\n|"))
9715 (if arg
9716 ;; combine with field above
9717 (let ((s (org-table-blank-field))
9718 (col (org-table-current-column)))
9719 (beginning-of-line 0)
9720 (while (org-at-table-hline-p) (beginning-of-line 0))
9721 (org-table-goto-column col)
9722 (skip-chars-forward "^|")
9723 (skip-chars-backward " ")
9724 (insert " " (org-trim s))
9725 (org-table-align))
9726 ;; split field
9727 (if (looking-at "\\([^|]+\\)+|")
9728 (let ((s (match-string 1)))
9729 (replace-match " |")
9730 (goto-char (match-beginning 0))
9731 (org-table-next-row)
9732 (insert (org-trim s) " ")
9733 (org-table-align))
9734 (org-table-next-row)))))
9736 (defvar org-field-marker nil)
9738 (defun org-table-edit-field (arg)
9739 "Edit table field in a different window.
9740 This is mainly useful for fields that contain hidden parts.
9741 When called with a \\[universal-argument] prefix, just make the full field visible so that
9742 it can be edited in place."
9743 (interactive "P")
9744 (if arg
9745 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9746 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9747 (remove-text-properties b e '(org-cwidth t invisible t
9748 display t intangible t))
9749 (if (and (boundp 'font-lock-mode) font-lock-mode)
9750 (font-lock-fontify-block)))
9751 (let ((pos (move-marker (make-marker) (point)))
9752 (field (org-table-get-field))
9753 (cw (current-window-configuration))
9755 (org-switch-to-buffer-other-window "*Org tmp*")
9756 (erase-buffer)
9757 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9758 (let ((org-inhibit-startup t)) (org-mode))
9759 (goto-char (setq p (point-max)))
9760 (insert (org-trim field))
9761 (remove-text-properties p (point-max)
9762 '(invisible t org-cwidth t display t
9763 intangible t))
9764 (goto-char p)
9765 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9766 (org-set-local 'org-window-configuration cw)
9767 (org-set-local 'org-field-marker pos)
9768 (message "Edit and finish with C-c C-c"))))
9770 (defun org-table-finish-edit-field ()
9771 "Finish editing a table data field.
9772 Remove all newline characters, insert the result into the table, realign
9773 the table and kill the editing buffer."
9774 (let ((pos org-field-marker)
9775 (cw org-window-configuration)
9776 (cb (current-buffer))
9777 text)
9778 (goto-char (point-min))
9779 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9780 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9781 (replace-match " "))
9782 (setq text (org-trim (buffer-string)))
9783 (set-window-configuration cw)
9784 (kill-buffer cb)
9785 (select-window (get-buffer-window (marker-buffer pos)))
9786 (goto-char pos)
9787 (move-marker pos nil)
9788 (org-table-check-inside-data-field)
9789 (org-table-get-field nil text)
9790 (org-table-align)
9791 (message "New field value inserted")))
9793 (defun org-trim (s)
9794 "Remove whitespace at beginning and end of string."
9795 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9796 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9799 (defun org-wrap (string &optional width lines)
9800 "Wrap string to either a number of lines, or a width in characters.
9801 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9802 that costs. If there is a word longer than WIDTH, the text is actually
9803 wrapped to the length of that word.
9804 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9805 many lines, whatever width that takes.
9806 The return value is a list of lines, without newlines at the end."
9807 (let* ((words (org-split-string string "[ \t\n]+"))
9808 (maxword (apply 'max (mapcar 'org-string-width words)))
9809 w ll)
9810 (cond (width
9811 (org-do-wrap words (max maxword width)))
9812 (lines
9813 (setq w maxword)
9814 (setq ll (org-do-wrap words maxword))
9815 (if (<= (length ll) lines)
9817 (setq ll words)
9818 (while (> (length ll) lines)
9819 (setq w (1+ w))
9820 (setq ll (org-do-wrap words w)))
9821 ll))
9822 (t (error "Cannot wrap this")))))
9825 (defun org-do-wrap (words width)
9826 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9827 (let (lines line)
9828 (while words
9829 (setq line (pop words))
9830 (while (and words (< (+ (length line) (length (car words))) width))
9831 (setq line (concat line " " (pop words))))
9832 (setq lines (push line lines)))
9833 (nreverse lines)))
9835 (defun org-split-string (string &optional separators)
9836 "Splits STRING into substrings at SEPARATORS.
9837 No empty strings are returned if there are matches at the beginning
9838 and end of string."
9839 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9840 (start 0)
9841 notfirst
9842 (list nil))
9843 (while (and (string-match rexp string
9844 (if (and notfirst
9845 (= start (match-beginning 0))
9846 (< start (length string)))
9847 (1+ start) start))
9848 (< (match-beginning 0) (length string)))
9849 (setq notfirst t)
9850 (or (eq (match-beginning 0) 0)
9851 (and (eq (match-beginning 0) (match-end 0))
9852 (eq (match-beginning 0) start))
9853 (setq list
9854 (cons (substring string start (match-beginning 0))
9855 list)))
9856 (setq start (match-end 0)))
9857 (or (eq start (length string))
9858 (setq list
9859 (cons (substring string start)
9860 list)))
9861 (nreverse list)))
9863 (defun org-table-map-tables (function)
9864 "Apply FUNCTION to the start of all tables in the buffer."
9865 (save-excursion
9866 (save-restriction
9867 (widen)
9868 (goto-char (point-min))
9869 (while (re-search-forward org-table-any-line-regexp nil t)
9870 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9871 (beginning-of-line 1)
9872 (if (looking-at org-table-line-regexp)
9873 (save-excursion (funcall function)))
9874 (re-search-forward org-table-any-border-regexp nil 1))))
9875 (message "Mapping tables: done"))
9877 (defvar org-timecnt) ; dynamically scoped parameter
9879 (defun org-table-sum (&optional beg end nlast)
9880 "Sum numbers in region of current table column.
9881 The result will be displayed in the echo area, and will be available
9882 as kill to be inserted with \\[yank].
9884 If there is an active region, it is interpreted as a rectangle and all
9885 numbers in that rectangle will be summed. If there is no active
9886 region and point is located in a table column, sum all numbers in that
9887 column.
9889 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9890 numbers are assumed to be times as well (in decimal hours) and the
9891 numbers are added as such.
9893 If NLAST is a number, only the NLAST fields will actually be summed."
9894 (interactive)
9895 (save-excursion
9896 (let (col (org-timecnt 0) diff h m s org-table-clip)
9897 (cond
9898 ((and beg end)) ; beg and end given explicitly
9899 ((org-region-active-p)
9900 (setq beg (region-beginning) end (region-end)))
9902 (setq col (org-table-current-column))
9903 (goto-char (org-table-begin))
9904 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9905 (error "No table data"))
9906 (org-table-goto-column col)
9907 (setq beg (point))
9908 (goto-char (org-table-end))
9909 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9910 (error "No table data"))
9911 (org-table-goto-column col)
9912 (setq end (point))))
9913 (let* ((items (apply 'append (org-table-copy-region beg end)))
9914 (items1 (cond ((not nlast) items)
9915 ((>= nlast (length items)) items)
9916 (t (setq items (reverse items))
9917 (setcdr (nthcdr (1- nlast) items) nil)
9918 (nreverse items))))
9919 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9920 items1)))
9921 (res (apply '+ numbers))
9922 (sres (if (= org-timecnt 0)
9923 (format "%g" res)
9924 (setq diff (* 3600 res)
9925 h (floor (/ diff 3600)) diff (mod diff 3600)
9926 m (floor (/ diff 60)) diff (mod diff 60)
9927 s diff)
9928 (format "%d:%02d:%02d" h m s))))
9929 (kill-new sres)
9930 (if (interactive-p)
9931 (message "%s"
9932 (substitute-command-keys
9933 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9934 (length numbers) sres))))
9935 sres))))
9937 (defun org-table-get-number-for-summing (s)
9938 (let (n)
9939 (if (string-match "^ *|? *" s)
9940 (setq s (replace-match "" nil nil s)))
9941 (if (string-match " *|? *$" s)
9942 (setq s (replace-match "" nil nil s)))
9943 (setq n (string-to-number s))
9944 (cond
9945 ((and (string-match "0" s)
9946 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9947 ((string-match "\\`[ \t]+\\'" s) nil)
9948 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9949 (let ((h (string-to-number (or (match-string 1 s) "0")))
9950 (m (string-to-number (or (match-string 2 s) "0")))
9951 (s (string-to-number (or (match-string 4 s) "0"))))
9952 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9953 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9954 ((equal n 0) nil)
9955 (t n))))
9957 (defun org-table-current-field-formula (&optional key noerror)
9958 "Return the formula active for the current field.
9959 Assumes that specials are in place.
9960 If KEY is given, return the key to this formula.
9961 Otherwise return the formula preceeded with \"=\" or \":=\"."
9962 (let* ((name (car (rassoc (list (org-current-line)
9963 (org-table-current-column))
9964 org-table-named-field-locations)))
9965 (col (org-table-current-column))
9966 (scol (int-to-string col))
9967 (ref (format "@%d$%d" (org-table-current-dline) col))
9968 (stored-list (org-table-get-stored-formulas noerror))
9969 (ass (or (assoc name stored-list)
9970 (assoc ref stored-list)
9971 (assoc scol stored-list))))
9972 (if key
9973 (car ass)
9974 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9975 (cdr ass))))))
9977 (defun org-table-get-formula (&optional equation named)
9978 "Read a formula from the minibuffer, offer stored formula as default.
9979 When NAMED is non-nil, look for a named equation."
9980 (let* ((stored-list (org-table-get-stored-formulas))
9981 (name (car (rassoc (list (org-current-line)
9982 (org-table-current-column))
9983 org-table-named-field-locations)))
9984 (ref (format "@%d$%d" (org-table-current-dline)
9985 (org-table-current-column)))
9986 (refass (assoc ref stored-list))
9987 (scol (if named
9988 (if name name ref)
9989 (int-to-string (org-table-current-column))))
9990 (dummy (and (or name refass) (not named)
9991 (not (y-or-n-p "Replace field formula with column formula? " ))
9992 (error "Abort")))
9993 (name (or name ref))
9994 (org-table-may-need-update nil)
9995 (stored (cdr (assoc scol stored-list)))
9996 (eq (cond
9997 ((and stored equation (string-match "^ *=? *$" equation))
9998 stored)
9999 ((stringp equation)
10000 equation)
10001 (t (org-table-formula-from-user
10002 (read-string
10003 (org-table-formula-to-user
10004 (format "%s formula %s%s="
10005 (if named "Field" "Column")
10006 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
10007 scol))
10008 (if stored (org-table-formula-to-user stored) "")
10009 'org-table-formula-history
10010 )))))
10011 mustsave)
10012 (when (not (string-match "\\S-" eq))
10013 ;; remove formula
10014 (setq stored-list (delq (assoc scol stored-list) stored-list))
10015 (org-table-store-formulas stored-list)
10016 (error "Formula removed"))
10017 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
10018 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
10019 (if (and name (not named))
10020 ;; We set the column equation, delete the named one.
10021 (setq stored-list (delq (assoc name stored-list) stored-list)
10022 mustsave t))
10023 (if stored
10024 (setcdr (assoc scol stored-list) eq)
10025 (setq stored-list (cons (cons scol eq) stored-list)))
10026 (if (or mustsave (not (equal stored eq)))
10027 (org-table-store-formulas stored-list))
10028 eq))
10030 (defun org-table-store-formulas (alist)
10031 "Store the list of formulas below the current table."
10032 (setq alist (sort alist 'org-table-formula-less-p))
10033 (save-excursion
10034 (goto-char (org-table-end))
10035 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10036 (progn
10037 ;; don't overwrite TBLFM, we might use text properties to store stuff
10038 (goto-char (match-beginning 2))
10039 (delete-region (match-beginning 2) (match-end 0)))
10040 (insert "#+TBLFM:"))
10041 (insert " "
10042 (mapconcat (lambda (x)
10043 (concat
10044 (if (equal (string-to-char (car x)) ?@) "" "$")
10045 (car x) "=" (cdr x)))
10046 alist "::")
10047 "\n")))
10049 (defsubst org-table-formula-make-cmp-string (a)
10050 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10051 (concat
10052 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10053 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10054 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10056 (defun org-table-formula-less-p (a b)
10057 "Compare two formulas for sorting."
10058 (let ((as (org-table-formula-make-cmp-string (car a)))
10059 (bs (org-table-formula-make-cmp-string (car b))))
10060 (and as bs (string< as bs))))
10062 (defun org-table-get-stored-formulas (&optional noerror)
10063 "Return an alist with the stored formulas directly after current table."
10064 (interactive)
10065 (let (scol eq eq-alist strings string seen)
10066 (save-excursion
10067 (goto-char (org-table-end))
10068 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10069 (setq strings (org-split-string (match-string 2) " *:: *"))
10070 (while (setq string (pop strings))
10071 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10072 (setq scol (if (match-end 2)
10073 (match-string 2 string)
10074 (match-string 1 string))
10075 eq (match-string 3 string)
10076 eq-alist (cons (cons scol eq) eq-alist))
10077 (if (member scol seen)
10078 (if noerror
10079 (progn
10080 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10081 (ding)
10082 (sit-for 2))
10083 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10084 (push scol seen))))))
10085 (nreverse eq-alist)))
10087 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10088 "Modify the equations after the table structure has been edited.
10089 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10090 For all numbers larger than LIMIT, shift them by DELTA."
10091 (save-excursion
10092 (goto-char (org-table-end))
10093 (when (looking-at "#\\+TBLFM:")
10094 (let ((re (concat key "\\([0-9]+\\)"))
10095 (re2
10096 (when remove
10097 (if (equal key "$")
10098 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10099 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10100 s n a)
10101 (when remove
10102 (while (re-search-forward re2 (point-at-eol) t)
10103 (replace-match "")))
10104 (while (re-search-forward re (point-at-eol) t)
10105 (setq s (match-string 1) n (string-to-number s))
10106 (cond
10107 ((setq a (assoc s replace))
10108 (replace-match (concat key (cdr a)) t t))
10109 ((and limit (> n limit))
10110 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10112 (defun org-table-get-specials ()
10113 "Get the column names and local parameters for this table."
10114 (save-excursion
10115 (let ((beg (org-table-begin)) (end (org-table-end))
10116 names name fields fields1 field cnt
10117 c v l line col types dlines hlines)
10118 (setq org-table-column-names nil
10119 org-table-local-parameters nil
10120 org-table-named-field-locations nil
10121 org-table-current-begin-line nil
10122 org-table-current-begin-pos nil
10123 org-table-current-line-types nil)
10124 (goto-char beg)
10125 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10126 (setq names (org-split-string (match-string 1) " *| *")
10127 cnt 1)
10128 (while (setq name (pop names))
10129 (setq cnt (1+ cnt))
10130 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10131 (push (cons name (int-to-string cnt)) org-table-column-names))))
10132 (setq org-table-column-names (nreverse org-table-column-names))
10133 (setq org-table-column-name-regexp
10134 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10135 (goto-char beg)
10136 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10137 (setq fields (org-split-string (match-string 1) " *| *"))
10138 (while (setq field (pop fields))
10139 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10140 (push (cons (match-string 1 field) (match-string 2 field))
10141 org-table-local-parameters))))
10142 (goto-char beg)
10143 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10144 (setq c (match-string 1)
10145 fields (org-split-string (match-string 2) " *| *"))
10146 (save-excursion
10147 (beginning-of-line (if (equal c "_") 2 0))
10148 (setq line (org-current-line) col 1)
10149 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10150 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10151 (while (and fields1 (setq field (pop fields)))
10152 (setq v (pop fields1) col (1+ col))
10153 (when (and (stringp field) (stringp v)
10154 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10155 (push (cons field v) org-table-local-parameters)
10156 (push (list field line col) org-table-named-field-locations))))
10157 ;; Analyse the line types
10158 (goto-char beg)
10159 (setq org-table-current-begin-line (org-current-line)
10160 org-table-current-begin-pos (point)
10161 l org-table-current-begin-line)
10162 (while (looking-at "[ \t]*|\\(-\\)?")
10163 (push (if (match-end 1) 'hline 'dline) types)
10164 (if (match-end 1) (push l hlines) (push l dlines))
10165 (beginning-of-line 2)
10166 (setq l (1+ l)))
10167 (setq org-table-current-line-types (apply 'vector (nreverse types))
10168 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10169 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10171 (defun org-table-maybe-eval-formula ()
10172 "Check if the current field starts with \"=\" or \":=\".
10173 If yes, store the formula and apply it."
10174 ;; We already know we are in a table. Get field will only return a formula
10175 ;; when appropriate. It might return a separator line, but no problem.
10176 (when org-table-formula-evaluate-inline
10177 (let* ((field (org-trim (or (org-table-get-field) "")))
10178 named eq)
10179 (when (string-match "^:?=\\(.*\\)" field)
10180 (setq named (equal (string-to-char field) ?:)
10181 eq (match-string 1 field))
10182 (if (or (fboundp 'calc-eval)
10183 (equal (substring eq 0 (min 2 (length eq))) "'("))
10184 (org-table-eval-formula (if named '(4) nil)
10185 (org-table-formula-from-user eq))
10186 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10188 (defvar org-recalc-commands nil
10189 "List of commands triggering the recalculation of a line.
10190 Will be filled automatically during use.")
10192 (defvar org-recalc-marks
10193 '((" " . "Unmarked: no special line, no automatic recalculation")
10194 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10195 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10196 ("!" . "Column name definition line. Reference in formula as $name.")
10197 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10198 ("_" . "Names for values in row below this one.")
10199 ("^" . "Names for values in row above this one.")))
10201 (defun org-table-rotate-recalc-marks (&optional newchar)
10202 "Rotate the recalculation mark in the first column.
10203 If in any row, the first field is not consistent with a mark,
10204 insert a new column for the markers.
10205 When there is an active region, change all the lines in the region,
10206 after prompting for the marking character.
10207 After each change, a message will be displayed indicating the meaning
10208 of the new mark."
10209 (interactive)
10210 (unless (org-at-table-p) (error "Not at a table"))
10211 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10212 (beg (org-table-begin))
10213 (end (org-table-end))
10214 (l (org-current-line))
10215 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10216 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10217 (have-col
10218 (save-excursion
10219 (goto-char beg)
10220 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10221 (col (org-table-current-column))
10222 (forcenew (car (assoc newchar org-recalc-marks)))
10223 epos new)
10224 (when l1
10225 (message "Change region to what mark? Type # * ! $ or SPC: ")
10226 (setq newchar (char-to-string (read-char-exclusive))
10227 forcenew (car (assoc newchar org-recalc-marks))))
10228 (if (and newchar (not forcenew))
10229 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10230 newchar))
10231 (if l1 (goto-line l1))
10232 (save-excursion
10233 (beginning-of-line 1)
10234 (unless (looking-at org-table-dataline-regexp)
10235 (error "Not at a table data line")))
10236 (unless have-col
10237 (org-table-goto-column 1)
10238 (org-table-insert-column)
10239 (org-table-goto-column (1+ col)))
10240 (setq epos (point-at-eol))
10241 (save-excursion
10242 (beginning-of-line 1)
10243 (org-table-get-field
10244 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10245 (concat " "
10246 (setq new (or forcenew
10247 (cadr (member (match-string 1) marks))))
10248 " ")
10249 " # ")))
10250 (if (and l1 l2)
10251 (progn
10252 (goto-line l1)
10253 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10254 (and (looking-at org-table-dataline-regexp)
10255 (org-table-get-field 1 (concat " " new " "))))
10256 (goto-line l1)))
10257 (if (not (= epos (point-at-eol))) (org-table-align))
10258 (goto-line l)
10259 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10261 (defun org-table-maybe-recalculate-line ()
10262 "Recompute the current line if marked for it, and if we haven't just done it."
10263 (interactive)
10264 (and org-table-allow-automatic-line-recalculation
10265 (not (and (memq last-command org-recalc-commands)
10266 (equal org-last-recalc-line (org-current-line))))
10267 (save-excursion (beginning-of-line 1)
10268 (looking-at org-table-auto-recalculate-regexp))
10269 (org-table-recalculate) t))
10271 (defvar org-table-formula-debug nil
10272 "Non-nil means, debug table formulas.
10273 When nil, simply write \"#ERROR\" in corrupted fields.")
10274 (make-variable-buffer-local 'org-table-formula-debug)
10276 (defvar modes)
10277 (defsubst org-set-calc-mode (var &optional value)
10278 (if (stringp var)
10279 (setq var (assoc var '(("D" calc-angle-mode deg)
10280 ("R" calc-angle-mode rad)
10281 ("F" calc-prefer-frac t)
10282 ("S" calc-symbolic-mode t)))
10283 value (nth 2 var) var (nth 1 var)))
10284 (if (memq var modes)
10285 (setcar (cdr (memq var modes)) value)
10286 (cons var (cons value modes)))
10287 modes)
10289 (defun org-table-eval-formula (&optional arg equation
10290 suppress-align suppress-const
10291 suppress-store suppress-analysis)
10292 "Replace the table field value at the cursor by the result of a calculation.
10294 This function makes use of Dave Gillespie's Calc package, in my view the
10295 most exciting program ever written for GNU Emacs. So you need to have Calc
10296 installed in order to use this function.
10298 In a table, this command replaces the value in the current field with the
10299 result of a formula. It also installs the formula as the \"current\" column
10300 formula, by storing it in a special line below the table. When called
10301 with a `C-u' prefix, the current field must ba a named field, and the
10302 formula is installed as valid in only this specific field.
10304 When called with two `C-u' prefixes, insert the active equation
10305 for the field back into the current field, so that it can be
10306 edited there. This is useful in order to use \\[org-table-show-reference]
10307 to check the referenced fields.
10309 When called, the command first prompts for a formula, which is read in
10310 the minibuffer. Previously entered formulas are available through the
10311 history list, and the last used formula is offered as a default.
10312 These stored formulas are adapted correctly when moving, inserting, or
10313 deleting columns with the corresponding commands.
10315 The formula can be any algebraic expression understood by the Calc package.
10316 For details, see the Org-mode manual.
10318 This function can also be called from Lisp programs and offers
10319 additional arguments: EQUATION can be the formula to apply. If this
10320 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10321 used to speed-up recursive calls by by-passing unnecessary aligns.
10322 SUPPRESS-CONST suppresses the interpretation of constants in the
10323 formula, assuming that this has been done already outside the function.
10324 SUPPRESS-STORE means the formula should not be stored, either because
10325 it is already stored, or because it is a modified equation that should
10326 not overwrite the stored one."
10327 (interactive "P")
10328 (org-table-check-inside-data-field)
10329 (or suppress-analysis (org-table-get-specials))
10330 (if (equal arg '(16))
10331 (let ((eq (org-table-current-field-formula)))
10332 (or eq (error "No equation active for current field"))
10333 (org-table-get-field nil eq)
10334 (org-table-align)
10335 (setq org-table-may-need-update t))
10336 (let* (fields
10337 (ndown (if (integerp arg) arg 1))
10338 (org-table-automatic-realign nil)
10339 (case-fold-search nil)
10340 (down (> ndown 1))
10341 (formula (if (and equation suppress-store)
10342 equation
10343 (org-table-get-formula equation (equal arg '(4)))))
10344 (n0 (org-table-current-column))
10345 (modes (copy-sequence org-calc-default-modes))
10346 (numbers nil) ; was a variable, now fixed default
10347 (keep-empty nil)
10348 n form form0 bw fmt x ev orig c lispp literal)
10349 ;; Parse the format string. Since we have a lot of modes, this is
10350 ;; a lot of work. However, I think calc still uses most of the time.
10351 (if (string-match ";" formula)
10352 (let ((tmp (org-split-string formula ";")))
10353 (setq formula (car tmp)
10354 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10355 (nth 1 tmp)))
10356 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10357 (setq c (string-to-char (match-string 1 fmt))
10358 n (string-to-number (match-string 2 fmt)))
10359 (if (= c ?p)
10360 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10361 (setq modes (org-set-calc-mode
10362 'calc-float-format
10363 (list (cdr (assoc c '((?n . float) (?f . fix)
10364 (?s . sci) (?e . eng))))
10365 n))))
10366 (setq fmt (replace-match "" t t fmt)))
10367 (if (string-match "[NT]" fmt)
10368 (setq numbers (equal (match-string 0 fmt) "N")
10369 fmt (replace-match "" t t fmt)))
10370 (if (string-match "L" fmt)
10371 (setq literal t
10372 fmt (replace-match "" t t fmt)))
10373 (if (string-match "E" fmt)
10374 (setq keep-empty t
10375 fmt (replace-match "" t t fmt)))
10376 (while (string-match "[DRFS]" fmt)
10377 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10378 (setq fmt (replace-match "" t t fmt)))
10379 (unless (string-match "\\S-" fmt)
10380 (setq fmt nil))))
10381 (if (and (not suppress-const) org-table-formula-use-constants)
10382 (setq formula (org-table-formula-substitute-names formula)))
10383 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10384 (while (> ndown 0)
10385 (setq fields (org-split-string
10386 (org-no-properties
10387 (buffer-substring (point-at-bol) (point-at-eol)))
10388 " *| *"))
10389 (if (eq numbers t)
10390 (setq fields (mapcar
10391 (lambda (x) (number-to-string (string-to-number x)))
10392 fields)))
10393 (setq ndown (1- ndown))
10394 (setq form (copy-sequence formula)
10395 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10396 (if (and lispp literal) (setq lispp 'literal))
10397 ;; Check for old vertical references
10398 (setq form (org-rewrite-old-row-references form))
10399 ;; Insert complex ranges
10400 (while (string-match org-table-range-regexp form)
10401 (setq form
10402 (replace-match
10403 (save-match-data
10404 (org-table-make-reference
10405 (org-table-get-range (match-string 0 form) nil n0)
10406 keep-empty numbers lispp))
10407 t t form)))
10408 ;; Insert simple ranges
10409 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10410 (setq form
10411 (replace-match
10412 (save-match-data
10413 (org-table-make-reference
10414 (org-sublist
10415 fields (string-to-number (match-string 1 form))
10416 (string-to-number (match-string 2 form)))
10417 keep-empty numbers lispp))
10418 t t form)))
10419 (setq form0 form)
10420 ;; Insert the references to fields in same row
10421 (while (string-match "\\$\\([0-9]+\\)" form)
10422 (setq n (string-to-number (match-string 1 form))
10423 x (nth (1- (if (= n 0) n0 n)) fields))
10424 (unless x (error "Invalid field specifier \"%s\""
10425 (match-string 0 form)))
10426 (setq form (replace-match
10427 (save-match-data
10428 (org-table-make-reference x nil numbers lispp))
10429 t t form)))
10431 (if lispp
10432 (setq ev (condition-case nil
10433 (eval (eval (read form)))
10434 (error "#ERROR"))
10435 ev (if (numberp ev) (number-to-string ev) ev))
10436 (or (fboundp 'calc-eval)
10437 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10438 (setq ev (calc-eval (cons form modes)
10439 (if numbers 'num))))
10441 (when org-table-formula-debug
10442 (with-output-to-temp-buffer "*Substitution History*"
10443 (princ (format "Substitution history of formula
10444 Orig: %s
10445 $xyz-> %s
10446 @r$c-> %s
10447 $1-> %s\n" orig formula form0 form))
10448 (if (listp ev)
10449 (princ (format " %s^\nError: %s"
10450 (make-string (car ev) ?\-) (nth 1 ev)))
10451 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10452 ev (or fmt "NONE")
10453 (if fmt (format fmt (string-to-number ev)) ev)))))
10454 (setq bw (get-buffer-window "*Substitution History*"))
10455 (shrink-window-if-larger-than-buffer bw)
10456 (unless (and (interactive-p) (not ndown))
10457 (unless (let (inhibit-redisplay)
10458 (y-or-n-p "Debugging Formula. Continue to next? "))
10459 (org-table-align)
10460 (error "Abort"))
10461 (delete-window bw)
10462 (message "")))
10463 (if (listp ev) (setq fmt nil ev "#ERROR"))
10464 (org-table-justify-field-maybe
10465 (if fmt (format fmt (string-to-number ev)) ev))
10466 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10467 (call-interactively 'org-return)
10468 (setq ndown 0)))
10469 (and down (org-table-maybe-recalculate-line))
10470 (or suppress-align (and org-table-may-need-update
10471 (org-table-align))))))
10473 (defun org-table-put-field-property (prop value)
10474 (save-excursion
10475 (put-text-property (progn (skip-chars-backward "^|") (point))
10476 (progn (skip-chars-forward "^|") (point))
10477 prop value)))
10479 (defun org-table-get-range (desc &optional tbeg col highlight)
10480 "Get a calc vector from a column, accorting to descriptor DESC.
10481 Optional arguments TBEG and COL can give the beginning of the table and
10482 the current column, to avoid unnecessary parsing.
10483 HIGHLIGHT means, just highlight the range."
10484 (if (not (equal (string-to-char desc) ?@))
10485 (setq desc (concat "@" desc)))
10486 (save-excursion
10487 (or tbeg (setq tbeg (org-table-begin)))
10488 (or col (setq col (org-table-current-column)))
10489 (let ((thisline (org-current-line))
10490 beg end c1 c2 r1 r2 rangep tmp)
10491 (unless (string-match org-table-range-regexp desc)
10492 (error "Invalid table range specifier `%s'" desc))
10493 (setq rangep (match-end 3)
10494 r1 (and (match-end 1) (match-string 1 desc))
10495 r2 (and (match-end 4) (match-string 4 desc))
10496 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10497 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10499 (and c1 (setq c1 (+ (string-to-number c1)
10500 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10501 (and c2 (setq c2 (+ (string-to-number c2)
10502 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10503 (if (equal r1 "") (setq r1 nil))
10504 (if (equal r2 "") (setq r2 nil))
10505 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10506 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10507 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10508 (if (not r1) (setq r1 thisline))
10509 (if (not r2) (setq r2 thisline))
10510 (if (not c1) (setq c1 col))
10511 (if (not c2) (setq c2 col))
10512 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10513 ;; just one field
10514 (progn
10515 (goto-line r1)
10516 (while (not (looking-at org-table-dataline-regexp))
10517 (beginning-of-line 2))
10518 (prog1 (org-trim (org-table-get-field c1))
10519 (if highlight (org-table-highlight-rectangle (point) (point)))))
10520 ;; A range, return a vector
10521 ;; First sort the numbers to get a regular ractangle
10522 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10523 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10524 (goto-line r1)
10525 (while (not (looking-at org-table-dataline-regexp))
10526 (beginning-of-line 2))
10527 (org-table-goto-column c1)
10528 (setq beg (point))
10529 (goto-line r2)
10530 (while (not (looking-at org-table-dataline-regexp))
10531 (beginning-of-line 0))
10532 (org-table-goto-column c2)
10533 (setq end (point))
10534 (if highlight
10535 (org-table-highlight-rectangle
10536 beg (progn (skip-chars-forward "^|\n") (point))))
10537 ;; return string representation of calc vector
10538 (mapcar 'org-trim
10539 (apply 'append (org-table-copy-region beg end)))))))
10541 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10542 "Analyze descriptor DESC and retrieve the corresponding line number.
10543 The cursor is currently in line CLINE, the table begins in line BLINE,
10544 and TABLE is a vector with line types."
10545 (if (string-match "^[0-9]+$" desc)
10546 (aref org-table-dlines (string-to-number desc))
10547 (setq cline (or cline (org-current-line))
10548 bline (or bline org-table-current-begin-line)
10549 table (or table org-table-current-line-types))
10550 (if (or
10551 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10552 ;; 1 2 3 4 5 6
10553 (and (not (match-end 3)) (not (match-end 6)))
10554 (and (match-end 3) (match-end 6) (not (match-end 5))))
10555 (error "invalid row descriptor `%s'" desc))
10556 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10557 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10558 (odir (and (match-end 5) (match-string 5 desc)))
10559 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10560 (i (- cline bline))
10561 (rel (and (match-end 6)
10562 (or (and (match-end 1) (not (match-end 3)))
10563 (match-end 5)))))
10564 (if (and hn (not hdir))
10565 (progn
10566 (setq i 0 hdir "+")
10567 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10568 (if (and (not hn) on (not odir))
10569 (error "should never happen");;(aref org-table-dlines on)
10570 (if (and hn (> hn 0))
10571 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10572 (if on
10573 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10574 (+ bline i)))))
10576 (defun org-find-row-type (table i type backwards relative n)
10577 (let ((l (length table)))
10578 (while (> n 0)
10579 (while (and (setq i (+ i (if backwards -1 1)))
10580 (>= i 0) (< i l)
10581 (not (eq (aref table i) type))
10582 (if (and relative (eq (aref table i) 'hline))
10583 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10584 t)))
10585 (setq n (1- n)))
10586 (if (or (< i 0) (>= i l))
10587 (error "Row descriptor leads outside table")
10588 i)))
10590 (defun org-rewrite-old-row-references (s)
10591 (if (string-match "&[-+0-9I]" s)
10592 (error "Formula contains old &row reference, please rewrite using @-syntax")
10595 (defun org-table-make-reference (elements keep-empty numbers lispp)
10596 "Convert list ELEMENTS to something appropriate to insert into formula.
10597 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10598 NUMBERS indicates that everything should be converted to numbers.
10599 LISPP means to return something appropriate for a Lisp list."
10600 (if (stringp elements) ; just a single val
10601 (if lispp
10602 (if (eq lispp 'literal)
10603 elements
10604 (prin1-to-string (if numbers (string-to-number elements) elements)))
10605 (if (equal elements "") (setq elements "0"))
10606 (if numbers (number-to-string (string-to-number elements)) elements))
10607 (unless keep-empty
10608 (setq elements
10609 (delq nil
10610 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10611 elements))))
10612 (setq elements (or elements '("0")))
10613 (if lispp
10614 (mapconcat
10615 (lambda (x)
10616 (if (eq lispp 'literal)
10618 (prin1-to-string (if numbers (string-to-number x) x))))
10619 elements " ")
10620 (concat "[" (mapconcat
10621 (lambda (x)
10622 (if numbers (number-to-string (string-to-number x)) x))
10623 elements
10624 ",") "]"))))
10626 (defun org-table-recalculate (&optional all noalign)
10627 "Recalculate the current table line by applying all stored formulas.
10628 With prefix arg ALL, do this for all lines in the table."
10629 (interactive "P")
10630 (or (memq this-command org-recalc-commands)
10631 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10632 (unless (org-at-table-p) (error "Not at a table"))
10633 (if (equal all '(16))
10634 (org-table-iterate)
10635 (org-table-get-specials)
10636 (let* ((eqlist (sort (org-table-get-stored-formulas)
10637 (lambda (a b) (string< (car a) (car b)))))
10638 (inhibit-redisplay (not debug-on-error))
10639 (line-re org-table-dataline-regexp)
10640 (thisline (org-current-line))
10641 (thiscol (org-table-current-column))
10642 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10643 ;; Insert constants in all formulas
10644 (setq eqlist
10645 (mapcar (lambda (x)
10646 (setcdr x (org-table-formula-substitute-names (cdr x)))
10648 eqlist))
10649 ;; Split the equation list
10650 (while (setq eq (pop eqlist))
10651 (if (<= (string-to-char (car eq)) ?9)
10652 (push eq eqlnum)
10653 (push eq eqlname)))
10654 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10655 (if all
10656 (progn
10657 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10658 (goto-char (setq beg (org-table-begin)))
10659 (if (re-search-forward org-table-calculate-mark-regexp end t)
10660 ;; This is a table with marked lines, compute selected lines
10661 (setq line-re org-table-recalculate-regexp)
10662 ;; Move forward to the first non-header line
10663 (if (and (re-search-forward org-table-dataline-regexp end t)
10664 (re-search-forward org-table-hline-regexp end t)
10665 (re-search-forward org-table-dataline-regexp end t))
10666 (setq beg (match-beginning 0))
10667 nil))) ;; just leave beg where it is
10668 (setq beg (point-at-bol)
10669 end (move-marker (make-marker) (1+ (point-at-eol)))))
10670 (goto-char beg)
10671 (and all (message "Re-applying formulas to full table..."))
10673 ;; First find the named fields, and mark them untouchanble
10674 (remove-text-properties beg end '(org-untouchable t))
10675 (while (setq eq (pop eqlname))
10676 (setq name (car eq)
10677 a (assoc name org-table-named-field-locations))
10678 (and (not a)
10679 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10680 (setq a (list name
10681 (aref org-table-dlines
10682 (string-to-number (match-string 1 name)))
10683 (string-to-number (match-string 2 name)))))
10684 (when (and a (or all (equal (nth 1 a) thisline)))
10685 (message "Re-applying formula to field: %s" name)
10686 (goto-line (nth 1 a))
10687 (org-table-goto-column (nth 2 a))
10688 (push (append a (list (cdr eq))) eqlname1)
10689 (org-table-put-field-property :org-untouchable t)))
10691 ;; Now evauluate the column formulas, but skip fields covered by
10692 ;; field formulas
10693 (goto-char beg)
10694 (while (re-search-forward line-re end t)
10695 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10696 ;; Unprotected line, recalculate
10697 (and all (message "Re-applying formulas to full table...(line %d)"
10698 (setq cnt (1+ cnt))))
10699 (setq org-last-recalc-line (org-current-line))
10700 (setq eql eqlnum)
10701 (while (setq entry (pop eql))
10702 (goto-line org-last-recalc-line)
10703 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10704 (unless (get-text-property (point) :org-untouchable)
10705 (org-table-eval-formula nil (cdr entry)
10706 'noalign 'nocst 'nostore 'noanalysis)))))
10708 ;; Now evaluate the field formulas
10709 (while (setq eq (pop eqlname1))
10710 (message "Re-applying formula to field: %s" (car eq))
10711 (goto-line (nth 1 eq))
10712 (org-table-goto-column (nth 2 eq))
10713 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10714 'nostore 'noanalysis))
10716 (goto-line thisline)
10717 (org-table-goto-column thiscol)
10718 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10719 (or noalign (and org-table-may-need-update (org-table-align))
10720 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10722 ;; back to initial position
10723 (message "Re-applying formulas...done")
10724 (goto-line thisline)
10725 (org-table-goto-column thiscol)
10726 (or noalign (and org-table-may-need-update (org-table-align))
10727 (and all (message "Re-applying formulas...done"))))))
10729 (defun org-table-iterate (&optional arg)
10730 "Recalculate the table until it does not change anymore."
10731 (interactive "P")
10732 (let ((imax (if arg (prefix-numeric-value arg) 10))
10733 (i 0)
10734 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10735 thistbl)
10736 (catch 'exit
10737 (while (< i imax)
10738 (setq i (1+ i))
10739 (org-table-recalculate 'all)
10740 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10741 (if (not (string= lasttbl thistbl))
10742 (setq lasttbl thistbl)
10743 (if (> i 1)
10744 (message "Convergence after %d iterations" i)
10745 (message "Table was already stable"))
10746 (throw 'exit t)))
10747 (error "No convergence after %d iterations" i))))
10749 (defun org-table-formula-substitute-names (f)
10750 "Replace $const with values in string F."
10751 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10752 ;; First, check for column names
10753 (while (setq start (string-match org-table-column-name-regexp f start))
10754 (setq start (1+ start))
10755 (setq a (assoc (match-string 1 f) org-table-column-names))
10756 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10757 ;; Parameters and constants
10758 (setq start 0)
10759 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10760 (setq start (1+ start))
10761 (if (setq a (save-match-data
10762 (org-table-get-constant (match-string 1 f))))
10763 (setq f (replace-match
10764 (concat (if pp "(") a (if pp ")")) t t f))))
10765 (if org-table-formula-debug
10766 (put-text-property 0 (length f) :orig-formula f1 f))
10769 (defun org-table-get-constant (const)
10770 "Find the value for a parameter or constant in a formula.
10771 Parameters get priority."
10772 (or (cdr (assoc const org-table-local-parameters))
10773 (cdr (assoc const org-table-formula-constants-local))
10774 (cdr (assoc const org-table-formula-constants))
10775 (and (fboundp 'constants-get) (constants-get const))
10776 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10777 (org-entry-get nil (substring const 5) 'inherit))
10778 "#UNDEFINED_NAME"))
10780 (defvar org-table-fedit-map
10781 (let ((map (make-sparse-keymap)))
10782 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10783 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10784 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10785 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10786 (org-defkey map "\C-c?" 'org-table-show-reference)
10787 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10788 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10789 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10790 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10791 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10792 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10793 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10794 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10795 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10796 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10797 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10798 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10799 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10800 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10801 map))
10803 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10804 '("Edit-Formulas"
10805 ["Finish and Install" org-table-fedit-finish t]
10806 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10807 ["Abort" org-table-fedit-abort t]
10808 "--"
10809 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10810 ["Complete Lisp Symbol" lisp-complete-symbol t]
10811 "--"
10812 "Shift Reference at Point"
10813 ["Up" org-table-fedit-ref-up t]
10814 ["Down" org-table-fedit-ref-down t]
10815 ["Left" org-table-fedit-ref-left t]
10816 ["Right" org-table-fedit-ref-right t]
10818 "Change Test Row for Column Formulas"
10819 ["Up" org-table-fedit-line-up t]
10820 ["Down" org-table-fedit-line-down t]
10821 "--"
10822 ["Scroll Table Window" org-table-fedit-scroll t]
10823 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10824 ["Show Table Grid" org-table-fedit-toggle-coordinates
10825 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10826 org-table-overlay-coordinates)]
10827 "--"
10828 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10829 :style toggle :selected org-table-buffer-is-an]))
10831 (defvar org-pos)
10833 (defun org-table-edit-formulas ()
10834 "Edit the formulas of the current table in a separate buffer."
10835 (interactive)
10836 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10837 (beginning-of-line 0))
10838 (unless (org-at-table-p) (error "Not at a table"))
10839 (org-table-get-specials)
10840 (let ((key (org-table-current-field-formula 'key 'noerror))
10841 (eql (sort (org-table-get-stored-formulas 'noerror)
10842 'org-table-formula-less-p))
10843 (pos (move-marker (make-marker) (point)))
10844 (startline 1)
10845 (wc (current-window-configuration))
10846 (titles '((column . "# Column Formulas\n")
10847 (field . "# Field Formulas\n")
10848 (named . "# Named Field Formulas\n")))
10849 entry s type title)
10850 (org-switch-to-buffer-other-window "*Edit Formulas*")
10851 (erase-buffer)
10852 ;; Keep global-font-lock-mode from turning on font-lock-mode
10853 (let ((font-lock-global-modes '(not fundamental-mode)))
10854 (fundamental-mode))
10855 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10856 (org-set-local 'org-pos pos)
10857 (org-set-local 'org-window-configuration wc)
10858 (use-local-map org-table-fedit-map)
10859 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10860 (easy-menu-add org-table-fedit-menu)
10861 (setq startline (org-current-line))
10862 (while (setq entry (pop eql))
10863 (setq type (cond
10864 ((equal (string-to-char (car entry)) ?@) 'field)
10865 ((string-match "^[0-9]" (car entry)) 'column)
10866 (t 'named)))
10867 (when (setq title (assq type titles))
10868 (or (bobp) (insert "\n"))
10869 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10870 (setq titles (delq title titles)))
10871 (if (equal key (car entry)) (setq startline (org-current-line)))
10872 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10873 (car entry) " = " (cdr entry) "\n"))
10874 (remove-text-properties 0 (length s) '(face nil) s)
10875 (insert s))
10876 (if (eq org-table-use-standard-references t)
10877 (org-table-fedit-toggle-ref-type))
10878 (goto-line startline)
10879 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10881 (defun org-table-fedit-post-command ()
10882 (when (not (memq this-command '(lisp-complete-symbol)))
10883 (let ((win (selected-window)))
10884 (save-excursion
10885 (condition-case nil
10886 (org-table-show-reference)
10887 (error nil))
10888 (select-window win)))))
10890 (defun org-table-formula-to-user (s)
10891 "Convert a formula from internal to user representation."
10892 (if (eq org-table-use-standard-references t)
10893 (org-table-convert-refs-to-an s)
10896 (defun org-table-formula-from-user (s)
10897 "Convert a formula from user to internal representation."
10898 (if org-table-use-standard-references
10899 (org-table-convert-refs-to-rc s)
10902 (defun org-table-convert-refs-to-rc (s)
10903 "Convert spreadsheet references from AB7 to @7$28.
10904 Works for single references, but also for entire formulas and even the
10905 full TBLFM line."
10906 (let ((start 0))
10907 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10908 (cond
10909 ((match-end 3)
10910 ;; format match, just advance
10911 (setq start (match-end 0)))
10912 ((and (> (match-beginning 0) 0)
10913 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10914 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10915 ;; 3.e5 or something like this.
10916 (setq start (match-end 0)))
10918 (setq start (match-beginning 0)
10919 s (replace-match
10920 (if (equal (match-string 2 s) "&")
10921 (format "$%d" (org-letters-to-number (match-string 1 s)))
10922 (format "@%d$%d"
10923 (string-to-number (match-string 2 s))
10924 (org-letters-to-number (match-string 1 s))))
10925 t t s)))))
10928 (defun org-table-convert-refs-to-an (s)
10929 "Convert spreadsheet references from to @7$28 to AB7.
10930 Works for single references, but also for entire formulas and even the
10931 full TBLFM line."
10932 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10933 (setq s (replace-match
10934 (format "%s%d"
10935 (org-number-to-letters
10936 (string-to-number (match-string 2 s)))
10937 (string-to-number (match-string 1 s)))
10938 t t s)))
10939 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10940 (setq s (replace-match (concat "\\1"
10941 (org-number-to-letters
10942 (string-to-number (match-string 2 s))) "&")
10943 t nil s)))
10946 (defun org-letters-to-number (s)
10947 "Convert a base 26 number represented by letters into an integer.
10948 For example: AB -> 28."
10949 (let ((n 0))
10950 (setq s (upcase s))
10951 (while (> (length s) 0)
10952 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10953 s (substring s 1)))
10956 (defun org-number-to-letters (n)
10957 "Convert an integer into a base 26 number represented by letters.
10958 For example: 28 -> AB."
10959 (let ((s ""))
10960 (while (> n 0)
10961 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10962 n (/ (1- n) 26)))
10965 (defun org-table-fedit-convert-buffer (function)
10966 "Convert all references in this buffer, using FUNTION."
10967 (let ((line (org-current-line)))
10968 (goto-char (point-min))
10969 (while (not (eobp))
10970 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10971 (delete-region (point) (point-at-eol))
10972 (or (eobp) (forward-char 1)))
10973 (goto-line line)))
10975 (defun org-table-fedit-toggle-ref-type ()
10976 "Convert all references in the buffer from B3 to @3$2 and back."
10977 (interactive)
10978 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10979 (org-table-fedit-convert-buffer
10980 (if org-table-buffer-is-an
10981 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10982 (message "Reference type switched to %s"
10983 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10985 (defun org-table-fedit-ref-up ()
10986 "Shift the reference at point one row/hline up."
10987 (interactive)
10988 (org-table-fedit-shift-reference 'up))
10989 (defun org-table-fedit-ref-down ()
10990 "Shift the reference at point one row/hline down."
10991 (interactive)
10992 (org-table-fedit-shift-reference 'down))
10993 (defun org-table-fedit-ref-left ()
10994 "Shift the reference at point one field to the left."
10995 (interactive)
10996 (org-table-fedit-shift-reference 'left))
10997 (defun org-table-fedit-ref-right ()
10998 "Shift the reference at point one field to the right."
10999 (interactive)
11000 (org-table-fedit-shift-reference 'right))
11002 (defun org-table-fedit-shift-reference (dir)
11003 (cond
11004 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
11005 (if (memq dir '(left right))
11006 (org-rematch-and-replace 1 (eq dir 'left))
11007 (error "Cannot shift reference in this direction")))
11008 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
11009 ;; A B3-like reference
11010 (if (memq dir '(up down))
11011 (org-rematch-and-replace 2 (eq dir 'up))
11012 (org-rematch-and-replace 1 (eq dir 'left))))
11013 ((org-at-regexp-p
11014 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
11015 ;; An internal reference
11016 (if (memq dir '(up down))
11017 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
11018 (org-rematch-and-replace 5 (eq dir 'left))))))
11020 (defun org-rematch-and-replace (n &optional decr hline)
11021 "Re-match the group N, and replace it with the shifted refrence."
11022 (or (match-end n) (error "Cannot shift reference in this direction"))
11023 (goto-char (match-beginning n))
11024 (and (looking-at (regexp-quote (match-string n)))
11025 (replace-match (org-shift-refpart (match-string 0) decr hline)
11026 t t)))
11028 (defun org-shift-refpart (ref &optional decr hline)
11029 "Shift a refrence part REF.
11030 If DECR is set, decrease the references row/column, else increase.
11031 If HLINE is set, this may be a hline reference, it certainly is not
11032 a translation reference."
11033 (save-match-data
11034 (let* ((sign (string-match "^[-+]" ref)) n)
11036 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11037 (cond
11038 ((and hline (string-match "^I+" ref))
11039 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11040 (setq n (+ n (if decr -1 1)))
11041 (if (= n 0) (setq n (+ n (if decr -1 1))))
11042 (if sign
11043 (setq sign (if (< n 0) "-" "+") n (abs n))
11044 (setq n (max 1 n)))
11045 (concat sign (make-string n ?I)))
11047 ((string-match "^[0-9]+" ref)
11048 (setq n (string-to-number (concat sign ref)))
11049 (setq n (+ n (if decr -1 1)))
11050 (if sign
11051 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11052 (number-to-string (max 1 n))))
11054 ((string-match "^[a-zA-Z]+" ref)
11055 (org-number-to-letters
11056 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11058 (t (error "Cannot shift reference"))))))
11060 (defun org-table-fedit-toggle-coordinates ()
11061 "Toggle the display of coordinates in the refrenced table."
11062 (interactive)
11063 (let ((pos (marker-position org-pos)))
11064 (with-current-buffer (marker-buffer org-pos)
11065 (save-excursion
11066 (goto-char pos)
11067 (org-table-toggle-coordinate-overlays)))))
11069 (defun org-table-fedit-finish (&optional arg)
11070 "Parse the buffer for formula definitions and install them.
11071 With prefix ARG, apply the new formulas to the table."
11072 (interactive "P")
11073 (org-table-remove-rectangle-highlight)
11074 (if org-table-use-standard-references
11075 (progn
11076 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11077 (setq org-table-buffer-is-an nil)))
11078 (let ((pos org-pos) eql var form)
11079 (goto-char (point-min))
11080 (while (re-search-forward
11081 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11082 nil t)
11083 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11084 form (match-string 3))
11085 (setq form (org-trim form))
11086 (when (not (equal form ""))
11087 (while (string-match "[ \t]*\n[ \t]*" form)
11088 (setq form (replace-match " " t t form)))
11089 (when (assoc var eql)
11090 (error "Double formulas for %s" var))
11091 (push (cons var form) eql)))
11092 (setq org-pos nil)
11093 (set-window-configuration org-window-configuration)
11094 (select-window (get-buffer-window (marker-buffer pos)))
11095 (goto-char pos)
11096 (unless (org-at-table-p)
11097 (error "Lost table position - cannot install formulae"))
11098 (org-table-store-formulas eql)
11099 (move-marker pos nil)
11100 (kill-buffer "*Edit Formulas*")
11101 (if arg
11102 (org-table-recalculate 'all)
11103 (message "New formulas installed - press C-u C-c C-c to apply."))))
11105 (defun org-table-fedit-abort ()
11106 "Abort editing formulas, without installing the changes."
11107 (interactive)
11108 (org-table-remove-rectangle-highlight)
11109 (let ((pos org-pos))
11110 (set-window-configuration org-window-configuration)
11111 (select-window (get-buffer-window (marker-buffer pos)))
11112 (goto-char pos)
11113 (move-marker pos nil)
11114 (message "Formula editing aborted without installing changes")))
11116 (defun org-table-fedit-lisp-indent ()
11117 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11118 (interactive)
11119 (let ((pos (point)) beg end ind)
11120 (beginning-of-line 1)
11121 (cond
11122 ((looking-at "[ \t]")
11123 (goto-char pos)
11124 (call-interactively 'lisp-indent-line))
11125 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11126 ((not (fboundp 'pp-buffer))
11127 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11128 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11129 (goto-char (- (match-end 0) 2))
11130 (setq beg (point))
11131 (setq ind (make-string (current-column) ?\ ))
11132 (condition-case nil (forward-sexp 1)
11133 (error
11134 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11135 (setq end (point))
11136 (save-restriction
11137 (narrow-to-region beg end)
11138 (if (eq last-command this-command)
11139 (progn
11140 (goto-char (point-min))
11141 (setq this-command nil)
11142 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11143 (replace-match " ")))
11144 (pp-buffer)
11145 (untabify (point-min) (point-max))
11146 (goto-char (1+ (point-min)))
11147 (while (re-search-forward "^." nil t)
11148 (beginning-of-line 1)
11149 (insert ind))
11150 (goto-char (point-max))
11151 (backward-delete-char 1)))
11152 (goto-char beg))
11153 (t nil))))
11155 (defvar org-show-positions nil)
11157 (defun org-table-show-reference (&optional local)
11158 "Show the location/value of the $ expression at point."
11159 (interactive)
11160 (org-table-remove-rectangle-highlight)
11161 (catch 'exit
11162 (let ((pos (if local (point) org-pos))
11163 (face2 'highlight)
11164 (org-inhibit-highlight-removal t)
11165 (win (selected-window))
11166 (org-show-positions nil)
11167 var name e what match dest)
11168 (if local (org-table-get-specials))
11169 (setq what (cond
11170 ((or (org-at-regexp-p org-table-range-regexp2)
11171 (org-at-regexp-p org-table-translate-regexp)
11172 (org-at-regexp-p org-table-range-regexp))
11173 (setq match
11174 (save-match-data
11175 (org-table-convert-refs-to-rc (match-string 0))))
11176 'range)
11177 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11178 ((org-at-regexp-p "\\$[0-9]+") 'column)
11179 ((not local) nil)
11180 (t (error "No reference at point")))
11181 match (and what (or match (match-string 0))))
11182 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11183 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11184 'secondary-selection))
11185 (org-add-hook 'before-change-functions
11186 'org-table-remove-rectangle-highlight)
11187 (if (eq what 'name) (setq var (substring match 1)))
11188 (when (eq what 'range)
11189 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11190 (setq match (org-table-formula-substitute-names match)))
11191 (unless local
11192 (save-excursion
11193 (end-of-line 1)
11194 (re-search-backward "^\\S-" nil t)
11195 (beginning-of-line 1)
11196 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11197 (setq dest
11198 (save-match-data
11199 (org-table-convert-refs-to-rc (match-string 1))))
11200 (org-table-add-rectangle-overlay
11201 (match-beginning 1) (match-end 1) face2))))
11202 (if (and (markerp pos) (marker-buffer pos))
11203 (if (get-buffer-window (marker-buffer pos))
11204 (select-window (get-buffer-window (marker-buffer pos)))
11205 (org-switch-to-buffer-other-window (get-buffer-window
11206 (marker-buffer pos)))))
11207 (goto-char pos)
11208 (org-table-force-dataline)
11209 (when dest
11210 (setq name (substring dest 1))
11211 (cond
11212 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11213 (setq e (assoc name org-table-named-field-locations))
11214 (goto-line (nth 1 e))
11215 (org-table-goto-column (nth 2 e)))
11216 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11217 (let ((l (string-to-number (match-string 1 dest)))
11218 (c (string-to-number (match-string 2 dest))))
11219 (goto-line (aref org-table-dlines l))
11220 (org-table-goto-column c)))
11221 (t (org-table-goto-column (string-to-number name))))
11222 (move-marker pos (point))
11223 (org-table-highlight-rectangle nil nil face2))
11224 (cond
11225 ((equal dest match))
11226 ((not match))
11227 ((eq what 'range)
11228 (condition-case nil
11229 (save-excursion
11230 (org-table-get-range match nil nil 'highlight))
11231 (error nil)))
11232 ((setq e (assoc var org-table-named-field-locations))
11233 (goto-line (nth 1 e))
11234 (org-table-goto-column (nth 2 e))
11235 (org-table-highlight-rectangle (point) (point))
11236 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11237 ((setq e (assoc var org-table-column-names))
11238 (org-table-goto-column (string-to-number (cdr e)))
11239 (org-table-highlight-rectangle (point) (point))
11240 (goto-char (org-table-begin))
11241 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11242 (org-table-end) t)
11243 (progn
11244 (goto-char (match-beginning 1))
11245 (org-table-highlight-rectangle)
11246 (message "Named column (column %s)" (cdr e)))
11247 (error "Column name not found")))
11248 ((eq what 'column)
11249 ;; column number
11250 (org-table-goto-column (string-to-number (substring match 1)))
11251 (org-table-highlight-rectangle (point) (point))
11252 (message "Column %s" (substring match 1)))
11253 ((setq e (assoc var org-table-local-parameters))
11254 (goto-char (org-table-begin))
11255 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11256 (progn
11257 (goto-char (match-beginning 1))
11258 (org-table-highlight-rectangle)
11259 (message "Local parameter."))
11260 (error "Parameter not found")))
11262 (cond
11263 ((not var) (error "No reference at point"))
11264 ((setq e (assoc var org-table-formula-constants-local))
11265 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11266 var (cdr e)))
11267 ((setq e (assoc var org-table-formula-constants))
11268 (message "Constant: $%s=%s in `org-table-formula-constants'."
11269 var (cdr e)))
11270 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11271 (message "Constant: $%s=%s, from `constants.el'%s."
11272 var e (format " (%s units)" constants-unit-system)))
11273 (t (error "Undefined name $%s" var)))))
11274 (goto-char pos)
11275 (when (and org-show-positions
11276 (not (memq this-command '(org-table-fedit-scroll
11277 org-table-fedit-scroll-down))))
11278 (push pos org-show-positions)
11279 (push org-table-current-begin-pos org-show-positions)
11280 (let ((min (apply 'min org-show-positions))
11281 (max (apply 'max org-show-positions)))
11282 (goto-char min) (recenter 0)
11283 (goto-char max)
11284 (or (pos-visible-in-window-p max) (recenter -1))))
11285 (select-window win))))
11287 (defun org-table-force-dataline ()
11288 "Make sure the cursor is in a dataline in a table."
11289 (unless (save-excursion
11290 (beginning-of-line 1)
11291 (looking-at org-table-dataline-regexp))
11292 (let* ((re org-table-dataline-regexp)
11293 (p1 (save-excursion (re-search-forward re nil 'move)))
11294 (p2 (save-excursion (re-search-backward re nil 'move))))
11295 (cond ((and p1 p2)
11296 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11297 p1 p2)))
11298 ((or p1 p2) (goto-char (or p1 p2)))
11299 (t (error "No table dataline around here"))))))
11301 (defun org-table-fedit-line-up ()
11302 "Move cursor one line up in the window showing the table."
11303 (interactive)
11304 (org-table-fedit-move 'previous-line))
11306 (defun org-table-fedit-line-down ()
11307 "Move cursor one line down in the window showing the table."
11308 (interactive)
11309 (org-table-fedit-move 'next-line))
11311 (defun org-table-fedit-move (command)
11312 "Move the cursor in the window shoinw the table.
11313 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11314 (let ((org-table-allow-automatic-line-recalculation nil)
11315 (pos org-pos) (win (selected-window)) p)
11316 (select-window (get-buffer-window (marker-buffer org-pos)))
11317 (setq p (point))
11318 (call-interactively command)
11319 (while (and (org-at-table-p)
11320 (org-at-table-hline-p))
11321 (call-interactively command))
11322 (or (org-at-table-p) (goto-char p))
11323 (move-marker pos (point))
11324 (select-window win)))
11326 (defun org-table-fedit-scroll (N)
11327 (interactive "p")
11328 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11329 (scroll-other-window N)))
11331 (defun org-table-fedit-scroll-down (N)
11332 (interactive "p")
11333 (org-table-fedit-scroll (- N)))
11335 (defvar org-table-rectangle-overlays nil)
11337 (defun org-table-add-rectangle-overlay (beg end &optional face)
11338 "Add a new overlay."
11339 (let ((ov (org-make-overlay beg end)))
11340 (org-overlay-put ov 'face (or face 'secondary-selection))
11341 (push ov org-table-rectangle-overlays)))
11343 (defun org-table-highlight-rectangle (&optional beg end face)
11344 "Highlight rectangular region in a table."
11345 (setq beg (or beg (point)) end (or end (point)))
11346 (let ((b (min beg end))
11347 (e (max beg end))
11348 l1 c1 l2 c2 tmp)
11349 (and (boundp 'org-show-positions)
11350 (setq org-show-positions (cons b (cons e org-show-positions))))
11351 (goto-char (min beg end))
11352 (setq l1 (org-current-line)
11353 c1 (org-table-current-column))
11354 (goto-char (max beg end))
11355 (setq l2 (org-current-line)
11356 c2 (org-table-current-column))
11357 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11358 (goto-line l1)
11359 (beginning-of-line 1)
11360 (loop for line from l1 to l2 do
11361 (when (looking-at org-table-dataline-regexp)
11362 (org-table-goto-column c1)
11363 (skip-chars-backward "^|\n") (setq beg (point))
11364 (org-table-goto-column c2)
11365 (skip-chars-forward "^|\n") (setq end (point))
11366 (org-table-add-rectangle-overlay beg end face))
11367 (beginning-of-line 2))
11368 (goto-char b))
11369 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11371 (defun org-table-remove-rectangle-highlight (&rest ignore)
11372 "Remove the rectangle overlays."
11373 (unless org-inhibit-highlight-removal
11374 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11375 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11376 (setq org-table-rectangle-overlays nil)))
11378 (defvar org-table-coordinate-overlays nil
11379 "Collects the cooordinate grid overlays, so that they can be removed.")
11380 (make-variable-buffer-local 'org-table-coordinate-overlays)
11382 (defun org-table-overlay-coordinates ()
11383 "Add overlays to the table at point, to show row/column coordinates."
11384 (interactive)
11385 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11386 (setq org-table-coordinate-overlays nil)
11387 (save-excursion
11388 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11389 (goto-char (org-table-begin))
11390 (while (org-at-table-p)
11391 (setq eol (point-at-eol))
11392 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11393 (push ov org-table-coordinate-overlays)
11394 (setq hline (looking-at org-table-hline-regexp))
11395 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11396 (format "%4d" (setq id (1+ id)))))
11397 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11398 (when hline
11399 (setq ic 0)
11400 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11401 (setq beg (1+ (match-beginning 0))
11402 ic (1+ ic)
11403 s1 (concat "$" (int-to-string ic))
11404 s2 (org-number-to-letters ic)
11405 str (if (eq org-table-use-standard-references t) s2 s1))
11406 (setq ov (org-make-overlay beg (+ beg (length str))))
11407 (push ov org-table-coordinate-overlays)
11408 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11409 (beginning-of-line 2)))))
11411 (defun org-table-toggle-coordinate-overlays ()
11412 "Toggle the display of Row/Column numbers in tables."
11413 (interactive)
11414 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11415 (message "Row/Column number display turned %s"
11416 (if org-table-overlay-coordinates "on" "off"))
11417 (if (and (org-at-table-p) org-table-overlay-coordinates)
11418 (org-table-align))
11419 (unless org-table-overlay-coordinates
11420 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11421 (setq org-table-coordinate-overlays nil)))
11423 (defun org-table-toggle-formula-debugger ()
11424 "Toggle the formula debugger in tables."
11425 (interactive)
11426 (setq org-table-formula-debug (not org-table-formula-debug))
11427 (message "Formula debugging has been turned %s"
11428 (if org-table-formula-debug "on" "off")))
11430 ;;; The orgtbl minor mode
11432 ;; Define a minor mode which can be used in other modes in order to
11433 ;; integrate the org-mode table editor.
11435 ;; This is really a hack, because the org-mode table editor uses several
11436 ;; keys which normally belong to the major mode, for example the TAB and
11437 ;; RET keys. Here is how it works: The minor mode defines all the keys
11438 ;; necessary to operate the table editor, but wraps the commands into a
11439 ;; function which tests if the cursor is currently inside a table. If that
11440 ;; is the case, the table editor command is executed. However, when any of
11441 ;; those keys is used outside a table, the function uses `key-binding' to
11442 ;; look up if the key has an associated command in another currently active
11443 ;; keymap (minor modes, major mode, global), and executes that command.
11444 ;; There might be problems if any of the keys used by the table editor is
11445 ;; otherwise used as a prefix key.
11447 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11448 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11449 ;; addresses this by checking explicitly for both bindings.
11451 ;; The optimized version (see variable `orgtbl-optimized') takes over
11452 ;; all keys which are bound to `self-insert-command' in the *global map*.
11453 ;; Some modes bind other commands to simple characters, for example
11454 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11455 ;; active, this binding is ignored inside tables and replaced with a
11456 ;; modified self-insert.
11458 (defvar orgtbl-mode nil
11459 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11460 table editor in arbitrary modes.")
11461 (make-variable-buffer-local 'orgtbl-mode)
11463 (defvar orgtbl-mode-map (make-keymap)
11464 "Keymap for `orgtbl-mode'.")
11466 ;;;###autoload
11467 (defun turn-on-orgtbl ()
11468 "Unconditionally turn on `orgtbl-mode'."
11469 (orgtbl-mode 1))
11471 (defvar org-old-auto-fill-inhibit-regexp nil
11472 "Local variable used by `orgtbl-mode'")
11474 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11475 "Matches a line belonging to an orgtbl.")
11477 (defconst orgtbl-extra-font-lock-keywords
11478 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11479 0 (quote 'org-table) 'prepend))
11480 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11482 ;;;###autoload
11483 (defun orgtbl-mode (&optional arg)
11484 "The `org-mode' table editor as a minor mode for use in other modes."
11485 (interactive)
11486 (org-load-modules-maybe)
11487 (if (org-mode-p)
11488 ;; Exit without error, in case some hook functions calls this
11489 ;; by accident in org-mode.
11490 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11491 (setq orgtbl-mode
11492 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11493 (if orgtbl-mode
11494 (progn
11495 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11496 ;; Make sure we are first in minor-mode-map-alist
11497 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11498 (and c (setq minor-mode-map-alist
11499 (cons c (delq c minor-mode-map-alist)))))
11500 (org-set-local (quote org-table-may-need-update) t)
11501 (org-add-hook 'before-change-functions 'org-before-change-function
11502 nil 'local)
11503 (org-set-local 'org-old-auto-fill-inhibit-regexp
11504 auto-fill-inhibit-regexp)
11505 (org-set-local 'auto-fill-inhibit-regexp
11506 (if auto-fill-inhibit-regexp
11507 (concat orgtbl-line-start-regexp "\\|"
11508 auto-fill-inhibit-regexp)
11509 orgtbl-line-start-regexp))
11510 (org-add-to-invisibility-spec '(org-cwidth))
11511 (when (fboundp 'font-lock-add-keywords)
11512 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11513 (org-restart-font-lock))
11514 (easy-menu-add orgtbl-mode-menu)
11515 (run-hooks 'orgtbl-mode-hook))
11516 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11517 (org-cleanup-narrow-column-properties)
11518 (org-remove-from-invisibility-spec '(org-cwidth))
11519 (remove-hook 'before-change-functions 'org-before-change-function t)
11520 (when (fboundp 'font-lock-remove-keywords)
11521 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11522 (org-restart-font-lock))
11523 (easy-menu-remove orgtbl-mode-menu)
11524 (force-mode-line-update 'all))))
11526 (defun org-cleanup-narrow-column-properties ()
11527 "Remove all properties related to narrow-column invisibility."
11528 (let ((s 1))
11529 (while (setq s (text-property-any s (point-max)
11530 'display org-narrow-column-arrow))
11531 (remove-text-properties s (1+ s) '(display t)))
11532 (setq s 1)
11533 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11534 (remove-text-properties s (1+ s) '(org-cwidth t)))
11535 (setq s 1)
11536 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11537 (remove-text-properties s (1+ s) '(invisible t)))))
11539 ;; Install it as a minor mode.
11540 (put 'orgtbl-mode :included t)
11541 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11542 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11544 (defun orgtbl-make-binding (fun n &rest keys)
11545 "Create a function for binding in the table minor mode.
11546 FUN is the command to call inside a table. N is used to create a unique
11547 command name. KEYS are keys that should be checked in for a command
11548 to execute outside of tables."
11549 (eval
11550 (list 'defun
11551 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11552 '(arg)
11553 (concat "In tables, run `" (symbol-name fun) "'.\n"
11554 "Outside of tables, run the binding of `"
11555 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11556 "'.")
11557 '(interactive "p")
11558 (list 'if
11559 '(org-at-table-p)
11560 (list 'call-interactively (list 'quote fun))
11561 (list 'let '(orgtbl-mode)
11562 (list 'call-interactively
11563 (append '(or)
11564 (mapcar (lambda (k)
11565 (list 'key-binding k))
11566 keys)
11567 '('orgtbl-error))))))))
11569 (defun orgtbl-error ()
11570 "Error when there is no default binding for a table key."
11571 (interactive)
11572 (error "This key has no function outside tables"))
11574 (defun orgtbl-setup ()
11575 "Setup orgtbl keymaps."
11576 (let ((nfunc 0)
11577 (bindings
11578 (list
11579 '([(meta shift left)] org-table-delete-column)
11580 '([(meta left)] org-table-move-column-left)
11581 '([(meta right)] org-table-move-column-right)
11582 '([(meta shift right)] org-table-insert-column)
11583 '([(meta shift up)] org-table-kill-row)
11584 '([(meta shift down)] org-table-insert-row)
11585 '([(meta up)] org-table-move-row-up)
11586 '([(meta down)] org-table-move-row-down)
11587 '("\C-c\C-w" org-table-cut-region)
11588 '("\C-c\M-w" org-table-copy-region)
11589 '("\C-c\C-y" org-table-paste-rectangle)
11590 '("\C-c-" org-table-insert-hline)
11591 '("\C-c}" org-table-toggle-coordinate-overlays)
11592 '("\C-c{" org-table-toggle-formula-debugger)
11593 '("\C-m" org-table-next-row)
11594 '([(shift return)] org-table-copy-down)
11595 '("\C-c\C-q" org-table-wrap-region)
11596 '("\C-c?" org-table-field-info)
11597 '("\C-c " org-table-blank-field)
11598 '("\C-c+" org-table-sum)
11599 '("\C-c=" org-table-eval-formula)
11600 '("\C-c'" org-table-edit-formulas)
11601 '("\C-c`" org-table-edit-field)
11602 '("\C-c*" org-table-recalculate)
11603 '("\C-c|" org-table-create-or-convert-from-region)
11604 '("\C-c^" org-table-sort-lines)
11605 '([(control ?#)] org-table-rotate-recalc-marks)))
11606 elt key fun cmd)
11607 (while (setq elt (pop bindings))
11608 (setq nfunc (1+ nfunc))
11609 (setq key (org-key (car elt))
11610 fun (nth 1 elt)
11611 cmd (orgtbl-make-binding fun nfunc key))
11612 (org-defkey orgtbl-mode-map key cmd))
11614 ;; Special treatment needed for TAB and RET
11615 (org-defkey orgtbl-mode-map [(return)]
11616 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11617 (org-defkey orgtbl-mode-map "\C-m"
11618 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11620 (org-defkey orgtbl-mode-map [(tab)]
11621 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11622 (org-defkey orgtbl-mode-map "\C-i"
11623 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11625 (org-defkey orgtbl-mode-map [(shift tab)]
11626 (orgtbl-make-binding 'org-table-previous-field 104
11627 [(shift tab)] [(tab)] "\C-i"))
11629 (org-defkey orgtbl-mode-map "\M-\C-m"
11630 (orgtbl-make-binding 'org-table-wrap-region 105
11631 "\M-\C-m" [(meta return)]))
11632 (org-defkey orgtbl-mode-map [(meta return)]
11633 (orgtbl-make-binding 'org-table-wrap-region 106
11634 [(meta return)] "\M-\C-m"))
11636 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11637 (when orgtbl-optimized
11638 ;; If the user wants maximum table support, we need to hijack
11639 ;; some standard editing functions
11640 (org-remap orgtbl-mode-map
11641 'self-insert-command 'orgtbl-self-insert-command
11642 'delete-char 'org-delete-char
11643 'delete-backward-char 'org-delete-backward-char)
11644 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11645 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11646 '("OrgTbl"
11647 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11648 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11649 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11650 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11651 "--"
11652 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11653 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11654 ["Copy Field from Above"
11655 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11656 "--"
11657 ("Column"
11658 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11659 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11660 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11661 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11662 ("Row"
11663 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11664 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11665 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11666 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11667 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11668 "--"
11669 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11670 ("Rectangle"
11671 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11672 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11673 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11674 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11675 "--"
11676 ("Radio tables"
11677 ["Insert table template" orgtbl-insert-radio-table
11678 (assq major-mode orgtbl-radio-table-templates)]
11679 ["Comment/uncomment table" orgtbl-toggle-comment t])
11680 "--"
11681 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11682 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11683 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11684 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11685 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11686 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11687 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11688 ["Sum Column/Rectangle" org-table-sum
11689 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11690 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11691 ["Debug Formulas"
11692 org-table-toggle-formula-debugger :active (org-at-table-p)
11693 :keys "C-c {"
11694 :style toggle :selected org-table-formula-debug]
11695 ["Show Col/Row Numbers"
11696 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11697 :keys "C-c }"
11698 :style toggle :selected org-table-overlay-coordinates]
11702 (defun orgtbl-ctrl-c-ctrl-c (arg)
11703 "If the cursor is inside a table, realign the table.
11704 It it is a table to be sent away to a receiver, do it.
11705 With prefix arg, also recompute table."
11706 (interactive "P")
11707 (let ((pos (point)) action)
11708 (save-excursion
11709 (beginning-of-line 1)
11710 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11711 ((looking-at "[ \t]*|") pos)
11712 ((looking-at "#\\+TBLFM:") 'recalc))))
11713 (cond
11714 ((integerp action)
11715 (goto-char action)
11716 (org-table-maybe-eval-formula)
11717 (if arg
11718 (call-interactively 'org-table-recalculate)
11719 (org-table-maybe-recalculate-line))
11720 (call-interactively 'org-table-align)
11721 (orgtbl-send-table 'maybe))
11722 ((eq action 'recalc)
11723 (save-excursion
11724 (beginning-of-line 1)
11725 (skip-chars-backward " \r\n\t")
11726 (if (org-at-table-p)
11727 (org-call-with-arg 'org-table-recalculate t))))
11728 (t (let (orgtbl-mode)
11729 (call-interactively (key-binding "\C-c\C-c")))))))
11731 (defun orgtbl-tab (arg)
11732 "Justification and field motion for `orgtbl-mode'."
11733 (interactive "P")
11734 (if arg (org-table-edit-field t)
11735 (org-table-justify-field-maybe)
11736 (org-table-next-field)))
11738 (defun orgtbl-ret ()
11739 "Justification and field motion for `orgtbl-mode'."
11740 (interactive)
11741 (org-table-justify-field-maybe)
11742 (org-table-next-row))
11744 (defun orgtbl-self-insert-command (N)
11745 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11746 If the cursor is in a table looking at whitespace, the whitespace is
11747 overwritten, and the table is not marked as requiring realignment."
11748 (interactive "p")
11749 (if (and (org-at-table-p)
11751 (and org-table-auto-blank-field
11752 (member last-command
11753 '(orgtbl-hijacker-command-100
11754 orgtbl-hijacker-command-101
11755 orgtbl-hijacker-command-102
11756 orgtbl-hijacker-command-103
11757 orgtbl-hijacker-command-104
11758 orgtbl-hijacker-command-105))
11759 (org-table-blank-field))
11761 (eq N 1)
11762 (looking-at "[^|\n]* +|"))
11763 (let (org-table-may-need-update)
11764 (goto-char (1- (match-end 0)))
11765 (delete-backward-char 1)
11766 (goto-char (match-beginning 0))
11767 (self-insert-command N))
11768 (setq org-table-may-need-update t)
11769 (let (orgtbl-mode)
11770 (call-interactively (key-binding (vector last-input-event))))))
11772 (defun org-force-self-insert (N)
11773 "Needed to enforce self-insert under remapping."
11774 (interactive "p")
11775 (self-insert-command N))
11777 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11778 "Regula expression matching exponentials as produced by calc.")
11780 (defvar org-table-clean-did-remove-column nil)
11782 (defun orgtbl-export (table target)
11783 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11784 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11785 org-table-last-alignment org-table-last-column-widths
11786 maxcol column)
11787 (if (not (fboundp func))
11788 (error "Cannot export orgtbl table to %s" target))
11789 (setq lines (org-table-clean-before-export lines))
11790 (setq table
11791 (mapcar
11792 (lambda (x)
11793 (if (string-match org-table-hline-regexp x)
11794 'hline
11795 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11796 lines))
11797 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11798 table)))
11799 (loop for i from (1- maxcol) downto 0 do
11800 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11801 (setq column (delq nil column))
11802 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11803 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
11804 (funcall func table nil)))
11806 (defun orgtbl-send-table (&optional maybe)
11807 "Send a tranformed version of this table to the receiver position.
11808 With argument MAYBE, fail quietly if no transformation is defined for
11809 this table."
11810 (interactive)
11811 (catch 'exit
11812 (unless (org-at-table-p) (error "Not at a table"))
11813 ;; when non-interactive, we assume align has just happened.
11814 (when (interactive-p) (org-table-align))
11815 (save-excursion
11816 (goto-char (org-table-begin))
11817 (beginning-of-line 0)
11818 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11819 (if maybe
11820 (throw 'exit nil)
11821 (error "Don't know how to transform this table."))))
11822 (let* ((name (match-string 1))
11824 (transform (intern (match-string 2)))
11825 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11826 (skip (plist-get params :skip))
11827 (skipcols (plist-get params :skipcols))
11828 (txt (buffer-substring-no-properties
11829 (org-table-begin) (org-table-end)))
11830 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11831 (lines (org-table-clean-before-export lines))
11832 (i0 (if org-table-clean-did-remove-column 2 1))
11833 (table (mapcar
11834 (lambda (x)
11835 (if (string-match org-table-hline-regexp x)
11836 'hline
11837 (org-remove-by-index
11838 (org-split-string (org-trim x) "\\s-*|\\s-*")
11839 skipcols i0)))
11840 lines))
11841 (fun (if (= i0 2) 'cdr 'identity))
11842 (org-table-last-alignment
11843 (org-remove-by-index (funcall fun org-table-last-alignment)
11844 skipcols i0))
11845 (org-table-last-column-widths
11846 (org-remove-by-index (funcall fun org-table-last-column-widths)
11847 skipcols i0)))
11849 (unless (fboundp transform)
11850 (error "No such transformation function %s" transform))
11851 (setq txt (funcall transform table params))
11852 ;; Find the insertion place
11853 (save-excursion
11854 (goto-char (point-min))
11855 (unless (re-search-forward
11856 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11857 (error "Don't know where to insert translated table"))
11858 (goto-char (match-beginning 0))
11859 (beginning-of-line 2)
11860 (setq beg (point))
11861 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11862 (error "Cannot find end of insertion region"))
11863 (beginning-of-line 1)
11864 (delete-region beg (point))
11865 (goto-char beg)
11866 (insert txt "\n"))
11867 (message "Table converted and installed at receiver location"))))
11869 (defun org-remove-by-index (list indices &optional i0)
11870 "Remove the elements in LIST with indices in INDICES.
11871 First element has index 0, or I0 if given."
11872 (if (not indices)
11873 list
11874 (if (integerp indices) (setq indices (list indices)))
11875 (setq i0 (1- (or i0 0)))
11876 (delq :rm (mapcar (lambda (x)
11877 (setq i0 (1+ i0))
11878 (if (memq i0 indices) :rm x))
11879 list))))
11881 (defun orgtbl-toggle-comment ()
11882 "Comment or uncomment the orgtbl at point."
11883 (interactive)
11884 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11885 (re2 (concat "^" orgtbl-line-start-regexp))
11886 (commented (save-excursion (beginning-of-line 1)
11887 (cond ((looking-at re1) t)
11888 ((looking-at re2) nil)
11889 (t (error "Not at an org table")))))
11890 (re (if commented re1 re2))
11891 beg end)
11892 (save-excursion
11893 (beginning-of-line 1)
11894 (while (looking-at re) (beginning-of-line 0))
11895 (beginning-of-line 2)
11896 (setq beg (point))
11897 (while (looking-at re) (beginning-of-line 2))
11898 (setq end (point)))
11899 (comment-region beg end (if commented '(4) nil))))
11901 (defun orgtbl-insert-radio-table ()
11902 "Insert a radio table template appropriate for this major mode."
11903 (interactive)
11904 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11905 (txt (nth 1 e))
11906 name pos)
11907 (unless e (error "No radio table setup defined for %s" major-mode))
11908 (setq name (read-string "Table name: "))
11909 (while (string-match "%n" txt)
11910 (setq txt (replace-match name t t txt)))
11911 (or (bolp) (insert "\n"))
11912 (setq pos (point))
11913 (insert txt)
11914 (goto-char pos)))
11916 (defun org-get-param (params header i sym &optional hsym)
11917 "Get parameter value for symbol SYM.
11918 If this is a header line, actually get the value for the symbol with an
11919 additional \"h\" inserted after the colon.
11920 If the value is a protperty list, get the element for the current column.
11921 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11922 (let ((val (plist-get params sym)))
11923 (and hsym header (setq val (or (plist-get params hsym) val)))
11924 (if (consp val) (plist-get val i) val)))
11926 (defun orgtbl-to-generic (table params)
11927 "Convert the orgtbl-mode TABLE to some other format.
11928 This generic routine can be used for many standard cases.
11929 TABLE is a list, each entry either the symbol `hline' for a horizontal
11930 separator line, or a list of fields for that line.
11931 PARAMS is a property list of parameters that can influence the conversion.
11932 For the generic converter, some parameters are obligatory: You need to
11933 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11934 :splice, you must have :tstart and :tend.
11936 Valid parameters are
11938 :tstart String to start the table. Ignored when :splice is t.
11939 :tend String to end the table. Ignored when :splice is t.
11941 :splice When set to t, return only table body lines, don't wrap
11942 them into :tstart and :tend. Default is nil.
11944 :hline String to be inserted on horizontal separation lines.
11945 May be nil to ignore hlines.
11947 :lstart String to start a new table line.
11948 :lend String to end a table line
11949 :sep Separator between two fields
11950 :lfmt Format for entire line, with enough %s to capture all fields.
11951 If this is present, :lstart, :lend, and :sep are ignored.
11952 :fmt A format to be used to wrap the field, should contain
11953 %s for the original field value. For example, to wrap
11954 everything in dollars, you could use :fmt \"$%s$\".
11955 This may also be a property list with column numbers and
11956 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11958 :hlstart :hlend :hlsep :hlfmt :hfmt
11959 Same as above, specific for the header lines in the table.
11960 All lines before the first hline are treated as header.
11961 If any of these is not present, the data line value is used.
11963 :efmt Use this format to print numbers with exponentials.
11964 The format should have %s twice for inserting mantissa
11965 and exponent, for example \"%s\\\\times10^{%s}\". This
11966 may also be a property list with column numbers and
11967 formats. :fmt will still be applied after :efmt.
11969 In addition to this, the parameters :skip and :skipcols are always handled
11970 directly by `orgtbl-send-table'. See manual."
11971 (interactive)
11972 (let* ((p params)
11973 (splicep (plist-get p :splice))
11974 (hline (plist-get p :hline))
11975 rtn line i fm efm lfmt h)
11977 ;; Do we have a header?
11978 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11979 (setq h t))
11981 ;; Put header
11982 (unless splicep
11983 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11985 ;; Now loop over all lines
11986 (while (setq line (pop table))
11987 (if (eq line 'hline)
11988 ;; A horizontal separator line
11989 (progn (if hline (push hline rtn))
11990 (setq h nil)) ; no longer in header
11991 ;; A normal line. Convert the fields, push line onto the result list
11992 (setq i 0)
11993 (setq line
11994 (mapcar
11995 (lambda (f)
11996 (setq i (1+ i)
11997 fm (org-get-param p h i :fmt :hfmt)
11998 efm (org-get-param p h i :efmt))
11999 (if (and efm (string-match orgtbl-exp-regexp f))
12000 (setq f (format
12001 efm (match-string 1 f) (match-string 2 f))))
12002 (if fm (setq f (format fm f)))
12004 line))
12005 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
12006 (push (apply 'format lfmt line) rtn)
12007 (push (concat
12008 (org-get-param p h i :lstart :hlstart)
12009 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
12010 (org-get-param p h i :lend :hlend))
12011 rtn))))
12013 (unless splicep
12014 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
12016 (mapconcat 'identity (nreverse rtn) "\n")))
12018 (defun orgtbl-to-latex (table params)
12019 "Convert the orgtbl-mode TABLE to LaTeX.
12020 TABLE is a list, each entry either the symbol `hline' for a horizontal
12021 separator line, or a list of fields for that line.
12022 PARAMS is a property list of parameters that can influence the conversion.
12023 Supports all parameters from `orgtbl-to-generic'. Most important for
12024 LaTeX are:
12026 :splice When set to t, return only table body lines, don't wrap
12027 them into a tabular environment. Default is nil.
12029 :fmt A format to be used to wrap the field, should contain %s for the
12030 original field value. For example, to wrap everything in dollars,
12031 use :fmt \"$%s$\". This may also be a property list with column
12032 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12034 :efmt Format for transforming numbers with exponentials. The format
12035 should have %s twice for inserting mantissa and exponent, for
12036 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12037 This may also be a property list with column numbers and formats.
12039 The general parameters :skip and :skipcols have already been applied when
12040 this function is called."
12041 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12042 org-table-last-alignment ""))
12043 (params2
12044 (list
12045 :tstart (concat "\\begin{tabular}{" alignment "}")
12046 :tend "\\end{tabular}"
12047 :lstart "" :lend " \\\\" :sep " & "
12048 :efmt "%s\\,(%s)" :hline "\\hline")))
12049 (orgtbl-to-generic table (org-combine-plists params2 params))))
12051 (defun orgtbl-to-html (table params)
12052 "Convert the orgtbl-mode TABLE to LaTeX.
12053 TABLE is a list, each entry either the symbol `hline' for a horizontal
12054 separator line, or a list of fields for that line.
12055 PARAMS is a property list of parameters that can influence the conversion.
12056 Currently this function recognizes the following parameters:
12058 :splice When set to t, return only table body lines, don't wrap
12059 them into a <table> environment. Default is nil.
12061 The general parameters :skip and :skipcols have already been applied when
12062 this function is called. The function does *not* use `orgtbl-to-generic',
12063 so you cannot specify parameters for it."
12064 (let* ((splicep (plist-get params :splice))
12065 html)
12066 ;; Just call the formatter we already have
12067 ;; We need to make text lines for it, so put the fields back together.
12068 (setq html (org-format-org-table-html
12069 (mapcar
12070 (lambda (x)
12071 (if (eq x 'hline)
12072 "|----+----|"
12073 (concat "| " (mapconcat 'identity x " | ") " |")))
12074 table)
12075 splicep))
12076 (if (string-match "\n+\\'" html)
12077 (setq html (replace-match "" t t html)))
12078 html))
12080 (defun orgtbl-to-texinfo (table params)
12081 "Convert the orgtbl-mode TABLE to TeXInfo.
12082 TABLE is a list, each entry either the symbol `hline' for a horizontal
12083 separator line, or a list of fields for that line.
12084 PARAMS is a property list of parameters that can influence the conversion.
12085 Supports all parameters from `orgtbl-to-generic'. Most important for
12086 TeXInfo are:
12088 :splice nil/t When set to t, return only table body lines, don't wrap
12089 them into a multitable environment. Default is nil.
12091 :fmt fmt A format to be used to wrap the field, should contain
12092 %s for the original field value. For example, to wrap
12093 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12094 This may also be a property list with column numbers and
12095 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12097 :cf \"f1 f2..\" The column fractions for the table. By default these
12098 are computed automatically from the width of the columns
12099 under org-mode.
12101 The general parameters :skip and :skipcols have already been applied when
12102 this function is called."
12103 (let* ((total (float (apply '+ org-table-last-column-widths)))
12104 (colfrac (or (plist-get params :cf)
12105 (mapconcat
12106 (lambda (x) (format "%.3f" (/ (float x) total)))
12107 org-table-last-column-widths " ")))
12108 (params2
12109 (list
12110 :tstart (concat "@multitable @columnfractions " colfrac)
12111 :tend "@end multitable"
12112 :lstart "@item " :lend "" :sep " @tab "
12113 :hlstart "@headitem ")))
12114 (orgtbl-to-generic table (org-combine-plists params2 params))))
12116 ;;;; Link Stuff
12118 ;;; Link abbreviations
12120 (defun org-link-expand-abbrev (link)
12121 "Apply replacements as defined in `org-link-abbrev-alist."
12122 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12123 (let* ((key (match-string 1 link))
12124 (as (or (assoc key org-link-abbrev-alist-local)
12125 (assoc key org-link-abbrev-alist)))
12126 (tag (and (match-end 2) (match-string 3 link)))
12127 rpl)
12128 (if (not as)
12129 link
12130 (setq rpl (cdr as))
12131 (cond
12132 ((symbolp rpl) (funcall rpl tag))
12133 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12134 (t (concat rpl tag)))))
12135 link))
12137 ;;; Storing and inserting links
12139 (defvar org-insert-link-history nil
12140 "Minibuffer history for links inserted with `org-insert-link'.")
12142 (defvar org-stored-links nil
12143 "Contains the links stored with `org-store-link'.")
12145 (defvar org-store-link-plist nil
12146 "Plist with info about the most recently link created with `org-store-link'.")
12148 (defvar org-link-protocols nil
12149 "Link protocols added to Org-mode using `org-add-link-type'.")
12151 (defvar org-store-link-functions nil
12152 "List of functions that are called to create and store a link.
12153 Each function will be called in turn until one returns a non-nil
12154 value. Each function should check if it is responsible for creating
12155 this link (for example by looking at the major mode).
12156 If not, it must exit and return nil.
12157 If yes, it should return a non-nil value after a calling
12158 `org-store-link-props' with a list of properties and values.
12159 Special properties are:
12161 :type The link prefix. like \"http\". This must be given.
12162 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12163 This is obligatory as well.
12164 :description Optional default description for the second pair
12165 of brackets in an Org-mode link. The user can still change
12166 this when inserting this link into an Org-mode buffer.
12168 In addition to these, any additional properties can be specified
12169 and then used in remember templates.")
12171 (defun org-add-link-type (type &optional follow export)
12172 "Add TYPE to the list of `org-link-types'.
12173 Re-compute all regular expressions depending on `org-link-types'
12175 FOLLOW and EXPORT are two functions.
12177 FOLLOW should take the link path as the single argument and do whatever
12178 is necessary to follow the link, for example find a file or display
12179 a mail message.
12181 EXPORT should format the link path for export to one of the export formats.
12182 It should be a function accepting three arguments:
12184 path the path of the link, the text after the prefix (like \"http:\")
12185 desc the description of the link, if any, nil if there was no descripton
12186 format the export format, a symbol like `html' or `latex'.
12188 The function may use the FORMAT information to return different values
12189 depending on the format. The return value will be put literally into
12190 the exported file.
12191 Org-mode has a built-in default for exporting links. If you are happy with
12192 this default, there is no need to define an export function for the link
12193 type. For a simple example of an export function, see `org-bbdb.el'."
12194 (add-to-list 'org-link-types type t)
12195 (org-make-link-regexps)
12196 (if (assoc type org-link-protocols)
12197 (setcdr (assoc type org-link-protocols) (list follow export))
12198 (push (list type follow export) org-link-protocols)))
12201 (defun org-add-agenda-custom-command (entry)
12202 "Replace or add a command in `org-agenda-custom-commands'.
12203 This is mostly for hacking and trying a new command - once the command
12204 works you probably want to add it to `org-agenda-custom-commands' for good."
12205 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12206 (if ass
12207 (setcdr ass (cdr entry))
12208 (push entry org-agenda-custom-commands))))
12210 ;;;###autoload
12211 (defun org-store-link (arg)
12212 "\\<org-mode-map>Store an org-link to the current location.
12213 This link is added to `org-stored-links' and can later be inserted
12214 into an org-buffer with \\[org-insert-link].
12216 For some link types, a prefix arg is interpreted:
12217 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12218 For file links, arg negates `org-context-in-file-links'."
12219 (interactive "P")
12220 (org-load-modules-maybe)
12221 (setq org-store-link-plist nil) ; reset
12222 (let (link cpltxt desc description search txt)
12223 (cond
12225 ((run-hook-with-args-until-success 'org-store-link-functions)
12226 (setq link (plist-get org-store-link-plist :link)
12227 desc (or (plist-get org-store-link-plist :description) link)))
12229 ((eq major-mode 'calendar-mode)
12230 (let ((cd (calendar-cursor-to-date)))
12231 (setq link
12232 (format-time-string
12233 (car org-time-stamp-formats)
12234 (apply 'encode-time
12235 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12236 nil nil nil))))
12237 (org-store-link-props :type "calendar" :date cd)))
12239 ((eq major-mode 'w3-mode)
12240 (setq cpltxt (url-view-url t)
12241 link (org-make-link cpltxt))
12242 (org-store-link-props :type "w3" :url (url-view-url t)))
12244 ((eq major-mode 'w3m-mode)
12245 (setq cpltxt (or w3m-current-title w3m-current-url)
12246 link (org-make-link w3m-current-url))
12247 (org-store-link-props :type "w3m" :url (url-view-url t)))
12249 ((setq search (run-hook-with-args-until-success
12250 'org-create-file-search-functions))
12251 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12252 "::" search))
12253 (setq cpltxt (or description link)))
12255 ((eq major-mode 'image-mode)
12256 (setq cpltxt (concat "file:"
12257 (abbreviate-file-name buffer-file-name))
12258 link (org-make-link cpltxt))
12259 (org-store-link-props :type "image" :file buffer-file-name))
12261 ((eq major-mode 'dired-mode)
12262 ;; link to the file in the current line
12263 (setq cpltxt (concat "file:"
12264 (abbreviate-file-name
12265 (expand-file-name
12266 (dired-get-filename nil t))))
12267 link (org-make-link cpltxt)))
12269 ((and buffer-file-name (org-mode-p))
12270 ;; Just link to current headline
12271 (setq cpltxt (concat "file:"
12272 (abbreviate-file-name buffer-file-name)))
12273 ;; Add a context search string
12274 (when (org-xor org-context-in-file-links arg)
12275 ;; Check if we are on a target
12276 (if (org-in-regexp "<<\\(.*?\\)>>")
12277 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12278 (setq txt (cond
12279 ((org-on-heading-p) nil)
12280 ((org-region-active-p)
12281 (buffer-substring (region-beginning) (region-end)))
12282 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12283 (when (or (null txt) (string-match "\\S-" txt))
12284 (setq cpltxt
12285 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12286 desc "NONE"))))
12287 (if (string-match "::\\'" cpltxt)
12288 (setq cpltxt (substring cpltxt 0 -2)))
12289 (setq link (org-make-link cpltxt)))
12291 ((buffer-file-name (buffer-base-buffer))
12292 ;; Just link to this file here.
12293 (setq cpltxt (concat "file:"
12294 (abbreviate-file-name
12295 (buffer-file-name (buffer-base-buffer)))))
12296 ;; Add a context string
12297 (when (org-xor org-context-in-file-links arg)
12298 (setq txt (if (org-region-active-p)
12299 (buffer-substring (region-beginning) (region-end))
12300 (buffer-substring (point-at-bol) (point-at-eol))))
12301 ;; Only use search option if there is some text.
12302 (when (string-match "\\S-" txt)
12303 (setq cpltxt
12304 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12305 desc "NONE")))
12306 (setq link (org-make-link cpltxt)))
12308 ((interactive-p)
12309 (error "Cannot link to a buffer which is not visiting a file"))
12311 (t (setq link nil)))
12313 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12314 (setq link (or link cpltxt)
12315 desc (or desc cpltxt))
12316 (if (equal desc "NONE") (setq desc nil))
12318 (if (and (interactive-p) link)
12319 (progn
12320 (setq org-stored-links
12321 (cons (list link desc) org-stored-links))
12322 (message "Stored: %s" (or desc link)))
12323 (and link (org-make-link-string link desc)))))
12325 (defun org-store-link-props (&rest plist)
12326 "Store link properties, extract names and addresses."
12327 (let (x adr)
12328 (when (setq x (plist-get plist :from))
12329 (setq adr (mail-extract-address-components x))
12330 (plist-put plist :fromname (car adr))
12331 (plist-put plist :fromaddress (nth 1 adr)))
12332 (when (setq x (plist-get plist :to))
12333 (setq adr (mail-extract-address-components x))
12334 (plist-put plist :toname (car adr))
12335 (plist-put plist :toaddress (nth 1 adr))))
12336 (let ((from (plist-get plist :from))
12337 (to (plist-get plist :to)))
12338 (when (and from to org-from-is-user-regexp)
12339 (plist-put plist :fromto
12340 (if (string-match org-from-is-user-regexp from)
12341 (concat "to %t")
12342 (concat "from %f")))))
12343 (setq org-store-link-plist plist))
12345 (defun org-add-link-props (&rest plist)
12346 "Add these properties to the link property list."
12347 (let (key value)
12348 (while plist
12349 (setq key (pop plist) value (pop plist))
12350 (setq org-store-link-plist
12351 (plist-put org-store-link-plist key value)))))
12353 (defun org-email-link-description (&optional fmt)
12354 "Return the description part of an email link.
12355 This takes information from `org-store-link-plist' and formats it
12356 according to FMT (default from `org-email-link-description-format')."
12357 (setq fmt (or fmt org-email-link-description-format))
12358 (let* ((p org-store-link-plist)
12359 (to (plist-get p :toaddress))
12360 (from (plist-get p :fromaddress))
12361 (table
12362 (list
12363 (cons "%c" (plist-get p :fromto))
12364 (cons "%F" (plist-get p :from))
12365 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12366 (cons "%T" (plist-get p :to))
12367 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12368 (cons "%s" (plist-get p :subject))
12369 (cons "%m" (plist-get p :message-id)))))
12370 (when (string-match "%c" fmt)
12371 ;; Check if the user wrote this message
12372 (if (and org-from-is-user-regexp from to
12373 (save-match-data (string-match org-from-is-user-regexp from)))
12374 (setq fmt (replace-match "to %t" t t fmt))
12375 (setq fmt (replace-match "from %f" t t fmt))))
12376 (org-replace-escapes fmt table)))
12378 (defun org-make-org-heading-search-string (&optional string heading)
12379 "Make search string for STRING or current headline."
12380 (interactive)
12381 (let ((s (or string (org-get-heading))))
12382 (unless (and string (not heading))
12383 ;; We are using a headline, clean up garbage in there.
12384 (if (string-match org-todo-regexp s)
12385 (setq s (replace-match "" t t s)))
12386 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12387 (setq s (replace-match "" t t s)))
12388 (setq s (org-trim s))
12389 (if (string-match (concat "^\\(" org-quote-string "\\|"
12390 org-comment-string "\\)") s)
12391 (setq s (replace-match "" t t s)))
12392 (while (string-match org-ts-regexp s)
12393 (setq s (replace-match "" t t s))))
12394 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12395 (setq s (replace-match " " t t s)))
12396 (or string (setq s (concat "*" s))) ; Add * for headlines
12397 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12399 (defun org-make-link (&rest strings)
12400 "Concatenate STRINGS."
12401 (apply 'concat strings))
12403 (defun org-make-link-string (link &optional description)
12404 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12405 (unless (string-match "\\S-" link)
12406 (error "Empty link"))
12407 (when (stringp description)
12408 ;; Remove brackets from the description, they are fatal.
12409 (while (string-match "\\[" description)
12410 (setq description (replace-match "{" t t description)))
12411 (while (string-match "\\]" description)
12412 (setq description (replace-match "}" t t description))))
12413 (when (equal (org-link-escape link) description)
12414 ;; No description needed, it is identical
12415 (setq description nil))
12416 (when (and (not description)
12417 (not (equal link (org-link-escape link))))
12418 (setq description link))
12419 (concat "[[" (org-link-escape link) "]"
12420 (if description (concat "[" description "]") "")
12421 "]"))
12423 (defconst org-link-escape-chars
12424 '((?\ . "%20")
12425 (?\[ . "%5B")
12426 (?\] . "%5D")
12427 (?\340 . "%E0") ; `a
12428 (?\342 . "%E2") ; ^a
12429 (?\347 . "%E7") ; ,c
12430 (?\350 . "%E8") ; `e
12431 (?\351 . "%E9") ; 'e
12432 (?\352 . "%EA") ; ^e
12433 (?\356 . "%EE") ; ^i
12434 (?\364 . "%F4") ; ^o
12435 (?\371 . "%F9") ; `u
12436 (?\373 . "%FB") ; ^u
12437 (?\; . "%3B")
12438 (?? . "%3F")
12439 (?= . "%3D")
12440 (?+ . "%2B")
12442 "Association list of escapes for some characters problematic in links.
12443 This is the list that is used for internal purposes.")
12445 (defconst org-link-escape-chars-browser
12446 '((?\ . "%20")) ; 32 for the SPC char
12447 "Association list of escapes for some characters problematic in links.
12448 This is the list that is used before handing over to the browser.")
12450 (defun org-link-escape (text &optional table)
12451 "Escape charaters in TEXT that are problematic for links."
12452 (setq table (or table org-link-escape-chars))
12453 (when text
12454 (let ((re (mapconcat (lambda (x) (regexp-quote
12455 (char-to-string (car x))))
12456 table "\\|")))
12457 (while (string-match re text)
12458 (setq text
12459 (replace-match
12460 (cdr (assoc (string-to-char (match-string 0 text))
12461 table))
12462 t t text)))
12463 text)))
12465 (defun org-link-unescape (text &optional table)
12466 "Reverse the action of `org-link-escape'."
12467 (setq table (or table org-link-escape-chars))
12468 (when text
12469 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12470 table "\\|")))
12471 (while (string-match re text)
12472 (setq text
12473 (replace-match
12474 (char-to-string (car (rassoc (match-string 0 text) table)))
12475 t t text)))
12476 text)))
12478 (defun org-xor (a b)
12479 "Exclusive or."
12480 (if a (not b) b))
12482 (defun org-get-header (header)
12483 "Find a header field in the current buffer."
12484 (save-excursion
12485 (goto-char (point-min))
12486 (let ((case-fold-search t) s)
12487 (cond
12488 ((eq header 'from)
12489 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12490 (setq s (match-string 1)))
12491 (while (string-match "\"" s)
12492 (setq s (replace-match "" t t s)))
12493 (if (string-match "[<(].*" s)
12494 (setq s (replace-match "" t t s))))
12495 ((eq header 'message-id)
12496 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12497 (setq s (match-string 1))))
12498 ((eq header 'subject)
12499 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12500 (setq s (match-string 1)))))
12501 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12502 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12503 s)))
12506 (defun org-fixup-message-id-for-http (s)
12507 "Replace special characters in a message id, so it can be used in an http query."
12508 (while (string-match "<" s)
12509 (setq s (replace-match "%3C" t t s)))
12510 (while (string-match ">" s)
12511 (setq s (replace-match "%3E" t t s)))
12512 (while (string-match "@" s)
12513 (setq s (replace-match "%40" t t s)))
12516 ;;;###autoload
12517 (defun org-insert-link-global ()
12518 "Insert a link like Org-mode does.
12519 This command can be called in any mode to insert a link in Org-mode syntax."
12520 (interactive)
12521 (org-load-modules-maybe)
12522 (org-run-like-in-org-mode 'org-insert-link))
12524 (defun org-insert-link (&optional complete-file)
12525 "Insert a link. At the prompt, enter the link.
12527 Completion can be used to select a link previously stored with
12528 `org-store-link'. When the empty string is entered (i.e. if you just
12529 press RET at the prompt), the link defaults to the most recently
12530 stored link. As SPC triggers completion in the minibuffer, you need to
12531 use M-SPC or C-q SPC to force the insertion of a space character.
12533 You will also be prompted for a description, and if one is given, it will
12534 be displayed in the buffer instead of the link.
12536 If there is already a link at point, this command will allow you to edit link
12537 and description parts.
12539 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12540 selected using completion. The path to the file will be relative to
12541 the current directory if the file is in the current directory or a
12542 subdirectory. Otherwise, the link will be the absolute path as
12543 completed in the minibuffer (i.e. normally ~/path/to/file).
12545 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12546 is in the current directory or below.
12547 With three \\[universal-argument] prefixes, negate the meaning of
12548 `org-keep-stored-link-after-insertion'."
12549 (interactive "P")
12550 (let* ((wcf (current-window-configuration))
12551 (region (if (org-region-active-p)
12552 (buffer-substring (region-beginning) (region-end))))
12553 (remove (and region (list (region-beginning) (region-end))))
12554 (desc region)
12555 tmphist ; byte-compile incorrectly complains about this
12556 link entry file)
12557 (cond
12558 ((org-in-regexp org-bracket-link-regexp 1)
12559 ;; We do have a link at point, and we are going to edit it.
12560 (setq remove (list (match-beginning 0) (match-end 0)))
12561 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12562 (setq link (read-string "Link: "
12563 (org-link-unescape
12564 (org-match-string-no-properties 1)))))
12565 ((or (org-in-regexp org-angle-link-re)
12566 (org-in-regexp org-plain-link-re))
12567 ;; Convert to bracket link
12568 (setq remove (list (match-beginning 0) (match-end 0))
12569 link (read-string "Link: "
12570 (org-remove-angle-brackets (match-string 0)))))
12571 ((equal complete-file '(4))
12572 ;; Completing read for file names.
12573 (setq file (read-file-name "File: "))
12574 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12575 (pwd1 (file-name-as-directory (abbreviate-file-name
12576 (expand-file-name ".")))))
12577 (cond
12578 ((equal complete-file '(16))
12579 (setq link (org-make-link
12580 "file:"
12581 (abbreviate-file-name (expand-file-name file)))))
12582 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12583 (setq link (org-make-link "file:" (match-string 1 file))))
12584 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12585 (expand-file-name file))
12586 (setq link (org-make-link
12587 "file:" (match-string 1 (expand-file-name file)))))
12588 (t (setq link (org-make-link "file:" file))))))
12590 ;; Read link, with completion for stored links.
12591 (with-output-to-temp-buffer "*Org Links*"
12592 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12593 (when org-stored-links
12594 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12595 (princ (mapconcat
12596 (lambda (x)
12597 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12598 (reverse org-stored-links) "\n"))))
12599 (let ((cw (selected-window)))
12600 (select-window (get-buffer-window "*Org Links*"))
12601 (shrink-window-if-larger-than-buffer)
12602 (setq truncate-lines t)
12603 (select-window cw))
12604 ;; Fake a link history, containing the stored links.
12605 (setq tmphist (append (mapcar 'car org-stored-links)
12606 org-insert-link-history))
12607 (unwind-protect
12608 (setq link (org-completing-read
12609 "Link: "
12610 (append
12611 (mapcar (lambda (x) (list (concat (car x) ":")))
12612 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12613 (mapcar (lambda (x) (list (concat x ":")))
12614 org-link-types))
12615 nil nil nil
12616 'tmphist
12617 (or (car (car org-stored-links)))))
12618 (set-window-configuration wcf)
12619 (kill-buffer "*Org Links*"))
12620 (setq entry (assoc link org-stored-links))
12621 (or entry (push link org-insert-link-history))
12622 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12623 (not org-keep-stored-link-after-insertion))
12624 (setq org-stored-links (delq (assoc link org-stored-links)
12625 org-stored-links)))
12626 (setq desc (or desc (nth 1 entry)))))
12628 (if (string-match org-plain-link-re link)
12629 ;; URL-like link, normalize the use of angular brackets.
12630 (setq link (org-make-link (org-remove-angle-brackets link))))
12632 ;; Check if we are linking to the current file with a search option
12633 ;; If yes, simplify the link by using only the search option.
12634 (when (and buffer-file-name
12635 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12636 (let* ((path (match-string 1 link))
12637 (case-fold-search nil)
12638 (search (match-string 2 link)))
12639 (save-match-data
12640 (if (equal (file-truename buffer-file-name) (file-truename path))
12641 ;; We are linking to this same file, with a search option
12642 (setq link search)))))
12644 ;; Check if we can/should use a relative path. If yes, simplify the link
12645 (when (string-match "\\<file:\\(.*\\)" link)
12646 (let* ((path (match-string 1 link))
12647 (origpath path)
12648 (case-fold-search nil))
12649 (cond
12650 ((eq org-link-file-path-type 'absolute)
12651 (setq path (abbreviate-file-name (expand-file-name path))))
12652 ((eq org-link-file-path-type 'noabbrev)
12653 (setq path (expand-file-name path)))
12654 ((eq org-link-file-path-type 'relative)
12655 (setq path (file-relative-name path)))
12657 (save-match-data
12658 (if (string-match (concat "^" (regexp-quote
12659 (file-name-as-directory
12660 (expand-file-name "."))))
12661 (expand-file-name path))
12662 ;; We are linking a file with relative path name.
12663 (setq path (substring (expand-file-name path)
12664 (match-end 0)))))))
12665 (setq link (concat "file:" path))
12666 (if (equal desc origpath)
12667 (setq desc path))))
12669 (setq desc (read-string "Description: " desc))
12670 (unless (string-match "\\S-" desc) (setq desc nil))
12671 (if remove (apply 'delete-region remove))
12672 (insert (org-make-link-string link desc))))
12674 (defun org-completing-read (&rest args)
12675 (let ((minibuffer-local-completion-map
12676 (copy-keymap minibuffer-local-completion-map)))
12677 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12678 (apply 'completing-read args)))
12680 ;;; Opening/following a link
12681 (defvar org-link-search-failed nil)
12683 (defun org-next-link ()
12684 "Move forward to the next link.
12685 If the link is in hidden text, expose it."
12686 (interactive)
12687 (when (and org-link-search-failed (eq this-command last-command))
12688 (goto-char (point-min))
12689 (message "Link search wrapped back to beginning of buffer"))
12690 (setq org-link-search-failed nil)
12691 (let* ((pos (point))
12692 (ct (org-context))
12693 (a (assoc :link ct)))
12694 (if a (goto-char (nth 2 a)))
12695 (if (re-search-forward org-any-link-re nil t)
12696 (progn
12697 (goto-char (match-beginning 0))
12698 (if (org-invisible-p) (org-show-context)))
12699 (goto-char pos)
12700 (setq org-link-search-failed t)
12701 (error "No further link found"))))
12703 (defun org-previous-link ()
12704 "Move backward to the previous link.
12705 If the link is in hidden text, expose it."
12706 (interactive)
12707 (when (and org-link-search-failed (eq this-command last-command))
12708 (goto-char (point-max))
12709 (message "Link search wrapped back to end of buffer"))
12710 (setq org-link-search-failed nil)
12711 (let* ((pos (point))
12712 (ct (org-context))
12713 (a (assoc :link ct)))
12714 (if a (goto-char (nth 1 a)))
12715 (if (re-search-backward org-any-link-re nil t)
12716 (progn
12717 (goto-char (match-beginning 0))
12718 (if (org-invisible-p) (org-show-context)))
12719 (goto-char pos)
12720 (setq org-link-search-failed t)
12721 (error "No further link found"))))
12723 (defun org-find-file-at-mouse (ev)
12724 "Open file link or URL at mouse."
12725 (interactive "e")
12726 (mouse-set-point ev)
12727 (org-open-at-point 'in-emacs))
12729 (defun org-open-at-mouse (ev)
12730 "Open file link or URL at mouse."
12731 (interactive "e")
12732 (mouse-set-point ev)
12733 (org-open-at-point))
12735 (defvar org-window-config-before-follow-link nil
12736 "The window configuration before following a link.
12737 This is saved in case the need arises to restore it.")
12739 (defvar org-open-link-marker (make-marker)
12740 "Marker pointing to the location where `org-open-at-point; was called.")
12742 ;;;###autoload
12743 (defun org-open-at-point-global ()
12744 "Follow a link like Org-mode does.
12745 This command can be called in any mode to follow a link that has
12746 Org-mode syntax."
12747 (interactive)
12748 (org-run-like-in-org-mode 'org-open-at-point))
12750 (defun org-open-at-point (&optional in-emacs)
12751 "Open link at or after point.
12752 If there is no link at point, this function will search forward up to
12753 the end of the current subtree.
12754 Normally, files will be opened by an appropriate application. If the
12755 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12756 (interactive "P")
12757 (org-load-modules-maybe)
12758 (move-marker org-open-link-marker (point))
12759 (setq org-window-config-before-follow-link (current-window-configuration))
12760 (org-remove-occur-highlights nil nil t)
12761 (if (org-at-timestamp-p t)
12762 (org-follow-timestamp-link)
12763 (let (type path link line search (pos (point)))
12764 (catch 'match
12765 (save-excursion
12766 (skip-chars-forward "^]\n\r")
12767 (when (org-in-regexp org-bracket-link-regexp)
12768 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12769 (while (string-match " *\n *" link)
12770 (setq link (replace-match " " t t link)))
12771 (setq link (org-link-expand-abbrev link))
12772 (if (string-match org-link-re-with-space2 link)
12773 (setq type (match-string 1 link) path (match-string 2 link))
12774 (setq type "thisfile" path link))
12775 (throw 'match t)))
12777 (when (get-text-property (point) 'org-linked-text)
12778 (setq type "thisfile"
12779 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12780 (1+ (point)) (point))
12781 path (buffer-substring
12782 (previous-single-property-change pos 'org-linked-text)
12783 (next-single-property-change pos 'org-linked-text)))
12784 (throw 'match t))
12786 (save-excursion
12787 (when (or (org-in-regexp org-angle-link-re)
12788 (org-in-regexp org-plain-link-re))
12789 (setq type (match-string 1) path (match-string 2))
12790 (throw 'match t)))
12791 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12792 (setq type "tree-match"
12793 path (match-string 1))
12794 (throw 'match t))
12795 (save-excursion
12796 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12797 (setq type "tags"
12798 path (match-string 1))
12799 (while (string-match ":" path)
12800 (setq path (replace-match "+" t t path)))
12801 (throw 'match t))))
12802 (unless path
12803 (error "No link found"))
12804 ;; Remove any trailing spaces in path
12805 (if (string-match " +\\'" path)
12806 (setq path (replace-match "" t t path)))
12808 (cond
12810 ((assoc type org-link-protocols)
12811 (funcall (nth 1 (assoc type org-link-protocols)) path))
12813 ((equal type "mailto")
12814 (let ((cmd (car org-link-mailto-program))
12815 (args (cdr org-link-mailto-program)) args1
12816 (address path) (subject "") a)
12817 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12818 (setq address (match-string 1 path)
12819 subject (org-link-escape (match-string 2 path))))
12820 (while args
12821 (cond
12822 ((not (stringp (car args))) (push (pop args) args1))
12823 (t (setq a (pop args))
12824 (if (string-match "%a" a)
12825 (setq a (replace-match address t t a)))
12826 (if (string-match "%s" a)
12827 (setq a (replace-match subject t t a)))
12828 (push a args1))))
12829 (apply cmd (nreverse args1))))
12831 ((member type '("http" "https" "ftp" "news"))
12832 (browse-url (concat type ":" (org-link-escape
12833 path org-link-escape-chars-browser))))
12835 ((member type '("message"))
12836 (browse-url (concat type ":" path)))
12838 ((string= type "tags")
12839 (org-tags-view in-emacs path))
12840 ((string= type "thisfile")
12841 (if in-emacs
12842 (switch-to-buffer-other-window
12843 (org-get-buffer-for-internal-link (current-buffer)))
12844 (org-mark-ring-push))
12845 (let ((cmd `(org-link-search
12846 ,path
12847 ,(cond ((equal in-emacs '(4)) 'occur)
12848 ((equal in-emacs '(16)) 'org-occur)
12849 (t nil))
12850 ,pos)))
12851 (condition-case nil (eval cmd)
12852 (error (progn (widen) (eval cmd))))))
12854 ((string= type "tree-match")
12855 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12857 ((string= type "file")
12858 (if (string-match "::\\([0-9]+\\)\\'" path)
12859 (setq line (string-to-number (match-string 1 path))
12860 path (substring path 0 (match-beginning 0)))
12861 (if (string-match "::\\(.+\\)\\'" path)
12862 (setq search (match-string 1 path)
12863 path (substring path 0 (match-beginning 0)))))
12864 (if (string-match "[*?{]" (file-name-nondirectory path))
12865 (dired path)
12866 (org-open-file path in-emacs line search)))
12868 ((string= type "news")
12869 (require 'org-gnus)
12870 (org-gnus-follow-link path))
12872 ((string= type "shell")
12873 (let ((cmd path))
12874 (if (or (not org-confirm-shell-link-function)
12875 (funcall org-confirm-shell-link-function
12876 (format "Execute \"%s\" in shell? "
12877 (org-add-props cmd nil
12878 'face 'org-warning))))
12879 (progn
12880 (message "Executing %s" cmd)
12881 (shell-command cmd))
12882 (error "Abort"))))
12884 ((string= type "elisp")
12885 (let ((cmd path))
12886 (if (or (not org-confirm-elisp-link-function)
12887 (funcall org-confirm-elisp-link-function
12888 (format "Execute \"%s\" as elisp? "
12889 (org-add-props cmd nil
12890 'face 'org-warning))))
12891 (message "%s => %s" cmd (eval (read cmd)))
12892 (error "Abort"))))
12895 (browse-url-at-point)))))
12896 (move-marker org-open-link-marker nil)
12897 (run-hook-with-args 'org-follow-link-hook))
12899 ;;; File search
12901 (defvar org-create-file-search-functions nil
12902 "List of functions to construct the right search string for a file link.
12903 These functions are called in turn with point at the location to
12904 which the link should point.
12906 A function in the hook should first test if it would like to
12907 handle this file type, for example by checking the major-mode or
12908 the file extension. If it decides not to handle this file, it
12909 should just return nil to give other functions a chance. If it
12910 does handle the file, it must return the search string to be used
12911 when following the link. The search string will be part of the
12912 file link, given after a double colon, and `org-open-at-point'
12913 will automatically search for it. If special measures must be
12914 taken to make the search successful, another function should be
12915 added to the companion hook `org-execute-file-search-functions',
12916 which see.
12918 A function in this hook may also use `setq' to set the variable
12919 `description' to provide a suggestion for the descriptive text to
12920 be used for this link when it gets inserted into an Org-mode
12921 buffer with \\[org-insert-link].")
12923 (defvar org-execute-file-search-functions nil
12924 "List of functions to execute a file search triggered by a link.
12926 Functions added to this hook must accept a single argument, the
12927 search string that was part of the file link, the part after the
12928 double colon. The function must first check if it would like to
12929 handle this search, for example by checking the major-mode or the
12930 file extension. If it decides not to handle this search, it
12931 should just return nil to give other functions a chance. If it
12932 does handle the search, it must return a non-nil value to keep
12933 other functions from trying.
12935 Each function can access the current prefix argument through the
12936 variable `current-prefix-argument'. Note that a single prefix is
12937 used to force opening a link in Emacs, so it may be good to only
12938 use a numeric or double prefix to guide the search function.
12940 In case this is needed, a function in this hook can also restore
12941 the window configuration before `org-open-at-point' was called using:
12943 (set-window-configuration org-window-config-before-follow-link)")
12945 (defun org-link-search (s &optional type avoid-pos)
12946 "Search for a link search option.
12947 If S is surrounded by forward slashes, it is interpreted as a
12948 regular expression. In org-mode files, this will create an `org-occur'
12949 sparse tree. In ordinary files, `occur' will be used to list matches.
12950 If the current buffer is in `dired-mode', grep will be used to search
12951 in all files. If AVOID-POS is given, ignore matches near that position."
12952 (let ((case-fold-search t)
12953 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12954 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12955 (append '(("") (" ") ("\t") ("\n"))
12956 org-emphasis-alist)
12957 "\\|") "\\)"))
12958 (pos (point))
12959 (pre "") (post "")
12960 words re0 re1 re2 re3 re4 re5 re2a reall)
12961 (cond
12962 ;; First check if there are any special
12963 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12964 ;; Now try the builtin stuff
12965 ((save-excursion
12966 (goto-char (point-min))
12967 (and
12968 (re-search-forward
12969 (concat "<<" (regexp-quote s0) ">>") nil t)
12970 (setq pos (match-beginning 0))))
12971 ;; There is an exact target for this
12972 (goto-char pos))
12973 ((string-match "^/\\(.*\\)/$" s)
12974 ;; A regular expression
12975 (cond
12976 ((org-mode-p)
12977 (org-occur (match-string 1 s)))
12978 ;;((eq major-mode 'dired-mode)
12979 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12980 (t (org-do-occur (match-string 1 s)))))
12982 ;; A normal search strings
12983 (when (equal (string-to-char s) ?*)
12984 ;; Anchor on headlines, post may include tags.
12985 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12986 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12987 s (substring s 1)))
12988 (remove-text-properties
12989 0 (length s)
12990 '(face nil mouse-face nil keymap nil fontified nil) s)
12991 ;; Make a series of regular expressions to find a match
12992 (setq words (org-split-string s "[ \n\r\t]+")
12993 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12994 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12995 "\\)" markers)
12996 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12997 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12998 re1 (concat pre re2 post)
12999 re3 (concat pre re4 post)
13000 re5 (concat pre ".*" re4)
13001 re2 (concat pre re2)
13002 re2a (concat pre re2a)
13003 re4 (concat pre re4)
13004 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13005 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13006 re5 "\\)"
13008 (cond
13009 ((eq type 'org-occur) (org-occur reall))
13010 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13011 (t (goto-char (point-min))
13012 (if (or (org-search-not-self 1 re0 nil t)
13013 (org-search-not-self 1 re1 nil t)
13014 (org-search-not-self 1 re2 nil t)
13015 (org-search-not-self 1 re2a nil t)
13016 (org-search-not-self 1 re3 nil t)
13017 (org-search-not-self 1 re4 nil t)
13018 (org-search-not-self 1 re5 nil t)
13020 (goto-char (match-beginning 1))
13021 (goto-char pos)
13022 (error "No match")))))
13024 ;; Normal string-search
13025 (goto-char (point-min))
13026 (if (search-forward s nil t)
13027 (goto-char (match-beginning 0))
13028 (error "No match"))))
13029 (and (org-mode-p) (org-show-context 'link-search))))
13031 (defun org-search-not-self (group &rest args)
13032 "Execute `re-search-forward', but only accept matches that do not
13033 enclose the position of `org-open-link-marker'."
13034 (let ((m org-open-link-marker))
13035 (catch 'exit
13036 (while (apply 're-search-forward args)
13037 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13038 (goto-char (match-end group))
13039 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13040 (> (match-beginning 0) (marker-position m))
13041 (< (match-end 0) (marker-position m)))
13042 (save-match-data
13043 (or (not (org-in-regexp
13044 org-bracket-link-analytic-regexp 1))
13045 (not (match-end 4)) ; no description
13046 (and (<= (match-beginning 4) (point))
13047 (>= (match-end 4) (point))))))
13048 (throw 'exit (point))))))))
13050 (defun org-get-buffer-for-internal-link (buffer)
13051 "Return a buffer to be used for displaying the link target of internal links."
13052 (cond
13053 ((not org-display-internal-link-with-indirect-buffer)
13054 buffer)
13055 ((string-match "(Clone)$" (buffer-name buffer))
13056 (message "Buffer is already a clone, not making another one")
13057 ;; we also do not modify visibility in this case
13058 buffer)
13059 (t ; make a new indirect buffer for displaying the link
13060 (let* ((bn (buffer-name buffer))
13061 (ibn (concat bn "(Clone)"))
13062 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13063 (with-current-buffer ib (org-overview))
13064 ib))))
13066 (defun org-do-occur (regexp &optional cleanup)
13067 "Call the Emacs command `occur'.
13068 If CLEANUP is non-nil, remove the printout of the regular expression
13069 in the *Occur* buffer. This is useful if the regex is long and not useful
13070 to read."
13071 (occur regexp)
13072 (when cleanup
13073 (let ((cwin (selected-window)) win beg end)
13074 (when (setq win (get-buffer-window "*Occur*"))
13075 (select-window win))
13076 (goto-char (point-min))
13077 (when (re-search-forward "match[a-z]+" nil t)
13078 (setq beg (match-end 0))
13079 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13080 (setq end (1- (match-beginning 0)))))
13081 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13082 (goto-char (point-min))
13083 (select-window cwin))))
13085 ;;; The mark ring for links jumps
13087 (defvar org-mark-ring nil
13088 "Mark ring for positions before jumps in Org-mode.")
13089 (defvar org-mark-ring-last-goto nil
13090 "Last position in the mark ring used to go back.")
13091 ;; Fill and close the ring
13092 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13093 (loop for i from 1 to org-mark-ring-length do
13094 (push (make-marker) org-mark-ring))
13095 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13096 org-mark-ring)
13098 (defun org-mark-ring-push (&optional pos buffer)
13099 "Put the current position or POS into the mark ring and rotate it."
13100 (interactive)
13101 (setq pos (or pos (point)))
13102 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13103 (move-marker (car org-mark-ring)
13104 (or pos (point))
13105 (or buffer (current-buffer)))
13106 (message "%s"
13107 (substitute-command-keys
13108 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13110 (defun org-mark-ring-goto (&optional n)
13111 "Jump to the previous position in the mark ring.
13112 With prefix arg N, jump back that many stored positions. When
13113 called several times in succession, walk through the entire ring.
13114 Org-mode commands jumping to a different position in the current file,
13115 or to another Org-mode file, automatically push the old position
13116 onto the ring."
13117 (interactive "p")
13118 (let (p m)
13119 (if (eq last-command this-command)
13120 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13121 (setq p org-mark-ring))
13122 (setq org-mark-ring-last-goto p)
13123 (setq m (car p))
13124 (switch-to-buffer (marker-buffer m))
13125 (goto-char m)
13126 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13128 (defun org-remove-angle-brackets (s)
13129 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13130 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13132 (defun org-add-angle-brackets (s)
13133 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13134 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13137 ;;; Following specific links
13139 (defun org-follow-timestamp-link ()
13140 (cond
13141 ((org-at-date-range-p t)
13142 (let ((org-agenda-start-on-weekday)
13143 (t1 (match-string 1))
13144 (t2 (match-string 2)))
13145 (setq t1 (time-to-days (org-time-string-to-time t1))
13146 t2 (time-to-days (org-time-string-to-time t2)))
13147 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13148 ((org-at-timestamp-p t)
13149 (org-agenda-list nil (time-to-days (org-time-string-to-time
13150 (substring (match-string 1) 0 10)))
13152 (t (error "This should not happen"))))
13155 ;;; BibTeX links
13157 ;; Use the custom search meachnism to construct and use search strings for
13158 ;; file links to BibTeX database entries.
13160 (defun org-create-file-search-in-bibtex ()
13161 "Create the search string and description for a BibTeX database entry."
13162 (when (eq major-mode 'bibtex-mode)
13163 ;; yes, we want to construct this search string.
13164 ;; Make a good description for this entry, using names, year and the title
13165 ;; Put it into the `description' variable which is dynamically scoped.
13166 (let ((bibtex-autokey-names 1)
13167 (bibtex-autokey-names-stretch 1)
13168 (bibtex-autokey-name-case-convert-function 'identity)
13169 (bibtex-autokey-name-separator " & ")
13170 (bibtex-autokey-additional-names " et al.")
13171 (bibtex-autokey-year-length 4)
13172 (bibtex-autokey-name-year-separator " ")
13173 (bibtex-autokey-titlewords 3)
13174 (bibtex-autokey-titleword-separator " ")
13175 (bibtex-autokey-titleword-case-convert-function 'identity)
13176 (bibtex-autokey-titleword-length 'infty)
13177 (bibtex-autokey-year-title-separator ": "))
13178 (setq description (bibtex-generate-autokey)))
13179 ;; Now parse the entry, get the key and return it.
13180 (save-excursion
13181 (bibtex-beginning-of-entry)
13182 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13184 (defun org-execute-file-search-in-bibtex (s)
13185 "Find the link search string S as a key for a database entry."
13186 (when (eq major-mode 'bibtex-mode)
13187 ;; Yes, we want to do the search in this file.
13188 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13189 (goto-char (point-min))
13190 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13191 (regexp-quote s) "[ \t\n]*,") nil t)
13192 (goto-char (match-beginning 0)))
13193 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13194 ;; Use double prefix to indicate that any web link should be browsed
13195 (let ((b (current-buffer)) (p (point)))
13196 ;; Restore the window configuration because we just use the web link
13197 (set-window-configuration org-window-config-before-follow-link)
13198 (save-excursion (set-buffer b) (goto-char p)
13199 (bibtex-url)))
13200 (recenter 0)) ; Move entry start to beginning of window
13201 ;; return t to indicate that the search is done.
13204 ;; Finally add the functions to the right hooks.
13205 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13206 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13208 ;; end of Bibtex link setup
13210 ;;; Following file links
13212 (defun org-open-file (path &optional in-emacs line search)
13213 "Open the file at PATH.
13214 First, this expands any special file name abbreviations. Then the
13215 configuration variable `org-file-apps' is checked if it contains an
13216 entry for this file type, and if yes, the corresponding command is launched.
13217 If no application is found, Emacs simply visits the file.
13218 With optional argument IN-EMACS, Emacs will visit the file.
13219 Optional LINE specifies a line to go to, optional SEARCH a string to
13220 search for. If LINE or SEARCH is given, the file will always be
13221 opened in Emacs.
13222 If the file does not exist, an error is thrown."
13223 (setq in-emacs (or in-emacs line search))
13224 (let* ((file (if (equal path "")
13225 buffer-file-name
13226 (substitute-in-file-name (expand-file-name path))))
13227 (apps (append org-file-apps (org-default-apps)))
13228 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13229 (dirp (if remp nil (file-directory-p file)))
13230 (dfile (downcase file))
13231 (old-buffer (current-buffer))
13232 (old-pos (point))
13233 (old-mode major-mode)
13234 ext cmd)
13235 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13236 (setq ext (match-string 1 dfile))
13237 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13238 (setq ext (match-string 1 dfile))))
13239 (if in-emacs
13240 (setq cmd 'emacs)
13241 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13242 (and dirp (cdr (assoc 'directory apps)))
13243 (cdr (assoc ext apps))
13244 (cdr (assoc t apps)))))
13245 (when (eq cmd 'mailcap)
13246 (require 'mailcap)
13247 (mailcap-parse-mailcaps)
13248 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13249 (command (mailcap-mime-info mime-type)))
13250 (if (stringp command)
13251 (setq cmd command)
13252 (setq cmd 'emacs))))
13253 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13254 (not (file-exists-p file))
13255 (not org-open-non-existing-files))
13256 (error "No such file: %s" file))
13257 (cond
13258 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13259 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13260 (while (string-match "['\"]%s['\"]" cmd)
13261 (setq cmd (replace-match "%s" t t cmd)))
13262 (while (string-match "%s" cmd)
13263 (setq cmd (replace-match
13264 (save-match-data (shell-quote-argument file))
13265 t t cmd)))
13266 (save-window-excursion
13267 (start-process-shell-command cmd nil cmd)))
13268 ((or (stringp cmd)
13269 (eq cmd 'emacs))
13270 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13271 (widen)
13272 (if line (goto-line line)
13273 (if search (org-link-search search))))
13274 ((consp cmd)
13275 (eval cmd))
13276 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13277 (and (org-mode-p) (eq old-mode 'org-mode)
13278 (or (not (equal old-buffer (current-buffer)))
13279 (not (equal old-pos (point))))
13280 (org-mark-ring-push old-pos old-buffer))))
13282 (defun org-default-apps ()
13283 "Return the default applications for this operating system."
13284 (cond
13285 ((eq system-type 'darwin)
13286 org-file-apps-defaults-macosx)
13287 ((eq system-type 'windows-nt)
13288 org-file-apps-defaults-windowsnt)
13289 (t org-file-apps-defaults-gnu)))
13291 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13292 (defun org-file-remote-p (file)
13293 "Test whether FILE specifies a location on a remote system.
13294 Return non-nil if the location is indeed remote.
13296 For example, the filename \"/user@host:/foo\" specifies a location
13297 on the system \"/user@host:\"."
13298 (cond ((fboundp 'file-remote-p)
13299 (file-remote-p file))
13300 ((fboundp 'tramp-handle-file-remote-p)
13301 (tramp-handle-file-remote-p file))
13302 ((and (boundp 'ange-ftp-name-format)
13303 (string-match (car ange-ftp-name-format) file))
13305 (t nil)))
13308 ;;;; Hooks for remember.el, and refiling
13310 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13311 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13313 ;;;###autoload
13314 (defun org-remember-insinuate ()
13315 "Setup remember.el for use wiht Org-mode."
13316 (require 'remember)
13317 (setq remember-annotation-functions '(org-remember-annotation))
13318 (setq remember-handler-functions '(org-remember-handler))
13319 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13321 ;;;###autoload
13322 (defun org-remember-annotation ()
13323 "Return a link to the current location as an annotation for remember.el.
13324 If you are using Org-mode files as target for data storage with
13325 remember.el, then the annotations should include a link compatible with the
13326 conventions in Org-mode. This function returns such a link."
13327 (org-store-link nil))
13329 (defconst org-remember-help
13330 "Select a destination location for the note.
13331 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13332 RET on headline -> Store as sublevel entry to current headline
13333 RET at beg-of-buf -> Append to file as level 2 headline
13334 <left>/<right> -> before/after current headline, same headings level")
13336 (defvar org-remember-previous-location nil)
13337 (defvar org-force-remember-template-char) ;; dynamically scoped
13339 ;; Save the major mode of the buffer we called remember from
13340 (defvar org-select-template-temp-major-mode nil)
13342 ;; Temporary store the buffer where remember was called from
13343 (defvar org-select-template-original-buffer nil)
13345 (defun org-select-remember-template (&optional use-char)
13346 (when org-remember-templates
13347 (let* ((pre-selected-templates
13348 (mapcar
13349 (lambda (tpl)
13350 (let ((ctxt (nth 5 tpl))
13351 (mode org-select-template-temp-major-mode)
13352 (buf org-select-template-original-buffer))
13353 (and (or (not ctxt) (eq ctxt t)
13354 (and (listp ctxt) (memq mode ctxt))
13355 (and (functionp ctxt)
13356 (with-current-buffer buf
13357 ;; Protect the user-defined function from error
13358 (condition-case nil (funcall ctxt) (error nil)))))
13359 tpl)))
13360 org-remember-templates))
13361 ;; If no template at this point, add the default templates:
13362 (pre-selected-templates1
13363 (if (not (delq nil pre-selected-templates))
13364 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13365 org-remember-templates)
13366 pre-selected-templates))
13367 ;; Then unconditionnally add template for any contexts
13368 (pre-selected-templates2
13369 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13370 org-remember-templates)
13371 (delq nil pre-selected-templates1)))
13372 (templates (mapcar (lambda (x)
13373 (if (stringp (car x))
13374 (append (list (nth 1 x) (car x)) (cddr x))
13375 (append (list (car x) "") (cdr x))))
13376 (delq nil pre-selected-templates2)))
13377 (char (or use-char
13378 (cond
13379 ((= (length templates) 1)
13380 (caar templates))
13381 ((and (boundp 'org-force-remember-template-char)
13382 org-force-remember-template-char)
13383 (if (stringp org-force-remember-template-char)
13384 (string-to-char org-force-remember-template-char)
13385 org-force-remember-template-char))
13387 (message "Select template: %s"
13388 (mapconcat
13389 (lambda (x)
13390 (cond
13391 ((not (string-match "\\S-" (nth 1 x)))
13392 (format "[%c]" (car x)))
13393 ((equal (downcase (car x))
13394 (downcase (aref (nth 1 x) 0)))
13395 (format "[%c]%s" (car x)
13396 (substring (nth 1 x) 1)))
13397 (t (format "[%c]%s" (car x) (nth 1 x)))))
13398 templates " "))
13399 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13400 (when (equal char0 ?\C-g)
13401 (jump-to-register remember-register)
13402 (kill-buffer remember-buffer))
13403 char0))))))
13404 (cddr (assoc char templates)))))
13406 (defvar x-last-selected-text)
13407 (defvar x-last-selected-text-primary)
13409 ;;;###autoload
13410 (defun org-remember-apply-template (&optional use-char skip-interactive)
13411 "Initialize *remember* buffer with template, invoke `org-mode'.
13412 This function should be placed into `remember-mode-hook' and in fact requires
13413 to be run from that hook to function properly."
13414 (if org-remember-templates
13415 (let* ((entry (org-select-remember-template use-char))
13416 (tpl (car entry))
13417 (plist-p (if org-store-link-plist t nil))
13418 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13419 (string-match "\\S-" (nth 1 entry)))
13420 (nth 1 entry)
13421 org-default-notes-file))
13422 (headline (nth 2 entry))
13423 (v-c (or (and (eq window-system 'x)
13424 (fboundp 'x-cut-buffer-or-selection-value)
13425 (x-cut-buffer-or-selection-value))
13426 (org-bound-and-true-p x-last-selected-text)
13427 (org-bound-and-true-p x-last-selected-text-primary)
13428 (and (> (length kill-ring) 0) (current-kill 0))))
13429 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13430 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13431 (v-u (concat "[" (substring v-t 1 -1) "]"))
13432 (v-U (concat "[" (substring v-T 1 -1) "]"))
13433 ;; `initial' and `annotation' are bound in `remember'
13434 (v-i (if (boundp 'initial) initial))
13435 (v-a (if (and (boundp 'annotation) annotation)
13436 (if (equal annotation "[[]]") "" annotation)
13437 ""))
13438 (v-A (if (and v-a
13439 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13440 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13441 v-a))
13442 (v-n user-full-name)
13443 (org-startup-folded nil)
13444 org-time-was-given org-end-time-was-given x
13445 prompt completions char time pos default histvar)
13446 (when (and file (not (file-name-absolute-p file)))
13447 (setq file (expand-file-name file org-directory)))
13448 (setq org-store-link-plist
13449 (append (list :annotation v-a :initial v-i)
13450 org-store-link-plist))
13451 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13452 (erase-buffer)
13453 (insert (substitute-command-keys
13454 (format
13455 "## Filing location: Select interactively, default, or last used:
13456 ## %s to select file and header location interactively.
13457 ## %s \"%s\" -> \"* %s\"
13458 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13459 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13460 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13461 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13462 (abbreviate-file-name (or file org-default-notes-file))
13463 (or headline "")
13464 (or (car org-remember-previous-location) "???")
13465 (or (cdr org-remember-previous-location) "???"))))
13466 (insert tpl) (goto-char (point-min))
13467 ;; Simple %-escapes
13468 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13469 (when (and initial (equal (match-string 0) "%i"))
13470 (save-match-data
13471 (let* ((lead (buffer-substring
13472 (point-at-bol) (match-beginning 0))))
13473 (setq v-i (mapconcat 'identity
13474 (org-split-string initial "\n")
13475 (concat "\n" lead))))))
13476 (replace-match
13477 (or (eval (intern (concat "v-" (match-string 1)))) "")
13478 t t))
13480 ;; %[] Insert contents of a file.
13481 (goto-char (point-min))
13482 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13483 (let ((start (match-beginning 0))
13484 (end (match-end 0))
13485 (filename (expand-file-name (match-string 1))))
13486 (goto-char start)
13487 (delete-region start end)
13488 (condition-case error
13489 (insert-file-contents filename)
13490 (error (insert (format "%%![Couldn't insert %s: %s]"
13491 filename error))))))
13492 ;; %() embedded elisp
13493 (goto-char (point-min))
13494 (while (re-search-forward "%\\((.+)\\)" nil t)
13495 (goto-char (match-beginning 0))
13496 (let ((template-start (point)))
13497 (forward-char 1)
13498 (let ((result
13499 (condition-case error
13500 (eval (read (current-buffer)))
13501 (error (format "%%![Error: %s]" error)))))
13502 (delete-region template-start (point))
13503 (insert result))))
13505 ;; From the property list
13506 (when plist-p
13507 (goto-char (point-min))
13508 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13509 (and (setq x (or (plist-get org-store-link-plist
13510 (intern (match-string 1))) ""))
13511 (replace-match x t t))))
13513 ;; Turn on org-mode in the remember buffer, set local variables
13514 (org-mode)
13515 (org-set-local 'org-finish-function 'org-remember-finalize)
13516 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13517 (org-set-local 'org-default-notes-file file))
13518 (if (and headline (stringp headline) (string-match "\\S-" headline))
13519 (org-set-local 'org-remember-default-headline headline))
13520 ;; Interactive template entries
13521 (goto-char (point-min))
13522 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13523 (setq char (if (match-end 3) (match-string 3))
13524 prompt (if (match-end 2) (match-string 2)))
13525 (goto-char (match-beginning 0))
13526 (replace-match "")
13527 (setq completions nil default nil)
13528 (when prompt
13529 (setq completions (org-split-string prompt "|")
13530 prompt (pop completions)
13531 default (car completions)
13532 histvar (intern (concat
13533 "org-remember-template-prompt-history::"
13534 (or prompt "")))
13535 completions (mapcar 'list completions)))
13536 (cond
13537 ((member char '("G" "g"))
13538 (let* ((org-last-tags-completion-table
13539 (org-global-tags-completion-table
13540 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13541 (org-add-colon-after-tag-completion t)
13542 (ins (completing-read
13543 (if prompt (concat prompt ": ") "Tags: ")
13544 'org-tags-completion-function nil nil nil
13545 'org-tags-history)))
13546 (setq ins (mapconcat 'identity
13547 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13548 ":"))
13549 (when (string-match "\\S-" ins)
13550 (or (equal (char-before) ?:) (insert ":"))
13551 (insert ins)
13552 (or (equal (char-after) ?:) (insert ":")))))
13553 (char
13554 (setq org-time-was-given (equal (upcase char) char))
13555 (setq time (org-read-date (equal (upcase char) "U") t nil
13556 prompt))
13557 (org-insert-time-stamp time org-time-was-given
13558 (member char '("u" "U"))
13559 nil nil (list org-end-time-was-given)))
13561 (insert (org-completing-read
13562 (concat (if prompt prompt "Enter string")
13563 (if default (concat " [" default "]"))
13564 ": ")
13565 completions nil nil nil histvar default)))))
13566 (goto-char (point-min))
13567 (if (re-search-forward "%\\?" nil t)
13568 (replace-match "")
13569 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13570 (org-mode)
13571 (org-set-local 'org-finish-function 'org-remember-finalize))
13572 (when (save-excursion
13573 (goto-char (point-min))
13574 (re-search-forward "%!" nil t))
13575 (replace-match "")
13576 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13578 (defun org-remember-finish-immediately ()
13579 "File remember note immediately.
13580 This should be run in `post-command-hook' and will remove itself
13581 from that hook."
13582 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13583 (when org-finish-function
13584 (funcall org-finish-function)))
13586 (defvar org-clock-marker) ; Defined below
13587 (defun org-remember-finalize ()
13588 "Finalize the remember process."
13589 (unless (fboundp 'remember-finalize)
13590 (defalias 'remember-finalize 'remember-buffer))
13591 (when (and org-clock-marker
13592 (equal (marker-buffer org-clock-marker) (current-buffer)))
13593 ;; FIXME: test this, this is w/o notetaking!
13594 (let (org-log-note-clock-out) (org-clock-out)))
13595 (when buffer-file-name
13596 (save-buffer)
13597 (setq buffer-file-name nil))
13598 (remember-finalize))
13600 ;;;###autoload
13601 (defun org-remember (&optional goto org-force-remember-template-char)
13602 "Call `remember'. If this is already a remember buffer, re-apply template.
13603 If there is an active region, make sure remember uses it as initial content
13604 of the remember buffer.
13606 When called interactively with a `C-u' prefix argument GOTO, don't remember
13607 anything, just go to the file/headline where the selected template usually
13608 stores its notes. With a double prefix arg `C-u C-u', go to the last
13609 note stored by remember.
13611 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13612 associated with a template in `org-remember-templates'."
13613 (interactive "P")
13614 (cond
13615 ((equal goto '(4)) (org-go-to-remember-target))
13616 ((equal goto '(16)) (org-remember-goto-last-stored))
13618 ;; set temporary variables that will be needed in
13619 ;; `org-select-remember-template'
13620 (setq org-select-template-temp-major-mode major-mode)
13621 (setq org-select-template-original-buffer (current-buffer))
13622 (if (memq org-finish-function '(remember-buffer remember-finalize))
13623 (progn
13624 (when (< (length org-remember-templates) 2)
13625 (error "No other template available"))
13626 (erase-buffer)
13627 (let ((annotation (plist-get org-store-link-plist :annotation))
13628 (initial (plist-get org-store-link-plist :initial)))
13629 (org-remember-apply-template))
13630 (message "Press C-c C-c to remember data"))
13631 (if (org-region-active-p)
13632 (remember (buffer-substring (point) (mark)))
13633 (call-interactively 'remember))))))
13635 (defun org-remember-goto-last-stored ()
13636 "Go to the location where the last remember note was stored."
13637 (interactive)
13638 (bookmark-jump "org-remember-last-stored")
13639 (message "This is the last note stored by remember"))
13641 (defun org-go-to-remember-target (&optional template-key)
13642 "Go to the target location of a remember template.
13643 The user is queried for the template."
13644 (interactive)
13645 (let* (org-select-template-temp-major-mode
13646 (entry (org-select-remember-template template-key))
13647 (file (nth 1 entry))
13648 (heading (nth 2 entry))
13649 visiting)
13650 (unless (and file (stringp file) (string-match "\\S-" file))
13651 (setq file org-default-notes-file))
13652 (when (and file (not (file-name-absolute-p file)))
13653 (setq file (expand-file-name file org-directory)))
13654 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13655 (setq heading org-remember-default-headline))
13656 (setq visiting (org-find-base-buffer-visiting file))
13657 (if (not visiting) (find-file-noselect file))
13658 (switch-to-buffer (or visiting (get-file-buffer file)))
13659 (widen)
13660 (goto-char (point-min))
13661 (if (re-search-forward
13662 (concat "^\\*+[ \t]+" (regexp-quote heading)
13663 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13664 nil t)
13665 (goto-char (match-beginning 0))
13666 (error "Target headline not found: %s" heading))))
13668 (defvar org-note-abort nil) ; dynamically scoped
13670 ;;;###autoload
13671 (defun org-remember-handler ()
13672 "Store stuff from remember.el into an org file.
13673 First prompts for an org file. If the user just presses return, the value
13674 of `org-default-notes-file' is used.
13675 Then the command offers the headings tree of the selected file in order to
13676 file the text at a specific location.
13677 You can either immediately press RET to get the note appended to the
13678 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13679 find a better place. Then press RET or <left> or <right> in insert the note.
13681 Key Cursor position Note gets inserted
13682 -----------------------------------------------------------------------------
13683 RET buffer-start as level 1 heading at end of file
13684 RET on headline as sublevel of the heading at cursor
13685 RET no heading at cursor position, level taken from context.
13686 Or use prefix arg to specify level manually.
13687 <left> on headline as same level, before current heading
13688 <right> on headline as same level, after current heading
13690 So the fastest way to store the note is to press RET RET to append it to
13691 the default file. This way your current train of thought is not
13692 interrupted, in accordance with the principles of remember.el.
13693 You can also get the fast execution without prompting by using
13694 C-u C-c C-c to exit the remember buffer. See also the variable
13695 `org-remember-store-without-prompt'.
13697 Before being stored away, the function ensures that the text has a
13698 headline, i.e. a first line that starts with a \"*\". If not, a headline
13699 is constructed from the current date and some additional data.
13701 If the variable `org-adapt-indentation' is non-nil, the entire text is
13702 also indented so that it starts in the same column as the headline
13703 \(i.e. after the stars).
13705 See also the variable `org-reverse-note-order'."
13706 (goto-char (point-min))
13707 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13708 (replace-match ""))
13709 (goto-char (point-max))
13710 (beginning-of-line 1)
13711 (while (looking-at "[ \t]*$\\|##.*")
13712 (delete-region (1- (point)) (point-max))
13713 (beginning-of-line 1))
13714 (catch 'quit
13715 (if org-note-abort (throw 'quit nil))
13716 (let* ((txt (buffer-substring (point-min) (point-max)))
13717 (fastp (org-xor (equal current-prefix-arg '(4))
13718 org-remember-store-without-prompt))
13719 (file (cond
13720 (fastp org-default-notes-file)
13721 ((and (eq org-remember-interactive-interface 'refile)
13722 org-refile-targets)
13723 org-default-notes-file)
13724 ((not (and (equal current-prefix-arg '(16))
13725 org-remember-previous-location))
13726 (org-get-org-file))))
13727 (heading org-remember-default-headline)
13728 (visiting (and file (org-find-base-buffer-visiting file)))
13729 (org-startup-folded nil)
13730 (org-startup-align-all-tables nil)
13731 (org-goto-start-pos 1)
13732 spos exitcmd level indent reversed)
13733 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13734 (setq file (car org-remember-previous-location)
13735 heading (cdr org-remember-previous-location)
13736 fastp t))
13737 (setq current-prefix-arg nil)
13738 (if (string-match "[ \t\n]+\\'" txt)
13739 (setq txt (replace-match "" t t txt)))
13740 ;; Modify text so that it becomes a nice subtree which can be inserted
13741 ;; into an org tree.
13742 (let* ((lines (split-string txt "\n"))
13743 first)
13744 (setq first (car lines) lines (cdr lines))
13745 (if (string-match "^\\*+ " first)
13746 ;; Is already a headline
13747 (setq indent nil)
13748 ;; We need to add a headline: Use time and first buffer line
13749 (setq lines (cons first lines)
13750 first (concat "* " (current-time-string)
13751 " (" (remember-buffer-desc) ")")
13752 indent " "))
13753 (if (and org-adapt-indentation indent)
13754 (setq lines (mapcar
13755 (lambda (x)
13756 (if (string-match "\\S-" x)
13757 (concat indent x) x))
13758 lines)))
13759 (setq txt (concat first "\n"
13760 (mapconcat 'identity lines "\n"))))
13761 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13762 (setq txt (replace-match "\n\n" t t txt))
13763 (if (string-match "[ \t\n]*\\'" txt)
13764 (setq txt (replace-match "\n" t t txt))))
13765 ;; Put the modified text back into the remember buffer, for refile.
13766 (erase-buffer)
13767 (insert txt)
13768 (goto-char (point-min))
13769 (when (and (eq org-remember-interactive-interface 'refile)
13770 (not fastp))
13771 (org-refile nil (or visiting (find-file-noselect file)))
13772 (throw 'quit t))
13773 ;; Find the file
13774 (if (not visiting) (find-file-noselect file))
13775 (with-current-buffer (or visiting (get-file-buffer file))
13776 (unless (org-mode-p)
13777 (error "Target files for remember notes must be in Org-mode"))
13778 (save-excursion
13779 (save-restriction
13780 (widen)
13781 (and (goto-char (point-min))
13782 (not (re-search-forward "^\\* " nil t))
13783 (insert "\n* " (or heading "Notes") "\n"))
13784 (setq reversed (org-notes-order-reversed-p))
13786 ;; Find the default location
13787 (when (and heading (stringp heading) (string-match "\\S-" heading))
13788 (goto-char (point-min))
13789 (if (re-search-forward
13790 (concat "^\\*+[ \t]+" (regexp-quote heading)
13791 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13792 nil t)
13793 (setq org-goto-start-pos (match-beginning 0))
13794 (when fastp
13795 (goto-char (point-max))
13796 (unless (bolp) (newline))
13797 (insert "* " heading "\n")
13798 (setq org-goto-start-pos (point-at-bol 0)))))
13800 ;; Ask the User for a location, using the appropriate interface
13801 (cond
13802 (fastp (setq spos org-goto-start-pos
13803 exitcmd 'return))
13804 ((eq org-remember-interactive-interface 'outline)
13805 (setq spos (org-get-location (current-buffer)
13806 org-remember-help)
13807 exitcmd (cdr spos)
13808 spos (car spos)))
13809 ((eq org-remember-interactive-interface 'outline-path-completion)
13810 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13811 (org-refile-use-outline-path t))
13812 (setq spos (org-refile-get-location "Heading: ")
13813 exitcmd 'return
13814 spos (nth 3 spos))))
13815 (t (error "this should not hapen")))
13816 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13817 ; not handle this note
13818 (goto-char spos)
13819 (cond ((org-on-heading-p t)
13820 (org-back-to-heading t)
13821 (setq level (funcall outline-level))
13822 (cond
13823 ((eq exitcmd 'return)
13824 ;; sublevel of current
13825 (setq org-remember-previous-location
13826 (cons (abbreviate-file-name file)
13827 (org-get-heading 'notags)))
13828 (if reversed
13829 (outline-next-heading)
13830 (org-end-of-subtree t)
13831 (if (not (bolp))
13832 (if (looking-at "[ \t]*\n")
13833 (beginning-of-line 2)
13834 (end-of-line 1)
13835 (insert "\n"))))
13836 (bookmark-set "org-remember-last-stored")
13837 (org-paste-subtree (org-get-valid-level level 1) txt))
13838 ((eq exitcmd 'left)
13839 ;; before current
13840 (bookmark-set "org-remember-last-stored")
13841 (org-paste-subtree level txt))
13842 ((eq exitcmd 'right)
13843 ;; after current
13844 (org-end-of-subtree t)
13845 (bookmark-set "org-remember-last-stored")
13846 (org-paste-subtree level txt))
13847 (t (error "This should not happen"))))
13849 ((and (bobp) (not reversed))
13850 ;; Put it at the end, one level below level 1
13851 (save-restriction
13852 (widen)
13853 (goto-char (point-max))
13854 (if (not (bolp)) (newline))
13855 (bookmark-set "org-remember-last-stored")
13856 (org-paste-subtree (org-get-valid-level 1 1) txt)))
13858 ((and (bobp) reversed)
13859 ;; Put it at the start, as level 1
13860 (save-restriction
13861 (widen)
13862 (goto-char (point-min))
13863 (re-search-forward "^\\*+ " nil t)
13864 (beginning-of-line 1)
13865 (bookmark-set "org-remember-last-stored")
13866 (org-paste-subtree 1 txt)))
13868 ;; Put it right there, with automatic level determined by
13869 ;; org-paste-subtree or from prefix arg
13870 (bookmark-set "org-remember-last-stored")
13871 (org-paste-subtree
13872 (if (numberp current-prefix-arg) current-prefix-arg)
13873 txt)))
13874 (when remember-save-after-remembering
13875 (save-buffer)
13876 (if (not visiting) (kill-buffer (current-buffer)))))))))
13878 t) ;; return t to indicate that we took care of this note.
13880 (defun org-get-org-file ()
13881 "Read a filename, with default directory `org-directory'."
13882 (let ((default (or org-default-notes-file remember-data-file)))
13883 (read-file-name (format "File name [%s]: " default)
13884 (file-name-as-directory org-directory)
13885 default)))
13887 (defun org-notes-order-reversed-p ()
13888 "Check if the current file should receive notes in reversed order."
13889 (cond
13890 ((not org-reverse-note-order) nil)
13891 ((eq t org-reverse-note-order) t)
13892 ((not (listp org-reverse-note-order)) nil)
13893 (t (catch 'exit
13894 (let ((all org-reverse-note-order)
13895 entry)
13896 (while (setq entry (pop all))
13897 (if (string-match (car entry) buffer-file-name)
13898 (throw 'exit (cdr entry))))
13899 nil)))))
13901 ;;; Refiling
13903 (defvar org-refile-target-table nil
13904 "The list of refile targets, created by `org-refile'.")
13906 (defvar org-agenda-new-buffers nil
13907 "Buffers created to visit agenda files.")
13909 (defun org-get-refile-targets (&optional default-buffer)
13910 "Produce a table with refile targets."
13911 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13912 targets txt re files f desc descre)
13913 (with-current-buffer (or default-buffer (current-buffer))
13914 (while (setq entry (pop entries))
13915 (setq files (car entry) desc (cdr entry))
13916 (cond
13917 ((null files) (setq files (list (current-buffer))))
13918 ((eq files 'org-agenda-files)
13919 (setq files (org-agenda-files 'unrestricted)))
13920 ((and (symbolp files) (fboundp files))
13921 (setq files (funcall files)))
13922 ((and (symbolp files) (boundp files))
13923 (setq files (symbol-value files))))
13924 (if (stringp files) (setq files (list files)))
13925 (cond
13926 ((eq (car desc) :tag)
13927 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13928 ((eq (car desc) :todo)
13929 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13930 ((eq (car desc) :regexp)
13931 (setq descre (cdr desc)))
13932 ((eq (car desc) :level)
13933 (setq descre (concat "^\\*\\{" (number-to-string
13934 (if org-odd-levels-only
13935 (1- (* 2 (cdr desc)))
13936 (cdr desc)))
13937 "\\}[ \t]")))
13938 ((eq (car desc) :maxlevel)
13939 (setq descre (concat "^\\*\\{1," (number-to-string
13940 (if org-odd-levels-only
13941 (1- (* 2 (cdr desc)))
13942 (cdr desc)))
13943 "\\}[ \t]")))
13944 (t (error "Bad refiling target description %s" desc)))
13945 (while (setq f (pop files))
13946 (save-excursion
13947 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13948 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13949 (save-excursion
13950 (save-restriction
13951 (widen)
13952 (goto-char (point-min))
13953 (while (re-search-forward descre nil t)
13954 (goto-char (point-at-bol))
13955 (when (looking-at org-complex-heading-regexp)
13956 (setq txt (match-string 4)
13957 re (concat "^" (regexp-quote
13958 (buffer-substring (match-beginning 1)
13959 (match-end 4)))))
13960 (if (match-end 5) (setq re (concat re "[ \t]+"
13961 (regexp-quote
13962 (match-string 5)))))
13963 (setq re (concat re "[ \t]*$"))
13964 (when org-refile-use-outline-path
13965 (setq txt (mapconcat 'identity
13966 (append
13967 (if (eq org-refile-use-outline-path 'file)
13968 (list (file-name-nondirectory
13969 (buffer-file-name (buffer-base-buffer))))
13970 (if (eq org-refile-use-outline-path 'full-file-path)
13971 (list (buffer-file-name (buffer-base-buffer)))))
13972 (org-get-outline-path)
13973 (list txt))
13974 "/")))
13975 (push (list txt f re (point)) targets))
13976 (goto-char (point-at-eol))))))))
13977 (nreverse targets))))
13979 (defun org-get-outline-path ()
13980 "Return the outline path to the current entry, as a list."
13981 (let (rtn)
13982 (save-excursion
13983 (while (org-up-heading-safe)
13984 (when (looking-at org-complex-heading-regexp)
13985 (push (org-match-string-no-properties 4) rtn)))
13986 rtn)))
13988 (defvar org-refile-history nil
13989 "History for refiling operations.")
13991 (defun org-refile (&optional goto default-buffer)
13992 "Move the entry at point to another heading.
13993 The list of target headings is compiled using the information in
13994 `org-refile-targets', which see. This list is created upon first use, and
13995 you can update it by calling this command with a double prefix (`C-u C-u').
13996 FIXME: Can we find a better way of updating?
13998 At the target location, the entry is filed as a subitem of the target heading.
13999 Depending on `org-reverse-note-order', the new subitem will either be the
14000 first of the last subitem.
14002 With prefix arg GOTO, the command will only visit the target location,
14003 not actually move anything.
14004 With a double prefix `C-c C-c', go to the location where the last refiling
14005 operation has put the subtree.
14007 With a double prefix argument, the command can be used to jump to any
14008 heading in the current buffer."
14009 (interactive "P")
14010 (let* ((cbuf (current-buffer))
14011 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14012 pos it nbuf file re level reversed)
14013 (if (equal goto '(16))
14014 (org-refile-goto-last-stored)
14015 (when (setq it (org-refile-get-location
14016 (if goto "Goto: " "Refile to: ") default-buffer))
14017 (setq file (nth 1 it)
14018 re (nth 2 it)
14019 pos (nth 3 it))
14020 (setq nbuf (or (find-buffer-visiting file)
14021 (find-file-noselect file)))
14022 (if goto
14023 (progn
14024 (switch-to-buffer nbuf)
14025 (goto-char pos)
14026 (org-show-context 'org-goto))
14027 (org-copy-special)
14028 (save-excursion
14029 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14030 (find-file-noselect file))))
14031 (setq reversed (org-notes-order-reversed-p))
14032 (save-excursion
14033 (save-restriction
14034 (widen)
14035 (goto-char pos)
14036 (looking-at outline-regexp)
14037 (setq level (org-get-valid-level (funcall outline-level) 1))
14038 (goto-char
14039 (if reversed
14040 (outline-next-heading)
14041 (or (save-excursion (outline-get-next-sibling))
14042 (org-end-of-subtree t t)
14043 (point-max))))
14044 (bookmark-set "org-refile-last-stored")
14045 (org-paste-subtree level))))
14046 (org-cut-special)
14047 (message "Entry refiled to \"%s\"" (car it)))))))
14049 (defun org-refile-goto-last-stored ()
14050 "Go to the location where the last refile was stored."
14051 (interactive)
14052 (bookmark-jump "org-refile-last-stored")
14053 (message "This is the location of the last refile"))
14055 (defun org-refile-get-location (&optional prompt default-buffer)
14056 "Prompt the user for a refile location, using PROMPT."
14057 (let ((org-refile-targets org-refile-targets)
14058 (org-refile-use-outline-path org-refile-use-outline-path))
14059 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14060 (unless org-refile-target-table
14061 (error "No refile targets"))
14062 (let* ((cbuf (current-buffer))
14063 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14064 (fname (and filename (file-truename filename)))
14065 (tbl (mapcar
14066 (lambda (x)
14067 (if (not (equal fname (file-truename (nth 1 x))))
14068 (cons (concat (car x) " (" (file-name-nondirectory
14069 (nth 1 x)) ")")
14070 (cdr x))
14072 org-refile-target-table))
14073 (completion-ignore-case t))
14074 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14075 tbl)))
14077 ;;;; Dynamic blocks
14079 (defun org-find-dblock (name)
14080 "Find the first dynamic block with name NAME in the buffer.
14081 If not found, stay at current position and return nil."
14082 (let (pos)
14083 (save-excursion
14084 (goto-char (point-min))
14085 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14086 nil t)
14087 (match-beginning 0))))
14088 (if pos (goto-char pos))
14089 pos))
14091 (defconst org-dblock-start-re
14092 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14093 "Matches the startline of a dynamic block, with parameters.")
14095 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14096 "Matches the end of a dyhamic block.")
14098 (defun org-create-dblock (plist)
14099 "Create a dynamic block section, with parameters taken from PLIST.
14100 PLIST must containe a :name entry which is used as name of the block."
14101 (unless (bolp) (newline))
14102 (let ((name (plist-get plist :name)))
14103 (insert "#+BEGIN: " name)
14104 (while plist
14105 (if (eq (car plist) :name)
14106 (setq plist (cddr plist))
14107 (insert " " (prin1-to-string (pop plist)))))
14108 (insert "\n\n#+END:\n")
14109 (beginning-of-line -2)))
14111 (defun org-prepare-dblock ()
14112 "Prepare dynamic block for refresh.
14113 This empties the block, puts the cursor at the insert position and returns
14114 the property list including an extra property :name with the block name."
14115 (unless (looking-at org-dblock-start-re)
14116 (error "Not at a dynamic block"))
14117 (let* ((begdel (1+ (match-end 0)))
14118 (name (org-no-properties (match-string 1)))
14119 (params (append (list :name name)
14120 (read (concat "(" (match-string 3) ")")))))
14121 (unless (re-search-forward org-dblock-end-re nil t)
14122 (error "Dynamic block not terminated"))
14123 (setq params
14124 (append params
14125 (list :content (buffer-substring
14126 begdel (match-beginning 0)))))
14127 (delete-region begdel (match-beginning 0))
14128 (goto-char begdel)
14129 (open-line 1)
14130 params))
14132 (defun org-map-dblocks (&optional command)
14133 "Apply COMMAND to all dynamic blocks in the current buffer.
14134 If COMMAND is not given, use `org-update-dblock'."
14135 (let ((cmd (or command 'org-update-dblock))
14136 pos)
14137 (save-excursion
14138 (goto-char (point-min))
14139 (while (re-search-forward org-dblock-start-re nil t)
14140 (goto-char (setq pos (match-beginning 0)))
14141 (condition-case nil
14142 (funcall cmd)
14143 (error (message "Error during update of dynamic block")))
14144 (goto-char pos)
14145 (unless (re-search-forward org-dblock-end-re nil t)
14146 (error "Dynamic block not terminated"))))))
14148 (defun org-dblock-update (&optional arg)
14149 "User command for updating dynamic blocks.
14150 Update the dynamic block at point. With prefix ARG, update all dynamic
14151 blocks in the buffer."
14152 (interactive "P")
14153 (if arg
14154 (org-update-all-dblocks)
14155 (or (looking-at org-dblock-start-re)
14156 (org-beginning-of-dblock))
14157 (org-update-dblock)))
14159 (defun org-update-dblock ()
14160 "Update the dynamic block at point
14161 This means to empty the block, parse for parameters and then call
14162 the correct writing function."
14163 (save-window-excursion
14164 (let* ((pos (point))
14165 (line (org-current-line))
14166 (params (org-prepare-dblock))
14167 (name (plist-get params :name))
14168 (cmd (intern (concat "org-dblock-write:" name))))
14169 (message "Updating dynamic block `%s' at line %d..." name line)
14170 (funcall cmd params)
14171 (message "Updating dynamic block `%s' at line %d...done" name line)
14172 (goto-char pos))))
14174 (defun org-beginning-of-dblock ()
14175 "Find the beginning of the dynamic block at point.
14176 Error if there is no scuh block at point."
14177 (let ((pos (point))
14178 beg)
14179 (end-of-line 1)
14180 (if (and (re-search-backward org-dblock-start-re nil t)
14181 (setq beg (match-beginning 0))
14182 (re-search-forward org-dblock-end-re nil t)
14183 (> (match-end 0) pos))
14184 (goto-char beg)
14185 (goto-char pos)
14186 (error "Not in a dynamic block"))))
14188 (defun org-update-all-dblocks ()
14189 "Update all dynamic blocks in the buffer.
14190 This function can be used in a hook."
14191 (when (org-mode-p)
14192 (org-map-dblocks 'org-update-dblock)))
14195 ;;;; Completion
14197 (defconst org-additional-option-like-keywords
14198 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14199 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
14200 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14202 (defun org-complete (&optional arg)
14203 "Perform completion on word at point.
14204 At the beginning of a headline, this completes TODO keywords as given in
14205 `org-todo-keywords'.
14206 If the current word is preceded by a backslash, completes the TeX symbols
14207 that are supported for HTML support.
14208 If the current word is preceded by \"#+\", completes special words for
14209 setting file options.
14210 In the line after \"#+STARTUP:, complete valid keywords.\"
14211 At all other locations, this simply calls the value of
14212 `org-completion-fallback-command'."
14213 (interactive "P")
14214 (org-without-partial-completion
14215 (catch 'exit
14216 (let* ((end (point))
14217 (beg1 (save-excursion
14218 (skip-chars-backward (org-re "[:alnum:]_@"))
14219 (point)))
14220 (beg (save-excursion
14221 (skip-chars-backward "a-zA-Z0-9_:$")
14222 (point)))
14223 (confirm (lambda (x) (stringp (car x))))
14224 (searchhead (equal (char-before beg) ?*))
14225 (tag (and (equal (char-before beg1) ?:)
14226 (equal (char-after (point-at-bol)) ?*)))
14227 (prop (and (equal (char-before beg1) ?:)
14228 (not (equal (char-after (point-at-bol)) ?*))))
14229 (texp (equal (char-before beg) ?\\))
14230 (link (equal (char-before beg) ?\[))
14231 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14232 beg)
14233 "#+"))
14234 (startup (string-match "^#\\+STARTUP:.*"
14235 (buffer-substring (point-at-bol) (point))))
14236 (completion-ignore-case opt)
14237 (type nil)
14238 (tbl nil)
14239 (table (cond
14240 (opt
14241 (setq type :opt)
14242 (append
14243 (mapcar
14244 (lambda (x)
14245 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14246 (cons (match-string 2 x) (match-string 1 x)))
14247 (org-split-string (org-get-current-options) "\n"))
14248 (mapcar 'list org-additional-option-like-keywords)))
14249 (startup
14250 (setq type :startup)
14251 org-startup-options)
14252 (link (append org-link-abbrev-alist-local
14253 org-link-abbrev-alist))
14254 (texp
14255 (setq type :tex)
14256 org-html-entities)
14257 ((string-match "\\`\\*+[ \t]+\\'"
14258 (buffer-substring (point-at-bol) beg))
14259 (setq type :todo)
14260 (mapcar 'list org-todo-keywords-1))
14261 (searchhead
14262 (setq type :searchhead)
14263 (save-excursion
14264 (goto-char (point-min))
14265 (while (re-search-forward org-todo-line-regexp nil t)
14266 (push (list
14267 (org-make-org-heading-search-string
14268 (match-string 3) t))
14269 tbl)))
14270 tbl)
14271 (tag (setq type :tag beg beg1)
14272 (or org-tag-alist (org-get-buffer-tags)))
14273 (prop (setq type :prop beg beg1)
14274 (mapcar 'list (org-buffer-property-keys nil t t)))
14275 (t (progn
14276 (call-interactively org-completion-fallback-command)
14277 (throw 'exit nil)))))
14278 (pattern (buffer-substring-no-properties beg end))
14279 (completion (try-completion pattern table confirm)))
14280 (cond ((eq completion t)
14281 (if (not (assoc (upcase pattern) table))
14282 (message "Already complete")
14283 (if (and (equal type :opt)
14284 (not (member (car (assoc (upcase pattern) table))
14285 org-additional-option-like-keywords)))
14286 (insert (substring (cdr (assoc (upcase pattern) table))
14287 (length pattern)))
14288 (if (memq type '(:tag :prop)) (insert ":")))))
14289 ((null completion)
14290 (message "Can't find completion for \"%s\"" pattern)
14291 (ding))
14292 ((not (string= pattern completion))
14293 (delete-region beg end)
14294 (if (string-match " +$" completion)
14295 (setq completion (replace-match "" t t completion)))
14296 (insert completion)
14297 (if (get-buffer-window "*Completions*")
14298 (delete-window (get-buffer-window "*Completions*")))
14299 (if (assoc completion table)
14300 (if (eq type :todo) (insert " ")
14301 (if (memq type '(:tag :prop)) (insert ":"))))
14302 (if (and (equal type :opt) (assoc completion table))
14303 (message "%s" (substitute-command-keys
14304 "Press \\[org-complete] again to insert example settings"))))
14306 (message "Making completion list...")
14307 (let ((list (sort (all-completions pattern table confirm)
14308 'string<)))
14309 (with-output-to-temp-buffer "*Completions*"
14310 (condition-case nil
14311 ;; Protection needed for XEmacs and emacs 21
14312 (display-completion-list list pattern)
14313 (error (display-completion-list list)))))
14314 (message "Making completion list...%s" "done")))))))
14316 ;;;; TODO, DEADLINE, Comments
14318 (defun org-toggle-comment ()
14319 "Change the COMMENT state of an entry."
14320 (interactive)
14321 (save-excursion
14322 (org-back-to-heading)
14323 (let (case-fold-search)
14324 (if (looking-at (concat outline-regexp
14325 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14326 (replace-match "" t t nil 1)
14327 (if (looking-at outline-regexp)
14328 (progn
14329 (goto-char (match-end 0))
14330 (insert org-comment-string " ")))))))
14332 (defvar org-last-todo-state-is-todo nil
14333 "This is non-nil when the last TODO state change led to a TODO state.
14334 If the last change removed the TODO tag or switched to DONE, then
14335 this is nil.")
14337 (defvar org-setting-tags nil) ; dynamically skiped
14339 ;; FIXME: better place
14340 (defun org-property-or-variable-value (var &optional inherit)
14341 "Check if there is a property fixing the value of VAR.
14342 If yes, return this value. If not, return the current value of the variable."
14343 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14344 (if (and prop (stringp prop) (string-match "\\S-" prop))
14345 (read prop)
14346 (symbol-value var))))
14348 (defun org-parse-local-options (string var)
14349 "Parse STRING for startup setting relevant for variable VAR."
14350 (let ((rtn (symbol-value var))
14351 e opts)
14352 (save-match-data
14353 (if (or (not string) (not (string-match "\\S-" string)))
14355 (setq opts (delq nil (mapcar (lambda (x)
14356 (setq e (assoc x org-startup-options))
14357 (if (eq (nth 1 e) var) e nil))
14358 (org-split-string string "[ \t]+"))))
14359 (if (not opts)
14361 (setq rtn nil)
14362 (while (setq e (pop opts))
14363 (if (not (nth 3 e))
14364 (setq rtn (nth 2 e))
14365 (if (not (listp rtn)) (setq rtn nil))
14366 (push (nth 2 e) rtn)))
14367 rtn)))))
14369 (defvar org-blocker-hook nil
14370 "Hook for functions that are allowed to block a state change.
14372 Each function gets as its single argument a property list, see
14373 `org-trigger-hook' for more information about this list.
14375 If any of the functions in this hook returns nil, the state change
14376 is blocked.")
14378 (defvar org-trigger-hook nil
14379 "Hook for functions that are triggered by a state change.
14381 Each function gets as its single argument a property list with at least
14382 the following elements:
14384 (:type type-of-change :position pos-at-entry-start
14385 :from old-state :to new-state)
14387 Depending on the type, more properties may be present.
14389 This mechanism is currently implemented for:
14391 TODO state changes
14392 ------------------
14393 :type todo-state-change
14394 :from previous state (keyword as a string), or nil
14395 :to new state (keyword as a string), or nil")
14398 (defun org-todo (&optional arg)
14399 "Change the TODO state of an item.
14400 The state of an item is given by a keyword at the start of the heading,
14401 like
14402 *** TODO Write paper
14403 *** DONE Call mom
14405 The different keywords are specified in the variable `org-todo-keywords'.
14406 By default the available states are \"TODO\" and \"DONE\".
14407 So for this example: when the item starts with TODO, it is changed to DONE.
14408 When it starts with DONE, the DONE is removed. And when neither TODO nor
14409 DONE are present, add TODO at the beginning of the heading.
14411 With C-u prefix arg, use completion to determine the new state.
14412 With numeric prefix arg, switch to that state.
14414 For calling through lisp, arg is also interpreted in the following way:
14415 'none -> empty state
14416 \"\"(empty string) -> switch to empty state
14417 'done -> switch to DONE
14418 'nextset -> switch to the next set of keywords
14419 'previousset -> switch to the previous set of keywords
14420 \"WAITING\" -> switch to the specified keyword, but only if it
14421 really is a member of `org-todo-keywords'."
14422 (interactive "P")
14423 (save-excursion
14424 (catch 'exit
14425 (org-back-to-heading)
14426 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14427 (or (looking-at (concat " +" org-todo-regexp " *"))
14428 (looking-at " *"))
14429 (let* ((match-data (match-data))
14430 (startpos (point-at-bol))
14431 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14432 (org-log-done org-log-done)
14433 (org-log-repeat org-log-repeat)
14434 (org-todo-log-states org-todo-log-states)
14435 (this (match-string 1))
14436 (hl-pos (match-beginning 0))
14437 (head (org-get-todo-sequence-head this))
14438 (ass (assoc head org-todo-kwd-alist))
14439 (interpret (nth 1 ass))
14440 (done-word (nth 3 ass))
14441 (final-done-word (nth 4 ass))
14442 (last-state (or this ""))
14443 (completion-ignore-case t)
14444 (member (member this org-todo-keywords-1))
14445 (tail (cdr member))
14446 (state (cond
14447 ((and org-todo-key-trigger
14448 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14449 (and (not arg) org-use-fast-todo-selection
14450 (not (eq org-use-fast-todo-selection 'prefix)))))
14451 ;; Use fast selection
14452 (org-fast-todo-selection))
14453 ((and (equal arg '(4))
14454 (or (not org-use-fast-todo-selection)
14455 (not org-todo-key-trigger)))
14456 ;; Read a state with completion
14457 (completing-read "State: " (mapcar (lambda(x) (list x))
14458 org-todo-keywords-1)
14459 nil t))
14460 ((eq arg 'right)
14461 (if this
14462 (if tail (car tail) nil)
14463 (car org-todo-keywords-1)))
14464 ((eq arg 'left)
14465 (if (equal member org-todo-keywords-1)
14467 (if this
14468 (nth (- (length org-todo-keywords-1) (length tail) 2)
14469 org-todo-keywords-1)
14470 (org-last org-todo-keywords-1))))
14471 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14472 (setq arg nil))) ; hack to fall back to cycling
14473 (arg
14474 ;; user or caller requests a specific state
14475 (cond
14476 ((equal arg "") nil)
14477 ((eq arg 'none) nil)
14478 ((eq arg 'done) (or done-word (car org-done-keywords)))
14479 ((eq arg 'nextset)
14480 (or (car (cdr (member head org-todo-heads)))
14481 (car org-todo-heads)))
14482 ((eq arg 'previousset)
14483 (let ((org-todo-heads (reverse org-todo-heads)))
14484 (or (car (cdr (member head org-todo-heads)))
14485 (car org-todo-heads))))
14486 ((car (member arg org-todo-keywords-1)))
14487 ((nth (1- (prefix-numeric-value arg))
14488 org-todo-keywords-1))))
14489 ((null member) (or head (car org-todo-keywords-1)))
14490 ((equal this final-done-word) nil) ;; -> make empty
14491 ((null tail) nil) ;; -> first entry
14492 ((eq interpret 'sequence)
14493 (car tail))
14494 ((memq interpret '(type priority))
14495 (if (eq this-command last-command)
14496 (car tail)
14497 (if (> (length tail) 0)
14498 (or done-word (car org-done-keywords))
14499 nil)))
14500 (t nil)))
14501 (next (if state (concat " " state " ") " "))
14502 (change-plist (list :type 'todo-state-change :from this :to state
14503 :position startpos))
14504 dolog now-done-p)
14505 (when org-blocker-hook
14506 (unless (save-excursion
14507 (save-match-data
14508 (run-hook-with-args-until-failure
14509 'org-blocker-hook change-plist)))
14510 (if (interactive-p)
14511 (error "TODO state change from %s to %s blocked" this state)
14512 ;; fail silently
14513 (message "TODO state change from %s to %s blocked" this state)
14514 (throw 'exit nil))))
14515 (store-match-data match-data)
14516 (replace-match next t t)
14517 (unless (pos-visible-in-window-p hl-pos)
14518 (message "TODO state changed to %s" (org-trim next)))
14519 (unless head
14520 (setq head (org-get-todo-sequence-head state)
14521 ass (assoc head org-todo-kwd-alist)
14522 interpret (nth 1 ass)
14523 done-word (nth 3 ass)
14524 final-done-word (nth 4 ass)))
14525 (when (memq arg '(nextset previousset))
14526 (message "Keyword-Set %d/%d: %s"
14527 (- (length org-todo-sets) -1
14528 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14529 (length org-todo-sets)
14530 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14531 (setq org-last-todo-state-is-todo
14532 (not (member state org-done-keywords)))
14533 (setq now-done-p (and (member state org-done-keywords)
14534 (not (member this org-done-keywords))))
14535 (and logging (org-local-logging logging))
14536 (when (and (or org-todo-log-states org-log-done)
14537 (not (memq arg '(nextset previousset))))
14538 ;; we need to look at recording a time and note
14539 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14540 (nth 2 (assoc this org-todo-log-states))))
14541 (when (and state
14542 (member state org-not-done-keywords)
14543 (not (member this org-not-done-keywords)))
14544 ;; This is now a todo state and was not one before
14545 ;; If there was a CLOSED time stamp, get rid of it.
14546 (org-add-planning-info nil nil 'closed))
14547 (when (and now-done-p org-log-done)
14548 ;; It is now done, and it was not done before
14549 (org-add-planning-info 'closed (org-current-time))
14550 (if (and (not dolog) (eq 'note org-log-done))
14551 (org-add-log-maybe 'done state 'findpos 'note)))
14552 (when (and state dolog)
14553 ;; This is a non-nil state, and we need to log it
14554 (org-add-log-maybe 'state state 'findpos dolog)))
14555 ;; Fixup tag positioning
14556 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14557 (run-hooks 'org-after-todo-state-change-hook)
14558 (if (and arg (not (member state org-done-keywords)))
14559 (setq head (org-get-todo-sequence-head state)))
14560 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14561 ;; Do we need to trigger a repeat?
14562 (when now-done-p (org-auto-repeat-maybe state))
14563 ;; Fixup cursor location if close to the keyword
14564 (if (and (outline-on-heading-p)
14565 (not (bolp))
14566 (save-excursion (beginning-of-line 1)
14567 (looking-at org-todo-line-regexp))
14568 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14569 (progn
14570 (goto-char (or (match-end 2) (match-end 1)))
14571 (just-one-space)))
14572 (when org-trigger-hook
14573 (save-excursion
14574 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14576 (defun org-local-logging (value)
14577 "Get logging settings from a property VALUE."
14578 (let* (words w a)
14579 ;; directly set the variables, they are already local.
14580 (setq org-log-done nil
14581 org-log-repeat nil
14582 org-todo-log-states nil)
14583 (setq words (org-split-string value))
14584 (while (setq w (pop words))
14585 (cond
14586 ((setq a (assoc w org-startup-options))
14587 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14588 (set (nth 1 a) (nth 2 a))))
14589 ((setq a (org-extract-log-state-settings w))
14590 (and (member (car a) org-todo-keywords-1)
14591 (push a org-todo-log-states)))))))
14593 (defun org-get-todo-sequence-head (kwd)
14594 "Return the head of the TODO sequence to which KWD belongs.
14595 If KWD is not set, check if there is a text property remembering the
14596 right sequence."
14597 (let (p)
14598 (cond
14599 ((not kwd)
14600 (or (get-text-property (point-at-bol) 'org-todo-head)
14601 (progn
14602 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14603 nil (point-at-eol)))
14604 (get-text-property p 'org-todo-head))))
14605 ((not (member kwd org-todo-keywords-1))
14606 (car org-todo-keywords-1))
14607 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14609 (defun org-fast-todo-selection ()
14610 "Fast TODO keyword selection with single keys.
14611 Returns the new TODO keyword, or nil if no state change should occur."
14612 (let* ((fulltable org-todo-key-alist)
14613 (done-keywords org-done-keywords) ;; needed for the faces.
14614 (maxlen (apply 'max (mapcar
14615 (lambda (x)
14616 (if (stringp (car x)) (string-width (car x)) 0))
14617 fulltable)))
14618 (expert nil)
14619 (fwidth (+ maxlen 3 1 3))
14620 (ncol (/ (- (window-width) 4) fwidth))
14621 tg cnt e c tbl
14622 groups ingroup)
14623 (save-window-excursion
14624 (if expert
14625 (set-buffer (get-buffer-create " *Org todo*"))
14626 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14627 (erase-buffer)
14628 (org-set-local 'org-done-keywords done-keywords)
14629 (setq tbl fulltable cnt 0)
14630 (while (setq e (pop tbl))
14631 (cond
14632 ((equal e '(:startgroup))
14633 (push '() groups) (setq ingroup t)
14634 (when (not (= cnt 0))
14635 (setq cnt 0)
14636 (insert "\n"))
14637 (insert "{ "))
14638 ((equal e '(:endgroup))
14639 (setq ingroup nil cnt 0)
14640 (insert "}\n"))
14642 (setq tg (car e) c (cdr e))
14643 (if ingroup (push tg (car groups)))
14644 (setq tg (org-add-props tg nil 'face
14645 (org-get-todo-face tg)))
14646 (if (and (= cnt 0) (not ingroup)) (insert " "))
14647 (insert "[" c "] " tg (make-string
14648 (- fwidth 4 (length tg)) ?\ ))
14649 (when (= (setq cnt (1+ cnt)) ncol)
14650 (insert "\n")
14651 (if ingroup (insert " "))
14652 (setq cnt 0)))))
14653 (insert "\n")
14654 (goto-char (point-min))
14655 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14656 (fit-window-to-buffer))
14657 (message "[a-z..]:Set [SPC]:clear")
14658 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14659 (cond
14660 ((or (= c ?\C-g)
14661 (and (= c ?q) (not (rassoc c fulltable))))
14662 (setq quit-flag t))
14663 ((= c ?\ ) nil)
14664 ((setq e (rassoc c fulltable) tg (car e))
14666 (t (setq quit-flag t))))))
14668 (defun org-get-repeat ()
14669 "Check if tere is a deadline/schedule with repeater in this entry."
14670 (save-match-data
14671 (save-excursion
14672 (org-back-to-heading t)
14673 (if (re-search-forward
14674 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14675 (match-string 1)))))
14677 (defvar org-last-changed-timestamp)
14678 (defvar org-log-post-message)
14679 (defvar org-log-note-purpose)
14680 (defun org-auto-repeat-maybe (done-word)
14681 "Check if the current headline contains a repeated deadline/schedule.
14682 If yes, set TODO state back to what it was and change the base date
14683 of repeating deadline/scheduled time stamps to new date.
14684 This function is run automatically after each state change to a DONE state."
14685 ;; last-state is dynamically scoped into this function
14686 (let* ((repeat (org-get-repeat))
14687 (aa (assoc last-state org-todo-kwd-alist))
14688 (interpret (nth 1 aa))
14689 (head (nth 2 aa))
14690 (whata '(("d" . day) ("m" . month) ("y" . year)))
14691 (msg "Entry repeats: ")
14692 (org-log-done nil)
14693 (org-todo-log-states nil)
14694 (nshiftmax 10) (nshift 0)
14695 re type n what ts mb0 time)
14696 (when repeat
14697 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14698 (org-todo (if (eq interpret 'type) last-state head))
14699 (when (and org-log-repeat
14700 (or (not (memq 'org-add-log-note
14701 (default-value 'post-command-hook)))
14702 (eq org-log-note-purpose 'done)))
14703 ;; Make sure a note is taken;
14704 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14705 'findpos org-log-repeat))
14706 (org-back-to-heading t)
14707 (org-add-planning-info nil nil 'closed)
14708 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14709 org-deadline-time-regexp "\\)\\|\\("
14710 org-ts-regexp "\\)"))
14711 (while (re-search-forward
14712 re (save-excursion (outline-next-heading) (point)) t)
14713 (setq type (if (match-end 1) org-scheduled-string
14714 (if (match-end 3) org-deadline-string "Plain:"))
14715 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
14716 mb0 (match-beginning 0))
14717 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
14718 (setq n (string-to-number (match-string 2 ts))
14719 what (match-string 3 ts))
14720 (if (equal what "w") (setq n (* n 7) what "d"))
14721 ;; Preparation, see if we need to modify the start date for the change
14722 (when (match-end 1)
14723 (setq time (save-match-data (org-time-string-to-time ts)))
14724 (cond
14725 ((equal (match-string 1 ts) ".")
14726 ;; Shift starting date to today
14727 (org-timestamp-change
14728 (- (time-to-days (current-time)) (time-to-days time))
14729 'day))
14730 ((equal (match-string 1 ts) "+")
14731 (while (< (time-to-days time) (time-to-days (current-time)))
14732 (when (= (incf nshift) nshiftmax)
14733 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
14734 (error "Abort")))
14735 (org-timestamp-change n (cdr (assoc what whata)))
14736 (sit-for .0001) ;; so we can watch the date shifting
14737 (org-at-timestamp-p t)
14738 (setq ts (match-string 1))
14739 (setq time (save-match-data (org-time-string-to-time ts))))
14740 (org-timestamp-change (- n) (cdr (assoc what whata)))
14741 ;; rematch, so that we have everything in place for the real shift
14742 (org-at-timestamp-p t)
14743 (setq ts (match-string 1))
14744 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
14745 (org-timestamp-change n (cdr (assoc what whata)))
14746 (setq msg (concat msg type org-last-changed-timestamp " "))))
14747 (setq org-log-post-message msg)
14748 (message "%s" msg))))
14750 (defun org-show-todo-tree (arg)
14751 "Make a compact tree which shows all headlines marked with TODO.
14752 The tree will show the lines where the regexp matches, and all higher
14753 headlines above the match.
14754 With a \\[universal-argument] prefix, also show the DONE entries.
14755 With a numeric prefix N, construct a sparse tree for the Nth element
14756 of `org-todo-keywords-1'."
14757 (interactive "P")
14758 (let ((case-fold-search nil)
14759 (kwd-re
14760 (cond ((null arg) org-not-done-regexp)
14761 ((equal arg '(4))
14762 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14763 (mapcar 'list org-todo-keywords-1))))
14764 (concat "\\("
14765 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14766 "\\)\\>")))
14767 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14768 (regexp-quote (nth (1- (prefix-numeric-value arg))
14769 org-todo-keywords-1)))
14770 (t (error "Invalid prefix argument: %s" arg)))))
14771 (message "%d TODO entries found"
14772 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14774 (defun org-deadline (&optional remove)
14775 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14776 With argument REMOVE, remove any deadline from the item."
14777 (interactive "P")
14778 (if remove
14779 (progn
14780 (org-remove-timestamp-with-keyword org-deadline-string)
14781 (message "Item no longer has a deadline."))
14782 (org-add-planning-info 'deadline nil 'closed)))
14784 (defun org-schedule (&optional remove)
14785 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14786 With argument REMOVE, remove any scheduling date from the item."
14787 (interactive "P")
14788 (if remove
14789 (progn
14790 (org-remove-timestamp-with-keyword org-scheduled-string)
14791 (message "Item is no longer scheduled."))
14792 (org-add-planning-info 'scheduled nil 'closed)))
14794 (defun org-remove-timestamp-with-keyword (keyword)
14795 "Remove all time stamps with KEYWORD in the current entry."
14796 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14797 beg)
14798 (save-excursion
14799 (org-back-to-heading t)
14800 (setq beg (point))
14801 (org-end-of-subtree t t)
14802 (while (re-search-backward re beg t)
14803 (replace-match "")
14804 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14805 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14807 (defun org-add-planning-info (what &optional time &rest remove)
14808 "Insert new timestamp with keyword in the line directly after the headline.
14809 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14810 If non is given, the user is prompted for a date.
14811 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14812 be removed."
14813 (interactive)
14814 (let (org-time-was-given org-end-time-was-given ts
14815 end default-time default-input)
14817 (when (and (not time) (memq what '(scheduled deadline)))
14818 ;; Try to get a default date/time from existing timestamp
14819 (save-excursion
14820 (org-back-to-heading t)
14821 (setq end (save-excursion (outline-next-heading) (point)))
14822 (when (re-search-forward (if (eq what 'scheduled)
14823 org-scheduled-time-regexp
14824 org-deadline-time-regexp)
14825 end t)
14826 (setq ts (match-string 1)
14827 default-time
14828 (apply 'encode-time (org-parse-time-string ts))
14829 default-input (and ts (org-get-compact-tod ts))))))
14830 (when what
14831 ;; If necessary, get the time from the user
14832 (setq time (or time (org-read-date nil 'to-time nil nil
14833 default-time default-input))))
14835 (when (and org-insert-labeled-timestamps-at-point
14836 (member what '(scheduled deadline)))
14837 (insert
14838 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14839 (org-insert-time-stamp time org-time-was-given
14840 nil nil nil (list org-end-time-was-given))
14841 (setq what nil))
14842 (save-excursion
14843 (save-restriction
14844 (let (col list elt ts buffer-invisibility-spec)
14845 (org-back-to-heading t)
14846 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14847 (goto-char (match-end 1))
14848 (setq col (current-column))
14849 (goto-char (match-end 0))
14850 (if (eobp) (insert "\n") (forward-char 1))
14851 (if (and (not (looking-at outline-regexp))
14852 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14853 "[^\r\n]*"))
14854 (not (equal (match-string 1) org-clock-string)))
14855 (narrow-to-region (match-beginning 0) (match-end 0))
14856 (insert-before-markers "\n")
14857 (backward-char 1)
14858 (narrow-to-region (point) (point))
14859 (indent-to-column col))
14860 ;; Check if we have to remove something.
14861 (setq list (cons what remove))
14862 (while list
14863 (setq elt (pop list))
14864 (goto-char (point-min))
14865 (when (or (and (eq elt 'scheduled)
14866 (re-search-forward org-scheduled-time-regexp nil t))
14867 (and (eq elt 'deadline)
14868 (re-search-forward org-deadline-time-regexp nil t))
14869 (and (eq elt 'closed)
14870 (re-search-forward org-closed-time-regexp nil t)))
14871 (replace-match "")
14872 (if (looking-at "--+<[^>]+>") (replace-match ""))
14873 (if (looking-at " +") (replace-match ""))))
14874 (goto-char (point-max))
14875 (when what
14876 (insert
14877 (if (not (equal (char-before) ?\ )) " " "")
14878 (cond ((eq what 'scheduled) org-scheduled-string)
14879 ((eq what 'deadline) org-deadline-string)
14880 ((eq what 'closed) org-closed-string))
14881 " ")
14882 (setq ts (org-insert-time-stamp
14883 time
14884 (or org-time-was-given
14885 (and (eq what 'closed) org-log-done-with-time))
14886 (eq what 'closed)
14887 nil nil (list org-end-time-was-given)))
14888 (end-of-line 1))
14889 (goto-char (point-min))
14890 (widen)
14891 (if (looking-at "[ \t]+\r?\n")
14892 (replace-match ""))
14893 ts)))))
14895 (defvar org-log-note-marker (make-marker))
14896 (defvar org-log-note-purpose nil)
14897 (defvar org-log-note-state nil)
14898 (defvar org-log-note-how nil)
14899 (defvar org-log-note-window-configuration nil)
14900 (defvar org-log-note-return-to (make-marker))
14901 (defvar org-log-post-message nil
14902 "Message to be displayed after a log note has been stored.
14903 The auto-repeater uses this.")
14905 (defun org-add-log-maybe (&optional purpose state findpos how)
14906 "Set up the post command hook to take a note.
14907 If this is about to TODO state change, the new state is expected in STATE.
14908 When FINDPOS is non-nil, find the correct position for the note in
14909 the current entry. If not, assume that it can be inserted at point."
14910 (save-excursion
14911 (when findpos
14912 (org-back-to-heading t)
14913 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14914 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14915 "[^\r\n]*\\)?"))
14916 (goto-char (match-end 0))
14917 (unless org-log-states-order-reversed
14918 (and (= (char-after) ?\n) (forward-char 1))
14919 (org-skip-over-state-notes)
14920 (skip-chars-backward " \t\n\r")))
14921 (move-marker org-log-note-marker (point))
14922 (setq org-log-note-purpose purpose
14923 org-log-note-state state
14924 org-log-note-how how)
14925 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14927 (defun org-skip-over-state-notes ()
14928 "Skip past the list of State notes in an entry."
14929 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14930 (while (looking-at "[ \t]*- State")
14931 (condition-case nil
14932 (org-next-item)
14933 (error (org-end-of-item)))))
14935 (defun org-add-log-note (&optional purpose)
14936 "Pop up a window for taking a note, and add this note later at point."
14937 (remove-hook 'post-command-hook 'org-add-log-note)
14938 (setq org-log-note-window-configuration (current-window-configuration))
14939 (delete-other-windows)
14940 (move-marker org-log-note-return-to (point))
14941 (switch-to-buffer (marker-buffer org-log-note-marker))
14942 (goto-char org-log-note-marker)
14943 (org-switch-to-buffer-other-window "*Org Note*")
14944 (erase-buffer)
14945 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14946 (org-store-log-note)
14947 (let ((org-inhibit-startup t)) (org-mode))
14948 (insert (format "# Insert note for %s.
14949 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14950 (cond
14951 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14952 ((eq org-log-note-purpose 'done) "closed todo item")
14953 ((eq org-log-note-purpose 'state)
14954 (format "state change to \"%s\"" org-log-note-state))
14955 (t (error "This should not happen")))))
14956 (org-set-local 'org-finish-function 'org-store-log-note)))
14958 (defun org-store-log-note ()
14959 "Finish taking a log note, and insert it to where it belongs."
14960 (let ((txt (buffer-string))
14961 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14962 lines ind)
14963 (kill-buffer (current-buffer))
14964 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14965 (setq txt (replace-match "" t t txt)))
14966 (if (string-match "\\s-+\\'" txt)
14967 (setq txt (replace-match "" t t txt)))
14968 (setq lines (org-split-string txt "\n"))
14969 (when (and note (string-match "\\S-" note))
14970 (setq note
14971 (org-replace-escapes
14972 note
14973 (list (cons "%u" (user-login-name))
14974 (cons "%U" user-full-name)
14975 (cons "%t" (format-time-string
14976 (org-time-stamp-format 'long 'inactive)
14977 (current-time)))
14978 (cons "%s" (if org-log-note-state
14979 (concat "\"" org-log-note-state "\"")
14980 "")))))
14981 (if lines (setq note (concat note " \\\\")))
14982 (push note lines))
14983 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14984 (when lines
14985 (save-excursion
14986 (set-buffer (marker-buffer org-log-note-marker))
14987 (save-excursion
14988 (goto-char org-log-note-marker)
14989 (move-marker org-log-note-marker nil)
14990 (end-of-line 1)
14991 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14992 (indent-relative nil)
14993 (insert "- " (pop lines))
14994 (org-indent-line-function)
14995 (beginning-of-line 1)
14996 (looking-at "[ \t]*")
14997 (setq ind (concat (match-string 0) " "))
14998 (end-of-line 1)
14999 (while lines (insert "\n" ind (pop lines)))))))
15000 (set-window-configuration org-log-note-window-configuration)
15001 (with-current-buffer (marker-buffer org-log-note-return-to)
15002 (goto-char org-log-note-return-to))
15003 (move-marker org-log-note-return-to nil)
15004 (and org-log-post-message (message "%s" org-log-post-message)))
15006 ;; FIXME: what else would be useful?
15007 ;; - priority
15008 ;; - date
15010 (defun org-sparse-tree (&optional arg)
15011 "Create a sparse tree, prompt for the details.
15012 This command can create sparse trees. You first need to select the type
15013 of match used to create the tree:
15015 t Show entries with a specific TODO keyword.
15016 T Show entries selected by a tags match.
15017 p Enter a property name and its value (both with completion on existing
15018 names/values) and show entries with that property.
15019 r Show entries matching a regular expression
15020 d Show deadlines due within `org-deadline-warning-days'."
15021 (interactive "P")
15022 (let (ans kwd value)
15023 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15024 (setq ans (read-char-exclusive))
15025 (cond
15026 ((equal ans ?d)
15027 (call-interactively 'org-check-deadlines))
15028 ((equal ans ?b)
15029 (call-interactively 'org-check-before-date))
15030 ((equal ans ?t)
15031 (org-show-todo-tree '(4)))
15032 ((equal ans ?T)
15033 (call-interactively 'org-tags-sparse-tree))
15034 ((member ans '(?p ?P))
15035 (setq kwd (completing-read "Property: "
15036 (mapcar 'list (org-buffer-property-keys))))
15037 (setq value (completing-read "Value: "
15038 (mapcar 'list (org-property-values kwd))))
15039 (unless (string-match "\\`{.*}\\'" value)
15040 (setq value (concat "\"" value "\"")))
15041 (org-tags-sparse-tree arg (concat kwd "=" value)))
15042 ((member ans '(?r ?R ?/))
15043 (call-interactively 'org-occur))
15044 (t (error "No such sparse tree command \"%c\"" ans)))))
15046 (defvar org-occur-highlights nil
15047 "List of overlays used for occur matches.")
15048 (make-variable-buffer-local 'org-occur-highlights)
15049 (defvar org-occur-parameters nil
15050 "Parameters of the active org-occur calls.
15051 This is a list, each call to org-occur pushes as cons cell,
15052 containing the regular expression and the callback, onto the list.
15053 The list can contain several entries if `org-occur' has been called
15054 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15055 will only contain one set of parameters. When the highlights are
15056 removed (for example with `C-c C-c', or with the next edit (depending
15057 on `org-remove-highlights-with-change'), this variable is emptied
15058 as well.")
15059 (make-variable-buffer-local 'org-occur-parameters)
15061 (defun org-occur (regexp &optional keep-previous callback)
15062 "Make a compact tree which shows all matches of REGEXP.
15063 The tree will show the lines where the regexp matches, and all higher
15064 headlines above the match. It will also show the heading after the match,
15065 to make sure editing the matching entry is easy.
15066 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15067 call to `org-occur' will be kept, to allow stacking of calls to this
15068 command.
15069 If CALLBACK is non-nil, it is a function which is called to confirm
15070 that the match should indeed be shown."
15071 (interactive "sRegexp: \nP")
15072 (unless keep-previous
15073 (org-remove-occur-highlights nil nil t))
15074 (push (cons regexp callback) org-occur-parameters)
15075 (let ((cnt 0))
15076 (save-excursion
15077 (goto-char (point-min))
15078 (if (or (not keep-previous) ; do not want to keep
15079 (not org-occur-highlights)) ; no previous matches
15080 ;; hide everything
15081 (org-overview))
15082 (while (re-search-forward regexp nil t)
15083 (when (or (not callback)
15084 (save-match-data (funcall callback)))
15085 (setq cnt (1+ cnt))
15086 (when org-highlight-sparse-tree-matches
15087 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15088 (org-show-context 'occur-tree))))
15089 (when org-remove-highlights-with-change
15090 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15091 nil 'local))
15092 (unless org-sparse-tree-open-archived-trees
15093 (org-hide-archived-subtrees (point-min) (point-max)))
15094 (run-hooks 'org-occur-hook)
15095 (if (interactive-p)
15096 (message "%d match(es) for regexp %s" cnt regexp))
15097 cnt))
15099 (defun org-show-context (&optional key)
15100 "Make sure point and context and visible.
15101 How much context is shown depends upon the variables
15102 `org-show-hierarchy-above', `org-show-following-heading'. and
15103 `org-show-siblings'."
15104 (let ((heading-p (org-on-heading-p t))
15105 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15106 (following-p (org-get-alist-option org-show-following-heading key))
15107 (entry-p (org-get-alist-option org-show-entry-below key))
15108 (siblings-p (org-get-alist-option org-show-siblings key)))
15109 (catch 'exit
15110 ;; Show heading or entry text
15111 (if (and heading-p (not entry-p))
15112 (org-flag-heading nil) ; only show the heading
15113 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15114 (org-show-hidden-entry))) ; show entire entry
15115 (when following-p
15116 ;; Show next sibling, or heading below text
15117 (save-excursion
15118 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15119 (org-flag-heading nil))))
15120 (when siblings-p (org-show-siblings))
15121 (when hierarchy-p
15122 ;; show all higher headings, possibly with siblings
15123 (save-excursion
15124 (while (and (condition-case nil
15125 (progn (org-up-heading-all 1) t)
15126 (error nil))
15127 (not (bobp)))
15128 (org-flag-heading nil)
15129 (when siblings-p (org-show-siblings))))))))
15131 (defun org-reveal (&optional siblings)
15132 "Show current entry, hierarchy above it, and the following headline.
15133 This can be used to show a consistent set of context around locations
15134 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15135 not t for the search context.
15137 With optional argument SIBLINGS, on each level of the hierarchy all
15138 siblings are shown. This repairs the tree structure to what it would
15139 look like when opened with hierarchical calls to `org-cycle'."
15140 (interactive "P")
15141 (let ((org-show-hierarchy-above t)
15142 (org-show-following-heading t)
15143 (org-show-siblings (if siblings t org-show-siblings)))
15144 (org-show-context nil)))
15146 (defun org-highlight-new-match (beg end)
15147 "Highlight from BEG to END and mark the highlight is an occur headline."
15148 (let ((ov (org-make-overlay beg end)))
15149 (org-overlay-put ov 'face 'secondary-selection)
15150 (push ov org-occur-highlights)))
15152 (defun org-remove-occur-highlights (&optional beg end noremove)
15153 "Remove the occur highlights from the buffer.
15154 BEG and END are ignored. If NOREMOVE is nil, remove this function
15155 from the `before-change-functions' in the current buffer."
15156 (interactive)
15157 (unless org-inhibit-highlight-removal
15158 (mapc 'org-delete-overlay org-occur-highlights)
15159 (setq org-occur-highlights nil)
15160 (setq org-occur-parameters nil)
15161 (unless noremove
15162 (remove-hook 'before-change-functions
15163 'org-remove-occur-highlights 'local))))
15165 ;;;; Priorities
15167 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15168 "Regular expression matching the priority indicator.")
15170 (defvar org-remove-priority-next-time nil)
15172 (defun org-priority-up ()
15173 "Increase the priority of the current item."
15174 (interactive)
15175 (org-priority 'up))
15177 (defun org-priority-down ()
15178 "Decrease the priority of the current item."
15179 (interactive)
15180 (org-priority 'down))
15182 (defun org-priority (&optional action)
15183 "Change the priority of an item by ARG.
15184 ACTION can be `set', `up', `down', or a character."
15185 (interactive)
15186 (setq action (or action 'set))
15187 (let (current new news have remove)
15188 (save-excursion
15189 (org-back-to-heading)
15190 (if (looking-at org-priority-regexp)
15191 (setq current (string-to-char (match-string 2))
15192 have t)
15193 (setq current org-default-priority))
15194 (cond
15195 ((or (eq action 'set) (integerp action))
15196 (if (integerp action)
15197 (setq new action)
15198 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15199 (setq new (read-char-exclusive)))
15200 (if (and (= (upcase org-highest-priority) org-highest-priority)
15201 (= (upcase org-lowest-priority) org-lowest-priority))
15202 (setq new (upcase new)))
15203 (cond ((equal new ?\ ) (setq remove t))
15204 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15205 (error "Priority must be between `%c' and `%c'"
15206 org-highest-priority org-lowest-priority))))
15207 ((eq action 'up)
15208 (if (and (not have) (eq last-command this-command))
15209 (setq new org-lowest-priority)
15210 (setq new (if (and org-priority-start-cycle-with-default (not have))
15211 org-default-priority (1- current)))))
15212 ((eq action 'down)
15213 (if (and (not have) (eq last-command this-command))
15214 (setq new org-highest-priority)
15215 (setq new (if (and org-priority-start-cycle-with-default (not have))
15216 org-default-priority (1+ current)))))
15217 (t (error "Invalid action")))
15218 (if (or (< (upcase new) org-highest-priority)
15219 (> (upcase new) org-lowest-priority))
15220 (setq remove t))
15221 (setq news (format "%c" new))
15222 (if have
15223 (if remove
15224 (replace-match "" t t nil 1)
15225 (replace-match news t t nil 2))
15226 (if remove
15227 (error "No priority cookie found in line")
15228 (looking-at org-todo-line-regexp)
15229 (if (match-end 2)
15230 (progn
15231 (goto-char (match-end 2))
15232 (insert " [#" news "]"))
15233 (goto-char (match-beginning 3))
15234 (insert "[#" news "] ")))))
15235 (org-preserve-lc (org-set-tags nil 'align))
15236 (if remove
15237 (message "Priority removed")
15238 (message "Priority of current item set to %s" news))))
15241 (defun org-get-priority (s)
15242 "Find priority cookie and return priority."
15243 (save-match-data
15244 (if (not (string-match org-priority-regexp s))
15245 (* 1000 (- org-lowest-priority org-default-priority))
15246 (* 1000 (- org-lowest-priority
15247 (string-to-char (match-string 2 s)))))))
15249 ;;;; Tags
15251 (defun org-scan-tags (action matcher &optional todo-only)
15252 "Scan headline tags with inheritance and produce output ACTION.
15253 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15254 evaluated, testing if a given set of tags qualifies a headline for
15255 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15256 are included in the output."
15257 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15258 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15259 (org-re
15260 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15261 (props (list 'face nil
15262 'done-face 'org-done
15263 'undone-face nil
15264 'mouse-face 'highlight
15265 'org-not-done-regexp org-not-done-regexp
15266 'org-todo-regexp org-todo-regexp
15267 'keymap org-agenda-keymap
15268 'help-echo
15269 (format "mouse-2 or RET jump to org file %s"
15270 (abbreviate-file-name
15271 (or (buffer-file-name (buffer-base-buffer))
15272 (buffer-name (buffer-base-buffer)))))))
15273 (case-fold-search nil)
15274 lspos
15275 tags tags-list tags-alist (llast 0) rtn level category i txt
15276 todo marker entry priority)
15277 (save-excursion
15278 (goto-char (point-min))
15279 (when (eq action 'sparse-tree)
15280 (org-overview)
15281 (org-remove-occur-highlights))
15282 (while (re-search-forward re nil t)
15283 (catch :skip
15284 (setq todo (if (match-end 1) (match-string 2))
15285 tags (if (match-end 4) (match-string 4)))
15286 (goto-char (setq lspos (1+ (match-beginning 0))))
15287 (setq level (org-reduced-level (funcall outline-level))
15288 category (org-get-category))
15289 (setq i llast llast level)
15290 ;; remove tag lists from same and sublevels
15291 (while (>= i level)
15292 (when (setq entry (assoc i tags-alist))
15293 (setq tags-alist (delete entry tags-alist)))
15294 (setq i (1- i)))
15295 ;; add the next tags
15296 (when tags
15297 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15298 tags-alist
15299 (cons (cons level tags) tags-alist)))
15300 ;; compile tags for current headline
15301 (setq tags-list
15302 (if org-use-tag-inheritance
15303 (apply 'append (mapcar 'cdr tags-alist))
15304 tags))
15305 (when (and tags org-use-tag-inheritance
15306 (not (eq t org-use-tag-inheritance)))
15307 ;; selective inheritance, remove uninherited ones
15308 (setcdr (car tags-alist)
15309 (org-remove-uniherited-tags (cdar tags-alist))))
15310 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15311 (eval matcher)
15312 (or (not org-agenda-skip-archived-trees)
15313 (not (member org-archive-tag tags-list))))
15314 (and (eq action 'agenda) (org-agenda-skip))
15315 ;; list this headline
15317 (if (eq action 'sparse-tree)
15318 (progn
15319 (and org-highlight-sparse-tree-matches
15320 (org-get-heading) (match-end 0)
15321 (org-highlight-new-match
15322 (match-beginning 0) (match-beginning 1)))
15323 (org-show-context 'tags-tree))
15324 (setq txt (org-format-agenda-item
15326 (concat
15327 (if org-tags-match-list-sublevels
15328 (make-string (1- level) ?.) "")
15329 (org-get-heading))
15330 category tags-list)
15331 priority (org-get-priority txt))
15332 (goto-char lspos)
15333 (setq marker (org-agenda-new-marker))
15334 (org-add-props txt props
15335 'org-marker marker 'org-hd-marker marker 'org-category category
15336 'priority priority 'type "tagsmatch")
15337 (push txt rtn))
15338 ;; if we are to skip sublevels, jump to end of subtree
15339 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15340 (when (and (eq action 'sparse-tree)
15341 (not org-sparse-tree-open-archived-trees))
15342 (org-hide-archived-subtrees (point-min) (point-max)))
15343 (nreverse rtn)))
15345 (defun org-remove-uniherited-tags (tags)
15346 "Remove all tags that are not inherited from the list TAGS."
15347 (cond
15348 ((eq org-use-tag-inheritance t) tags)
15349 ((not org-use-tag-inheritance) nil)
15350 ((stringp org-use-tag-inheritance)
15351 (delq nil (mapcar
15352 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
15353 tags)))
15354 ((listp org-use-tag-inheritance)
15355 (org-delete-all org-use-tag-inheritance tags))))
15357 (defvar todo-only) ;; dynamically scoped
15359 (defun org-tags-sparse-tree (&optional todo-only match)
15360 "Create a sparse tree according to tags string MATCH.
15361 MATCH can contain positive and negative selection of tags, like
15362 \"+WORK+URGENT-WITHBOSS\".
15363 If optional argument TODO_ONLY is non-nil, only select lines that are
15364 also TODO lines."
15365 (interactive "P")
15366 (org-prepare-agenda-buffers (list (current-buffer)))
15367 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15369 (defvar org-cached-props nil)
15370 (defun org-cached-entry-get (pom property)
15371 (if (or (eq t org-use-property-inheritance)
15372 (and (stringp org-use-property-inheritance)
15373 (string-match org-use-property-inheritance property))
15374 (and (listp org-use-property-inheritance)
15375 (member property org-use-property-inheritance)))
15376 ;; Caching is not possible, check it directly
15377 (org-entry-get pom property 'inherit)
15378 ;; Get all properties, so that we can do complicated checks easily
15379 (cdr (assoc property (or org-cached-props
15380 (setq org-cached-props
15381 (org-entry-properties pom)))))))
15383 (defun org-global-tags-completion-table (&optional files)
15384 "Return the list of all tags in all agenda buffer/files."
15385 (save-excursion
15386 (org-uniquify
15387 (delq nil
15388 (apply 'append
15389 (mapcar
15390 (lambda (file)
15391 (set-buffer (find-file-noselect file))
15392 (append (org-get-buffer-tags)
15393 (mapcar (lambda (x) (if (stringp (car-safe x))
15394 (list (car-safe x)) nil))
15395 org-tag-alist)))
15396 (if (and files (car files))
15397 files
15398 (org-agenda-files))))))))
15400 (defun org-make-tags-matcher (match)
15401 "Create the TAGS//TODO matcher form for the selection string MATCH."
15402 ;; todo-only is scoped dynamically into this function, and the function
15403 ;; may change it it the matcher asksk for it.
15404 (unless match
15405 ;; Get a new match request, with completion
15406 (let ((org-last-tags-completion-table
15407 (org-global-tags-completion-table)))
15408 (setq match (completing-read
15409 "Match: " 'org-tags-completion-function nil nil nil
15410 'org-tags-history))))
15412 ;; Parse the string and create a lisp form
15413 (let ((match0 match)
15414 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15415 minus tag mm
15416 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15417 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15418 (if (string-match "/+" match)
15419 ;; match contains also a todo-matching request
15420 (progn
15421 (setq tagsmatch (substring match 0 (match-beginning 0))
15422 todomatch (substring match (match-end 0)))
15423 (if (string-match "^!" todomatch)
15424 (setq todo-only t todomatch (substring todomatch 1)))
15425 (if (string-match "^\\s-*$" todomatch)
15426 (setq todomatch nil)))
15427 ;; only matching tags
15428 (setq tagsmatch match todomatch nil))
15430 ;; Make the tags matcher
15431 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15432 (setq tagsmatcher t)
15433 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15434 (while (setq term (pop orterms))
15435 (while (and (equal (substring term -1) "\\") orterms)
15436 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15437 (while (string-match re term)
15438 (setq minus (and (match-end 1)
15439 (equal (match-string 1 term) "-"))
15440 tag (match-string 2 term)
15441 re-p (equal (string-to-char tag) ?{)
15442 level-p (match-end 3)
15443 prop-p (match-end 4)
15444 mm (cond
15445 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15446 (level-p `(= level ,(string-to-number
15447 (match-string 3 term))))
15448 (prop-p
15449 (setq pn (match-string 4 term)
15450 pv (match-string 5 term)
15451 cat-p (equal pn "CATEGORY")
15452 re-p (equal (string-to-char pv) ?{)
15453 pv (substring pv 1 -1))
15454 (if (equal pn "CATEGORY")
15455 (setq gv '(get-text-property (point) 'org-category))
15456 (setq gv `(org-cached-entry-get nil ,pn)))
15457 (if re-p
15458 `(string-match ,pv (or ,gv ""))
15459 `(equal ,pv (or ,gv ""))))
15460 (t `(member ,(downcase tag) tags-list)))
15461 mm (if minus (list 'not mm) mm)
15462 term (substring term (match-end 0)))
15463 (push mm tagsmatcher))
15464 (push (if (> (length tagsmatcher) 1)
15465 (cons 'and tagsmatcher)
15466 (car tagsmatcher))
15467 orlist)
15468 (setq tagsmatcher nil))
15469 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15470 (setq tagsmatcher
15471 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15473 ;; Make the todo matcher
15474 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15475 (setq todomatcher t)
15476 (setq orterms (org-split-string todomatch "|") orlist nil)
15477 (while (setq term (pop orterms))
15478 (while (string-match re term)
15479 (setq minus (and (match-end 1)
15480 (equal (match-string 1 term) "-"))
15481 kwd (match-string 2 term)
15482 re-p (equal (string-to-char kwd) ?{)
15483 term (substring term (match-end 0))
15484 mm (if re-p
15485 `(string-match ,(substring kwd 1 -1) todo)
15486 (list 'equal 'todo kwd))
15487 mm (if minus (list 'not mm) mm))
15488 (push mm todomatcher))
15489 (push (if (> (length todomatcher) 1)
15490 (cons 'and todomatcher)
15491 (car todomatcher))
15492 orlist)
15493 (setq todomatcher nil))
15494 (setq todomatcher (if (> (length orlist) 1)
15495 (cons 'or orlist) (car orlist))))
15497 ;; Return the string and lisp forms of the matcher
15498 (setq matcher (if todomatcher
15499 (list 'and tagsmatcher todomatcher)
15500 tagsmatcher))
15501 (cons match0 matcher)))
15503 (defun org-match-any-p (re list)
15504 "Does re match any element of list?"
15505 (setq list (mapcar (lambda (x) (string-match re x)) list))
15506 (delq nil list))
15508 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15509 (defvar org-tags-overlay (org-make-overlay 1 1))
15510 (org-detach-overlay org-tags-overlay)
15512 (defun org-align-tags-here (to-col)
15513 ;; Assumes that this is a headline
15514 (let ((pos (point)) (col (current-column)) tags)
15515 (beginning-of-line 1)
15516 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15517 (< pos (match-beginning 2)))
15518 (progn
15519 (setq tags (match-string 2))
15520 (goto-char (match-beginning 1))
15521 (insert " ")
15522 (delete-region (point) (1+ (match-end 0)))
15523 (backward-char 1)
15524 (move-to-column
15525 (max (1+ (current-column))
15526 (1+ col)
15527 (if (> to-col 0)
15528 to-col
15529 (- (abs to-col) (length tags))))
15531 (insert tags)
15532 (move-to-column (min (current-column) col) t))
15533 (goto-char pos))))
15535 (defun org-set-tags (&optional arg just-align)
15536 "Set the tags for the current headline.
15537 With prefix ARG, realign all tags in headings in the current buffer."
15538 (interactive "P")
15539 (let* ((re (concat "^" outline-regexp))
15540 (current (org-get-tags-string))
15541 (col (current-column))
15542 (org-setting-tags t)
15543 table current-tags inherited-tags ; computed below when needed
15544 tags p0 c0 c1 rpl)
15545 (if arg
15546 (save-excursion
15547 (goto-char (point-min))
15548 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15549 (while (re-search-forward re nil t)
15550 (org-set-tags nil t)
15551 (end-of-line 1)))
15552 (message "All tags realigned to column %d" org-tags-column))
15553 (if just-align
15554 (setq tags current)
15555 ;; Get a new set of tags from the user
15556 (save-excursion
15557 (setq table (or org-tag-alist (org-get-buffer-tags))
15558 org-last-tags-completion-table table
15559 current-tags (org-split-string current ":")
15560 inherited-tags (nreverse
15561 (nthcdr (length current-tags)
15562 (nreverse (org-get-tags-at))))
15563 tags
15564 (if (or (eq t org-use-fast-tag-selection)
15565 (and org-use-fast-tag-selection
15566 (delq nil (mapcar 'cdr table))))
15567 (org-fast-tag-selection
15568 current-tags inherited-tags table
15569 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15570 (let ((org-add-colon-after-tag-completion t))
15571 (org-trim
15572 (org-without-partial-completion
15573 (completing-read "Tags: " 'org-tags-completion-function
15574 nil nil current 'org-tags-history)))))))
15575 (while (string-match "[-+&]+" tags)
15576 ;; No boolean logic, just a list
15577 (setq tags (replace-match ":" t t tags))))
15579 (if (string-match "\\`[\t ]*\\'" tags)
15580 (setq tags "")
15581 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15582 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15584 ;; Insert new tags at the correct column
15585 (beginning-of-line 1)
15586 (cond
15587 ((and (equal current "") (equal tags "")))
15588 ((re-search-forward
15589 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15590 (point-at-eol) t)
15591 (if (equal tags "")
15592 (setq rpl "")
15593 (goto-char (match-beginning 0))
15594 (setq c0 (current-column) p0 (point)
15595 c1 (max (1+ c0) (if (> org-tags-column 0)
15596 org-tags-column
15597 (- (- org-tags-column) (length tags))))
15598 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15599 (replace-match rpl t t)
15600 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15601 tags)
15602 (t (error "Tags alignment failed")))
15603 (move-to-column col)
15604 (unless just-align
15605 (run-hooks 'org-after-tags-change-hook)))))
15607 (defun org-change-tag-in-region (beg end tag off)
15608 "Add or remove TAG for each entry in the region.
15609 This works in the agenda, and also in an org-mode buffer."
15610 (interactive
15611 (list (region-beginning) (region-end)
15612 (let ((org-last-tags-completion-table
15613 (if (org-mode-p)
15614 (org-get-buffer-tags)
15615 (org-global-tags-completion-table))))
15616 (completing-read
15617 "Tag: " 'org-tags-completion-function nil nil nil
15618 'org-tags-history))
15619 (progn
15620 (message "[s]et or [r]emove? ")
15621 (equal (read-char-exclusive) ?r))))
15622 (if (fboundp 'deactivate-mark) (deactivate-mark))
15623 (let ((agendap (equal major-mode 'org-agenda-mode))
15624 l1 l2 m buf pos newhead (cnt 0))
15625 (goto-char end)
15626 (setq l2 (1- (org-current-line)))
15627 (goto-char beg)
15628 (setq l1 (org-current-line))
15629 (loop for l from l1 to l2 do
15630 (goto-line l)
15631 (setq m (get-text-property (point) 'org-hd-marker))
15632 (when (or (and (org-mode-p) (org-on-heading-p))
15633 (and agendap m))
15634 (setq buf (if agendap (marker-buffer m) (current-buffer))
15635 pos (if agendap m (point)))
15636 (with-current-buffer buf
15637 (save-excursion
15638 (save-restriction
15639 (goto-char pos)
15640 (setq cnt (1+ cnt))
15641 (org-toggle-tag tag (if off 'off 'on))
15642 (setq newhead (org-get-heading)))))
15643 (and agendap (org-agenda-change-all-lines newhead m))))
15644 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15646 (defun org-tags-completion-function (string predicate &optional flag)
15647 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15648 (confirm (lambda (x) (stringp (car x)))))
15649 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15650 (setq s1 (match-string 1 string)
15651 s2 (match-string 2 string))
15652 (setq s1 "" s2 string))
15653 (cond
15654 ((eq flag nil)
15655 ;; try completion
15656 (setq rtn (try-completion s2 ctable confirm))
15657 (if (stringp rtn)
15658 (setq rtn
15659 (concat s1 s2 (substring rtn (length s2))
15660 (if (and org-add-colon-after-tag-completion
15661 (assoc rtn ctable))
15662 ":" ""))))
15663 rtn)
15664 ((eq flag t)
15665 ;; all-completions
15666 (all-completions s2 ctable confirm)
15668 ((eq flag 'lambda)
15669 ;; exact match?
15670 (assoc s2 ctable)))
15673 (defun org-fast-tag-insert (kwd tags face &optional end)
15674 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15675 (insert (format "%-12s" (concat kwd ":"))
15676 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15677 (or end "")))
15679 (defun org-fast-tag-show-exit (flag)
15680 (save-excursion
15681 (goto-line 3)
15682 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15683 (replace-match ""))
15684 (when flag
15685 (end-of-line 1)
15686 (move-to-column (- (window-width) 19) t)
15687 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15689 (defun org-set-current-tags-overlay (current prefix)
15690 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15691 (if (featurep 'xemacs)
15692 (org-overlay-display org-tags-overlay (concat prefix s)
15693 'secondary-selection)
15694 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15695 (org-overlay-display org-tags-overlay (concat prefix s)))))
15697 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15698 "Fast tag selection with single keys.
15699 CURRENT is the current list of tags in the headline, INHERITED is the
15700 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15701 possibly with grouping information. TODO-TABLE is a similar table with
15702 TODO keywords, should these have keys assigned to them.
15703 If the keys are nil, a-z are automatically assigned.
15704 Returns the new tags string, or nil to not change the current settings."
15705 (let* ((fulltable (append table todo-table))
15706 (maxlen (apply 'max (mapcar
15707 (lambda (x)
15708 (if (stringp (car x)) (string-width (car x)) 0))
15709 fulltable)))
15710 (buf (current-buffer))
15711 (expert (eq org-fast-tag-selection-single-key 'expert))
15712 (buffer-tags nil)
15713 (fwidth (+ maxlen 3 1 3))
15714 (ncol (/ (- (window-width) 4) fwidth))
15715 (i-face 'org-done)
15716 (c-face 'org-todo)
15717 tg cnt e c char c1 c2 ntable tbl rtn
15718 ov-start ov-end ov-prefix
15719 (exit-after-next org-fast-tag-selection-single-key)
15720 (done-keywords org-done-keywords)
15721 groups ingroup)
15722 (save-excursion
15723 (beginning-of-line 1)
15724 (if (looking-at
15725 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15726 (setq ov-start (match-beginning 1)
15727 ov-end (match-end 1)
15728 ov-prefix "")
15729 (setq ov-start (1- (point-at-eol))
15730 ov-end (1+ ov-start))
15731 (skip-chars-forward "^\n\r")
15732 (setq ov-prefix
15733 (concat
15734 (buffer-substring (1- (point)) (point))
15735 (if (> (current-column) org-tags-column)
15737 (make-string (- org-tags-column (current-column)) ?\ ))))))
15738 (org-move-overlay org-tags-overlay ov-start ov-end)
15739 (save-window-excursion
15740 (if expert
15741 (set-buffer (get-buffer-create " *Org tags*"))
15742 (delete-other-windows)
15743 (split-window-vertically)
15744 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15745 (erase-buffer)
15746 (org-set-local 'org-done-keywords done-keywords)
15747 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15748 (org-fast-tag-insert "Current" current c-face "\n\n")
15749 (org-fast-tag-show-exit exit-after-next)
15750 (org-set-current-tags-overlay current ov-prefix)
15751 (setq tbl fulltable char ?a cnt 0)
15752 (while (setq e (pop tbl))
15753 (cond
15754 ((equal e '(:startgroup))
15755 (push '() groups) (setq ingroup t)
15756 (when (not (= cnt 0))
15757 (setq cnt 0)
15758 (insert "\n"))
15759 (insert "{ "))
15760 ((equal e '(:endgroup))
15761 (setq ingroup nil cnt 0)
15762 (insert "}\n"))
15764 (setq tg (car e) c2 nil)
15765 (if (cdr e)
15766 (setq c (cdr e))
15767 ;; automatically assign a character.
15768 (setq c1 (string-to-char
15769 (downcase (substring
15770 tg (if (= (string-to-char tg) ?@) 1 0)))))
15771 (if (or (rassoc c1 ntable) (rassoc c1 table))
15772 (while (or (rassoc char ntable) (rassoc char table))
15773 (setq char (1+ char)))
15774 (setq c2 c1))
15775 (setq c (or c2 char)))
15776 (if ingroup (push tg (car groups)))
15777 (setq tg (org-add-props tg nil 'face
15778 (cond
15779 ((not (assoc tg table))
15780 (org-get-todo-face tg))
15781 ((member tg current) c-face)
15782 ((member tg inherited) i-face)
15783 (t nil))))
15784 (if (and (= cnt 0) (not ingroup)) (insert " "))
15785 (insert "[" c "] " tg (make-string
15786 (- fwidth 4 (length tg)) ?\ ))
15787 (push (cons tg c) ntable)
15788 (when (= (setq cnt (1+ cnt)) ncol)
15789 (insert "\n")
15790 (if ingroup (insert " "))
15791 (setq cnt 0)))))
15792 (setq ntable (nreverse ntable))
15793 (insert "\n")
15794 (goto-char (point-min))
15795 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15796 (fit-window-to-buffer))
15797 (setq rtn
15798 (catch 'exit
15799 (while t
15800 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15801 (if groups " [!] no groups" " [!]groups")
15802 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15803 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15804 (cond
15805 ((= c ?\r) (throw 'exit t))
15806 ((= c ?!)
15807 (setq groups (not groups))
15808 (goto-char (point-min))
15809 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15810 ((= c ?\C-c)
15811 (if (not expert)
15812 (org-fast-tag-show-exit
15813 (setq exit-after-next (not exit-after-next)))
15814 (setq expert nil)
15815 (delete-other-windows)
15816 (split-window-vertically)
15817 (org-switch-to-buffer-other-window " *Org tags*")
15818 (and (fboundp 'fit-window-to-buffer)
15819 (fit-window-to-buffer))))
15820 ((or (= c ?\C-g)
15821 (and (= c ?q) (not (rassoc c ntable))))
15822 (org-detach-overlay org-tags-overlay)
15823 (setq quit-flag t))
15824 ((= c ?\ )
15825 (setq current nil)
15826 (if exit-after-next (setq exit-after-next 'now)))
15827 ((= c ?\t)
15828 (condition-case nil
15829 (setq tg (completing-read
15830 "Tag: "
15831 (or buffer-tags
15832 (with-current-buffer buf
15833 (org-get-buffer-tags)))))
15834 (quit (setq tg "")))
15835 (when (string-match "\\S-" tg)
15836 (add-to-list 'buffer-tags (list tg))
15837 (if (member tg current)
15838 (setq current (delete tg current))
15839 (push tg current)))
15840 (if exit-after-next (setq exit-after-next 'now)))
15841 ((setq e (rassoc c todo-table) tg (car e))
15842 (with-current-buffer buf
15843 (save-excursion (org-todo tg)))
15844 (if exit-after-next (setq exit-after-next 'now)))
15845 ((setq e (rassoc c ntable) tg (car e))
15846 (if (member tg current)
15847 (setq current (delete tg current))
15848 (loop for g in groups do
15849 (if (member tg g)
15850 (mapc (lambda (x)
15851 (setq current (delete x current)))
15852 g)))
15853 (push tg current))
15854 (if exit-after-next (setq exit-after-next 'now))))
15856 ;; Create a sorted list
15857 (setq current
15858 (sort current
15859 (lambda (a b)
15860 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15861 (if (eq exit-after-next 'now) (throw 'exit t))
15862 (goto-char (point-min))
15863 (beginning-of-line 2)
15864 (delete-region (point) (point-at-eol))
15865 (org-fast-tag-insert "Current" current c-face)
15866 (org-set-current-tags-overlay current ov-prefix)
15867 (while (re-search-forward
15868 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15869 (setq tg (match-string 1))
15870 (add-text-properties
15871 (match-beginning 1) (match-end 1)
15872 (list 'face
15873 (cond
15874 ((member tg current) c-face)
15875 ((member tg inherited) i-face)
15876 (t (get-text-property (match-beginning 1) 'face))))))
15877 (goto-char (point-min)))))
15878 (org-detach-overlay org-tags-overlay)
15879 (if rtn
15880 (mapconcat 'identity current ":")
15881 nil))))
15883 (defun org-get-tags-string ()
15884 "Get the TAGS string in the current headline."
15885 (unless (org-on-heading-p t)
15886 (error "Not on a heading"))
15887 (save-excursion
15888 (beginning-of-line 1)
15889 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15890 (org-match-string-no-properties 1)
15891 "")))
15893 (defun org-get-tags ()
15894 "Get the list of tags specified in the current headline."
15895 (org-split-string (org-get-tags-string) ":"))
15897 (defun org-get-buffer-tags ()
15898 "Get a table of all tags used in the buffer, for completion."
15899 (let (tags)
15900 (save-excursion
15901 (goto-char (point-min))
15902 (while (re-search-forward
15903 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15904 (when (equal (char-after (point-at-bol 0)) ?*)
15905 (mapc (lambda (x) (add-to-list 'tags x))
15906 (org-split-string (org-match-string-no-properties 1) ":")))))
15907 (mapcar 'list tags)))
15910 ;;;; Properties
15912 ;;; Setting and retrieving properties
15914 (defconst org-special-properties
15915 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15916 "TIMESTAMP" "TIMESTAMP_IA")
15917 "The special properties valid in Org-mode.
15919 These are properties that are not defined in the property drawer,
15920 but in some other way.")
15922 (defconst org-default-properties
15923 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15924 "LOCATION" "LOGGING" "COLUMNS")
15925 "Some properties that are used by Org-mode for various purposes.
15926 Being in this list makes sure that they are offered for completion.")
15928 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15929 "Regular expression matching the first line of a property drawer.")
15931 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15932 "Regular expression matching the first line of a property drawer.")
15934 (defun org-property-action ()
15935 "Do an action on properties."
15936 (interactive)
15937 (let (c)
15938 (org-at-property-p)
15939 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15940 (setq c (read-char-exclusive))
15941 (cond
15942 ((equal c ?s)
15943 (call-interactively 'org-set-property))
15944 ((equal c ?d)
15945 (call-interactively 'org-delete-property))
15946 ((equal c ?D)
15947 (call-interactively 'org-delete-property-globally))
15948 ((equal c ?c)
15949 (call-interactively 'org-compute-property-at-point))
15950 (t (error "No such property action %c" c)))))
15952 (defun org-at-property-p ()
15953 "Is the cursor in a property line?"
15954 ;; FIXME: Does not check if we are actually in the drawer.
15955 ;; FIXME: also returns true on any drawers.....
15956 ;; This is used by C-c C-c for property action.
15957 (save-excursion
15958 (beginning-of-line 1)
15959 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15961 (defmacro org-with-point-at (pom &rest body)
15962 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15963 (declare (indent 1) (debug t))
15964 `(save-excursion
15965 (if (markerp pom) (set-buffer (marker-buffer pom)))
15966 (save-excursion
15967 (goto-char (or pom (point)))
15968 ,@body)))
15970 (defun org-get-property-block (&optional beg end force)
15971 "Return the (beg . end) range of the body of the property drawer.
15972 BEG and END can be beginning and end of subtree, if not given
15973 they will be found.
15974 If the drawer does not exist and FORCE is non-nil, create the drawer."
15975 (catch 'exit
15976 (save-excursion
15977 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15978 (end (or end (progn (outline-next-heading) (point)))))
15979 (goto-char beg)
15980 (if (re-search-forward org-property-start-re end t)
15981 (setq beg (1+ (match-end 0)))
15982 (if force
15983 (save-excursion
15984 (org-insert-property-drawer)
15985 (setq end (progn (outline-next-heading) (point))))
15986 (throw 'exit nil))
15987 (goto-char beg)
15988 (if (re-search-forward org-property-start-re end t)
15989 (setq beg (1+ (match-end 0)))))
15990 (if (re-search-forward org-property-end-re end t)
15991 (setq end (match-beginning 0))
15992 (or force (throw 'exit nil))
15993 (goto-char beg)
15994 (setq end beg)
15995 (org-indent-line-function)
15996 (insert ":END:\n"))
15997 (cons beg end)))))
15999 (defun org-entry-properties (&optional pom which)
16000 "Get all properties of the entry at point-or-marker POM.
16001 This includes the TODO keyword, the tags, time strings for deadline,
16002 scheduled, and clocking, and any additional properties defined in the
16003 entry. The return value is an alist, keys may occur multiple times
16004 if the property key was used several times.
16005 POM may also be nil, in which case the current entry is used.
16006 If WHICH is nil or `all', get all properties. If WHICH is
16007 `special' or `standard', only get that subclass."
16008 (setq which (or which 'all))
16009 (org-with-point-at pom
16010 (let ((clockstr (substring org-clock-string 0 -1))
16011 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16012 beg end range props sum-props key value string clocksum)
16013 (save-excursion
16014 (when (condition-case nil (org-back-to-heading t) (error nil))
16015 (setq beg (point))
16016 (setq sum-props (get-text-property (point) 'org-summaries))
16017 (setq clocksum (get-text-property (point) :org-clock-minutes))
16018 (outline-next-heading)
16019 (setq end (point))
16020 (when (memq which '(all special))
16021 ;; Get the special properties, like TODO and tags
16022 (goto-char beg)
16023 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16024 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16025 (when (looking-at org-priority-regexp)
16026 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16027 (when (and (setq value (org-get-tags-string))
16028 (string-match "\\S-" value))
16029 (push (cons "TAGS" value) props))
16030 (when (setq value (org-get-tags-at))
16031 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16032 props))
16033 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16034 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16035 string (if (equal key clockstr)
16036 (org-no-properties
16037 (org-trim
16038 (buffer-substring
16039 (match-beginning 3) (goto-char (point-at-eol)))))
16040 (substring (org-match-string-no-properties 3) 1 -1)))
16041 (unless key
16042 (if (= (char-after (match-beginning 3)) ?\[)
16043 (setq key "TIMESTAMP_IA")
16044 (setq key "TIMESTAMP")))
16045 (when (or (equal key clockstr) (not (assoc key props)))
16046 (push (cons key string) props)))
16050 (when (memq which '(all standard))
16051 ;; Get the standard properties, like :PORP: ...
16052 (setq range (org-get-property-block beg end))
16053 (when range
16054 (goto-char (car range))
16055 (while (re-search-forward
16056 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16057 (cdr range) t)
16058 (setq key (org-match-string-no-properties 1)
16059 value (org-trim (or (org-match-string-no-properties 2) "")))
16060 (unless (member key excluded)
16061 (push (cons key (or value "")) props)))))
16062 (if clocksum
16063 (push (cons "CLOCKSUM"
16064 (org-column-number-to-string (/ (float clocksum) 60.)
16065 'add_times))
16066 props))
16067 (append sum-props (nreverse props)))))))
16069 (defun org-entry-get (pom property &optional inherit)
16070 "Get value of PROPERTY for entry at point-or-marker POM.
16071 If INHERIT is non-nil and the entry does not have the property,
16072 then also check higher levels of the hierarchy.
16073 If INHERIT is the symbol `selective', use inheritance only if the setting
16074 in `org-use-property-inheritance' selects PROPERTY for inheritance.
16075 If the property is present but empty, the return value is the empty string.
16076 If the property is not present at all, nil is returned."
16077 (org-with-point-at pom
16078 (if (and inherit (if (eq inherit 'selective)
16079 (org-property-inherit-p property)
16081 (org-entry-get-with-inheritance property)
16082 (if (member property org-special-properties)
16083 ;; We need a special property. Use brute force, get all properties.
16084 (cdr (assoc property (org-entry-properties nil 'special)))
16085 (let ((range (org-get-property-block)))
16086 (if (and range
16087 (goto-char (car range))
16088 (re-search-forward
16089 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16090 (cdr range) t))
16091 ;; Found the property, return it.
16092 (if (match-end 1)
16093 (org-match-string-no-properties 1)
16094 "")))))))
16096 (defun org-entry-delete (pom property)
16097 "Delete the property PROPERTY from entry at point-or-marker POM."
16098 (org-with-point-at pom
16099 (if (member property org-special-properties)
16100 nil ; cannot delete these properties.
16101 (let ((range (org-get-property-block)))
16102 (if (and range
16103 (goto-char (car range))
16104 (re-search-forward
16105 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16106 (cdr range) t))
16107 (progn
16108 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16110 nil)))))
16112 ;; Multi-values properties are properties that contain multiple values
16113 ;; These values are assumed to be single words, separated by whitespace.
16114 (defun org-entry-add-to-multivalued-property (pom property value)
16115 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16116 (let* ((old (org-entry-get pom property))
16117 (values (and old (org-split-string old "[ \t]"))))
16118 (unless (member value values)
16119 (setq values (cons value values))
16120 (org-entry-put pom property
16121 (mapconcat 'identity values " ")))))
16123 (defun org-entry-remove-from-multivalued-property (pom property value)
16124 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16125 (let* ((old (org-entry-get pom property))
16126 (values (and old (org-split-string old "[ \t]"))))
16127 (when (member value values)
16128 (setq values (delete value values))
16129 (org-entry-put pom property
16130 (mapconcat 'identity values " ")))))
16132 (defun org-entry-member-in-multivalued-property (pom property value)
16133 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16134 (let* ((old (org-entry-get pom property))
16135 (values (and old (org-split-string old "[ \t]"))))
16136 (member value values)))
16138 (defvar org-entry-property-inherited-from (make-marker))
16140 (defun org-entry-get-with-inheritance (property)
16141 "Get entry property, and search higher levels if not present."
16142 (let (tmp)
16143 (save-excursion
16144 (save-restriction
16145 (widen)
16146 (catch 'ex
16147 (while t
16148 (when (setq tmp (org-entry-get nil property))
16149 (org-back-to-heading t)
16150 (move-marker org-entry-property-inherited-from (point))
16151 (throw 'ex tmp))
16152 (or (org-up-heading-safe) (throw 'ex nil)))))
16153 (or tmp (cdr (assoc property org-local-properties))
16154 (cdr (assoc property org-global-properties))))))
16156 (defun org-entry-put (pom property value)
16157 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16158 (org-with-point-at pom
16159 (org-back-to-heading t)
16160 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16161 range)
16162 (cond
16163 ((equal property "TODO")
16164 (when (and (stringp value) (string-match "\\S-" value)
16165 (not (member value org-todo-keywords-1)))
16166 (error "\"%s\" is not a valid TODO state" value))
16167 (if (or (not value)
16168 (not (string-match "\\S-" value)))
16169 (setq value 'none))
16170 (org-todo value)
16171 (org-set-tags nil 'align))
16172 ((equal property "PRIORITY")
16173 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16174 (string-to-char value) ?\ ))
16175 (org-set-tags nil 'align))
16176 ((equal property "SCHEDULED")
16177 (if (re-search-forward org-scheduled-time-regexp end t)
16178 (cond
16179 ((eq value 'earlier) (org-timestamp-change -1 'day))
16180 ((eq value 'later) (org-timestamp-change 1 'day))
16181 (t (call-interactively 'org-schedule)))
16182 (call-interactively 'org-schedule)))
16183 ((equal property "DEADLINE")
16184 (if (re-search-forward org-deadline-time-regexp end t)
16185 (cond
16186 ((eq value 'earlier) (org-timestamp-change -1 'day))
16187 ((eq value 'later) (org-timestamp-change 1 'day))
16188 (t (call-interactively 'org-deadline)))
16189 (call-interactively 'org-deadline)))
16190 ((member property org-special-properties)
16191 (error "The %s property can not yet be set with `org-entry-put'"
16192 property))
16193 (t ; a non-special property
16194 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16195 (setq range (org-get-property-block beg end 'force))
16196 (goto-char (car range))
16197 (if (re-search-forward
16198 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16199 (progn
16200 (delete-region (match-beginning 1) (match-end 1))
16201 (goto-char (match-beginning 1)))
16202 (goto-char (cdr range))
16203 (insert "\n")
16204 (backward-char 1)
16205 (org-indent-line-function)
16206 (insert ":" property ":"))
16207 (and value (insert " " value))
16208 (org-indent-line-function)))))))
16210 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16211 "Get all property keys in the current buffer.
16212 With INCLUDE-SPECIALS, also list the special properties that relect things
16213 like tags and TODO state.
16214 With INCLUDE-DEFAULTS, also include properties that has special meaning
16215 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16216 With INCLUDE-COLUMNS, also include property names given in COLUMN
16217 formats in the current buffer."
16218 (let (rtn range cfmt cols s p)
16219 (save-excursion
16220 (save-restriction
16221 (widen)
16222 (goto-char (point-min))
16223 (while (re-search-forward org-property-start-re nil t)
16224 (setq range (org-get-property-block))
16225 (goto-char (car range))
16226 (while (re-search-forward
16227 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16228 (cdr range) t)
16229 (add-to-list 'rtn (org-match-string-no-properties 1)))
16230 (outline-next-heading))))
16232 (when include-specials
16233 (setq rtn (append org-special-properties rtn)))
16235 (when include-defaults
16236 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16238 (when include-columns
16239 (save-excursion
16240 (save-restriction
16241 (widen)
16242 (goto-char (point-min))
16243 (while (re-search-forward
16244 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16245 nil t)
16246 (setq cfmt (match-string 2) s 0)
16247 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16248 cfmt s)
16249 (setq s (match-end 0)
16250 p (match-string 1 cfmt))
16251 (unless (or (equal p "ITEM")
16252 (member p org-special-properties))
16253 (add-to-list 'rtn (match-string 1 cfmt))))))))
16255 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16257 (defun org-property-values (key)
16258 "Return a list of all values of property KEY."
16259 (save-excursion
16260 (save-restriction
16261 (widen)
16262 (goto-char (point-min))
16263 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16264 values)
16265 (while (re-search-forward re nil t)
16266 (add-to-list 'values (org-trim (match-string 1))))
16267 (delete "" values)))))
16269 (defun org-insert-property-drawer ()
16270 "Insert a property drawer into the current entry."
16271 (interactive)
16272 (org-back-to-heading t)
16273 (looking-at outline-regexp)
16274 (let ((indent (- (match-end 0)(match-beginning 0)))
16275 (beg (point))
16276 (re (concat "^[ \t]*" org-keyword-time-regexp))
16277 end hiddenp)
16278 (outline-next-heading)
16279 (setq end (point))
16280 (goto-char beg)
16281 (while (re-search-forward re end t))
16282 (setq hiddenp (org-invisible-p))
16283 (end-of-line 1)
16284 (and (equal (char-after) ?\n) (forward-char 1))
16285 (org-skip-over-state-notes)
16286 (skip-chars-backward " \t\n\r")
16287 (if (eq (char-before) ?*) (forward-char 1))
16288 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16289 (beginning-of-line 0)
16290 (indent-to-column indent)
16291 (beginning-of-line 2)
16292 (indent-to-column indent)
16293 (beginning-of-line 0)
16294 (if hiddenp
16295 (save-excursion
16296 (org-back-to-heading t)
16297 (hide-entry))
16298 (org-flag-drawer t))))
16300 (defun org-set-property (property value)
16301 "In the current entry, set PROPERTY to VALUE.
16302 When called interactively, this will prompt for a property name, offering
16303 completion on existing and default properties. And then it will prompt
16304 for a value, offering competion either on allowed values (via an inherited
16305 xxx_ALL property) or on existing values in other instances of this property
16306 in the current file."
16307 (interactive
16308 (let* ((prop (completing-read
16309 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16310 (cur (org-entry-get nil prop))
16311 (allowed (org-property-get-allowed-values nil prop 'table))
16312 (existing (mapcar 'list (org-property-values prop)))
16313 (val (if allowed
16314 (completing-read "Value: " allowed nil 'req-match)
16315 (completing-read
16316 (concat "Value" (if (and cur (string-match "\\S-" cur))
16317 (concat "[" cur "]") "")
16318 ": ")
16319 existing nil nil "" nil cur))))
16320 (list prop (if (equal val "") cur val))))
16321 (unless (equal (org-entry-get nil property) value)
16322 (org-entry-put nil property value)))
16324 (defun org-delete-property (property)
16325 "In the current entry, delete PROPERTY."
16326 (interactive
16327 (let* ((prop (completing-read
16328 "Property: " (org-entry-properties nil 'standard))))
16329 (list prop)))
16330 (message "Property %s %s" property
16331 (if (org-entry-delete nil property)
16332 "deleted"
16333 "was not present in the entry")))
16335 (defun org-delete-property-globally (property)
16336 "Remove PROPERTY globally, from all entries."
16337 (interactive
16338 (let* ((prop (completing-read
16339 "Globally remove property: "
16340 (mapcar 'list (org-buffer-property-keys)))))
16341 (list prop)))
16342 (save-excursion
16343 (save-restriction
16344 (widen)
16345 (goto-char (point-min))
16346 (let ((cnt 0))
16347 (while (re-search-forward
16348 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16349 nil t)
16350 (setq cnt (1+ cnt))
16351 (replace-match ""))
16352 (message "Property \"%s\" removed from %d entries" property cnt)))))
16354 (defvar org-columns-current-fmt-compiled) ; defined below
16356 (defun org-compute-property-at-point ()
16357 "Compute the property at point.
16358 This looks for an enclosing column format, extracts the operator and
16359 then applies it to the proerty in the column format's scope."
16360 (interactive)
16361 (unless (org-at-property-p)
16362 (error "Not at a property"))
16363 (let ((prop (org-match-string-no-properties 2)))
16364 (org-columns-get-format-and-top-level)
16365 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16366 (error "No operator defined for property %s" prop))
16367 (org-columns-compute prop)))
16369 (defun org-property-get-allowed-values (pom property &optional table)
16370 "Get allowed values for the property PROPERTY.
16371 When TABLE is non-nil, return an alist that can directly be used for
16372 completion."
16373 (let (vals)
16374 (cond
16375 ((equal property "TODO")
16376 (setq vals (org-with-point-at pom
16377 (append org-todo-keywords-1 '("")))))
16378 ((equal property "PRIORITY")
16379 (let ((n org-lowest-priority))
16380 (while (>= n org-highest-priority)
16381 (push (char-to-string n) vals)
16382 (setq n (1- n)))))
16383 ((member property org-special-properties))
16385 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16387 (when (and vals (string-match "\\S-" vals))
16388 (setq vals (car (read-from-string (concat "(" vals ")"))))
16389 (setq vals (mapcar (lambda (x)
16390 (cond ((stringp x) x)
16391 ((numberp x) (number-to-string x))
16392 ((symbolp x) (symbol-name x))
16393 (t "???")))
16394 vals)))))
16395 (if table (mapcar 'list vals) vals)))
16397 (defun org-property-previous-allowed-value (&optional previous)
16398 "Switch to the next allowed value for this property."
16399 (interactive)
16400 (org-property-next-allowed-value t))
16402 (defun org-property-next-allowed-value (&optional previous)
16403 "Switch to the next allowed value for this property."
16404 (interactive)
16405 (unless (org-at-property-p)
16406 (error "Not at a property"))
16407 (let* ((key (match-string 2))
16408 (value (match-string 3))
16409 (allowed (or (org-property-get-allowed-values (point) key)
16410 (and (member value '("[ ]" "[-]" "[X]"))
16411 '("[ ]" "[X]"))))
16412 nval)
16413 (unless allowed
16414 (error "Allowed values for this property have not been defined"))
16415 (if previous (setq allowed (reverse allowed)))
16416 (if (member value allowed)
16417 (setq nval (car (cdr (member value allowed)))))
16418 (setq nval (or nval (car allowed)))
16419 (if (equal nval value)
16420 (error "Only one allowed value for this property"))
16421 (org-at-property-p)
16422 (replace-match (concat " :" key ": " nval) t t)
16423 (org-indent-line-function)
16424 (beginning-of-line 1)
16425 (skip-chars-forward " \t")))
16427 (defun org-find-entry-with-id (ident)
16428 "Locate the entry that contains the ID property with exact value IDENT.
16429 IDENT can be a string, a symbol or a number, this function will search for
16430 the string representation of it.
16431 Return the position where this entry starts, or nil if there is no such entry."
16432 (let ((id (cond
16433 ((stringp ident) ident)
16434 ((symbol-name ident) (symbol-name ident))
16435 ((numberp ident) (number-to-string ident))
16436 (t (error "IDENT %s must be a string, symbol or number" ident))))
16437 (case-fold-search nil))
16438 (save-excursion
16439 (save-restriction
16440 (widen)
16441 (goto-char (point-min))
16442 (when (re-search-forward
16443 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16444 nil t)
16445 (org-back-to-heading)
16446 (point))))))
16448 ;;; Column View
16450 (defvar org-columns-overlays nil
16451 "Holds the list of current column overlays.")
16453 (defvar org-columns-current-fmt nil
16454 "Local variable, holds the currently active column format.")
16455 (defvar org-columns-current-fmt-compiled nil
16456 "Local variable, holds the currently active column format.
16457 This is the compiled version of the format.")
16458 (defvar org-columns-current-widths nil
16459 "Loval variable, holds the currently widths of fields.")
16460 (defvar org-columns-current-maxwidths nil
16461 "Loval variable, holds the currently active maximum column widths.")
16462 (defvar org-columns-begin-marker (make-marker)
16463 "Points to the position where last a column creation command was called.")
16464 (defvar org-columns-top-level-marker (make-marker)
16465 "Points to the position where current columns region starts.")
16467 (defvar org-columns-map (make-sparse-keymap)
16468 "The keymap valid in column display.")
16470 (defun org-columns-content ()
16471 "Switch to contents view while in columns view."
16472 (interactive)
16473 (org-overview)
16474 (org-content))
16476 (org-defkey org-columns-map "c" 'org-columns-content)
16477 (org-defkey org-columns-map "o" 'org-overview)
16478 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16479 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16480 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16481 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16482 (org-defkey org-columns-map "v" 'org-columns-show-value)
16483 (org-defkey org-columns-map "q" 'org-columns-quit)
16484 (org-defkey org-columns-map "r" 'org-columns-redo)
16485 (org-defkey org-columns-map "g" 'org-columns-redo)
16486 (org-defkey org-columns-map [left] 'backward-char)
16487 (org-defkey org-columns-map "\M-b" 'backward-char)
16488 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16489 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16490 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16491 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16492 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16493 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16494 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16495 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16496 (org-defkey org-columns-map "<" 'org-columns-narrow)
16497 (org-defkey org-columns-map ">" 'org-columns-widen)
16498 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16499 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16500 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16501 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16503 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16504 '("Column"
16505 ["Edit property" org-columns-edit-value t]
16506 ["Next allowed value" org-columns-next-allowed-value t]
16507 ["Previous allowed value" org-columns-previous-allowed-value t]
16508 ["Show full value" org-columns-show-value t]
16509 ["Edit allowed values" org-columns-edit-allowed t]
16510 "--"
16511 ["Edit column attributes" org-columns-edit-attributes t]
16512 ["Increase column width" org-columns-widen t]
16513 ["Decrease column width" org-columns-narrow t]
16514 "--"
16515 ["Move column right" org-columns-move-right t]
16516 ["Move column left" org-columns-move-left t]
16517 ["Add column" org-columns-new t]
16518 ["Delete column" org-columns-delete t]
16519 "--"
16520 ["CONTENTS" org-columns-content t]
16521 ["OVERVIEW" org-overview t]
16522 ["Refresh columns display" org-columns-redo t]
16523 "--"
16524 ["Open link" org-columns-open-link t]
16525 "--"
16526 ["Quit" org-columns-quit t]))
16528 (defun org-columns-new-overlay (beg end &optional string face)
16529 "Create a new column overlay and add it to the list."
16530 (let ((ov (org-make-overlay beg end)))
16531 (org-overlay-put ov 'face (or face 'secondary-selection))
16532 (org-overlay-display ov string face)
16533 (push ov org-columns-overlays)
16534 ov))
16536 (defun org-columns-display-here (&optional props)
16537 "Overlay the current line with column display."
16538 (interactive)
16539 (let* ((fmt org-columns-current-fmt-compiled)
16540 (beg (point-at-bol))
16541 (level-face (save-excursion
16542 (beginning-of-line 1)
16543 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16544 (org-get-level-face 2))))
16545 (color (list :foreground
16546 (face-attribute (or level-face 'default) :foreground)))
16547 props pom property ass width f string ov column val modval)
16548 ;; Check if the entry is in another buffer.
16549 (unless props
16550 (if (eq major-mode 'org-agenda-mode)
16551 (setq pom (or (get-text-property (point) 'org-hd-marker)
16552 (get-text-property (point) 'org-marker))
16553 props (if pom (org-entry-properties pom) nil))
16554 (setq props (org-entry-properties nil))))
16555 ;; Walk the format
16556 (while (setq column (pop fmt))
16557 (setq property (car column)
16558 ass (if (equal property "ITEM")
16559 (cons "ITEM"
16560 (save-match-data
16561 (org-no-properties
16562 (org-remove-tabs
16563 (buffer-substring-no-properties
16564 (point-at-bol) (point-at-eol))))))
16565 (assoc property props))
16566 width (or (cdr (assoc property org-columns-current-maxwidths))
16567 (nth 2 column)
16568 (length property))
16569 f (format "%%-%d.%ds | " width width)
16570 val (or (cdr ass) "")
16571 modval (if (equal property "ITEM")
16572 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16573 string (format f (or modval val)))
16574 ;; Create the overlay
16575 (org-unmodified
16576 (setq ov (org-columns-new-overlay
16577 beg (setq beg (1+ beg)) string
16578 (list color 'org-column)))
16579 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16580 (org-overlay-put ov 'keymap org-columns-map)
16581 (org-overlay-put ov 'org-columns-key property)
16582 (org-overlay-put ov 'org-columns-value (cdr ass))
16583 (org-overlay-put ov 'org-columns-value-modified modval)
16584 (org-overlay-put ov 'org-columns-pom pom)
16585 (org-overlay-put ov 'org-columns-format f))
16586 (if (or (not (char-after beg))
16587 (equal (char-after beg) ?\n))
16588 (let ((inhibit-read-only t))
16589 (save-excursion
16590 (goto-char beg)
16591 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16592 ;; Make the rest of the line disappear.
16593 (org-unmodified
16594 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16595 (org-overlay-put ov 'invisible t)
16596 (org-overlay-put ov 'keymap org-columns-map)
16597 (org-overlay-put ov 'intangible t)
16598 (push ov org-columns-overlays)
16599 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16600 (org-overlay-put ov 'keymap org-columns-map)
16601 (push ov org-columns-overlays)
16602 (let ((inhibit-read-only t))
16603 (put-text-property (max (point-min) (1- (point-at-bol)))
16604 (min (point-max) (1+ (point-at-eol)))
16605 'read-only "Type `e' to edit property")))))
16607 (defvar org-previous-header-line-format nil
16608 "The header line format before column view was turned on.")
16609 (defvar org-columns-inhibit-recalculation nil
16610 "Inhibit recomputing of columns on column view startup.")
16613 (defvar header-line-format)
16614 (defun org-columns-display-here-title ()
16615 "Overlay the newline before the current line with the table title."
16616 (interactive)
16617 (let ((fmt org-columns-current-fmt-compiled)
16618 string (title "")
16619 property width f column str widths)
16620 (while (setq column (pop fmt))
16621 (setq property (car column)
16622 str (or (nth 1 column) property)
16623 width (or (cdr (assoc property org-columns-current-maxwidths))
16624 (nth 2 column)
16625 (length str))
16626 widths (push width widths)
16627 f (format "%%-%d.%ds | " width width)
16628 string (format f str)
16629 title (concat title string)))
16630 (setq title (concat
16631 (org-add-props " " nil 'display '(space :align-to 0))
16632 (org-add-props title nil 'face '(:weight bold :underline t))))
16633 (org-set-local 'org-previous-header-line-format header-line-format)
16634 (org-set-local 'org-columns-current-widths (nreverse widths))
16635 (setq header-line-format title)))
16637 (defun org-columns-remove-overlays ()
16638 "Remove all currently active column overlays."
16639 (interactive)
16640 (when (marker-buffer org-columns-begin-marker)
16641 (with-current-buffer (marker-buffer org-columns-begin-marker)
16642 (when (local-variable-p 'org-previous-header-line-format)
16643 (setq header-line-format org-previous-header-line-format)
16644 (kill-local-variable 'org-previous-header-line-format))
16645 (move-marker org-columns-begin-marker nil)
16646 (move-marker org-columns-top-level-marker nil)
16647 (org-unmodified
16648 (mapc 'org-delete-overlay org-columns-overlays)
16649 (setq org-columns-overlays nil)
16650 (let ((inhibit-read-only t))
16651 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16653 (defun org-columns-cleanup-item (item fmt)
16654 "Remove from ITEM what is a column in the format FMT."
16655 (if (not org-complex-heading-regexp)
16656 item
16657 (when (string-match org-complex-heading-regexp item)
16658 (concat
16659 (org-add-props (concat (match-string 1 item) " ") nil
16660 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16661 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16662 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16663 " " (match-string 4 item)
16664 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16666 (defun org-columns-show-value ()
16667 "Show the full value of the property."
16668 (interactive)
16669 (let ((value (get-char-property (point) 'org-columns-value)))
16670 (message "Value is: %s" (or value ""))))
16672 (defun org-columns-quit ()
16673 "Remove the column overlays and in this way exit column editing."
16674 (interactive)
16675 (org-unmodified
16676 (org-columns-remove-overlays)
16677 (let ((inhibit-read-only t))
16678 (remove-text-properties (point-min) (point-max) '(read-only t))))
16679 (when (eq major-mode 'org-agenda-mode)
16680 (message
16681 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16683 (defun org-columns-check-computed ()
16684 "Check if this column value is computed.
16685 If yes, throw an error indicating that changing it does not make sense."
16686 (let ((val (get-char-property (point) 'org-columns-value)))
16687 (when (and (stringp val)
16688 (get-char-property 0 'org-computed val))
16689 (error "This value is computed from the entry's children"))))
16691 (defun org-columns-todo (&optional arg)
16692 "Change the TODO state during column view."
16693 (interactive "P")
16694 (org-columns-edit-value "TODO"))
16696 (defun org-columns-set-tags-or-toggle (&optional arg)
16697 "Toggle checkbox at point, or set tags for current headline."
16698 (interactive "P")
16699 (if (string-match "\\`\\[[ xX-]\\]\\'"
16700 (get-char-property (point) 'org-columns-value))
16701 (org-columns-next-allowed-value)
16702 (org-columns-edit-value "TAGS")))
16704 (defun org-columns-edit-value (&optional key)
16705 "Edit the value of the property at point in column view.
16706 Where possible, use the standard interface for changing this line."
16707 (interactive)
16708 (org-columns-check-computed)
16709 (let* ((external-key key)
16710 (col (current-column))
16711 (key (or key (get-char-property (point) 'org-columns-key)))
16712 (value (get-char-property (point) 'org-columns-value))
16713 (bol (point-at-bol)) (eol (point-at-eol))
16714 (pom (or (get-text-property bol 'org-hd-marker)
16715 (point))) ; keep despite of compiler waring
16716 (line-overlays
16717 (delq nil (mapcar (lambda (x)
16718 (and (eq (overlay-buffer x) (current-buffer))
16719 (>= (overlay-start x) bol)
16720 (<= (overlay-start x) eol)
16722 org-columns-overlays)))
16723 nval eval allowed)
16724 (cond
16725 ((equal key "CLOCKSUM")
16726 (error "This special column cannot be edited"))
16727 ((equal key "ITEM")
16728 (setq eval '(org-with-point-at pom
16729 (org-edit-headline))))
16730 ((equal key "TODO")
16731 (setq eval '(org-with-point-at pom
16732 (let ((current-prefix-arg
16733 (if external-key current-prefix-arg '(4))))
16734 (call-interactively 'org-todo)))))
16735 ((equal key "PRIORITY")
16736 (setq eval '(org-with-point-at pom
16737 (call-interactively 'org-priority))))
16738 ((equal key "TAGS")
16739 (setq eval '(org-with-point-at pom
16740 (let ((org-fast-tag-selection-single-key
16741 (if (eq org-fast-tag-selection-single-key 'expert)
16742 t org-fast-tag-selection-single-key)))
16743 (call-interactively 'org-set-tags)))))
16744 ((equal key "DEADLINE")
16745 (setq eval '(org-with-point-at pom
16746 (call-interactively 'org-deadline))))
16747 ((equal key "SCHEDULED")
16748 (setq eval '(org-with-point-at pom
16749 (call-interactively 'org-schedule))))
16751 (setq allowed (org-property-get-allowed-values pom key 'table))
16752 (if allowed
16753 (setq nval (completing-read "Value: " allowed nil t))
16754 (setq nval (read-string "Edit: " value)))
16755 (setq nval (org-trim nval))
16756 (when (not (equal nval value))
16757 (setq eval '(org-entry-put pom key nval)))))
16758 (when eval
16759 (let ((inhibit-read-only t))
16760 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16761 (unwind-protect
16762 (progn
16763 (setq org-columns-overlays
16764 (org-delete-all line-overlays org-columns-overlays))
16765 (mapc 'org-delete-overlay line-overlays)
16766 (org-columns-eval eval))
16767 (org-columns-display-here))))
16768 (move-to-column col)
16769 (if (and (org-mode-p)
16770 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16771 (org-columns-update key))))
16773 (defun org-edit-headline () ; FIXME: this is not columns specific
16774 "Edit the current headline, the part without TODO keyword, TAGS."
16775 (org-back-to-heading)
16776 (when (looking-at org-todo-line-regexp)
16777 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16778 (txt (match-string 3))
16779 (post "")
16780 txt2)
16781 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16782 (setq post (match-string 0 txt)
16783 txt (substring txt 0 (match-beginning 0))))
16784 (setq txt2 (read-string "Edit: " txt))
16785 (when (not (equal txt txt2))
16786 (beginning-of-line 1)
16787 (insert pre txt2 post)
16788 (delete-region (point) (point-at-eol))
16789 (org-set-tags nil t)))))
16791 (defun org-columns-edit-allowed ()
16792 "Edit the list of allowed values for the current property."
16793 (interactive)
16794 (let* ((key (get-char-property (point) 'org-columns-key))
16795 (key1 (concat key "_ALL"))
16796 (allowed (org-entry-get (point) key1 t))
16797 nval)
16798 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16799 (setq nval (read-string "Allowed: " allowed))
16800 (org-entry-put
16801 (cond ((marker-position org-entry-property-inherited-from)
16802 org-entry-property-inherited-from)
16803 ((marker-position org-columns-top-level-marker)
16804 org-columns-top-level-marker))
16805 key1 nval)))
16807 (defmacro org-no-warnings (&rest body)
16808 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16810 (defun org-columns-eval (form)
16811 (let (hidep)
16812 (save-excursion
16813 (beginning-of-line 1)
16814 ;; `next-line' is needed here, because it skips invisible line.
16815 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16816 (setq hidep (org-on-heading-p 1)))
16817 (eval form)
16818 (and hidep (hide-entry))))
16820 (defun org-columns-previous-allowed-value ()
16821 "Switch to the previous allowed value for this column."
16822 (interactive)
16823 (org-columns-next-allowed-value t))
16825 (defun org-columns-next-allowed-value (&optional previous)
16826 "Switch to the next allowed value for this column."
16827 (interactive)
16828 (org-columns-check-computed)
16829 (let* ((col (current-column))
16830 (key (get-char-property (point) 'org-columns-key))
16831 (value (get-char-property (point) 'org-columns-value))
16832 (bol (point-at-bol)) (eol (point-at-eol))
16833 (pom (or (get-text-property bol 'org-hd-marker)
16834 (point))) ; keep despite of compiler waring
16835 (line-overlays
16836 (delq nil (mapcar (lambda (x)
16837 (and (eq (overlay-buffer x) (current-buffer))
16838 (>= (overlay-start x) bol)
16839 (<= (overlay-start x) eol)
16841 org-columns-overlays)))
16842 (allowed (or (org-property-get-allowed-values pom key)
16843 (and (memq
16844 (nth 4 (assoc key org-columns-current-fmt-compiled))
16845 '(checkbox checkbox-n-of-m checkbox-percent))
16846 '("[ ]" "[X]"))))
16847 nval)
16848 (when (equal key "ITEM")
16849 (error "Cannot edit item headline from here"))
16850 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16851 (error "Allowed values for this property have not been defined"))
16852 (if (member key '("SCHEDULED" "DEADLINE"))
16853 (setq nval (if previous 'earlier 'later))
16854 (if previous (setq allowed (reverse allowed)))
16855 (if (member value allowed)
16856 (setq nval (car (cdr (member value allowed)))))
16857 (setq nval (or nval (car allowed)))
16858 (if (equal nval value)
16859 (error "Only one allowed value for this property")))
16860 (let ((inhibit-read-only t))
16861 (remove-text-properties (1- bol) eol '(read-only t))
16862 (unwind-protect
16863 (progn
16864 (setq org-columns-overlays
16865 (org-delete-all line-overlays org-columns-overlays))
16866 (mapc 'org-delete-overlay line-overlays)
16867 (org-columns-eval '(org-entry-put pom key nval)))
16868 (org-columns-display-here)))
16869 (move-to-column col)
16870 (if (and (org-mode-p)
16871 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16872 (org-columns-update key))))
16874 (defun org-verify-version (task)
16875 (cond
16876 ((eq task 'columns)
16877 (if (or (featurep 'xemacs)
16878 (< emacs-major-version 22))
16879 (error "Emacs 22 is required for the columns feature")))))
16881 (defun org-columns-open-link (&optional arg)
16882 (interactive "P")
16883 (let ((value (get-char-property (point) 'org-columns-value)))
16884 (org-open-link-from-string value arg)))
16886 (defun org-open-link-from-string (s &optional arg)
16887 "Open a link in the string S, as if it was in Org-mode."
16888 (interactive)
16889 (with-temp-buffer
16890 (let ((org-inhibit-startup t))
16891 (org-mode)
16892 (insert s)
16893 (goto-char (point-min))
16894 (org-open-at-point arg))))
16896 (defun org-columns-get-format-and-top-level ()
16897 (let (fmt)
16898 (when (condition-case nil (org-back-to-heading) (error nil))
16899 (move-marker org-entry-property-inherited-from nil)
16900 (setq fmt (org-entry-get nil "COLUMNS" t)))
16901 (setq fmt (or fmt org-columns-default-format))
16902 (org-set-local 'org-columns-current-fmt fmt)
16903 (org-columns-compile-format fmt)
16904 (if (marker-position org-entry-property-inherited-from)
16905 (move-marker org-columns-top-level-marker
16906 org-entry-property-inherited-from)
16907 (move-marker org-columns-top-level-marker (point)))
16908 fmt))
16910 (defun org-columns ()
16911 "Turn on column view on an org-mode file."
16912 (interactive)
16913 (org-verify-version 'columns)
16914 (org-columns-remove-overlays)
16915 (move-marker org-columns-begin-marker (point))
16916 (let (beg end fmt cache maxwidths)
16917 (setq fmt (org-columns-get-format-and-top-level))
16918 (save-excursion
16919 (goto-char org-columns-top-level-marker)
16920 (setq beg (point))
16921 (unless org-columns-inhibit-recalculation
16922 (org-columns-compute-all))
16923 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16924 (point-max)))
16925 ;; Get and cache the properties
16926 (goto-char beg)
16927 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16928 (save-excursion
16929 (save-restriction
16930 (narrow-to-region beg end)
16931 (org-clock-sum))))
16932 (while (re-search-forward (concat "^" outline-regexp) end t)
16933 (push (cons (org-current-line) (org-entry-properties)) cache))
16934 (when cache
16935 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16936 (org-set-local 'org-columns-current-maxwidths maxwidths)
16937 (org-columns-display-here-title)
16938 (mapc (lambda (x)
16939 (goto-line (car x))
16940 (org-columns-display-here (cdr x)))
16941 cache)))))
16943 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16944 "Insert a new column, to the left of the current column."
16945 (interactive)
16946 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16947 cell)
16948 (setq prop (completing-read
16949 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16950 nil nil prop))
16951 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16952 (setq width (read-string "Column width: " (if width (number-to-string width))))
16953 (if (string-match "\\S-" width)
16954 (setq width (string-to-number width))
16955 (setq width nil))
16956 (setq fmt (completing-read "Summary [none]: "
16957 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16958 nil t))
16959 (if (string-match "\\S-" fmt)
16960 (setq fmt (intern fmt))
16961 (setq fmt nil))
16962 (if (eq fmt 'none) (setq fmt nil))
16963 (if editp
16964 (progn
16965 (setcar editp prop)
16966 (setcdr editp (list title width nil fmt)))
16967 (setq cell (nthcdr (1- (current-column))
16968 org-columns-current-fmt-compiled))
16969 (setcdr cell (cons (list prop title width nil fmt)
16970 (cdr cell))))
16971 (org-columns-store-format)
16972 (org-columns-redo)))
16974 (defun org-columns-delete ()
16975 "Delete the column at point from columns view."
16976 (interactive)
16977 (let* ((n (current-column))
16978 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16979 (when (y-or-n-p
16980 (format "Are you sure you want to remove column \"%s\"? " title))
16981 (setq org-columns-current-fmt-compiled
16982 (delq (nth n org-columns-current-fmt-compiled)
16983 org-columns-current-fmt-compiled))
16984 (org-columns-store-format)
16985 (org-columns-redo)
16986 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16987 (backward-char 1)))))
16989 (defun org-columns-edit-attributes ()
16990 "Edit the attributes of the current column."
16991 (interactive)
16992 (let* ((n (current-column))
16993 (info (nth n org-columns-current-fmt-compiled)))
16994 (apply 'org-columns-new info)))
16996 (defun org-columns-widen (arg)
16997 "Make the column wider by ARG characters."
16998 (interactive "p")
16999 (let* ((n (current-column))
17000 (entry (nth n org-columns-current-fmt-compiled))
17001 (width (or (nth 2 entry)
17002 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17003 (setq width (max 1 (+ width arg)))
17004 (setcar (nthcdr 2 entry) width)
17005 (org-columns-store-format)
17006 (org-columns-redo)))
17008 (defun org-columns-narrow (arg)
17009 "Make the column nrrower by ARG characters."
17010 (interactive "p")
17011 (org-columns-widen (- arg)))
17013 (defun org-columns-move-right ()
17014 "Swap this column with the one to the right."
17015 (interactive)
17016 (let* ((n (current-column))
17017 (cell (nthcdr n org-columns-current-fmt-compiled))
17019 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17020 (error "Cannot shift this column further to the right"))
17021 (setq e (car cell))
17022 (setcar cell (car (cdr cell)))
17023 (setcdr cell (cons e (cdr (cdr cell))))
17024 (org-columns-store-format)
17025 (org-columns-redo)
17026 (forward-char 1)))
17028 (defun org-columns-move-left ()
17029 "Swap this column with the one to the left."
17030 (interactive)
17031 (let* ((n (current-column)))
17032 (when (= n 0)
17033 (error "Cannot shift this column further to the left"))
17034 (backward-char 1)
17035 (org-columns-move-right)
17036 (backward-char 1)))
17038 (defun org-columns-store-format ()
17039 "Store the text version of the current columns format in appropriate place.
17040 This is either in the COLUMNS property of the node starting the current column
17041 display, or in the #+COLUMNS line of the current buffer."
17042 (let (fmt (cnt 0))
17043 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17044 (org-set-local 'org-columns-current-fmt fmt)
17045 (if (marker-position org-columns-top-level-marker)
17046 (save-excursion
17047 (goto-char org-columns-top-level-marker)
17048 (if (and (org-at-heading-p)
17049 (org-entry-get nil "COLUMNS"))
17050 (org-entry-put nil "COLUMNS" fmt)
17051 (goto-char (point-min))
17052 ;; Overwrite all #+COLUMNS lines....
17053 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17054 (setq cnt (1+ cnt))
17055 (replace-match (concat "#+COLUMNS: " fmt) t t))
17056 (unless (> cnt 0)
17057 (goto-char (point-min))
17058 (or (org-on-heading-p t) (outline-next-heading))
17059 (let ((inhibit-read-only t))
17060 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17061 (org-set-local 'org-columns-default-format fmt))))))
17063 (defvar org-overriding-columns-format nil
17064 "When set, overrides any other definition.")
17065 (defvar org-agenda-view-columns-initially nil
17066 "When set, switch to columns view immediately after creating the agenda.")
17068 (defun org-agenda-columns ()
17069 "Turn on column view in the agenda."
17070 (interactive)
17071 (org-verify-version 'columns)
17072 (org-columns-remove-overlays)
17073 (move-marker org-columns-begin-marker (point))
17074 (let (fmt cache maxwidths m)
17075 (cond
17076 ((and (local-variable-p 'org-overriding-columns-format)
17077 org-overriding-columns-format)
17078 (setq fmt org-overriding-columns-format))
17079 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17080 (setq fmt (org-entry-get m "COLUMNS" t)))
17081 ((and (boundp 'org-columns-current-fmt)
17082 (local-variable-p 'org-columns-current-fmt)
17083 org-columns-current-fmt)
17084 (setq fmt org-columns-current-fmt))
17085 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17086 (setq m (get-text-property m 'org-hd-marker))
17087 (setq fmt (org-entry-get m "COLUMNS" t))))
17088 (setq fmt (or fmt org-columns-default-format))
17089 (org-set-local 'org-columns-current-fmt fmt)
17090 (org-columns-compile-format fmt)
17091 (save-excursion
17092 ;; Get and cache the properties
17093 (goto-char (point-min))
17094 (while (not (eobp))
17095 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17096 (get-text-property (point) 'org-marker)))
17097 (push (cons (org-current-line) (org-entry-properties m)) cache))
17098 (beginning-of-line 2))
17099 (when cache
17100 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17101 (org-set-local 'org-columns-current-maxwidths maxwidths)
17102 (org-columns-display-here-title)
17103 (mapc (lambda (x)
17104 (goto-line (car x))
17105 (org-columns-display-here (cdr x)))
17106 cache)))))
17108 (defun org-columns-get-autowidth-alist (s cache)
17109 "Derive the maximum column widths from the format and the cache."
17110 (let ((start 0) rtn)
17111 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17112 (push (cons (match-string 1 s) 1) rtn)
17113 (setq start (match-end 0)))
17114 (mapc (lambda (x)
17115 (setcdr x (apply 'max
17116 (mapcar
17117 (lambda (y)
17118 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17119 cache))))
17120 rtn)
17121 rtn))
17123 (defun org-columns-compute-all ()
17124 "Compute all columns that have operators defined."
17125 (org-unmodified
17126 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17127 (let ((columns org-columns-current-fmt-compiled) col)
17128 (while (setq col (pop columns))
17129 (when (nth 3 col)
17130 (save-excursion
17131 (org-columns-compute (car col)))))))
17133 (defun org-columns-update (property)
17134 "Recompute PROPERTY, and update the columns display for it."
17135 (org-columns-compute property)
17136 (let (fmt val pos)
17137 (save-excursion
17138 (mapc (lambda (ov)
17139 (when (equal (org-overlay-get ov 'org-columns-key) property)
17140 (setq pos (org-overlay-start ov))
17141 (goto-char pos)
17142 (when (setq val (cdr (assoc property
17143 (get-text-property
17144 (point-at-bol) 'org-summaries))))
17145 (setq fmt (org-overlay-get ov 'org-columns-format))
17146 (org-overlay-put ov 'org-columns-value val)
17147 (org-overlay-put ov 'display (format fmt val)))))
17148 org-columns-overlays))))
17150 (defun org-columns-compute (property)
17151 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17152 (interactive)
17153 (let* ((re (concat "^" outline-regexp))
17154 (lmax 30) ; Does anyone use deeper levels???
17155 (lsum (make-vector lmax 0))
17156 (lflag (make-vector lmax nil))
17157 (level 0)
17158 (ass (assoc property org-columns-current-fmt-compiled))
17159 (format (nth 4 ass))
17160 (printf (nth 5 ass))
17161 (beg org-columns-top-level-marker)
17162 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17163 (save-excursion
17164 ;; Find the region to compute
17165 (goto-char beg)
17166 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17167 (goto-char end)
17168 ;; Walk the tree from the back and do the computations
17169 (while (re-search-backward re beg t)
17170 (setq sumpos (match-beginning 0)
17171 last-level level
17172 level (org-outline-level)
17173 val (org-entry-get nil property)
17174 valflag (and val (string-match "\\S-" val)))
17175 (cond
17176 ((< level last-level)
17177 ;; put the sum of lower levels here as a property
17178 (setq sum (aref lsum last-level) ; current sum
17179 flag (aref lflag last-level) ; any valid entries from children?
17180 str (org-column-number-to-string sum format printf)
17181 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17182 useval (if flag str1 (if valflag val ""))
17183 sum-alist (get-text-property sumpos 'org-summaries))
17184 (if (assoc property sum-alist)
17185 (setcdr (assoc property sum-alist) useval)
17186 (push (cons property useval) sum-alist)
17187 (org-unmodified
17188 (add-text-properties sumpos (1+ sumpos)
17189 (list 'org-summaries sum-alist))))
17190 (when val
17191 (org-entry-put nil property (if flag str val)))
17192 ;; add current to current level accumulator
17193 (when (or flag valflag)
17194 (aset lsum level (+ (aref lsum level)
17195 (if flag sum (org-column-string-to-number
17196 (if flag str val) format))))
17197 (aset lflag level t))
17198 ;; clear accumulators for deeper levels
17199 (loop for l from (1+ level) to (1- lmax) do
17200 (aset lsum l 0)
17201 (aset lflag l nil)))
17202 ((>= level last-level)
17203 ;; add what we have here to the accumulator for this level
17204 (aset lsum level (+ (aref lsum level)
17205 (org-column-string-to-number (or val "0") format)))
17206 (and valflag (aset lflag level t)))
17207 (t (error "This should not happen")))))))
17209 (defun org-columns-redo ()
17210 "Construct the column display again."
17211 (interactive)
17212 (message "Recomputing columns...")
17213 (save-excursion
17214 (if (marker-position org-columns-begin-marker)
17215 (goto-char org-columns-begin-marker))
17216 (org-columns-remove-overlays)
17217 (if (org-mode-p)
17218 (call-interactively 'org-columns)
17219 (call-interactively 'org-agenda-columns)))
17220 (message "Recomputing columns...done"))
17222 (defun org-columns-not-in-agenda ()
17223 (if (eq major-mode 'org-agenda-mode)
17224 (error "This command is only allowed in Org-mode buffers")))
17227 (defun org-string-to-number (s)
17228 "Convert string to number, and interpret hh:mm:ss."
17229 (if (not (string-match ":" s))
17230 (string-to-number s)
17231 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17232 (while l
17233 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17234 sum)))
17236 (defun org-column-number-to-string (n fmt &optional printf)
17237 "Convert a computed column number to a string value, according to FMT."
17238 (cond
17239 ((eq fmt 'add_times)
17240 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17241 (format "%d:%02d" h m)))
17242 ((eq fmt 'checkbox)
17243 (cond ((= n (floor n)) "[X]")
17244 ((> n 1.) "[-]")
17245 (t "[ ]")))
17246 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17247 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17248 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17249 (printf (format printf n))
17250 ((eq fmt 'currency)
17251 (format "%.2f" n))
17252 (t (number-to-string n))))
17254 (defun org-nofm-to-completion (n m &optional percent)
17255 (if (not percent)
17256 (format "[%d/%d]" n m)
17257 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17259 (defun org-column-string-to-number (s fmt)
17260 "Convert a column value to a number that can be used for column computing."
17261 (cond
17262 ((string-match ":" s)
17263 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17264 (while l
17265 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17266 sum))
17267 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17268 (if (equal s "[X]") 1. 0.000001))
17269 (t (string-to-number s))))
17271 (defun org-columns-uncompile-format (cfmt)
17272 "Turn the compiled columns format back into a string representation."
17273 (let ((rtn "") e s prop title op width fmt printf)
17274 (while (setq e (pop cfmt))
17275 (setq prop (car e)
17276 title (nth 1 e)
17277 width (nth 2 e)
17278 op (nth 3 e)
17279 fmt (nth 4 e)
17280 printf (nth 5 e))
17281 (cond
17282 ((eq fmt 'add_times) (setq op ":"))
17283 ((eq fmt 'checkbox) (setq op "X"))
17284 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17285 ((eq fmt 'checkbox-percent) (setq op "X%"))
17286 ((eq fmt 'add_numbers) (setq op "+"))
17287 ((eq fmt 'currency) (setq op "$")))
17288 (if (and op printf) (setq op (concat op ";" printf)))
17289 (if (equal title prop) (setq title nil))
17290 (setq s (concat "%" (if width (number-to-string width))
17291 prop
17292 (if title (concat "(" title ")"))
17293 (if op (concat "{" op "}"))))
17294 (setq rtn (concat rtn " " s)))
17295 (org-trim rtn)))
17297 (defun org-columns-compile-format (fmt)
17298 "Turn a column format string into an alist of specifications.
17299 The alist has one entry for each column in the format. The elements of
17300 that list are:
17301 property the property
17302 title the title field for the columns
17303 width the column width in characters, can be nil for automatic
17304 operator the operator if any
17305 format the output format for computed results, derived from operator
17306 printf a printf format for computed values"
17307 (let ((start 0) width prop title op f printf)
17308 (setq org-columns-current-fmt-compiled nil)
17309 (while (string-match
17310 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17311 fmt start)
17312 (setq start (match-end 0)
17313 width (match-string 1 fmt)
17314 prop (match-string 2 fmt)
17315 title (or (match-string 3 fmt) prop)
17316 op (match-string 4 fmt)
17317 f nil
17318 printf nil)
17319 (if width (setq width (string-to-number width)))
17320 (when (and op (string-match ";" op))
17321 (setq printf (substring op (match-end 0))
17322 op (substring op 0 (match-beginning 0))))
17323 (cond
17324 ((equal op "+") (setq f 'add_numbers))
17325 ((equal op "$") (setq f 'currency))
17326 ((equal op ":") (setq f 'add_times))
17327 ((equal op "X") (setq f 'checkbox))
17328 ((equal op "X/") (setq f 'checkbox-n-of-m))
17329 ((equal op "X%") (setq f 'checkbox-percent))
17331 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17332 (setq org-columns-current-fmt-compiled
17333 (nreverse org-columns-current-fmt-compiled))))
17336 ;;; Dynamic block for Column view
17338 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17339 "Get the column view of the current buffer or subtree.
17340 The first optional argument MAXLEVEL sets the level limit. A
17341 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17342 empty rows, an empty row being one where all the column view
17343 specifiers except ITEM are empty. This function returns a list
17344 containing the title row and all other rows. Each row is a list
17345 of fields."
17346 (save-excursion
17347 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17348 (n (length title)) row tbl)
17349 (goto-char (point-min))
17350 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17351 (or (null maxlevel)
17352 (>= maxlevel
17353 (if org-odd-levels-only
17354 (/ (1+ (length (match-string 1))) 2)
17355 (length (match-string 1))))))
17356 (when (get-char-property (match-beginning 0) 'org-columns-key)
17357 (setq row nil)
17358 (loop for i from 0 to (1- n) do
17359 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17360 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17362 row))
17363 (setq row (nreverse row))
17364 (unless (and skip-empty-rows
17365 (eq 1 (length (delete "" (delete-dups row)))))
17366 (push row tbl))))
17367 (append (list title 'hline) (nreverse tbl)))))
17369 (defun org-dblock-write:columnview (params)
17370 "Write the column view table.
17371 PARAMS is a property list of parameters:
17373 :width enforce same column widths with <N> specifiers.
17374 :id the :ID: property of the entry where the columns view
17375 should be built, as a string. When `local', call locally.
17376 When `global' call column view with the cursor at the beginning
17377 of the buffer (usually this means that the whole buffer switches
17378 to column view).
17379 :hlines When t, insert a hline before each item. When a number, insert
17380 a hline before each level <= that number.
17381 :vlines When t, make each column a colgroup to enforce vertical lines.
17382 :maxlevel When set to a number, don't capture headlines below this level.
17383 :skip-empty-rows
17384 When t, skip rows where all specifiers other than ITEM are empty."
17385 (let ((pos (move-marker (make-marker) (point)))
17386 (hlines (plist-get params :hlines))
17387 (vlines (plist-get params :vlines))
17388 (maxlevel (plist-get params :maxlevel))
17389 (skip-empty-rows (plist-get params :skip-empty-rows))
17390 tbl id idpos nfields tmp)
17391 (save-excursion
17392 (save-restriction
17393 (when (setq id (plist-get params :id))
17394 (cond ((not id) nil)
17395 ((eq id 'global) (goto-char (point-min)))
17396 ((eq id 'local) nil)
17397 ((setq idpos (org-find-entry-with-id id))
17398 (goto-char idpos))
17399 (t (error "Cannot find entry with :ID: %s" id))))
17400 (org-columns)
17401 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17402 (setq nfields (length (car tbl)))
17403 (org-columns-quit)))
17404 (goto-char pos)
17405 (move-marker pos nil)
17406 (when tbl
17407 (when (plist-get params :hlines)
17408 (setq tmp nil)
17409 (while tbl
17410 (if (eq (car tbl) 'hline)
17411 (push (pop tbl) tmp)
17412 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17413 (if (and (not (eq (car tmp) 'hline))
17414 (or (eq hlines t)
17415 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17416 (push 'hline tmp)))
17417 (push (pop tbl) tmp)))
17418 (setq tbl (nreverse tmp)))
17419 (when vlines
17420 (setq tbl (mapcar (lambda (x)
17421 (if (eq 'hline x) x (cons "" x)))
17422 tbl))
17423 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17424 (setq pos (point))
17425 (insert (org-listtable-to-string tbl))
17426 (when (plist-get params :width)
17427 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17428 org-columns-current-widths "|")))
17429 (goto-char pos)
17430 (org-table-align))))
17432 (defun org-listtable-to-string (tbl)
17433 "Convert a listtable TBL to a string that contains the Org-mode table.
17434 The table still need to be alligned. The resulting string has no leading
17435 and tailing newline characters."
17436 (mapconcat
17437 (lambda (x)
17438 (cond
17439 ((listp x)
17440 (concat "|" (mapconcat 'identity x "|") "|"))
17441 ((eq x 'hline) "|-|")
17442 (t (error "Garbage in listtable: %s" x))))
17443 tbl "\n"))
17445 (defun org-insert-columns-dblock ()
17446 "Create a dynamic block capturing a column view table."
17447 (interactive)
17448 (let ((defaults '(:name "columnview" :hlines 1))
17449 (id (completing-read
17450 "Capture columns (local, global, entry with :ID: property) [local]: "
17451 (append '(("global") ("local"))
17452 (mapcar 'list (org-property-values "ID"))))))
17453 (if (equal id "") (setq id 'local))
17454 (if (equal id "global") (setq id 'global))
17455 (setq defaults (append defaults (list :id id)))
17456 (org-create-dblock defaults)
17457 (org-update-dblock)))
17459 ;;;; Timestamps
17461 (defvar org-last-changed-timestamp nil)
17462 (defvar org-time-was-given) ; dynamically scoped parameter
17463 (defvar org-end-time-was-given) ; dynamically scoped parameter
17464 (defvar org-ts-what) ; dynamically scoped parameter
17466 (defun org-time-stamp (arg)
17467 "Prompt for a date/time and insert a time stamp.
17468 If the user specifies a time like HH:MM, or if this command is called
17469 with a prefix argument, the time stamp will contain date and time.
17470 Otherwise, only the date will be included. All parts of a date not
17471 specified by the user will be filled in from the current date/time.
17472 So if you press just return without typing anything, the time stamp
17473 will represent the current date/time. If there is already a timestamp
17474 at the cursor, it will be modified."
17475 (interactive "P")
17476 (let* ((ts nil)
17477 (default-time
17478 ;; Default time is either today, or, when entering a range,
17479 ;; the range start.
17480 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17481 (save-excursion
17482 (re-search-backward
17483 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17484 (- (point) 20) t)))
17485 (apply 'encode-time (org-parse-time-string (match-string 1)))
17486 (current-time)))
17487 (default-input (and ts (org-get-compact-tod ts)))
17488 org-time-was-given org-end-time-was-given time)
17489 (cond
17490 ((and (org-at-timestamp-p)
17491 (eq last-command 'org-time-stamp)
17492 (eq this-command 'org-time-stamp))
17493 (insert "--")
17494 (setq time (let ((this-command this-command))
17495 (org-read-date arg 'totime nil nil default-time default-input)))
17496 (org-insert-time-stamp time (or org-time-was-given arg)))
17497 ((org-at-timestamp-p)
17498 (setq time (let ((this-command this-command))
17499 (org-read-date arg 'totime nil nil default-time default-input)))
17500 (when (org-at-timestamp-p) ; just to get the match data
17501 (replace-match "")
17502 (setq org-last-changed-timestamp
17503 (org-insert-time-stamp
17504 time (or org-time-was-given arg)
17505 nil nil nil (list org-end-time-was-given))))
17506 (message "Timestamp updated"))
17508 (setq time (let ((this-command this-command))
17509 (org-read-date arg 'totime nil nil default-time default-input)))
17510 (org-insert-time-stamp time (or org-time-was-given arg)
17511 nil nil nil (list org-end-time-was-given))))))
17513 ;; FIXME: can we use this for something else????
17514 ;; like computing time differences?????
17515 (defun org-get-compact-tod (s)
17516 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17517 (let* ((t1 (match-string 1 s))
17518 (h1 (string-to-number (match-string 2 s)))
17519 (m1 (string-to-number (match-string 3 s)))
17520 (t2 (and (match-end 4) (match-string 5 s)))
17521 (h2 (and t2 (string-to-number (match-string 6 s))))
17522 (m2 (and t2 (string-to-number (match-string 7 s))))
17523 dh dm)
17524 (if (not t2)
17526 (setq dh (- h2 h1) dm (- m2 m1))
17527 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17528 (concat t1 "+" (number-to-string dh)
17529 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17531 (defun org-time-stamp-inactive (&optional arg)
17532 "Insert an inactive time stamp.
17533 An inactive time stamp is enclosed in square brackets instead of angle
17534 brackets. It is inactive in the sense that it does not trigger agenda entries,
17535 does not link to the calendar and cannot be changed with the S-cursor keys.
17536 So these are more for recording a certain time/date."
17537 (interactive "P")
17538 (let (org-time-was-given org-end-time-was-given time)
17539 (setq time (org-read-date arg 'totime))
17540 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17541 nil nil (list org-end-time-was-given))))
17543 (defvar org-date-ovl (org-make-overlay 1 1))
17544 (org-overlay-put org-date-ovl 'face 'org-warning)
17545 (org-detach-overlay org-date-ovl)
17547 (defvar org-ans1) ; dynamically scoped parameter
17548 (defvar org-ans2) ; dynamically scoped parameter
17550 (defvar org-plain-time-of-day-regexp) ; defined below
17552 (defvar org-read-date-overlay nil)
17553 (defvar org-dcst nil) ; dynamically scoped
17555 (defun org-read-date (&optional with-time to-time from-string prompt
17556 default-time default-input)
17557 "Read a date, possibly a time, and make things smooth for the user.
17558 The prompt will suggest to enter an ISO date, but you can also enter anything
17559 which will at least partially be understood by `parse-time-string'.
17560 Unrecognized parts of the date will default to the current day, month, year,
17561 hour and minute. If this command is called to replace a timestamp at point,
17562 of to enter the second timestamp of a range, the default time is taken from the
17563 existing stamp. For example,
17564 3-2-5 --> 2003-02-05
17565 feb 15 --> currentyear-02-15
17566 sep 12 9 --> 2009-09-12
17567 12:45 --> today 12:45
17568 22 sept 0:34 --> currentyear-09-22 0:34
17569 12 --> currentyear-currentmonth-12
17570 Fri --> nearest Friday (today or later)
17571 etc.
17573 Furthermore you can specify a relative date by giving, as the *first* thing
17574 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17575 change in days weeks, months, years.
17576 With a single plus or minus, the date is relative to today. With a double
17577 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17578 +4d --> four days from today
17579 +4 --> same as above
17580 +2w --> two weeks from today
17581 ++5 --> five days from default date
17583 The function understands only English month and weekday abbreviations,
17584 but this can be configured with the variables `parse-time-months' and
17585 `parse-time-weekdays'.
17587 While prompting, a calendar is popped up - you can also select the
17588 date with the mouse (button 1). The calendar shows a period of three
17589 months. To scroll it to other months, use the keys `>' and `<'.
17590 If you don't like the calendar, turn it off with
17591 \(setq org-read-date-popup-calendar nil)
17593 With optional argument TO-TIME, the date will immediately be converted
17594 to an internal time.
17595 With an optional argument WITH-TIME, the prompt will suggest to also
17596 insert a time. Note that when WITH-TIME is not set, you can still
17597 enter a time, and this function will inform the calling routine about
17598 this change. The calling routine may then choose to change the format
17599 used to insert the time stamp into the buffer to include the time.
17600 With optional argument FROM-STRING, read from this string instead from
17601 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17602 the time/date that is used for everything that is not specified by the
17603 user."
17604 (require 'parse-time)
17605 (let* ((org-time-stamp-rounding-minutes
17606 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17607 (org-dcst org-display-custom-times)
17608 (ct (org-current-time))
17609 (def (or default-time ct))
17610 (defdecode (decode-time def))
17611 (dummy (progn
17612 (when (< (nth 2 defdecode) org-extend-today-until)
17613 (setcar (nthcdr 2 defdecode) -1)
17614 (setcar (nthcdr 1 defdecode) 59)
17615 (setq def (apply 'encode-time defdecode)
17616 defdecode (decode-time def)))))
17617 (calendar-move-hook nil)
17618 (view-diary-entries-initially nil)
17619 (view-calendar-holidays-initially nil)
17620 (timestr (format-time-string
17621 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17622 (prompt (concat (if prompt (concat prompt " ") "")
17623 (format "Date+time [%s]: " timestr)))
17624 ans (org-ans0 "") org-ans1 org-ans2 final)
17626 (cond
17627 (from-string (setq ans from-string))
17628 (org-read-date-popup-calendar
17629 (save-excursion
17630 (save-window-excursion
17631 (calendar)
17632 (calendar-forward-day (- (time-to-days def)
17633 (calendar-absolute-from-gregorian
17634 (calendar-current-date))))
17635 (org-eval-in-calendar nil t)
17636 (let* ((old-map (current-local-map))
17637 (map (copy-keymap calendar-mode-map))
17638 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17639 (org-defkey map (kbd "RET") 'org-calendar-select)
17640 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17641 'org-calendar-select-mouse)
17642 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17643 'org-calendar-select-mouse)
17644 (org-defkey minibuffer-local-map [(meta shift left)]
17645 (lambda () (interactive)
17646 (org-eval-in-calendar '(calendar-backward-month 1))))
17647 (org-defkey minibuffer-local-map [(meta shift right)]
17648 (lambda () (interactive)
17649 (org-eval-in-calendar '(calendar-forward-month 1))))
17650 (org-defkey minibuffer-local-map [(meta shift up)]
17651 (lambda () (interactive)
17652 (org-eval-in-calendar '(calendar-backward-year 1))))
17653 (org-defkey minibuffer-local-map [(meta shift down)]
17654 (lambda () (interactive)
17655 (org-eval-in-calendar '(calendar-forward-year 1))))
17656 (org-defkey minibuffer-local-map [(shift up)]
17657 (lambda () (interactive)
17658 (org-eval-in-calendar '(calendar-backward-week 1))))
17659 (org-defkey minibuffer-local-map [(shift down)]
17660 (lambda () (interactive)
17661 (org-eval-in-calendar '(calendar-forward-week 1))))
17662 (org-defkey minibuffer-local-map [(shift left)]
17663 (lambda () (interactive)
17664 (org-eval-in-calendar '(calendar-backward-day 1))))
17665 (org-defkey minibuffer-local-map [(shift right)]
17666 (lambda () (interactive)
17667 (org-eval-in-calendar '(calendar-forward-day 1))))
17668 (org-defkey minibuffer-local-map ">"
17669 (lambda () (interactive)
17670 (org-eval-in-calendar '(scroll-calendar-left 1))))
17671 (org-defkey minibuffer-local-map "<"
17672 (lambda () (interactive)
17673 (org-eval-in-calendar '(scroll-calendar-right 1))))
17674 (unwind-protect
17675 (progn
17676 (use-local-map map)
17677 (add-hook 'post-command-hook 'org-read-date-display)
17678 (setq org-ans0 (read-string prompt default-input nil nil))
17679 ;; org-ans0: from prompt
17680 ;; org-ans1: from mouse click
17681 ;; org-ans2: from calendar motion
17682 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17683 (remove-hook 'post-command-hook 'org-read-date-display)
17684 (use-local-map old-map)
17685 (when org-read-date-overlay
17686 (org-delete-overlay org-read-date-overlay)
17687 (setq org-read-date-overlay nil)))))))
17689 (t ; Naked prompt only
17690 (unwind-protect
17691 (setq ans (read-string prompt default-input nil timestr))
17692 (when org-read-date-overlay
17693 (org-delete-overlay org-read-date-overlay)
17694 (setq org-read-date-overlay nil)))))
17696 (setq final (org-read-date-analyze ans def defdecode))
17698 (if to-time
17699 (apply 'encode-time final)
17700 (if (and (boundp 'org-time-was-given) org-time-was-given)
17701 (format "%04d-%02d-%02d %02d:%02d"
17702 (nth 5 final) (nth 4 final) (nth 3 final)
17703 (nth 2 final) (nth 1 final))
17704 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17705 (defvar def)
17706 (defvar defdecode)
17707 (defvar with-time)
17708 (defun org-read-date-display ()
17709 "Display the currrent date prompt interpretation in the minibuffer."
17710 (when org-read-date-display-live
17711 (when org-read-date-overlay
17712 (org-delete-overlay org-read-date-overlay))
17713 (let ((p (point)))
17714 (end-of-line 1)
17715 (while (not (equal (buffer-substring
17716 (max (point-min) (- (point) 4)) (point))
17717 " "))
17718 (insert " "))
17719 (goto-char p))
17720 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17721 " " (or org-ans1 org-ans2)))
17722 (org-end-time-was-given nil)
17723 (f (org-read-date-analyze ans def defdecode))
17724 (fmts (if org-dcst
17725 org-time-stamp-custom-formats
17726 org-time-stamp-formats))
17727 (fmt (if (or with-time
17728 (and (boundp 'org-time-was-given) org-time-was-given))
17729 (cdr fmts)
17730 (car fmts)))
17731 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17732 (when (and org-end-time-was-given
17733 (string-match org-plain-time-of-day-regexp txt))
17734 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17735 org-end-time-was-given
17736 (substring txt (match-end 0)))))
17737 (setq org-read-date-overlay
17738 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17739 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17741 (defun org-read-date-analyze (ans def defdecode)
17742 "Analyze the combined answer of the date prompt."
17743 ;; FIXME: cleanup and comment
17744 (let (delta deltan deltaw deltadef year month day
17745 hour minute second wday pm h2 m2 tl wday1
17746 iso-year iso-weekday iso-week iso-year iso-date)
17748 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17749 (setq ans (replace-match "" t t ans)
17750 deltan (car delta)
17751 deltaw (nth 1 delta)
17752 deltadef (nth 2 delta)))
17754 ;; Check if there is an iso week date in there
17755 ;; If yes, sore the info and ostpone interpreting it until the rest
17756 ;; of the parsing is done
17757 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17758 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
17759 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
17760 iso-week (string-to-number (match-string 2 ans)))
17761 (setq ans (replace-match "" t t ans)))
17763 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17764 (when (string-match
17765 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17766 (setq year (if (match-end 2)
17767 (string-to-number (match-string 2 ans))
17768 (string-to-number (format-time-string "%Y")))
17769 month (string-to-number (match-string 3 ans))
17770 day (string-to-number (match-string 4 ans)))
17771 (if (< year 100) (setq year (+ 2000 year)))
17772 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17773 t nil ans)))
17774 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17775 ;; If there is a time with am/pm, and *no* time without it, we convert
17776 ;; so that matching will be successful.
17777 (loop for i from 1 to 2 do ; twice, for end time as well
17778 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17779 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17780 (setq hour (string-to-number (match-string 1 ans))
17781 minute (if (match-end 3)
17782 (string-to-number (match-string 3 ans))
17784 pm (equal ?p
17785 (string-to-char (downcase (match-string 4 ans)))))
17786 (if (and (= hour 12) (not pm))
17787 (setq hour 0)
17788 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17789 (setq ans (replace-match (format "%02d:%02d" hour minute)
17790 t t ans))))
17792 ;; Check if a time range is given as a duration
17793 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17794 (setq hour (string-to-number (match-string 1 ans))
17795 h2 (+ hour (string-to-number (match-string 3 ans)))
17796 minute (string-to-number (match-string 2 ans))
17797 m2 (+ minute (if (match-end 5) (string-to-number
17798 (match-string 5 ans))0)))
17799 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17800 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17801 t t ans)))
17803 ;; Check if there is a time range
17804 (when (boundp 'org-end-time-was-given)
17805 (setq org-time-was-given nil)
17806 (when (and (string-match org-plain-time-of-day-regexp ans)
17807 (match-end 8))
17808 (setq org-end-time-was-given (match-string 8 ans))
17809 (setq ans (concat (substring ans 0 (match-beginning 7))
17810 (substring ans (match-end 7))))))
17812 (setq tl (parse-time-string ans)
17813 day (or (nth 3 tl) (nth 3 defdecode))
17814 month (or (nth 4 tl)
17815 (if (and org-read-date-prefer-future
17816 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17817 (1+ (nth 4 defdecode))
17818 (nth 4 defdecode)))
17819 year (or (nth 5 tl)
17820 (if (and org-read-date-prefer-future
17821 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17822 (1+ (nth 5 defdecode))
17823 (nth 5 defdecode)))
17824 hour (or (nth 2 tl) (nth 2 defdecode))
17825 minute (or (nth 1 tl) (nth 1 defdecode))
17826 second (or (nth 0 tl) 0)
17827 wday (nth 6 tl))
17829 ;; Special date definitions below
17830 (cond
17831 (iso-week
17832 ;; There was an iso week
17833 (setq year (or iso-year year)
17834 day (or iso-weekday wday 1)
17835 wday nil ; to make sure that the trigger below does not match
17836 iso-date (calendar-gregorian-from-absolute
17837 (calendar-absolute-from-iso
17838 (list iso-week day year))))
17839 ; FIXME: Should we also push ISO weeks into the future?
17840 ; (when (and org-read-date-prefer-future
17841 ; (not iso-year)
17842 ; (< (calendar-absolute-from-gregorian iso-date)
17843 ; (time-to-days (current-time))))
17844 ; (setq year (1+ year)
17845 ; iso-date (calendar-gregorian-from-absolute
17846 ; (calendar-absolute-from-iso
17847 ; (list iso-week day year)))))
17848 (setq month (car iso-date)
17849 year (nth 2 iso-date)
17850 day (nth 1 iso-date)))
17851 (deltan
17852 (unless deltadef
17853 (let ((now (decode-time (current-time))))
17854 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17855 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17856 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17857 ((equal deltaw "m") (setq month (+ month deltan)))
17858 ((equal deltaw "y") (setq year (+ year deltan)))))
17859 ((and wday (not (nth 3 tl)))
17860 ;; Weekday was given, but no day, so pick that day in the week
17861 ;; on or after the derived date.
17862 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17863 (unless (equal wday wday1)
17864 (setq day (+ day (% (- wday wday1 -7) 7))))))
17865 (if (and (boundp 'org-time-was-given)
17866 (nth 2 tl))
17867 (setq org-time-was-given t))
17868 (if (< year 100) (setq year (+ 2000 year)))
17869 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17870 (list second minute hour day month year)))
17872 (defvar parse-time-weekdays)
17874 (defun org-read-date-get-relative (s today default)
17875 "Check string S for special relative date string.
17876 TODAY and DEFAULT are internal times, for today and for a default.
17877 Return shift list (N what def-flag)
17878 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17879 N is the number of WHATs to shift.
17880 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17881 the DEFAULT date rather than TODAY."
17882 (when (string-match
17883 (concat
17884 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17885 "\\([0-9]+\\)?"
17886 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17887 "\\([ \t]\\|$\\)") s)
17888 (let* ((dir (if (match-end 1)
17889 (string-to-char (substring (match-string 1 s) -1))
17890 ?+))
17891 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17892 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17893 (what (if (match-end 3) (match-string 3 s) "d"))
17894 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17895 (date (if rel default today))
17896 (wday (nth 6 (decode-time date)))
17897 delta)
17898 (if wday1
17899 (progn
17900 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17901 (if (= dir ?-) (setq delta (- delta 7)))
17902 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17903 (list delta "d" rel))
17904 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17906 (defun org-eval-in-calendar (form &optional keepdate)
17907 "Eval FORM in the calendar window and return to current window.
17908 Also, store the cursor date in variable org-ans2."
17909 (let ((sw (selected-window)))
17910 (select-window (get-buffer-window "*Calendar*"))
17911 (eval form)
17912 (when (and (not keepdate) (calendar-cursor-to-date))
17913 (let* ((date (calendar-cursor-to-date))
17914 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17915 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17916 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17917 (select-window sw)))
17919 ; ;; Update the prompt to show new default date
17920 ; (save-excursion
17921 ; (goto-char (point-min))
17922 ; (when (and org-ans2
17923 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17924 ; (get-text-property (match-end 0) 'field))
17925 ; (let ((inhibit-read-only t))
17926 ; (replace-match (concat "[" org-ans2 "]") t t)
17927 ; (add-text-properties (point-min) (1+ (match-end 0))
17928 ; (text-properties-at (1+ (point-min)))))))))
17930 (defun org-calendar-select ()
17931 "Return to `org-read-date' with the date currently selected.
17932 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17933 (interactive)
17934 (when (calendar-cursor-to-date)
17935 (let* ((date (calendar-cursor-to-date))
17936 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17937 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17938 (if (active-minibuffer-window) (exit-minibuffer))))
17940 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17941 "Insert a date stamp for the date given by the internal TIME.
17942 WITH-HM means, use the stamp format that includes the time of the day.
17943 INACTIVE means use square brackets instead of angular ones, so that the
17944 stamp will not contribute to the agenda.
17945 PRE and POST are optional strings to be inserted before and after the
17946 stamp.
17947 The command returns the inserted time stamp."
17948 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17949 stamp)
17950 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17951 (insert-before-markers (or pre ""))
17952 (insert-before-markers (setq stamp (format-time-string fmt time)))
17953 (when (listp extra)
17954 (setq extra (car extra))
17955 (if (and (stringp extra)
17956 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17957 (setq extra (format "-%02d:%02d"
17958 (string-to-number (match-string 1 extra))
17959 (string-to-number (match-string 2 extra))))
17960 (setq extra nil)))
17961 (when extra
17962 (backward-char 1)
17963 (insert-before-markers extra)
17964 (forward-char 1))
17965 (insert-before-markers (or post ""))
17966 stamp))
17968 (defun org-toggle-time-stamp-overlays ()
17969 "Toggle the use of custom time stamp formats."
17970 (interactive)
17971 (setq org-display-custom-times (not org-display-custom-times))
17972 (unless org-display-custom-times
17973 (let ((p (point-min)) (bmp (buffer-modified-p)))
17974 (while (setq p (next-single-property-change p 'display))
17975 (if (and (get-text-property p 'display)
17976 (eq (get-text-property p 'face) 'org-date))
17977 (remove-text-properties
17978 p (setq p (next-single-property-change p 'display))
17979 '(display t))))
17980 (set-buffer-modified-p bmp)))
17981 (if (featurep 'xemacs)
17982 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17983 (org-restart-font-lock)
17984 (setq org-table-may-need-update t)
17985 (if org-display-custom-times
17986 (message "Time stamps are overlayed with custom format")
17987 (message "Time stamp overlays removed")))
17989 (defun org-display-custom-time (beg end)
17990 "Overlay modified time stamp format over timestamp between BED and END."
17991 (let* ((ts (buffer-substring beg end))
17992 t1 w1 with-hm tf time str w2 (off 0))
17993 (save-match-data
17994 (setq t1 (org-parse-time-string ts t))
17995 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
17996 (setq off (- (match-end 0) (match-beginning 0)))))
17997 (setq end (- end off))
17998 (setq w1 (- end beg)
17999 with-hm (and (nth 1 t1) (nth 2 t1))
18000 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18001 time (org-fix-decoded-time t1)
18002 str (org-add-props
18003 (format-time-string
18004 (substring tf 1 -1) (apply 'encode-time time))
18005 nil 'mouse-face 'highlight)
18006 w2 (length str))
18007 (if (not (= w2 w1))
18008 (add-text-properties (1+ beg) (+ 2 beg)
18009 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18010 (if (featurep 'xemacs)
18011 (progn
18012 (put-text-property beg end 'invisible t)
18013 (put-text-property beg end 'end-glyph (make-glyph str)))
18014 (put-text-property beg end 'display str))))
18016 (defun org-translate-time (string)
18017 "Translate all timestamps in STRING to custom format.
18018 But do this only if the variable `org-display-custom-times' is set."
18019 (when org-display-custom-times
18020 (save-match-data
18021 (let* ((start 0)
18022 (re org-ts-regexp-both)
18023 t1 with-hm inactive tf time str beg end)
18024 (while (setq start (string-match re string start))
18025 (setq beg (match-beginning 0)
18026 end (match-end 0)
18027 t1 (save-match-data
18028 (org-parse-time-string (substring string beg end) t))
18029 with-hm (and (nth 1 t1) (nth 2 t1))
18030 inactive (equal (substring string beg (1+ beg)) "[")
18031 tf (funcall (if with-hm 'cdr 'car)
18032 org-time-stamp-custom-formats)
18033 time (org-fix-decoded-time t1)
18034 str (format-time-string
18035 (concat
18036 (if inactive "[" "<") (substring tf 1 -1)
18037 (if inactive "]" ">"))
18038 (apply 'encode-time time))
18039 string (replace-match str t t string)
18040 start (+ start (length str)))))))
18041 string)
18043 (defun org-fix-decoded-time (time)
18044 "Set 0 instead of nil for the first 6 elements of time.
18045 Don't touch the rest."
18046 (let ((n 0))
18047 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18049 (defun org-days-to-time (timestamp-string)
18050 "Difference between TIMESTAMP-STRING and now in days."
18051 (- (time-to-days (org-time-string-to-time timestamp-string))
18052 (time-to-days (current-time))))
18054 (defun org-deadline-close (timestamp-string &optional ndays)
18055 "Is the time in TIMESTAMP-STRING close to the current date?"
18056 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18057 (and (< (org-days-to-time timestamp-string) ndays)
18058 (not (org-entry-is-done-p))))
18060 (defun org-get-wdays (ts)
18061 "Get the deadline lead time appropriate for timestring TS."
18062 (cond
18063 ((<= org-deadline-warning-days 0)
18064 ;; 0 or negative, enforce this value no matter what
18065 (- org-deadline-warning-days))
18066 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18067 ;; lead time is specified.
18068 (floor (* (string-to-number (match-string 1 ts))
18069 (cdr (assoc (match-string 2 ts)
18070 '(("d" . 1) ("w" . 7)
18071 ("m" . 30.4) ("y" . 365.25)))))))
18072 ;; go for the default.
18073 (t org-deadline-warning-days)))
18075 (defun org-calendar-select-mouse (ev)
18076 "Return to `org-read-date' with the date currently selected.
18077 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18078 (interactive "e")
18079 (mouse-set-point ev)
18080 (when (calendar-cursor-to-date)
18081 (let* ((date (calendar-cursor-to-date))
18082 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18083 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18084 (if (active-minibuffer-window) (exit-minibuffer))))
18086 (defun org-check-deadlines (ndays)
18087 "Check if there are any deadlines due or past due.
18088 A deadline is considered due if it happens within `org-deadline-warning-days'
18089 days from today's date. If the deadline appears in an entry marked DONE,
18090 it is not shown. The prefix arg NDAYS can be used to test that many
18091 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18092 (interactive "P")
18093 (let* ((org-warn-days
18094 (cond
18095 ((equal ndays '(4)) 100000)
18096 (ndays (prefix-numeric-value ndays))
18097 (t (abs org-deadline-warning-days))))
18098 (case-fold-search nil)
18099 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18100 (callback
18101 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18103 (message "%d deadlines past-due or due within %d days"
18104 (org-occur regexp nil callback)
18105 org-warn-days)))
18107 (defun org-check-before-date (date)
18108 "Check if there are deadlines or scheduled entries before DATE."
18109 (interactive (list (org-read-date)))
18110 (let ((case-fold-search nil)
18111 (regexp (concat "\\<\\(" org-deadline-string
18112 "\\|" org-scheduled-string
18113 "\\) *<\\([^>]+\\)>"))
18114 (callback
18115 (lambda () (time-less-p
18116 (org-time-string-to-time (match-string 2))
18117 (org-time-string-to-time date)))))
18118 (message "%d entries before %s"
18119 (org-occur regexp nil callback) date)))
18121 (defun org-evaluate-time-range (&optional to-buffer)
18122 "Evaluate a time range by computing the difference between start and end.
18123 Normally the result is just printed in the echo area, but with prefix arg
18124 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18125 If the time range is actually in a table, the result is inserted into the
18126 next column.
18127 For time difference computation, a year is assumed to be exactly 365
18128 days in order to avoid rounding problems."
18129 (interactive "P")
18131 (org-clock-update-time-maybe)
18132 (save-excursion
18133 (unless (org-at-date-range-p t)
18134 (goto-char (point-at-bol))
18135 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18136 (if (not (org-at-date-range-p t))
18137 (error "Not at a time-stamp range, and none found in current line")))
18138 (let* ((ts1 (match-string 1))
18139 (ts2 (match-string 2))
18140 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18141 (match-end (match-end 0))
18142 (time1 (org-time-string-to-time ts1))
18143 (time2 (org-time-string-to-time ts2))
18144 (t1 (time-to-seconds time1))
18145 (t2 (time-to-seconds time2))
18146 (diff (abs (- t2 t1)))
18147 (negative (< (- t2 t1) 0))
18148 ;; (ys (floor (* 365 24 60 60)))
18149 (ds (* 24 60 60))
18150 (hs (* 60 60))
18151 (fy "%dy %dd %02d:%02d")
18152 (fy1 "%dy %dd")
18153 (fd "%dd %02d:%02d")
18154 (fd1 "%dd")
18155 (fh "%02d:%02d")
18156 y d h m align)
18157 (if havetime
18158 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18160 d (floor (/ diff ds)) diff (mod diff ds)
18161 h (floor (/ diff hs)) diff (mod diff hs)
18162 m (floor (/ diff 60)))
18163 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18165 d (floor (+ (/ diff ds) 0.5))
18166 h 0 m 0))
18167 (if (not to-buffer)
18168 (message "%s" (org-make-tdiff-string y d h m))
18169 (if (org-at-table-p)
18170 (progn
18171 (goto-char match-end)
18172 (setq align t)
18173 (and (looking-at " *|") (goto-char (match-end 0))))
18174 (goto-char match-end))
18175 (if (looking-at
18176 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18177 (replace-match ""))
18178 (if negative (insert " -"))
18179 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18180 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18181 (insert " " (format fh h m))))
18182 (if align (org-table-align))
18183 (message "Time difference inserted")))))
18185 (defun org-make-tdiff-string (y d h m)
18186 (let ((fmt "")
18187 (l nil))
18188 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18189 l (push y l)))
18190 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18191 l (push d l)))
18192 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18193 l (push h l)))
18194 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18195 l (push m l)))
18196 (apply 'format fmt (nreverse l))))
18198 (defun org-time-string-to-time (s)
18199 (apply 'encode-time (org-parse-time-string s)))
18201 (defun org-time-string-to-absolute (s &optional daynr prefer)
18202 "Convert a time stamp to an absolute day number.
18203 If there is a specifyer for a cyclic time stamp, get the closest date to
18204 DAYNR."
18205 (cond
18206 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18207 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18208 daynr
18209 (+ daynr 1000)))
18210 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18211 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18212 (time-to-days (current-time))) (match-string 0 s)
18213 prefer))
18214 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18216 (defun org-time-from-absolute (d)
18217 "Return the time corresponding to date D.
18218 D may be an absolute day number, or a calendar-type list (month day year)."
18219 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18220 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18222 (defun org-calendar-holiday ()
18223 "List of holidays, for Diary display in Org-mode."
18224 (require 'holidays)
18225 (let ((hl (funcall
18226 (if (fboundp 'calendar-check-holidays)
18227 'calendar-check-holidays 'check-calendar-holidays) date)))
18228 (if hl (mapconcat 'identity hl "; "))))
18230 (defun org-diary-sexp-entry (sexp entry date)
18231 "Process a SEXP diary ENTRY for DATE."
18232 (require 'diary-lib)
18233 (let ((result (if calendar-debug-sexp
18234 (let ((stack-trace-on-error t))
18235 (eval (car (read-from-string sexp))))
18236 (condition-case nil
18237 (eval (car (read-from-string sexp)))
18238 (error
18239 (beep)
18240 (message "Bad sexp at line %d in %s: %s"
18241 (org-current-line)
18242 (buffer-file-name) sexp)
18243 (sleep-for 2))))))
18244 (cond ((stringp result) result)
18245 ((and (consp result)
18246 (stringp (cdr result))) (cdr result))
18247 (result entry)
18248 (t nil))))
18250 (defun org-diary-to-ical-string (frombuf)
18251 "Get iCalendar entries from diary entries in buffer FROMBUF.
18252 This uses the icalendar.el library."
18253 (let* ((tmpdir (if (featurep 'xemacs)
18254 (temp-directory)
18255 temporary-file-directory))
18256 (tmpfile (make-temp-name
18257 (expand-file-name "orgics" tmpdir)))
18258 buf rtn b e)
18259 (save-excursion
18260 (set-buffer frombuf)
18261 (icalendar-export-region (point-min) (point-max) tmpfile)
18262 (setq buf (find-buffer-visiting tmpfile))
18263 (set-buffer buf)
18264 (goto-char (point-min))
18265 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18266 (setq b (match-beginning 0)))
18267 (goto-char (point-max))
18268 (if (re-search-backward "^END:VEVENT" nil t)
18269 (setq e (match-end 0)))
18270 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18271 (kill-buffer buf)
18272 (kill-buffer frombuf)
18273 (delete-file tmpfile)
18274 rtn))
18276 (defun org-closest-date (start current change prefer)
18277 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18278 When PREFER is `past' return a date that is either CURRENT or past.
18279 When PREFER is `future', return a date that is either CURRENT or future."
18280 ;; Make the proper lists from the dates
18281 (catch 'exit
18282 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18283 dn dw sday cday n1 n2
18284 d m y y1 y2 date1 date2 nmonths nm ny m2)
18286 (setq start (org-date-to-gregorian start)
18287 current (org-date-to-gregorian
18288 (if org-agenda-repeating-timestamp-show-all
18289 current
18290 (time-to-days (current-time))))
18291 sday (calendar-absolute-from-gregorian start)
18292 cday (calendar-absolute-from-gregorian current))
18294 (if (<= cday sday) (throw 'exit sday))
18296 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18297 (setq dn (string-to-number (match-string 1 change))
18298 dw (cdr (assoc (match-string 2 change) a1)))
18299 (error "Invalid change specifyer: %s" change))
18300 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18301 (cond
18302 ((eq dw 'day)
18303 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18304 n2 (+ n1 dn)))
18305 ((eq dw 'year)
18306 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18307 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18308 (setq date1 (list m d y1)
18309 n1 (calendar-absolute-from-gregorian date1)
18310 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18311 n2 (calendar-absolute-from-gregorian date2)))
18312 ((eq dw 'month)
18313 ;; approx number of month between the tow dates
18314 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18315 ;; How often does dn fit in there?
18316 (setq d (nth 1 start) m (car start) y (nth 2 start)
18317 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18318 m (+ m nm)
18319 ny (floor (/ m 12))
18320 y (+ y ny)
18321 m (- m (* ny 12)))
18322 (while (> m 12) (setq m (- m 12) y (1+ y)))
18323 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18324 (setq m2 (+ m dn) y2 y)
18325 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18326 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18327 (while (< n2 cday)
18328 (setq n1 n2 m m2 y y2)
18329 (setq m2 (+ m dn) y2 y)
18330 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18331 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18333 (if org-agenda-repeating-timestamp-show-all
18334 (cond
18335 ((eq prefer 'past) n1)
18336 ((eq prefer 'future) (if (= cday n1) n1 n2))
18337 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18338 (cond
18339 ((eq prefer 'past) n1)
18340 ((eq prefer 'future) (if (= cday n1) n1 n2))
18341 (t (if (= cday n1) n1 n2)))))))
18343 (defun org-date-to-gregorian (date)
18344 "Turn any specification of DATE into a gregorian date for the calendar."
18345 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18346 ((and (listp date) (= (length date) 3)) date)
18347 ((stringp date)
18348 (setq date (org-parse-time-string date))
18349 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18350 ((listp date)
18351 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18353 (defun org-parse-time-string (s &optional nodefault)
18354 "Parse the standard Org-mode time string.
18355 This should be a lot faster than the normal `parse-time-string'.
18356 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18357 hour and minute fields will be nil if not given."
18358 (if (string-match org-ts-regexp0 s)
18359 (list 0
18360 (if (or (match-beginning 8) (not nodefault))
18361 (string-to-number (or (match-string 8 s) "0")))
18362 (if (or (match-beginning 7) (not nodefault))
18363 (string-to-number (or (match-string 7 s) "0")))
18364 (string-to-number (match-string 4 s))
18365 (string-to-number (match-string 3 s))
18366 (string-to-number (match-string 2 s))
18367 nil nil nil)
18368 (make-list 9 0)))
18370 (defun org-timestamp-up (&optional arg)
18371 "Increase the date item at the cursor by one.
18372 If the cursor is on the year, change the year. If it is on the month or
18373 the day, change that.
18374 With prefix ARG, change by that many units."
18375 (interactive "p")
18376 (org-timestamp-change (prefix-numeric-value arg)))
18378 (defun org-timestamp-down (&optional arg)
18379 "Decrease the date item at the cursor by one.
18380 If the cursor is on the year, change the year. If it is on the month or
18381 the day, change that.
18382 With prefix ARG, change by that many units."
18383 (interactive "p")
18384 (org-timestamp-change (- (prefix-numeric-value arg))))
18386 (defun org-timestamp-up-day (&optional arg)
18387 "Increase the date in the time stamp by one day.
18388 With prefix ARG, change that many days."
18389 (interactive "p")
18390 (if (and (not (org-at-timestamp-p t))
18391 (org-on-heading-p))
18392 (org-todo 'up)
18393 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18395 (defun org-timestamp-down-day (&optional arg)
18396 "Decrease the date in the time stamp by one day.
18397 With prefix ARG, change that many days."
18398 (interactive "p")
18399 (if (and (not (org-at-timestamp-p t))
18400 (org-on-heading-p))
18401 (org-todo 'down)
18402 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18404 (defsubst org-pos-in-match-range (pos n)
18405 (and (match-beginning n)
18406 (<= (match-beginning n) pos)
18407 (>= (match-end n) pos)))
18409 (defun org-at-timestamp-p (&optional inactive-ok)
18410 "Determine if the cursor is in or at a timestamp."
18411 (interactive)
18412 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18413 (pos (point))
18414 (ans (or (looking-at tsr)
18415 (save-excursion
18416 (skip-chars-backward "^[<\n\r\t")
18417 (if (> (point) (point-min)) (backward-char 1))
18418 (and (looking-at tsr)
18419 (> (- (match-end 0) pos) -1))))))
18420 (and ans
18421 (boundp 'org-ts-what)
18422 (setq org-ts-what
18423 (cond
18424 ((= pos (match-beginning 0)) 'bracket)
18425 ((= pos (1- (match-end 0))) 'bracket)
18426 ((org-pos-in-match-range pos 2) 'year)
18427 ((org-pos-in-match-range pos 3) 'month)
18428 ((org-pos-in-match-range pos 7) 'hour)
18429 ((org-pos-in-match-range pos 8) 'minute)
18430 ((or (org-pos-in-match-range pos 4)
18431 (org-pos-in-match-range pos 5)) 'day)
18432 ((and (> pos (or (match-end 8) (match-end 5)))
18433 (< pos (match-end 0)))
18434 (- pos (or (match-end 8) (match-end 5))))
18435 (t 'day))))
18436 ans))
18438 (defun org-toggle-timestamp-type ()
18439 "Toggle the type (<active> or [inactive]) of a time stamp."
18440 (interactive)
18441 (when (org-at-timestamp-p t)
18442 (save-excursion
18443 (goto-char (match-beginning 0))
18444 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18445 (goto-char (1- (match-end 0)))
18446 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18447 (message "Timestamp is now %sactive"
18448 (if (equal (char-before) ?>) "in" ""))))
18450 (defun org-timestamp-change (n &optional what)
18451 "Change the date in the time stamp at point.
18452 The date will be changed by N times WHAT. WHAT can be `day', `month',
18453 `year', `minute', `second'. If WHAT is not given, the cursor position
18454 in the timestamp determines what will be changed."
18455 (let ((pos (point))
18456 with-hm inactive
18457 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18458 org-ts-what
18459 extra rem
18460 ts time time0)
18461 (if (not (org-at-timestamp-p t))
18462 (error "Not at a timestamp"))
18463 (if (and (not what) (eq org-ts-what 'bracket))
18464 (org-toggle-timestamp-type)
18465 (if (and (not what) (not (eq org-ts-what 'day))
18466 org-display-custom-times
18467 (get-text-property (point) 'display)
18468 (not (get-text-property (1- (point)) 'display)))
18469 (setq org-ts-what 'day))
18470 (setq org-ts-what (or what org-ts-what)
18471 inactive (= (char-after (match-beginning 0)) ?\[)
18472 ts (match-string 0))
18473 (replace-match "")
18474 (if (string-match
18475 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18477 (setq extra (match-string 1 ts)))
18478 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18479 (setq with-hm t))
18480 (setq time0 (org-parse-time-string ts))
18481 (when (and (eq org-ts-what 'minute)
18482 (eq current-prefix-arg nil))
18483 (setq n (* dm (org-no-warnings (signum n))))
18484 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18485 (setcar (cdr time0) (+ (nth 1 time0)
18486 (if (> n 0) (- rem) (- dm rem))))))
18487 (setq time
18488 (encode-time (or (car time0) 0)
18489 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18490 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18491 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18492 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18493 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18494 (nthcdr 6 time0)))
18495 (when (integerp org-ts-what)
18496 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18497 (if (eq what 'calendar)
18498 (let ((cal-date (org-get-date-from-calendar)))
18499 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18500 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18501 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18502 (setcar time0 (or (car time0) 0))
18503 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18504 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18505 (setq time (apply 'encode-time time0))))
18506 (setq org-last-changed-timestamp
18507 (org-insert-time-stamp time with-hm inactive nil nil extra))
18508 (org-clock-update-time-maybe)
18509 (goto-char pos)
18510 ;; Try to recenter the calendar window, if any
18511 (if (and org-calendar-follow-timestamp-change
18512 (get-buffer-window "*Calendar*" t)
18513 (memq org-ts-what '(day month year)))
18514 (org-recenter-calendar (time-to-days time))))))
18516 ;; FIXME: does not yet work for lead times
18517 (defun org-modify-ts-extra (s pos n dm)
18518 "Change the different parts of the lead-time and repeat fields in timestamp."
18519 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18520 ng h m new rem)
18521 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18522 (cond
18523 ((or (org-pos-in-match-range pos 2)
18524 (org-pos-in-match-range pos 3))
18525 (setq m (string-to-number (match-string 3 s))
18526 h (string-to-number (match-string 2 s)))
18527 (if (org-pos-in-match-range pos 2)
18528 (setq h (+ h n))
18529 (setq n (* dm (org-no-warnings (signum n))))
18530 (when (not (= 0 (setq rem (% m dm))))
18531 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18532 (setq m (+ m n)))
18533 (if (< m 0) (setq m (+ m 60) h (1- h)))
18534 (if (> m 59) (setq m (- m 60) h (1+ h)))
18535 (setq h (min 24 (max 0 h)))
18536 (setq ng 1 new (format "-%02d:%02d" h m)))
18537 ((org-pos-in-match-range pos 6)
18538 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18539 ((org-pos-in-match-range pos 5)
18540 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18542 ((org-pos-in-match-range pos 9)
18543 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18544 ((org-pos-in-match-range pos 8)
18545 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18547 (when ng
18548 (setq s (concat
18549 (substring s 0 (match-beginning ng))
18551 (substring s (match-end ng))))))
18554 (defun org-recenter-calendar (date)
18555 "If the calendar is visible, recenter it to DATE."
18556 (let* ((win (selected-window))
18557 (cwin (get-buffer-window "*Calendar*" t))
18558 (calendar-move-hook nil))
18559 (when cwin
18560 (select-window cwin)
18561 (calendar-goto-date (if (listp date) date
18562 (calendar-gregorian-from-absolute date)))
18563 (select-window win))))
18565 (defun org-goto-calendar (&optional arg)
18566 "Go to the Emacs calendar at the current date.
18567 If there is a time stamp in the current line, go to that date.
18568 A prefix ARG can be used to force the current date."
18569 (interactive "P")
18570 (let ((tsr org-ts-regexp) diff
18571 (calendar-move-hook nil)
18572 (view-calendar-holidays-initially nil)
18573 (view-diary-entries-initially nil))
18574 (if (or (org-at-timestamp-p)
18575 (save-excursion
18576 (beginning-of-line 1)
18577 (looking-at (concat ".*" tsr))))
18578 (let ((d1 (time-to-days (current-time)))
18579 (d2 (time-to-days
18580 (org-time-string-to-time (match-string 1)))))
18581 (setq diff (- d2 d1))))
18582 (calendar)
18583 (calendar-goto-today)
18584 (if (and diff (not arg)) (calendar-forward-day diff))))
18586 (defun org-get-date-from-calendar ()
18587 "Return a list (month day year) of date at point in calendar."
18588 (with-current-buffer "*Calendar*"
18589 (save-match-data
18590 (calendar-cursor-to-date))))
18592 (defun org-date-from-calendar ()
18593 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18594 If there is already a time stamp at the cursor position, update it."
18595 (interactive)
18596 (if (org-at-timestamp-p t)
18597 (org-timestamp-change 0 'calendar)
18598 (let ((cal-date (org-get-date-from-calendar)))
18599 (org-insert-time-stamp
18600 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18602 (defvar appt-time-msg-list)
18604 ;;;###autoload
18605 (defun org-agenda-to-appt (&optional refresh filter)
18606 "Activate appointments found in `org-agenda-files'.
18607 With a \\[universal-argument] prefix, refresh the list of
18608 appointements.
18610 If FILTER is t, interactively prompt the user for a regular
18611 expression, and filter out entries that don't match it.
18613 If FILTER is a string, use this string as a regular expression
18614 for filtering entries out.
18616 FILTER can also be an alist with the car of each cell being
18617 either 'headline or 'category. For example:
18619 '((headline \"IMPORTANT\")
18620 (category \"Work\"))
18622 will only add headlines containing IMPORTANT or headlines
18623 belonging to the \"Work\" category."
18624 (interactive "P")
18625 (require 'calendar)
18626 (if refresh (setq appt-time-msg-list nil))
18627 (if (eq filter t)
18628 (setq filter (read-from-minibuffer "Regexp filter: ")))
18629 (let* ((cnt 0) ; count added events
18630 (org-agenda-new-buffers nil)
18631 (org-deadline-warning-days 0)
18632 (today (org-date-to-gregorian
18633 (time-to-days (current-time))))
18634 (files (org-agenda-files)) entries file)
18635 ;; Get all entries which may contain an appt
18636 (while (setq file (pop files))
18637 (setq entries
18638 (append entries
18639 (org-agenda-get-day-entries
18640 file today :timestamp :scheduled :deadline))))
18641 (setq entries (delq nil entries))
18642 ;; Map thru entries and find if we should filter them out
18643 (mapc
18644 (lambda(x)
18645 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18646 (cat (get-text-property 1 'org-category x))
18647 (tod (get-text-property 1 'time-of-day x))
18648 (ok (or (null filter)
18649 (and (stringp filter) (string-match filter evt))
18650 (and (listp filter)
18651 (or (string-match
18652 (cadr (assoc 'category filter)) cat)
18653 (string-match
18654 (cadr (assoc 'headline filter)) evt))))))
18655 ;; FIXME: Shall we remove text-properties for the appt text?
18656 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18657 (when (and ok tod)
18658 (setq tod (number-to-string tod)
18659 tod (when (string-match
18660 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18661 (concat (match-string 1 tod) ":"
18662 (match-string 2 tod))))
18663 (appt-add tod evt)
18664 (setq cnt (1+ cnt))))) entries)
18665 (org-release-buffers org-agenda-new-buffers)
18666 (if (eq cnt 0)
18667 (message "No event to add")
18668 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18670 ;;; The clock for measuring work time.
18672 (defvar org-mode-line-string "")
18673 (put 'org-mode-line-string 'risky-local-variable t)
18675 (defvar org-mode-line-timer nil)
18676 (defvar org-clock-heading "")
18677 (defvar org-clock-start-time "")
18679 (defun org-update-mode-line ()
18680 (let* ((delta (- (time-to-seconds (current-time))
18681 (time-to-seconds org-clock-start-time)))
18682 (h (floor delta 3600))
18683 (m (floor (- delta (* 3600 h)) 60)))
18684 (setq org-mode-line-string
18685 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18686 'help-echo "Org-mode clock is running"))
18687 (force-mode-line-update)))
18689 (defvar org-clock-marker (make-marker)
18690 "Marker recording the last clock-in.")
18691 (defvar org-clock-mode-line-entry nil
18692 "Information for the modeline about the running clock.")
18694 (defun org-clock-in ()
18695 "Start the clock on the current item.
18696 If necessary, clock-out of the currently active clock."
18697 (interactive)
18698 (org-clock-out t)
18699 (let (ts)
18700 (save-excursion
18701 (org-back-to-heading t)
18702 (when (and org-clock-in-switch-to-state
18703 (not (looking-at (concat outline-regexp "[ \t]*"
18704 org-clock-in-switch-to-state
18705 "\\>"))))
18706 (org-todo org-clock-in-switch-to-state))
18707 (if (and org-clock-heading-function
18708 (functionp org-clock-heading-function))
18709 (setq org-clock-heading (funcall org-clock-heading-function))
18710 (if (looking-at org-complex-heading-regexp)
18711 (setq org-clock-heading (match-string 4))
18712 (setq org-clock-heading "???")))
18713 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18714 (org-clock-find-position)
18716 (insert "\n") (backward-char 1)
18717 (indent-relative)
18718 (insert org-clock-string " ")
18719 (setq org-clock-start-time (current-time))
18720 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18721 (move-marker org-clock-marker (point) (buffer-base-buffer))
18722 (or global-mode-string (setq global-mode-string '("")))
18723 (or (memq 'org-mode-line-string global-mode-string)
18724 (setq global-mode-string
18725 (append global-mode-string '(org-mode-line-string))))
18726 (org-update-mode-line)
18727 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18728 (message "Clock started at %s" ts))))
18730 (defun org-clock-find-position ()
18731 "Find the location where the next clock line should be inserted."
18732 (org-back-to-heading t)
18733 (catch 'exit
18734 (let ((beg (save-excursion
18735 (beginning-of-line 2)
18736 (or (bolp) (newline))
18737 (point)))
18738 (end (progn (outline-next-heading) (point)))
18739 (re (concat "^[ \t]*" org-clock-string))
18740 (cnt 0)
18741 first last)
18742 (goto-char beg)
18743 (when (eobp) (newline) (setq end (max (point) end)))
18744 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18745 ;; we seem to have a CLOCK drawer, so go there.
18746 (beginning-of-line 2)
18747 (throw 'exit t))
18748 ;; Lets count the CLOCK lines
18749 (goto-char beg)
18750 (while (re-search-forward re end t)
18751 (setq first (or first (match-beginning 0))
18752 last (match-beginning 0)
18753 cnt (1+ cnt)))
18754 (when (and (integerp org-clock-into-drawer)
18755 (>= (1+ cnt) org-clock-into-drawer))
18756 ;; Wrap current entries into a new drawer
18757 (goto-char last)
18758 (beginning-of-line 2)
18759 (if (org-at-item-p) (org-end-of-item))
18760 (insert ":END:\n")
18761 (beginning-of-line 0)
18762 (org-indent-line-function)
18763 (goto-char first)
18764 (insert ":CLOCK:\n")
18765 (beginning-of-line 0)
18766 (org-indent-line-function)
18767 (org-flag-drawer t)
18768 (beginning-of-line 2)
18769 (throw 'exit nil))
18771 (goto-char beg)
18772 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18773 (not (equal (match-string 1) org-clock-string)))
18774 ;; Planning info, skip to after it
18775 (beginning-of-line 2)
18776 (or (bolp) (newline)))
18777 (when (eq t org-clock-into-drawer)
18778 (insert ":CLOCK:\n:END:\n")
18779 (beginning-of-line -1)
18780 (org-indent-line-function)
18781 (org-flag-drawer t)
18782 (beginning-of-line 2)
18783 (org-indent-line-function)))))
18785 (defun org-clock-out (&optional fail-quietly)
18786 "Stop the currently running clock.
18787 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18788 (interactive)
18789 (catch 'exit
18790 (if (not (marker-buffer org-clock-marker))
18791 (if fail-quietly (throw 'exit t) (error "No active clock")))
18792 (let (ts te s h m)
18793 (save-excursion
18794 (set-buffer (marker-buffer org-clock-marker))
18795 (goto-char org-clock-marker)
18796 (beginning-of-line 1)
18797 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18798 (equal (match-string 1) org-clock-string))
18799 (setq ts (match-string 2))
18800 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18801 (goto-char (match-end 0))
18802 (delete-region (point) (point-at-eol))
18803 (insert "--")
18804 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18805 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18806 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18807 h (floor (/ s 3600))
18808 s (- s (* 3600 h))
18809 m (floor (/ s 60))
18810 s (- s (* 60 s)))
18811 (insert " => " (format "%2d:%02d" h m))
18812 (move-marker org-clock-marker nil)
18813 (when org-log-note-clock-out
18814 (org-add-log-maybe 'clock-out))
18815 (when org-mode-line-timer
18816 (cancel-timer org-mode-line-timer)
18817 (setq org-mode-line-timer nil))
18818 (setq global-mode-string
18819 (delq 'org-mode-line-string global-mode-string))
18820 (force-mode-line-update)
18821 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18823 (defun org-clock-cancel ()
18824 "Cancel the running clock be removing the start timestamp."
18825 (interactive)
18826 (if (not (marker-buffer org-clock-marker))
18827 (error "No active clock"))
18828 (save-excursion
18829 (set-buffer (marker-buffer org-clock-marker))
18830 (goto-char org-clock-marker)
18831 (delete-region (1- (point-at-bol)) (point-at-eol)))
18832 (setq global-mode-string
18833 (delq 'org-mode-line-string global-mode-string))
18834 (force-mode-line-update)
18835 (message "Clock canceled"))
18837 (defun org-clock-goto (&optional delete-windows)
18838 "Go to the currently clocked-in entry."
18839 (interactive "P")
18840 (if (not (marker-buffer org-clock-marker))
18841 (error "No active clock"))
18842 (switch-to-buffer-other-window
18843 (marker-buffer org-clock-marker))
18844 (if delete-windows (delete-other-windows))
18845 (goto-char org-clock-marker)
18846 (org-show-entry)
18847 (org-back-to-heading)
18848 (recenter))
18850 (defvar org-clock-file-total-minutes nil
18851 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18852 (make-variable-buffer-local 'org-clock-file-total-minutes)
18854 (defun org-clock-sum (&optional tstart tend)
18855 "Sum the times for each subtree.
18856 Puts the resulting times in minutes as a text property on each headline."
18857 (interactive)
18858 (let* ((bmp (buffer-modified-p))
18859 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18860 org-clock-string
18861 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18862 (lmax 30)
18863 (ltimes (make-vector lmax 0))
18864 (t1 0)
18865 (level 0)
18866 ts te dt
18867 time)
18868 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18869 (save-excursion
18870 (goto-char (point-max))
18871 (while (re-search-backward re nil t)
18872 (cond
18873 ((match-end 2)
18874 ;; Two time stamps
18875 (setq ts (match-string 2)
18876 te (match-string 3)
18877 ts (time-to-seconds
18878 (apply 'encode-time (org-parse-time-string ts)))
18879 te (time-to-seconds
18880 (apply 'encode-time (org-parse-time-string te)))
18881 ts (if tstart (max ts tstart) ts)
18882 te (if tend (min te tend) te)
18883 dt (- te ts)
18884 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18885 ((match-end 4)
18886 ;; A naket time
18887 (setq t1 (+ t1 (string-to-number (match-string 5))
18888 (* 60 (string-to-number (match-string 4))))))
18889 (t ;; A headline
18890 (setq level (- (match-end 1) (match-beginning 1)))
18891 (when (or (> t1 0) (> (aref ltimes level) 0))
18892 (loop for l from 0 to level do
18893 (aset ltimes l (+ (aref ltimes l) t1)))
18894 (setq t1 0 time (aref ltimes level))
18895 (loop for l from level to (1- lmax) do
18896 (aset ltimes l 0))
18897 (goto-char (match-beginning 0))
18898 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18899 (setq org-clock-file-total-minutes (aref ltimes 0)))
18900 (set-buffer-modified-p bmp)))
18902 (defun org-clock-display (&optional total-only)
18903 "Show subtree times in the entire buffer.
18904 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18905 in the echo area."
18906 (interactive)
18907 (org-remove-clock-overlays)
18908 (let (time h m p)
18909 (org-clock-sum)
18910 (unless total-only
18911 (save-excursion
18912 (goto-char (point-min))
18913 (while (or (and (equal (setq p (point)) (point-min))
18914 (get-text-property p :org-clock-minutes))
18915 (setq p (next-single-property-change
18916 (point) :org-clock-minutes)))
18917 (goto-char p)
18918 (when (setq time (get-text-property p :org-clock-minutes))
18919 (org-put-clock-overlay time (funcall outline-level))))
18920 (setq h (/ org-clock-file-total-minutes 60)
18921 m (- org-clock-file-total-minutes (* 60 h)))
18922 ;; Arrange to remove the overlays upon next change.
18923 (when org-remove-highlights-with-change
18924 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18925 nil 'local))))
18926 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18928 (defvar org-clock-overlays nil)
18929 (make-variable-buffer-local 'org-clock-overlays)
18931 (defun org-put-clock-overlay (time &optional level)
18932 "Put an overlays on the current line, displaying TIME.
18933 If LEVEL is given, prefix time with a corresponding number of stars.
18934 This creates a new overlay and stores it in `org-clock-overlays', so that it
18935 will be easy to remove."
18936 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18937 (l (if level (org-get-valid-level level 0) 0))
18938 (off 0)
18939 ov tx)
18940 (move-to-column c)
18941 (unless (eolp) (skip-chars-backward "^ \t"))
18942 (skip-chars-backward " \t")
18943 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18944 tx (concat (buffer-substring (1- (point)) (point))
18945 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18946 (org-add-props (format "%s %2d:%02d%s"
18947 (make-string l ?*) h m
18948 (make-string (- 16 l) ?\ ))
18949 '(face secondary-selection))
18950 ""))
18951 (if (not (featurep 'xemacs))
18952 (org-overlay-put ov 'display tx)
18953 (org-overlay-put ov 'invisible t)
18954 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18955 (push ov org-clock-overlays)))
18957 (defun org-remove-clock-overlays (&optional beg end noremove)
18958 "Remove the occur highlights from the buffer.
18959 BEG and END are ignored. If NOREMOVE is nil, remove this function
18960 from the `before-change-functions' in the current buffer."
18961 (interactive)
18962 (unless org-inhibit-highlight-removal
18963 (mapc 'org-delete-overlay org-clock-overlays)
18964 (setq org-clock-overlays nil)
18965 (unless noremove
18966 (remove-hook 'before-change-functions
18967 'org-remove-clock-overlays 'local))))
18969 (defun org-clock-out-if-current ()
18970 "Clock out if the current entry contains the running clock.
18971 This is used to stop the clock after a TODO entry is marked DONE,
18972 and is only done if the variable `org-clock-out-when-done' is not nil."
18973 (when (and org-clock-out-when-done
18974 (member state org-done-keywords)
18975 (equal (marker-buffer org-clock-marker) (current-buffer))
18976 (< (point) org-clock-marker)
18977 (> (save-excursion (outline-next-heading) (point))
18978 org-clock-marker))
18979 ;; Clock out, but don't accept a logging message for this.
18980 (let ((org-log-note-clock-out nil))
18981 (org-clock-out))))
18983 (add-hook 'org-after-todo-state-change-hook
18984 'org-clock-out-if-current)
18986 (defun org-check-running-clock ()
18987 "Check if the current buffer contains the running clock.
18988 If yes, offer to stop it and to save the buffer with the changes."
18989 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18990 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18991 (buffer-name))))
18992 (org-clock-out)
18993 (when (y-or-n-p "Save changed buffer?")
18994 (save-buffer))))
18996 (defun org-clock-report (&optional arg)
18997 "Create a table containing a report about clocked time.
18998 If the cursor is inside an existing clocktable block, then the table
18999 will be updated. If not, a new clocktable will be inserted.
19000 When called with a prefix argument, move to the first clock table in the
19001 buffer and update it."
19002 (interactive "P")
19003 (org-remove-clock-overlays)
19004 (when arg
19005 (org-find-dblock "clocktable")
19006 (org-show-entry))
19007 (if (org-in-clocktable-p)
19008 (goto-char (org-in-clocktable-p))
19009 (org-create-dblock (list :name "clocktable"
19010 :maxlevel 2 :scope 'file)))
19011 (org-update-dblock))
19013 (defun org-in-clocktable-p ()
19014 "Check if the cursor is in a clocktable."
19015 (let ((pos (point)) start)
19016 (save-excursion
19017 (end-of-line 1)
19018 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19019 (setq start (match-beginning 0))
19020 (re-search-forward "^#\\+END:.*" nil t)
19021 (>= (match-end 0) pos)
19022 start))))
19024 (defun org-clock-update-time-maybe ()
19025 "If this is a CLOCK line, update it and return t.
19026 Otherwise, return nil."
19027 (interactive)
19028 (save-excursion
19029 (beginning-of-line 1)
19030 (skip-chars-forward " \t")
19031 (when (looking-at org-clock-string)
19032 (let ((re (concat "[ \t]*" org-clock-string
19033 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19034 "\\([ \t]*=>.*\\)?"))
19035 ts te h m s)
19036 (if (not (looking-at re))
19038 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19039 (end-of-line 1)
19040 (setq ts (match-string 1)
19041 te (match-string 2))
19042 (setq s (- (time-to-seconds
19043 (apply 'encode-time (org-parse-time-string te)))
19044 (time-to-seconds
19045 (apply 'encode-time (org-parse-time-string ts))))
19046 h (floor (/ s 3600))
19047 s (- s (* 3600 h))
19048 m (floor (/ s 60))
19049 s (- s (* 60 s)))
19050 (insert " => " (format "%2d:%02d" h m))
19051 t)))))
19053 (defun org-clock-special-range (key &optional time as-strings)
19054 "Return two times bordering a special time range.
19055 Key is a symbol specifying the range and can be one of `today', `yesterday',
19056 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19057 A week starts Monday 0:00 and ends Sunday 24:00.
19058 The range is determined relative to TIME. TIME defaults to the current time.
19059 The return value is a cons cell with two internal times like the ones
19060 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19061 the returned times will be formatted strings."
19062 (let* ((tm (decode-time (or time (current-time))))
19063 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19064 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19065 (dow (nth 6 tm))
19066 s1 m1 h1 d1 month1 y1 diff ts te fm)
19067 (cond
19068 ((eq key 'today)
19069 (setq h 0 m 0 h1 24 m1 0))
19070 ((eq key 'yesterday)
19071 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19072 ((eq key 'thisweek)
19073 (setq diff (if (= dow 0) 6 (1- dow))
19074 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19075 ((eq key 'lastweek)
19076 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19077 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19078 ((eq key 'thismonth)
19079 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19080 ((eq key 'lastmonth)
19081 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19082 ((eq key 'thisyear)
19083 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19084 ((eq key 'lastyear)
19085 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19086 (t (error "No such time block %s" key)))
19087 (setq ts (encode-time s m h d month y)
19088 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19089 (or d1 d) (or month1 month) (or y1 y)))
19090 (setq fm (cdr org-time-stamp-formats))
19091 (if as-strings
19092 (cons (format-time-string fm ts) (format-time-string fm te))
19093 (cons ts te))))
19095 (defun org-dblock-write:clocktable (params)
19096 "Write the standard clocktable."
19097 (catch 'exit
19098 (let* ((hlchars '((1 . "*") (2 . "/")))
19099 (ins (make-marker))
19100 (total-time nil)
19101 (scope (plist-get params :scope))
19102 (tostring (plist-get params :tostring))
19103 (multifile (plist-get params :multifile))
19104 (header (plist-get params :header))
19105 (maxlevel (or (plist-get params :maxlevel) 3))
19106 (step (plist-get params :step))
19107 (emph (plist-get params :emphasize))
19108 (ts (plist-get params :tstart))
19109 (te (plist-get params :tend))
19110 (block (plist-get params :block))
19111 (link (plist-get params :link))
19112 ipos time h m p level hlc hdl
19113 cc beg end pos tbl)
19114 (when step
19115 (org-clocktable-steps params)
19116 (throw 'exit nil))
19117 (when block
19118 (setq cc (org-clock-special-range block nil t)
19119 ts (car cc) te (cdr cc)))
19120 (if ts (setq ts (time-to-seconds
19121 (apply 'encode-time (org-parse-time-string ts)))))
19122 (if te (setq te (time-to-seconds
19123 (apply 'encode-time (org-parse-time-string te)))))
19124 (move-marker ins (point))
19125 (setq ipos (point))
19127 ;; Get the right scope
19128 (setq pos (point))
19129 (save-restriction
19130 (cond
19131 ((not scope))
19132 ((eq scope 'file) (widen))
19133 ((eq scope 'subtree) (org-narrow-to-subtree))
19134 ((eq scope 'tree)
19135 (while (org-up-heading-safe))
19136 (org-narrow-to-subtree))
19137 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19138 (symbol-name scope)))
19139 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19140 (catch 'exit
19141 (while (org-up-heading-safe)
19142 (looking-at outline-regexp)
19143 (if (<= (org-reduced-level (funcall outline-level)) level)
19144 (throw 'exit nil))))
19145 (org-narrow-to-subtree))
19146 ((or (listp scope) (eq scope 'agenda))
19147 (let* ((files (if (listp scope) scope (org-agenda-files)))
19148 (scope 'agenda)
19149 (p1 (copy-sequence params))
19150 file)
19151 (plist-put p1 :tostring t)
19152 (plist-put p1 :multifile t)
19153 (plist-put p1 :scope 'file)
19154 (org-prepare-agenda-buffers files)
19155 (while (setq file (pop files))
19156 (with-current-buffer (find-buffer-visiting file)
19157 (push (org-clocktable-add-file
19158 file (org-dblock-write:clocktable p1)) tbl)
19159 (setq total-time (+ (or total-time 0)
19160 org-clock-file-total-minutes)))))))
19161 (goto-char pos)
19163 (unless (eq scope 'agenda)
19164 (org-clock-sum ts te)
19165 (goto-char (point-min))
19166 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19167 (goto-char p)
19168 (when (setq time (get-text-property p :org-clock-minutes))
19169 (save-excursion
19170 (beginning-of-line 1)
19171 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19172 (setq level (org-reduced-level
19173 (- (match-end 1) (match-beginning 1))))
19174 (<= level maxlevel))
19175 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19176 hdl (if (not link)
19177 (match-string 2)
19178 (org-make-link-string
19179 (format "file:%s::%s"
19180 (buffer-file-name)
19181 (save-match-data
19182 (org-make-org-heading-search-string
19183 (match-string 2))))
19184 (match-string 2)))
19185 h (/ time 60)
19186 m (- time (* 60 h)))
19187 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19188 (push (concat
19189 "| " (int-to-string level) "|" hlc hdl hlc " |"
19190 (make-string (1- level) ?|)
19191 hlc (format "%d:%02d" h m) hlc
19192 " |") tbl))))))
19193 (setq tbl (nreverse tbl))
19194 (if tostring
19195 (if tbl (mapconcat 'identity tbl "\n") nil)
19196 (goto-char ins)
19197 (insert-before-markers
19198 (or header
19199 (concat
19200 "Clock summary at ["
19201 (substring
19202 (format-time-string (cdr org-time-stamp-formats))
19203 1 -1)
19204 "]."
19205 (if block
19206 (format " Considered range is /%s/." block)
19208 "\n\n"))
19209 (if (eq scope 'agenda) "|File" "")
19210 "|L|Headline|Time|\n")
19211 (setq total-time (or total-time org-clock-file-total-minutes)
19212 h (/ total-time 60)
19213 m (- total-time (* 60 h)))
19214 (insert-before-markers
19215 "|-\n|"
19216 (if (eq scope 'agenda) "|" "")
19218 "*Total time*| "
19219 (format "*%d:%02d*" h m)
19220 "|\n|-\n")
19221 (setq tbl (delq nil tbl))
19222 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19223 (equal (substring (car tbl) 0 2) "|-"))
19224 (pop tbl))
19225 (insert-before-markers (mapconcat
19226 'identity (delq nil tbl)
19227 (if (eq scope 'agenda) "\n|-\n" "\n")))
19228 (backward-delete-char 1)
19229 (goto-char ipos)
19230 (skip-chars-forward "^|")
19231 (org-table-align))))))
19233 (defun org-clocktable-steps (params)
19234 (let* ((p1 (copy-sequence params))
19235 (ts (plist-get p1 :tstart))
19236 (te (plist-get p1 :tend))
19237 (step0 (plist-get p1 :step))
19238 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19239 (block (plist-get p1 :block))
19241 (when block
19242 (setq cc (org-clock-special-range block nil t)
19243 ts (car cc) te (cdr cc)))
19244 (if ts (setq ts (time-to-seconds
19245 (apply 'encode-time (org-parse-time-string ts)))))
19246 (if te (setq te (time-to-seconds
19247 (apply 'encode-time (org-parse-time-string te)))))
19248 (plist-put p1 :header "")
19249 (plist-put p1 :step nil)
19250 (plist-put p1 :block nil)
19251 (while (< ts te)
19252 (or (bolp) (insert "\n"))
19253 (plist-put p1 :tstart (format-time-string
19254 (car org-time-stamp-formats)
19255 (seconds-to-time ts)))
19256 (plist-put p1 :tend (format-time-string
19257 (car org-time-stamp-formats)
19258 (seconds-to-time (setq ts (+ ts step)))))
19259 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19260 (plist-get p1 :tstart) "\n")
19261 (org-dblock-write:clocktable p1)
19262 (re-search-forward "#\\+END:")
19263 (end-of-line 0))))
19266 (defun org-clocktable-add-file (file table)
19267 (if table
19268 (let ((lines (org-split-string table "\n"))
19269 (ff (file-name-nondirectory file)))
19270 (mapconcat 'identity
19271 (mapcar (lambda (x)
19272 (if (string-match org-table-dataline-regexp x)
19273 (concat "|" ff x)
19275 lines)
19276 "\n"))))
19278 ;; FIXME: I don't think anybody uses this, ask David
19279 (defun org-collect-clock-time-entries ()
19280 "Return an internal list with clocking information.
19281 This list has one entry for each CLOCK interval.
19282 FIXME: describe the elements."
19283 (interactive)
19284 (let ((re (concat "^[ \t]*" org-clock-string
19285 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19286 rtn beg end next cont level title total closedp leafp
19287 clockpos titlepos h m donep)
19288 (save-excursion
19289 (org-clock-sum)
19290 (goto-char (point-min))
19291 (while (re-search-forward re nil t)
19292 (setq clockpos (match-beginning 0)
19293 beg (match-string 1) end (match-string 2)
19294 cont (match-end 0))
19295 (setq beg (apply 'encode-time (org-parse-time-string beg))
19296 end (apply 'encode-time (org-parse-time-string end)))
19297 (org-back-to-heading t)
19298 (setq donep (org-entry-is-done-p))
19299 (setq titlepos (point)
19300 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19301 h (/ total 60) m (- total (* 60 h))
19302 total (cons h m))
19303 (looking-at "\\(\\*+\\) +\\(.*\\)")
19304 (setq level (- (match-end 1) (match-beginning 1))
19305 title (org-match-string-no-properties 2))
19306 (save-excursion (outline-next-heading) (setq next (point)))
19307 (setq closedp (re-search-forward org-closed-time-regexp next t))
19308 (goto-char next)
19309 (setq leafp (and (looking-at "^\\*+ ")
19310 (<= (- (match-end 0) (point)) level)))
19311 (push (list beg end clockpos closedp donep
19312 total title titlepos level leafp)
19313 rtn)
19314 (goto-char cont)))
19315 (nreverse rtn)))
19317 ;;;; Agenda, and Diary Integration
19319 ;;; Define the Org-agenda-mode
19321 (defvar org-agenda-mode-map (make-sparse-keymap)
19322 "Keymap for `org-agenda-mode'.")
19324 (defvar org-agenda-menu) ; defined later in this file.
19325 (defvar org-agenda-follow-mode nil)
19326 (defvar org-agenda-show-log nil)
19327 (defvar org-agenda-redo-command nil)
19328 (defvar org-agenda-query-string nil)
19329 (defvar org-agenda-mode-hook nil)
19330 (defvar org-agenda-type nil)
19331 (defvar org-agenda-force-single-file nil)
19333 (defun org-agenda-mode ()
19334 "Mode for time-sorted view on action items in Org-mode files.
19336 The following commands are available:
19338 \\{org-agenda-mode-map}"
19339 (interactive)
19340 (kill-all-local-variables)
19341 (setq org-agenda-undo-list nil
19342 org-agenda-pending-undo-list nil)
19343 (setq major-mode 'org-agenda-mode)
19344 ;; Keep global-font-lock-mode from turning on font-lock-mode
19345 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19346 (setq mode-name "Org-Agenda")
19347 (use-local-map org-agenda-mode-map)
19348 (easy-menu-add org-agenda-menu)
19349 (if org-startup-truncated (setq truncate-lines t))
19350 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19351 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19352 ;; Make sure properties are removed when copying text
19353 (when (boundp 'buffer-substring-filters)
19354 (org-set-local 'buffer-substring-filters
19355 (cons (lambda (x)
19356 (set-text-properties 0 (length x) nil x) x)
19357 buffer-substring-filters)))
19358 (unless org-agenda-keep-modes
19359 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19360 org-agenda-show-log nil))
19361 (easy-menu-change
19362 '("Agenda") "Agenda Files"
19363 (append
19364 (list
19365 (vector
19366 (if (get 'org-agenda-files 'org-restrict)
19367 "Restricted to single file"
19368 "Edit File List")
19369 '(org-edit-agenda-file-list)
19370 (not (get 'org-agenda-files 'org-restrict)))
19371 "--")
19372 (mapcar 'org-file-menu-entry (org-agenda-files))))
19373 (org-agenda-set-mode-name)
19374 (apply
19375 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19376 (list 'org-agenda-mode-hook)))
19378 (substitute-key-definition 'undo 'org-agenda-undo
19379 org-agenda-mode-map global-map)
19380 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19381 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19382 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19383 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19384 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19385 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19386 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19387 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19388 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19389 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19390 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19391 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19392 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19393 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19394 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19395 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19396 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19397 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19398 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19399 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19400 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19401 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19402 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19403 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19404 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19405 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19406 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19407 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19408 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19410 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19411 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19412 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19413 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19414 (while l (org-defkey org-agenda-mode-map
19415 (int-to-string (pop l)) 'digit-argument)))
19417 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19418 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19419 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19420 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19421 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19422 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19423 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19424 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19425 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19426 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19427 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19428 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19429 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19430 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19431 (org-defkey org-agenda-mode-map "n" 'next-line)
19432 (org-defkey org-agenda-mode-map "p" 'previous-line)
19433 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19434 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19435 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19436 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19437 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19438 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19439 (eval-after-load "calendar"
19440 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19441 'org-calendar-goto-agenda))
19442 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19443 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19444 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19445 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19446 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19447 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19448 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19449 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19450 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19451 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19452 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19453 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19454 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19455 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19456 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19457 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19458 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19459 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19460 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19461 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19462 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19463 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19465 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19466 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19467 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19468 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19470 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19471 "Local keymap for agenda entries from Org-mode.")
19473 (org-defkey org-agenda-keymap
19474 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19475 (org-defkey org-agenda-keymap
19476 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19477 (when org-agenda-mouse-1-follows-link
19478 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19479 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19480 '("Agenda"
19481 ("Agenda Files")
19482 "--"
19483 ["Show" org-agenda-show t]
19484 ["Go To (other window)" org-agenda-goto t]
19485 ["Go To (this window)" org-agenda-switch-to t]
19486 ["Follow Mode" org-agenda-follow-mode
19487 :style toggle :selected org-agenda-follow-mode :active t]
19488 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19489 "--"
19490 ["Cycle TODO" org-agenda-todo t]
19491 ["Archive subtree" org-agenda-archive t]
19492 ["Delete subtree" org-agenda-kill t]
19493 "--"
19494 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19495 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19496 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19497 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19498 "--"
19499 ("Tags and Properties"
19500 ["Show all Tags" org-agenda-show-tags t]
19501 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19502 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19503 "--"
19504 ["Column View" org-columns t])
19505 ("Date/Schedule"
19506 ["Schedule" org-agenda-schedule t]
19507 ["Set Deadline" org-agenda-deadline t]
19508 "--"
19509 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19510 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19511 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19512 ("Clock"
19513 ["Clock in" org-agenda-clock-in t]
19514 ["Clock out" org-agenda-clock-out t]
19515 ["Clock cancel" org-agenda-clock-cancel t]
19516 ["Goto running clock" org-clock-goto t])
19517 ("Priority"
19518 ["Set Priority" org-agenda-priority t]
19519 ["Increase Priority" org-agenda-priority-up t]
19520 ["Decrease Priority" org-agenda-priority-down t]
19521 ["Show Priority" org-agenda-show-priority t])
19522 ("Calendar/Diary"
19523 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19524 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19525 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19526 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19527 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19528 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19529 "--"
19530 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19531 "--"
19532 ("View"
19533 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19534 :style radio :selected (equal org-agenda-ndays 1)]
19535 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19536 :style radio :selected (equal org-agenda-ndays 7)]
19537 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19538 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19539 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19540 :style radio :selected (member org-agenda-ndays '(365 366))]
19541 "--"
19542 ["Show Logbook entries" org-agenda-log-mode
19543 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19544 ["Include Diary" org-agenda-toggle-diary
19545 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19546 ["Use Time Grid" org-agenda-toggle-time-grid
19547 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19548 ["Write view to file" org-write-agenda t]
19549 ["Rebuild buffer" org-agenda-redo t]
19550 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19551 "--"
19552 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19553 "--"
19554 ["Quit" org-agenda-quit t]
19555 ["Exit and Release Buffers" org-agenda-exit t]
19558 ;;; Agenda undo
19560 (defvar org-agenda-allow-remote-undo t
19561 "Non-nil means, allow remote undo from the agenda buffer.")
19562 (defvar org-agenda-undo-list nil
19563 "List of undoable operations in the agenda since last refresh.")
19564 (defvar org-agenda-undo-has-started-in nil
19565 "Buffers that have already seen `undo-start' in the current undo sequence.")
19566 (defvar org-agenda-pending-undo-list nil
19567 "In a series of undo commands, this is the list of remaning undo items.")
19569 (defmacro org-if-unprotected (&rest body)
19570 "Execute BODY if there is no `org-protected' text property at point."
19571 (declare (debug t))
19572 `(unless (get-text-property (point) 'org-protected)
19573 ,@body))
19575 (defmacro org-with-remote-undo (_buffer &rest _body)
19576 "Execute BODY while recording undo information in two buffers."
19577 (declare (indent 1) (debug t))
19578 `(let ((_cline (org-current-line))
19579 (_cmd this-command)
19580 (_buf1 (current-buffer))
19581 (_buf2 ,_buffer)
19582 (_undo1 buffer-undo-list)
19583 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19584 _c1 _c2)
19585 ,@_body
19586 (when org-agenda-allow-remote-undo
19587 (setq _c1 (org-verify-change-for-undo
19588 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19589 _c2 (org-verify-change-for-undo
19590 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19591 (when (or _c1 _c2)
19592 ;; make sure there are undo boundaries
19593 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19594 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19595 ;; remember which buffer to undo
19596 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19597 org-agenda-undo-list)))))
19599 (defun org-agenda-undo ()
19600 "Undo a remote editing step in the agenda.
19601 This undoes changes both in the agenda buffer and in the remote buffer
19602 that have been changed along."
19603 (interactive)
19604 (or org-agenda-allow-remote-undo
19605 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19606 (if (not (eq this-command last-command))
19607 (setq org-agenda-undo-has-started-in nil
19608 org-agenda-pending-undo-list org-agenda-undo-list))
19609 (if (not org-agenda-pending-undo-list)
19610 (error "No further undo information"))
19611 (let* ((entry (pop org-agenda-pending-undo-list))
19612 buf line cmd rembuf)
19613 (setq cmd (pop entry) line (pop entry))
19614 (setq rembuf (nth 2 entry))
19615 (org-with-remote-undo rembuf
19616 (while (bufferp (setq buf (pop entry)))
19617 (if (pop entry)
19618 (with-current-buffer buf
19619 (let ((last-undo-buffer buf)
19620 (inhibit-read-only t))
19621 (unless (memq buf org-agenda-undo-has-started-in)
19622 (push buf org-agenda-undo-has-started-in)
19623 (make-local-variable 'pending-undo-list)
19624 (undo-start))
19625 (while (and pending-undo-list
19626 (listp pending-undo-list)
19627 (not (car pending-undo-list)))
19628 (pop pending-undo-list))
19629 (undo-more 1))))))
19630 (goto-line line)
19631 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19633 (defun org-verify-change-for-undo (l1 l2)
19634 "Verify that a real change occurred between the undo lists L1 and L2."
19635 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19636 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19637 (not (eq l1 l2)))
19639 ;;; Agenda dispatch
19641 (defvar org-agenda-restrict nil)
19642 (defvar org-agenda-restrict-begin (make-marker))
19643 (defvar org-agenda-restrict-end (make-marker))
19644 (defvar org-agenda-last-dispatch-buffer nil)
19645 (defvar org-agenda-overriding-restriction nil)
19647 ;;;###autoload
19648 (defun org-agenda (arg &optional keys restriction)
19649 "Dispatch agenda commands to collect entries to the agenda buffer.
19650 Prompts for a command to execute. Any prefix arg will be passed
19651 on to the selected command. The default selections are:
19653 a Call `org-agenda-list' to display the agenda for current day or week.
19654 t Call `org-todo-list' to display the global todo list.
19655 T Call `org-todo-list' to display the global todo list, select only
19656 entries with a specific TODO keyword (the user gets a prompt).
19657 m Call `org-tags-view' to display headlines with tags matching
19658 a condition (the user is prompted for the condition).
19659 M Like `m', but select only TODO entries, no ordinary headlines.
19660 L Create a timeline for the current buffer.
19661 e Export views to associated files.
19663 More commands can be added by configuring the variable
19664 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19665 searches can be pre-defined in this way.
19667 If the current buffer is in Org-mode and visiting a file, you can also
19668 first press `<' once to indicate that the agenda should be temporarily
19669 \(until the next use of \\[org-agenda]) restricted to the current file.
19670 Pressing `<' twice means to restrict to the current subtree or region
19671 \(if active)."
19672 (interactive "P")
19673 (catch 'exit
19674 (let* ((prefix-descriptions nil)
19675 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19676 (org-agenda-custom-commands
19677 ;; normalize different versions
19678 (delq nil
19679 (mapcar
19680 (lambda (x)
19681 (cond ((stringp (cdr x))
19682 (push x prefix-descriptions)
19683 nil)
19684 ((stringp (nth 1 x)) x)
19685 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19686 (t (cons (car x) (cons "" (cdr x))))))
19687 org-agenda-custom-commands)))
19688 (buf (current-buffer))
19689 (bfn (buffer-file-name (buffer-base-buffer)))
19690 entry key type match lprops ans)
19691 ;; Turn off restriction unless there is an overriding one
19692 (unless org-agenda-overriding-restriction
19693 (put 'org-agenda-files 'org-restrict nil)
19694 (setq org-agenda-restrict nil)
19695 (move-marker org-agenda-restrict-begin nil)
19696 (move-marker org-agenda-restrict-end nil))
19697 ;; Delete old local properties
19698 (put 'org-agenda-redo-command 'org-lprops nil)
19699 ;; Remember where this call originated
19700 (setq org-agenda-last-dispatch-buffer (current-buffer))
19701 (unless keys
19702 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19703 keys (car ans)
19704 restriction (cdr ans)))
19705 ;; Estabish the restriction, if any
19706 (when (and (not org-agenda-overriding-restriction) restriction)
19707 (put 'org-agenda-files 'org-restrict (list bfn))
19708 (cond
19709 ((eq restriction 'region)
19710 (setq org-agenda-restrict t)
19711 (move-marker org-agenda-restrict-begin (region-beginning))
19712 (move-marker org-agenda-restrict-end (region-end)))
19713 ((eq restriction 'subtree)
19714 (save-excursion
19715 (setq org-agenda-restrict t)
19716 (org-back-to-heading t)
19717 (move-marker org-agenda-restrict-begin (point))
19718 (move-marker org-agenda-restrict-end
19719 (progn (org-end-of-subtree t)))))))
19721 (require 'calendar) ; FIXME: can we avoid this for some commands?
19722 ;; For example the todo list should not need it (but does...)
19723 (cond
19724 ((setq entry (assoc keys org-agenda-custom-commands))
19725 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19726 (progn
19727 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19728 (put 'org-agenda-redo-command 'org-lprops lprops)
19729 (cond
19730 ((eq type 'agenda)
19731 (org-let lprops '(org-agenda-list current-prefix-arg)))
19732 ((eq type 'alltodo)
19733 (org-let lprops '(org-todo-list current-prefix-arg)))
19734 ((eq type 'search)
19735 (org-let lprops '(org-search-view current-prefix-arg match nil)))
19736 ((eq type 'stuck)
19737 (org-let lprops '(org-agenda-list-stuck-projects
19738 current-prefix-arg)))
19739 ((eq type 'tags)
19740 (org-let lprops '(org-tags-view current-prefix-arg match)))
19741 ((eq type 'tags-todo)
19742 (org-let lprops '(org-tags-view '(4) match)))
19743 ((eq type 'todo)
19744 (org-let lprops '(org-todo-list match)))
19745 ((eq type 'tags-tree)
19746 (org-check-for-org-mode)
19747 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19748 ((eq type 'todo-tree)
19749 (org-check-for-org-mode)
19750 (org-let lprops
19751 '(org-occur (concat "^" outline-regexp "[ \t]*"
19752 (regexp-quote match) "\\>"))))
19753 ((eq type 'occur-tree)
19754 (org-check-for-org-mode)
19755 (org-let lprops '(org-occur match)))
19756 ((functionp type)
19757 (org-let lprops '(funcall type match)))
19758 ((fboundp type)
19759 (org-let lprops '(funcall type match)))
19760 (t (error "Invalid custom agenda command type %s" type))))
19761 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19762 ((equal keys "C")
19763 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19764 (customize-variable 'org-agenda-custom-commands))
19765 ((equal keys "a") (call-interactively 'org-agenda-list))
19766 ((equal keys "s") (call-interactively 'org-search-view))
19767 ((equal keys "t") (call-interactively 'org-todo-list))
19768 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19769 ((equal keys "m") (call-interactively 'org-tags-view))
19770 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19771 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19772 ((equal keys "L")
19773 (unless (org-mode-p)
19774 (error "This is not an Org-mode file"))
19775 (unless restriction
19776 (put 'org-agenda-files 'org-restrict (list bfn))
19777 (org-call-with-arg 'org-timeline arg)))
19778 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19779 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19780 ((equal keys "!") (customize-variable 'org-stuck-projects))
19781 (t (error "Invalid agenda key"))))))
19783 (defun org-agenda-normalize-custom-commands (cmds)
19784 (delq nil
19785 (mapcar
19786 (lambda (x)
19787 (cond ((stringp (cdr x)) nil)
19788 ((stringp (nth 1 x)) x)
19789 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19790 (t (cons (car x) (cons "" (cdr x))))))
19791 cmds)))
19793 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19794 "The user interface for selecting an agenda command."
19795 (catch 'exit
19796 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19797 (restrict-ok (and bfn (org-mode-p)))
19798 (region-p (org-region-active-p))
19799 (custom org-agenda-custom-commands)
19800 (selstring "")
19801 restriction second-time
19802 c entry key type match prefixes rmheader header-end custom1 desc)
19803 (save-window-excursion
19804 (delete-other-windows)
19805 (org-switch-to-buffer-other-window " *Agenda Commands*")
19806 (erase-buffer)
19807 (insert (eval-when-compile
19808 (let ((header
19810 Press key for an agenda command: < Buffer,subtree/region restriction
19811 -------------------------------- > Remove restriction
19812 a Agenda for current week or day e Export agenda views
19813 t List of all TODO entries T Entries with special TODO kwd
19814 m Match a TAGS query M Like m, but only TODO entries
19815 L Timeline for current buffer # List stuck projects (!=configure)
19816 s Search for keywords C Configure custom agenda commands
19817 / Multi-occur
19819 (start 0))
19820 (while (string-match
19821 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19822 header start)
19823 (setq start (match-end 0))
19824 (add-text-properties (match-beginning 2) (match-end 2)
19825 '(face bold) header))
19826 header)))
19827 (setq header-end (move-marker (make-marker) (point)))
19828 (while t
19829 (setq custom1 custom)
19830 (when (eq rmheader t)
19831 (goto-line 1)
19832 (re-search-forward ":" nil t)
19833 (delete-region (match-end 0) (point-at-eol))
19834 (forward-char 1)
19835 (looking-at "-+")
19836 (delete-region (match-end 0) (point-at-eol))
19837 (move-marker header-end (match-end 0)))
19838 (goto-char header-end)
19839 (delete-region (point) (point-max))
19840 (while (setq entry (pop custom1))
19841 (setq key (car entry) desc (nth 1 entry)
19842 type (nth 2 entry) match (nth 3 entry))
19843 (if (> (length key) 1)
19844 (add-to-list 'prefixes (string-to-char key))
19845 (insert
19846 (format
19847 "\n%-4s%-14s: %s"
19848 (org-add-props (copy-sequence key)
19849 '(face bold))
19850 (cond
19851 ((string-match "\\S-" desc) desc)
19852 ((eq type 'agenda) "Agenda for current week or day")
19853 ((eq type 'alltodo) "List of all TODO entries")
19854 ((eq type 'search) "Word search")
19855 ((eq type 'stuck) "List of stuck projects")
19856 ((eq type 'todo) "TODO keyword")
19857 ((eq type 'tags) "Tags query")
19858 ((eq type 'tags-todo) "Tags (TODO)")
19859 ((eq type 'tags-tree) "Tags tree")
19860 ((eq type 'todo-tree) "TODO kwd tree")
19861 ((eq type 'occur-tree) "Occur tree")
19862 ((functionp type) (if (symbolp type)
19863 (symbol-name type)
19864 "Lambda expression"))
19865 (t "???"))
19866 (cond
19867 ((stringp match)
19868 (org-add-props match nil 'face 'org-warning))
19869 (match
19870 (format "set of %d commands" (length match)))
19871 (t ""))))))
19872 (when prefixes
19873 (mapc (lambda (x)
19874 (insert
19875 (format "\n%s %s"
19876 (org-add-props (char-to-string x)
19877 nil 'face 'bold)
19878 (or (cdr (assoc (concat selstring (char-to-string x))
19879 prefix-descriptions))
19880 "Prefix key"))))
19881 prefixes))
19882 (goto-char (point-min))
19883 (when (fboundp 'fit-window-to-buffer)
19884 (if second-time
19885 (if (not (pos-visible-in-window-p (point-max)))
19886 (fit-window-to-buffer))
19887 (setq second-time t)
19888 (fit-window-to-buffer)))
19889 (message "Press key for agenda command%s:"
19890 (if (or restrict-ok org-agenda-overriding-restriction)
19891 (if org-agenda-overriding-restriction
19892 " (restriction lock active)"
19893 (if restriction
19894 (format " (restricted to %s)" restriction)
19895 " (unrestricted)"))
19896 ""))
19897 (setq c (read-char-exclusive))
19898 (message "")
19899 (cond
19900 ((assoc (char-to-string c) custom)
19901 (setq selstring (concat selstring (char-to-string c)))
19902 (throw 'exit (cons selstring restriction)))
19903 ((memq c prefixes)
19904 (setq selstring (concat selstring (char-to-string c))
19905 prefixes nil
19906 rmheader (or rmheader t)
19907 custom (delq nil (mapcar
19908 (lambda (x)
19909 (if (or (= (length (car x)) 1)
19910 (/= (string-to-char (car x)) c))
19912 (cons (substring (car x) 1) (cdr x))))
19913 custom))))
19914 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19915 (message "Restriction is only possible in Org-mode buffers")
19916 (ding) (sit-for 1))
19917 ((eq c ?1)
19918 (org-agenda-remove-restriction-lock 'noupdate)
19919 (setq restriction 'buffer))
19920 ((eq c ?0)
19921 (org-agenda-remove-restriction-lock 'noupdate)
19922 (setq restriction (if region-p 'region 'subtree)))
19923 ((eq c ?<)
19924 (org-agenda-remove-restriction-lock 'noupdate)
19925 (setq restriction
19926 (cond
19927 ((eq restriction 'buffer)
19928 (if region-p 'region 'subtree))
19929 ((memq restriction '(subtree region))
19930 nil)
19931 (t 'buffer))))
19932 ((eq c ?>)
19933 (org-agenda-remove-restriction-lock 'noupdate)
19934 (setq restriction nil))
19935 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19936 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19937 ((and (> (length selstring) 0) (eq c ?\d))
19938 (delete-window)
19939 (org-agenda-get-restriction-and-command prefix-descriptions))
19941 ((equal c ?q) (error "Abort"))
19942 (t (error "Invalid key %c" c))))))))
19944 (defun org-run-agenda-series (name series)
19945 (org-prepare-agenda name)
19946 (let* ((org-agenda-multi t)
19947 (redo (list 'org-run-agenda-series name (list 'quote series)))
19948 (cmds (car series))
19949 (gprops (nth 1 series))
19950 match ;; The byte compiler incorrectly complains about this. Keep it!
19951 cmd type lprops)
19952 (while (setq cmd (pop cmds))
19953 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19954 (cond
19955 ((eq type 'agenda)
19956 (org-let2 gprops lprops
19957 '(call-interactively 'org-agenda-list)))
19958 ((eq type 'alltodo)
19959 (org-let2 gprops lprops
19960 '(call-interactively 'org-todo-list)))
19961 ((eq type 'search)
19962 (org-let2 gprops lprops
19963 '(org-search-view current-prefix-arg match nil)))
19964 ((eq type 'stuck)
19965 (org-let2 gprops lprops
19966 '(call-interactively 'org-agenda-list-stuck-projects)))
19967 ((eq type 'tags)
19968 (org-let2 gprops lprops
19969 '(org-tags-view current-prefix-arg match)))
19970 ((eq type 'tags-todo)
19971 (org-let2 gprops lprops
19972 '(org-tags-view '(4) match)))
19973 ((eq type 'todo)
19974 (org-let2 gprops lprops
19975 '(org-todo-list match)))
19976 ((fboundp type)
19977 (org-let2 gprops lprops
19978 '(funcall type match)))
19979 (t (error "Invalid type in command series"))))
19980 (widen)
19981 (setq org-agenda-redo-command redo)
19982 (goto-char (point-min)))
19983 (org-finalize-agenda))
19985 ;;;###autoload
19986 (defmacro org-batch-agenda (cmd-key &rest parameters)
19987 "Run an agenda command in batch mode and send the result to STDOUT.
19988 If CMD-KEY is a string of length 1, it is used as a key in
19989 `org-agenda-custom-commands' and triggers this command. If it is a
19990 longer string it is used as a tags/todo match string.
19991 Paramters are alternating variable names and values that will be bound
19992 before running the agenda command."
19993 (let (pars)
19994 (while parameters
19995 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19996 (if (> (length cmd-key) 2)
19997 (eval (list 'let (nreverse pars)
19998 (list 'org-tags-view nil cmd-key)))
19999 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20000 (set-buffer org-agenda-buffer-name)
20001 (princ (org-encode-for-stdout (buffer-string)))))
20003 (defun org-encode-for-stdout (string)
20004 (if (fboundp 'encode-coding-string)
20005 (encode-coding-string string buffer-file-coding-system)
20006 string))
20008 (defvar org-agenda-info nil)
20010 ;;;###autoload
20011 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20012 "Run an agenda command in batch mode and send the result to STDOUT.
20013 If CMD-KEY is a string of length 1, it is used as a key in
20014 `org-agenda-custom-commands' and triggers this command. If it is a
20015 longer string it is used as a tags/todo match string.
20016 Paramters are alternating variable names and values that will be bound
20017 before running the agenda command.
20019 The output gives a line for each selected agenda item. Each
20020 item is a list of comma-separated values, like this:
20022 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20024 category The category of the item
20025 head The headline, without TODO kwd, TAGS and PRIORITY
20026 type The type of the agenda entry, can be
20027 todo selected in TODO match
20028 tagsmatch selected in tags match
20029 diary imported from diary
20030 deadline a deadline on given date
20031 scheduled scheduled on given date
20032 timestamp entry has timestamp on given date
20033 closed entry was closed on given date
20034 upcoming-deadline warning about deadline
20035 past-scheduled forwarded scheduled item
20036 block entry has date block including g. date
20037 todo The todo keyword, if any
20038 tags All tags including inherited ones, separated by colons
20039 date The relevant date, like 2007-2-14
20040 time The time, like 15:00-16:50
20041 extra Sting with extra planning info
20042 priority-l The priority letter if any was given
20043 priority-n The computed numerical priority
20044 agenda-day The day in the agenda where this is listed"
20046 (let (pars)
20047 (while parameters
20048 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20049 (push (list 'org-agenda-remove-tags t) pars)
20050 (if (> (length cmd-key) 2)
20051 (eval (list 'let (nreverse pars)
20052 (list 'org-tags-view nil cmd-key)))
20053 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20054 (set-buffer org-agenda-buffer-name)
20055 (let* ((lines (org-split-string (buffer-string) "\n"))
20056 line)
20057 (while (setq line (pop lines))
20058 (catch 'next
20059 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20060 (setq org-agenda-info
20061 (org-fix-agenda-info (text-properties-at 0 line)))
20062 (princ
20063 (org-encode-for-stdout
20064 (mapconcat 'org-agenda-export-csv-mapper
20065 '(org-category txt type todo tags date time-of-day extra
20066 priority-letter priority agenda-day)
20067 ",")))
20068 (princ "\n"))))))
20070 (defun org-fix-agenda-info (props)
20071 "Make sure all properties on an agenda item have a canonical form,
20072 so the export commands can easily use it."
20073 (let (tmp re)
20074 (when (setq tmp (plist-get props 'tags))
20075 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20076 (when (setq tmp (plist-get props 'date))
20077 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20078 (let ((calendar-date-display-form '(year "-" month "-" day)))
20079 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20081 (setq tmp (calendar-date-string tmp)))
20082 (setq props (plist-put props 'date tmp)))
20083 (when (setq tmp (plist-get props 'day))
20084 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20085 (let ((calendar-date-display-form '(year "-" month "-" day)))
20086 (setq tmp (calendar-date-string tmp)))
20087 (setq props (plist-put props 'day tmp))
20088 (setq props (plist-put props 'agenda-day tmp)))
20089 (when (setq tmp (plist-get props 'txt))
20090 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20091 (plist-put props 'priority-letter (match-string 1 tmp))
20092 (setq tmp (replace-match "" t t tmp)))
20093 (when (and (setq re (plist-get props 'org-todo-regexp))
20094 (setq re (concat "\\`\\.*" re " ?"))
20095 (string-match re tmp))
20096 (plist-put props 'todo (match-string 1 tmp))
20097 (setq tmp (replace-match "" t t tmp)))
20098 (plist-put props 'txt tmp)))
20099 props)
20101 (defun org-agenda-export-csv-mapper (prop)
20102 (let ((res (plist-get org-agenda-info prop)))
20103 (setq res
20104 (cond
20105 ((not res) "")
20106 ((stringp res) res)
20107 (t (prin1-to-string res))))
20108 (while (string-match "," res)
20109 (setq res (replace-match ";" t t res)))
20110 (org-trim res)))
20113 ;;;###autoload
20114 (defun org-store-agenda-views (&rest parameters)
20115 (interactive)
20116 (eval (list 'org-batch-store-agenda-views)))
20118 ;; FIXME, why is this a macro?????
20119 ;;;###autoload
20120 (defmacro org-batch-store-agenda-views (&rest parameters)
20121 "Run all custom agenda commands that have a file argument."
20122 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20123 (pop-up-frames nil)
20124 (dir default-directory)
20125 pars cmd thiscmdkey files opts)
20126 (while parameters
20127 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20128 (setq pars (reverse pars))
20129 (save-window-excursion
20130 (while cmds
20131 (setq cmd (pop cmds)
20132 thiscmdkey (car cmd)
20133 opts (nth 4 cmd)
20134 files (nth 5 cmd))
20135 (if (stringp files) (setq files (list files)))
20136 (when files
20137 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20138 (list 'org-agenda nil thiscmdkey)))
20139 (set-buffer org-agenda-buffer-name)
20140 (while files
20141 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20142 (list 'org-write-agenda
20143 (expand-file-name (pop files) dir) t))))
20144 (and (get-buffer org-agenda-buffer-name)
20145 (kill-buffer org-agenda-buffer-name)))))))
20147 (defun org-write-agenda (file &optional nosettings)
20148 "Write the current buffer (an agenda view) as a file.
20149 Depending on the extension of the file name, plain text (.txt),
20150 HTML (.html or .htm) or Postscript (.ps) is produced.
20151 If the extension is .ics, run icalendar export over all files used
20152 to construct the agenda and limit the export to entries listed in the
20153 agenda now.
20154 If NOSETTINGS is given, do not scope the settings of
20155 `org-agenda-exporter-settings' into the export commands. This is used when
20156 the settings have already been scoped and we do not wish to overrule other,
20157 higher priority settings."
20158 (interactive "FWrite agenda to file: ")
20159 (if (not (file-writable-p file))
20160 (error "Cannot write agenda to file %s" file))
20161 (cond
20162 ((string-match "\\.html?\\'" file) (require 'htmlize))
20163 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20164 (org-let (if nosettings nil org-agenda-exporter-settings)
20165 '(save-excursion
20166 (save-window-excursion
20167 (cond
20168 ((string-match "\\.html?\\'" file)
20169 (set-buffer (htmlize-buffer (current-buffer)))
20171 (when (and org-agenda-export-html-style
20172 (string-match "<style>" org-agenda-export-html-style))
20173 ;; replace <style> section with org-agenda-export-html-style
20174 (goto-char (point-min))
20175 (kill-region (- (search-forward "<style") 6)
20176 (search-forward "</style>"))
20177 (insert org-agenda-export-html-style))
20178 (write-file file)
20179 (kill-buffer (current-buffer))
20180 (message "HTML written to %s" file))
20181 ((string-match "\\.ps\\'" file)
20182 (ps-print-buffer-with-faces file)
20183 (message "Postscript written to %s" file))
20184 ((string-match "\\.ics\\'" file)
20185 (let ((org-agenda-marker-table
20186 (org-create-marker-find-array
20187 (org-agenda-collect-markers)))
20188 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20189 (org-combined-agenda-icalendar-file file))
20190 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20192 (let ((bs (buffer-string)))
20193 (find-file file)
20194 (insert bs)
20195 (save-buffer 0)
20196 (kill-buffer (current-buffer))
20197 (message "Plain text written to %s" file))))))
20198 (set-buffer org-agenda-buffer-name)))
20200 (defun org-agenda-collect-markers ()
20201 "Collect the markers pointing to entries in the agenda buffer."
20202 (let (m markers)
20203 (save-excursion
20204 (goto-char (point-min))
20205 (while (not (eobp))
20206 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20207 (get-text-property (point) 'org-marker)))
20208 (push m markers))
20209 (beginning-of-line 2)))
20210 (nreverse markers)))
20212 (defun org-create-marker-find-array (marker-list)
20213 "Create a alist of files names with all marker positions in that file."
20214 (let (f tbl m a p)
20215 (while (setq m (pop marker-list))
20216 (setq p (marker-position m)
20217 f (buffer-file-name (or (buffer-base-buffer
20218 (marker-buffer m))
20219 (marker-buffer m))))
20220 (if (setq a (assoc f tbl))
20221 (push (marker-position m) (cdr a))
20222 (push (list f p) tbl)))
20223 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20224 tbl)))
20226 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20227 (defun org-check-agenda-marker-table ()
20228 "Check of the current entry is on the marker list."
20229 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20231 (and (setq a (assoc file org-agenda-marker-table))
20232 (save-match-data
20233 (save-excursion
20234 (org-back-to-heading t)
20235 (member (point) (cdr a)))))))
20237 (defmacro org-no-read-only (&rest body)
20238 "Inhibit read-only for BODY."
20239 `(let ((inhibit-read-only t)) ,@body))
20241 (defun org-check-for-org-mode ()
20242 "Make sure current buffer is in org-mode. Error if not."
20243 (or (org-mode-p)
20244 (error "Cannot execute org-mode agenda command on buffer in %s."
20245 major-mode)))
20247 (defun org-fit-agenda-window ()
20248 "Fit the window to the buffer size."
20249 (and (memq org-agenda-window-setup '(reorganize-frame))
20250 (fboundp 'fit-window-to-buffer)
20251 (fit-window-to-buffer
20253 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20254 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20256 ;;; Agenda file list
20258 (defun org-agenda-files (&optional unrestricted)
20259 "Get the list of agenda files.
20260 Optional UNRESTRICTED means return the full list even if a restriction
20261 is currently in place."
20262 (let ((files
20263 (cond
20264 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20265 ((stringp org-agenda-files) (org-read-agenda-file-list))
20266 ((listp org-agenda-files) org-agenda-files)
20267 (t (error "Invalid value of `org-agenda-files'")))))
20268 (setq files (apply 'append
20269 (mapcar (lambda (f)
20270 (if (file-directory-p f)
20271 (directory-files f t
20272 org-agenda-file-regexp)
20273 (list f)))
20274 files)))
20275 (if org-agenda-skip-unavailable-files
20276 (delq nil
20277 (mapcar (function
20278 (lambda (file)
20279 (and (file-readable-p file) file)))
20280 files))
20281 files))) ; `org-check-agenda-file' will remove them from the list
20283 (defun org-edit-agenda-file-list ()
20284 "Edit the list of agenda files.
20285 Depending on setup, this either uses customize to edit the variable
20286 `org-agenda-files', or it visits the file that is holding the list. In the
20287 latter case, the buffer is set up in a way that saving it automatically kills
20288 the buffer and restores the previous window configuration."
20289 (interactive)
20290 (if (stringp org-agenda-files)
20291 (let ((cw (current-window-configuration)))
20292 (find-file org-agenda-files)
20293 (org-set-local 'org-window-configuration cw)
20294 (org-add-hook 'after-save-hook
20295 (lambda ()
20296 (set-window-configuration
20297 (prog1 org-window-configuration
20298 (kill-buffer (current-buffer))))
20299 (org-install-agenda-files-menu)
20300 (message "New agenda file list installed"))
20301 nil 'local)
20302 (message "%s" (substitute-command-keys
20303 "Edit list and finish with \\[save-buffer]")))
20304 (customize-variable 'org-agenda-files)))
20306 (defun org-store-new-agenda-file-list (list)
20307 "Set new value for the agenda file list and save it correcly."
20308 (if (stringp org-agenda-files)
20309 (let ((f org-agenda-files) b)
20310 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20311 (with-temp-file f
20312 (insert (mapconcat 'identity list "\n") "\n")))
20313 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20314 (setq org-agenda-files list)
20315 (customize-save-variable 'org-agenda-files org-agenda-files))))
20317 (defun org-read-agenda-file-list ()
20318 "Read the list of agenda files from a file."
20319 (when (stringp org-agenda-files)
20320 (with-temp-buffer
20321 (insert-file-contents org-agenda-files)
20322 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20325 ;;;###autoload
20326 (defun org-cycle-agenda-files ()
20327 "Cycle through the files in `org-agenda-files'.
20328 If the current buffer visits an agenda file, find the next one in the list.
20329 If the current buffer does not, find the first agenda file."
20330 (interactive)
20331 (let* ((fs (org-agenda-files t))
20332 (files (append fs (list (car fs))))
20333 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20334 file)
20335 (unless files (error "No agenda files"))
20336 (catch 'exit
20337 (while (setq file (pop files))
20338 (if (equal (file-truename file) tcf)
20339 (when (car files)
20340 (find-file (car files))
20341 (throw 'exit t))))
20342 (find-file (car fs)))
20343 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20345 (defun org-agenda-file-to-front (&optional to-end)
20346 "Move/add the current file to the top of the agenda file list.
20347 If the file is not present in the list, it is added to the front. If it is
20348 present, it is moved there. With optional argument TO-END, add/move to the
20349 end of the list."
20350 (interactive "P")
20351 (let ((org-agenda-skip-unavailable-files nil)
20352 (file-alist (mapcar (lambda (x)
20353 (cons (file-truename x) x))
20354 (org-agenda-files t)))
20355 (ctf (file-truename buffer-file-name))
20356 x had)
20357 (setq x (assoc ctf file-alist) had x)
20359 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20360 (if to-end
20361 (setq file-alist (append (delq x file-alist) (list x)))
20362 (setq file-alist (cons x (delq x file-alist))))
20363 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20364 (org-install-agenda-files-menu)
20365 (message "File %s to %s of agenda file list"
20366 (if had "moved" "added") (if to-end "end" "front"))))
20368 (defun org-remove-file (&optional file)
20369 "Remove current file from the list of files in variable `org-agenda-files'.
20370 These are the files which are being checked for agenda entries.
20371 Optional argument FILE means, use this file instead of the current."
20372 (interactive)
20373 (let* ((org-agenda-skip-unavailable-files nil)
20374 (file (or file buffer-file-name))
20375 (true-file (file-truename file))
20376 (afile (abbreviate-file-name file))
20377 (files (delq nil (mapcar
20378 (lambda (x)
20379 (if (equal true-file
20380 (file-truename x))
20381 nil x))
20382 (org-agenda-files t)))))
20383 (if (not (= (length files) (length (org-agenda-files t))))
20384 (progn
20385 (org-store-new-agenda-file-list files)
20386 (org-install-agenda-files-menu)
20387 (message "Removed file: %s" afile))
20388 (message "File was not in list: %s (not removed)" afile))))
20390 (defun org-file-menu-entry (file)
20391 (vector file (list 'find-file file) t))
20393 (defun org-check-agenda-file (file)
20394 "Make sure FILE exists. If not, ask user what to do."
20395 (when (not (file-exists-p file))
20396 (message "non-existent file %s. [R]emove from list or [A]bort?"
20397 (abbreviate-file-name file))
20398 (let ((r (downcase (read-char-exclusive))))
20399 (cond
20400 ((equal r ?r)
20401 (org-remove-file file)
20402 (throw 'nextfile t))
20403 (t (error "Abort"))))))
20405 ;;; Agenda prepare and finalize
20407 (defvar org-agenda-multi nil) ; dynammically scoped
20408 (defvar org-agenda-buffer-name "*Org Agenda*")
20409 (defvar org-pre-agenda-window-conf nil)
20410 (defvar org-agenda-name nil)
20411 (defun org-prepare-agenda (&optional name)
20412 (setq org-todo-keywords-for-agenda nil)
20413 (setq org-done-keywords-for-agenda nil)
20414 (if org-agenda-multi
20415 (progn
20416 (setq buffer-read-only nil)
20417 (goto-char (point-max))
20418 (unless (or (bobp) org-agenda-compact-blocks)
20419 (insert "\n" (make-string (window-width) ?=) "\n"))
20420 (narrow-to-region (point) (point-max)))
20421 (org-agenda-reset-markers)
20422 (org-prepare-agenda-buffers (org-agenda-files))
20423 (setq org-todo-keywords-for-agenda
20424 (org-uniquify org-todo-keywords-for-agenda))
20425 (setq org-done-keywords-for-agenda
20426 (org-uniquify org-done-keywords-for-agenda))
20427 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20428 (awin (get-buffer-window abuf)))
20429 (cond
20430 ((equal (current-buffer) abuf) nil)
20431 (awin (select-window awin))
20432 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20433 ((equal org-agenda-window-setup 'current-window)
20434 (switch-to-buffer abuf))
20435 ((equal org-agenda-window-setup 'other-window)
20436 (org-switch-to-buffer-other-window abuf))
20437 ((equal org-agenda-window-setup 'other-frame)
20438 (switch-to-buffer-other-frame abuf))
20439 ((equal org-agenda-window-setup 'reorganize-frame)
20440 (delete-other-windows)
20441 (org-switch-to-buffer-other-window abuf))))
20442 (setq buffer-read-only nil)
20443 (erase-buffer)
20444 (org-agenda-mode)
20445 (and name (not org-agenda-name)
20446 (org-set-local 'org-agenda-name name)))
20447 (setq buffer-read-only nil))
20449 (defun org-finalize-agenda ()
20450 "Finishing touch for the agenda buffer, called just before displaying it."
20451 (unless org-agenda-multi
20452 (save-excursion
20453 (let ((inhibit-read-only t))
20454 (goto-char (point-min))
20455 (while (org-activate-bracket-links (point-max))
20456 (add-text-properties (match-beginning 0) (match-end 0)
20457 '(face org-link)))
20458 (org-agenda-align-tags)
20459 (unless org-agenda-with-colors
20460 (remove-text-properties (point-min) (point-max) '(face nil))))
20461 (if (and (boundp 'org-overriding-columns-format)
20462 org-overriding-columns-format)
20463 (org-set-local 'org-overriding-columns-format
20464 org-overriding-columns-format))
20465 (if (and (boundp 'org-agenda-view-columns-initially)
20466 org-agenda-view-columns-initially)
20467 (org-agenda-columns))
20468 (when org-agenda-fontify-priorities
20469 (org-fontify-priorities))
20470 (run-hooks 'org-finalize-agenda-hook)
20471 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20474 (defun org-fontify-priorities ()
20475 "Make highest priority lines bold, and lowest italic."
20476 (interactive)
20477 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20478 (org-delete-overlay o)))
20479 (org-overlays-in (point-min) (point-max)))
20480 (save-excursion
20481 (let ((inhibit-read-only t)
20482 b e p ov h l)
20483 (goto-char (point-min))
20484 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20485 (setq h (or (get-char-property (point) 'org-highest-priority)
20486 org-highest-priority)
20487 l (or (get-char-property (point) 'org-lowest-priority)
20488 org-lowest-priority)
20489 p (string-to-char (match-string 1))
20490 b (match-beginning 0) e (point-at-eol)
20491 ov (org-make-overlay b e))
20492 (org-overlay-put
20493 ov 'face
20494 (cond ((listp org-agenda-fontify-priorities)
20495 (cdr (assoc p org-agenda-fontify-priorities)))
20496 ((equal p l) 'italic)
20497 ((equal p h) 'bold)))
20498 (org-overlay-put ov 'org-type 'org-priority)))))
20500 (defun org-prepare-agenda-buffers (files)
20501 "Create buffers for all agenda files, protect archived trees and comments."
20502 (interactive)
20503 (let ((pa '(:org-archived t))
20504 (pc '(:org-comment t))
20505 (pall '(:org-archived t :org-comment t))
20506 (inhibit-read-only t)
20507 (rea (concat ":" org-archive-tag ":"))
20508 bmp file re)
20509 (save-excursion
20510 (save-restriction
20511 (while (setq file (pop files))
20512 (if (bufferp file)
20513 (set-buffer file)
20514 (org-check-agenda-file file)
20515 (set-buffer (org-get-agenda-file-buffer file)))
20516 (widen)
20517 (setq bmp (buffer-modified-p))
20518 (org-refresh-category-properties)
20519 (setq org-todo-keywords-for-agenda
20520 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20521 (setq org-done-keywords-for-agenda
20522 (append org-done-keywords-for-agenda org-done-keywords))
20523 (save-excursion
20524 (remove-text-properties (point-min) (point-max) pall)
20525 (when org-agenda-skip-archived-trees
20526 (goto-char (point-min))
20527 (while (re-search-forward rea nil t)
20528 (if (org-on-heading-p t)
20529 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20530 (goto-char (point-min))
20531 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20532 (while (re-search-forward re nil t)
20533 (add-text-properties
20534 (match-beginning 0) (org-end-of-subtree t) pc)))
20535 (set-buffer-modified-p bmp))))))
20537 (defvar org-agenda-skip-function nil
20538 "Function to be called at each match during agenda construction.
20539 If this function returns nil, the current match should not be skipped.
20540 Otherwise, the function must return a position from where the search
20541 should be continued.
20542 This may also be a Lisp form, it will be evaluated.
20543 Never set this variable using `setq' or so, because then it will apply
20544 to all future agenda commands. Instead, bind it with `let' to scope
20545 it dynamically into the agenda-constructing command. A good way to set
20546 it is through options in org-agenda-custom-commands.")
20548 (defun org-agenda-skip ()
20549 "Throw to `:skip' in places that should be skipped.
20550 Also moves point to the end of the skipped region, so that search can
20551 continue from there."
20552 (let ((p (point-at-bol)) to fp)
20553 (and org-agenda-skip-archived-trees
20554 (get-text-property p :org-archived)
20555 (org-end-of-subtree t)
20556 (throw :skip t))
20557 (and (get-text-property p :org-comment)
20558 (org-end-of-subtree t)
20559 (throw :skip t))
20560 (if (equal (char-after p) ?#) (throw :skip t))
20561 (when (and (or (setq fp (functionp org-agenda-skip-function))
20562 (consp org-agenda-skip-function))
20563 (setq to (save-excursion
20564 (save-match-data
20565 (if fp
20566 (funcall org-agenda-skip-function)
20567 (eval org-agenda-skip-function))))))
20568 (goto-char to)
20569 (throw :skip t))))
20571 (defvar org-agenda-markers nil
20572 "List of all currently active markers created by `org-agenda'.")
20573 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20574 "Creation time of the last agenda marker.")
20576 (defun org-agenda-new-marker (&optional pos)
20577 "Return a new agenda marker.
20578 Org-mode keeps a list of these markers and resets them when they are
20579 no longer in use."
20580 (let ((m (copy-marker (or pos (point)))))
20581 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20582 (push m org-agenda-markers)
20585 (defun org-agenda-reset-markers ()
20586 "Reset markers created by `org-agenda'."
20587 (while org-agenda-markers
20588 (move-marker (pop org-agenda-markers) nil)))
20590 (defun org-get-agenda-file-buffer (file)
20591 "Get a buffer visiting FILE. If the buffer needs to be created, add
20592 it to the list of buffers which might be released later."
20593 (let ((buf (org-find-base-buffer-visiting file)))
20594 (if buf
20595 buf ; just return it
20596 ;; Make a new buffer and remember it
20597 (setq buf (find-file-noselect file))
20598 (if buf (push buf org-agenda-new-buffers))
20599 buf)))
20601 (defun org-release-buffers (blist)
20602 "Release all buffers in list, asking the user for confirmation when needed.
20603 When a buffer is unmodified, it is just killed. When modified, it is saved
20604 \(if the user agrees) and then killed."
20605 (let (buf file)
20606 (while (setq buf (pop blist))
20607 (setq file (buffer-file-name buf))
20608 (when (and (buffer-modified-p buf)
20609 file
20610 (y-or-n-p (format "Save file %s? " file)))
20611 (with-current-buffer buf (save-buffer)))
20612 (kill-buffer buf))))
20614 (defun org-get-category (&optional pos)
20615 "Get the category applying to position POS."
20616 (get-text-property (or pos (point)) 'org-category))
20618 ;;; Agenda timeline
20620 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20622 (defun org-timeline (&optional include-all)
20623 "Show a time-sorted view of the entries in the current org file.
20624 Only entries with a time stamp of today or later will be listed. With
20625 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20626 under the current date.
20627 If the buffer contains an active region, only check the region for
20628 dates."
20629 (interactive "P")
20630 (require 'calendar)
20631 (org-compile-prefix-format 'timeline)
20632 (org-set-sorting-strategy 'timeline)
20633 (let* ((dopast t)
20634 (dotodo include-all)
20635 (doclosed org-agenda-show-log)
20636 (entry buffer-file-name)
20637 (date (calendar-current-date))
20638 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20639 (end (if (org-region-active-p) (region-end) (point-max)))
20640 (day-numbers (org-get-all-dates beg end 'no-ranges
20641 t doclosed ; always include today
20642 org-timeline-show-empty-dates))
20643 (org-deadline-warning-days 0)
20644 (org-agenda-only-exact-dates t)
20645 (today (time-to-days (current-time)))
20646 (past t)
20647 args
20648 s e rtn d emptyp)
20649 (setq org-agenda-redo-command
20650 (list 'progn
20651 (list 'org-switch-to-buffer-other-window (current-buffer))
20652 (list 'org-timeline (list 'quote include-all))))
20653 (if (not dopast)
20654 ;; Remove past dates from the list of dates.
20655 (setq day-numbers (delq nil (mapcar (lambda(x)
20656 (if (>= x today) x nil))
20657 day-numbers))))
20658 (org-prepare-agenda (concat "Timeline "
20659 (file-name-nondirectory buffer-file-name)))
20660 (if doclosed (push :closed args))
20661 (push :timestamp args)
20662 (push :deadline args)
20663 (push :scheduled args)
20664 (push :sexp args)
20665 (if dotodo (push :todo args))
20666 (while (setq d (pop day-numbers))
20667 (if (and (listp d) (eq (car d) :omitted))
20668 (progn
20669 (setq s (point))
20670 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20671 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20672 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20673 (if (and (>= d today)
20674 dopast
20675 past)
20676 (progn
20677 (setq past nil)
20678 (insert (make-string 79 ?-) "\n")))
20679 (setq date (calendar-gregorian-from-absolute d))
20680 (setq s (point))
20681 (setq rtn (and (not emptyp)
20682 (apply 'org-agenda-get-day-entries entry
20683 date args)))
20684 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20685 (progn
20686 (insert
20687 (if (stringp org-agenda-format-date)
20688 (format-time-string org-agenda-format-date
20689 (org-time-from-absolute date))
20690 (funcall org-agenda-format-date date))
20691 "\n")
20692 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20693 (put-text-property s (1- (point)) 'org-date-line t)
20694 (if (equal d today)
20695 (put-text-property s (1- (point)) 'org-today t))
20696 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20697 (put-text-property s (1- (point)) 'day d)))))
20698 (goto-char (point-min))
20699 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20700 (point-min)))
20701 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20702 (org-finalize-agenda)
20703 (setq buffer-read-only t)))
20705 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20706 "Return a list of all relevant day numbers from BEG to END buffer positions.
20707 If NO-RANGES is non-nil, include only the start and end dates of a range,
20708 not every single day in the range. If FORCE-TODAY is non-nil, make
20709 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20710 inactive time stamps (those in square brackets) are included.
20711 When EMPTY is non-nil, also include days without any entries."
20712 (let ((re (concat
20713 (if pre-re pre-re "")
20714 (if inactive org-ts-regexp-both org-ts-regexp)))
20715 dates dates1 date day day1 day2 ts1 ts2)
20716 (if force-today
20717 (setq dates (list (time-to-days (current-time)))))
20718 (save-excursion
20719 (goto-char beg)
20720 (while (re-search-forward re end t)
20721 (setq day (time-to-days (org-time-string-to-time
20722 (substring (match-string 1) 0 10))))
20723 (or (memq day dates) (push day dates)))
20724 (unless no-ranges
20725 (goto-char beg)
20726 (while (re-search-forward org-tr-regexp end t)
20727 (setq ts1 (substring (match-string 1) 0 10)
20728 ts2 (substring (match-string 2) 0 10)
20729 day1 (time-to-days (org-time-string-to-time ts1))
20730 day2 (time-to-days (org-time-string-to-time ts2)))
20731 (while (< (setq day1 (1+ day1)) day2)
20732 (or (memq day1 dates) (push day1 dates)))))
20733 (setq dates (sort dates '<))
20734 (when empty
20735 (while (setq day (pop dates))
20736 (setq day2 (car dates))
20737 (push day dates1)
20738 (when (and day2 empty)
20739 (if (or (eq empty t)
20740 (and (numberp empty) (<= (- day2 day) empty)))
20741 (while (< (setq day (1+ day)) day2)
20742 (push (list day) dates1))
20743 (push (cons :omitted (- day2 day)) dates1))))
20744 (setq dates (nreverse dates1)))
20745 dates)))
20747 ;;; Agenda Daily/Weekly
20749 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20750 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20751 (defvar org-agenda-last-arguments nil
20752 "The arguments of the previous call to org-agenda")
20753 (defvar org-starting-day nil) ; local variable in the agenda buffer
20754 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20755 (defvar org-include-all-loc nil) ; local variable
20756 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20758 ;;;###autoload
20759 (defun org-agenda-list (&optional include-all start-day ndays)
20760 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20761 The view will be for the current day or week, but from the overview buffer
20762 you will be able to go to other days/weeks.
20764 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20765 all unfinished TODO items will also be shown, before the agenda.
20766 This feature is considered obsolete, please use the TODO list or a block
20767 agenda instead.
20769 With a numeric prefix argument in an interactive call, the agenda will
20770 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20771 the number of days. NDAYS defaults to `org-agenda-ndays'.
20773 START-DAY defaults to TODAY, or to the most recent match for the weekday
20774 given in `org-agenda-start-on-weekday'."
20775 (interactive "P")
20776 (if (and (integerp include-all) (> include-all 0))
20777 (setq ndays include-all include-all nil))
20778 (setq ndays (or ndays org-agenda-ndays)
20779 start-day (or start-day org-agenda-start-day))
20780 (if org-agenda-overriding-arguments
20781 (setq include-all (car org-agenda-overriding-arguments)
20782 start-day (nth 1 org-agenda-overriding-arguments)
20783 ndays (nth 2 org-agenda-overriding-arguments)))
20784 (if (stringp start-day)
20785 ;; Convert to an absolute day number
20786 (setq start-day (time-to-days (org-read-date nil t start-day))))
20787 (setq org-agenda-last-arguments (list include-all start-day ndays))
20788 (org-compile-prefix-format 'agenda)
20789 (org-set-sorting-strategy 'agenda)
20790 (require 'calendar)
20791 (let* ((org-agenda-start-on-weekday
20792 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20793 org-agenda-start-on-weekday nil))
20794 (thefiles (org-agenda-files))
20795 (files thefiles)
20796 (today (time-to-days
20797 (time-subtract (current-time)
20798 (list 0 (* 3600 org-extend-today-until) 0))))
20799 (sd (or start-day today))
20800 (start (if (or (null org-agenda-start-on-weekday)
20801 (< org-agenda-ndays 7))
20803 (let* ((nt (calendar-day-of-week
20804 (calendar-gregorian-from-absolute sd)))
20805 (n1 org-agenda-start-on-weekday)
20806 (d (- nt n1)))
20807 (- sd (+ (if (< d 0) 7 0) d)))))
20808 (day-numbers (list start))
20809 (day-cnt 0)
20810 (inhibit-redisplay (not debug-on-error))
20811 s e rtn rtnall file date d start-pos end-pos todayp nd)
20812 (setq org-agenda-redo-command
20813 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20814 ;; Make the list of days
20815 (setq ndays (or ndays org-agenda-ndays)
20816 nd ndays)
20817 (while (> ndays 1)
20818 (push (1+ (car day-numbers)) day-numbers)
20819 (setq ndays (1- ndays)))
20820 (setq day-numbers (nreverse day-numbers))
20821 (org-prepare-agenda "Day/Week")
20822 (org-set-local 'org-starting-day (car day-numbers))
20823 (org-set-local 'org-include-all-loc include-all)
20824 (org-set-local 'org-agenda-span
20825 (org-agenda-ndays-to-span nd))
20826 (when (and (or include-all org-agenda-include-all-todo)
20827 (member today day-numbers))
20828 (setq files thefiles
20829 rtnall nil)
20830 (while (setq file (pop files))
20831 (catch 'nextfile
20832 (org-check-agenda-file file)
20833 (setq date (calendar-gregorian-from-absolute today)
20834 rtn (org-agenda-get-day-entries
20835 file date :todo))
20836 (setq rtnall (append rtnall rtn))))
20837 (when rtnall
20838 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20839 (add-text-properties (point-min) (1- (point))
20840 (list 'face 'org-agenda-structure))
20841 (insert (org-finalize-agenda-entries rtnall) "\n")))
20842 (unless org-agenda-compact-blocks
20843 (let* ((d1 (car day-numbers))
20844 (d2 (org-last day-numbers))
20845 (w1 (org-days-to-iso-week d1))
20846 (w2 (org-days-to-iso-week d2)))
20847 (setq s (point))
20848 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20849 "-agenda"
20850 (if (< (- d2 d1) 350)
20851 (if (= w1 w2)
20852 (format " (W%02d)" w1)
20853 (format " (W%02d-W%02d)" w1 w2))
20855 ":\n"))
20856 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20857 'org-date-line t)))
20858 (while (setq d (pop day-numbers))
20859 (setq date (calendar-gregorian-from-absolute d)
20860 s (point))
20861 (if (or (setq todayp (= d today))
20862 (and (not start-pos) (= d sd)))
20863 (setq start-pos (point))
20864 (if (and start-pos (not end-pos))
20865 (setq end-pos (point))))
20866 (setq files thefiles
20867 rtnall nil)
20868 (while (setq file (pop files))
20869 (catch 'nextfile
20870 (org-check-agenda-file file)
20871 (if org-agenda-show-log
20872 (setq rtn (org-agenda-get-day-entries
20873 file date
20874 :deadline :scheduled :timestamp :sexp :closed))
20875 (setq rtn (org-agenda-get-day-entries
20876 file date
20877 :deadline :scheduled :sexp :timestamp)))
20878 (setq rtnall (append rtnall rtn))))
20879 (if org-agenda-include-diary
20880 (progn
20881 (require 'diary-lib)
20882 (setq rtn (org-get-entries-from-diary date))
20883 (setq rtnall (append rtnall rtn))))
20884 (if (or rtnall org-agenda-show-all-dates)
20885 (progn
20886 (setq day-cnt (1+ day-cnt))
20887 (insert
20888 (if (stringp org-agenda-format-date)
20889 (format-time-string org-agenda-format-date
20890 (org-time-from-absolute date))
20891 (funcall org-agenda-format-date date))
20892 "\n")
20893 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20894 (put-text-property s (1- (point)) 'org-date-line t)
20895 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20896 (if todayp (put-text-property s (1- (point)) 'org-today t))
20897 (if rtnall (insert
20898 (org-finalize-agenda-entries
20899 (org-agenda-add-time-grid-maybe
20900 rtnall nd todayp))
20901 "\n"))
20902 (put-text-property s (1- (point)) 'day d)
20903 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20904 (goto-char (point-min))
20905 (org-fit-agenda-window)
20906 (unless (and (pos-visible-in-window-p (point-min))
20907 (pos-visible-in-window-p (point-max)))
20908 (goto-char (1- (point-max)))
20909 (recenter -1)
20910 (if (not (pos-visible-in-window-p (or start-pos 1)))
20911 (progn
20912 (goto-char (or start-pos 1))
20913 (recenter 1))))
20914 (goto-char (or start-pos 1))
20915 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20916 (org-finalize-agenda)
20917 (setq buffer-read-only t)
20918 (message "")))
20920 (defun org-agenda-ndays-to-span (n)
20921 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20923 ;;; Agenda word search
20925 (defvar org-agenda-search-history nil)
20926 (defvar org-todo-only nil)
20928 (defvar org-search-syntax-table nil
20929 "Special syntax table for org-mode search.
20930 In this table, we have single quotes not as word constituents, to
20931 that when \"+Ameli\" is searchd as a work, it will also match \"Ameli's\"")
20933 (defun org-search-syntax-table ()
20934 (unless org-search-syntax-table
20935 (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table))
20936 (modify-syntax-entry ?' "." org-search-syntax-table)
20937 (modify-syntax-entry ?` "." org-search-syntax-table))
20938 org-search-syntax-table)
20940 ;;;###autoload
20941 (defun org-search-view (&optional todo-only string edit-at)
20942 "Show all entries that contain words or regular expressions.
20943 If the first character of the search string is an asterisks,
20944 search only the headlines.
20946 With optional prefix argument TODO-ONLY, only consider entries that are
20947 TODO entries. The argument STRING can be used to pass a default search
20948 string into this function. If EDIT-AT is non-nil, it means that the
20949 user should get a chance to edit this string, with cursor at position
20950 EDIT-AT.
20952 The search string is broken into \"words\" by splitting at whitespace.
20953 The individual words are then interpreted as a boolean expression with
20954 logical AND. Words prefixed with a minus must not occur in the entry.
20955 Words without a prefix or prefixed with a plus must occur in the entry.
20956 Matching is case-insensitive and the words are enclosed by word delimiters.
20958 Words enclosed by curly braces are interpreted as regular expressions
20959 that must or must not match in the entry.
20961 If the search string starts with an asterisk, search only in headlines.
20962 If (possibly after the leading star) the search string starts with an
20963 exclamation mark, this also means to look at TODO entries only, an effect
20964 that can also be achieved with a prefix argument.
20966 This command searches the agenda files, and in addition the files listed
20967 in `org-agenda-text-search-extra-files'."
20968 (interactive "P")
20969 (org-compile-prefix-format 'search)
20970 (org-set-sorting-strategy 'search)
20971 (org-prepare-agenda "SEARCH")
20972 (let* ((props (list 'face nil
20973 'done-face 'org-done
20974 'org-not-done-regexp org-not-done-regexp
20975 'org-todo-regexp org-todo-regexp
20976 'mouse-face 'highlight
20977 'keymap org-agenda-keymap
20978 'help-echo (format "mouse-2 or RET jump to location")))
20979 regexp rtn rtnall files file pos
20980 marker priority category tags c neg re
20981 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20982 (unless (and (not edit-at)
20983 (stringp string)
20984 (string-match "\\S-" string))
20985 (setq string (read-string "[+-]Word/{Regexp} ...: "
20986 (cond
20987 ((integerp edit-at) (cons string edit-at))
20988 (edit-at string))
20989 'org-agenda-search-history)))
20990 (org-set-local 'org-todo-only todo-only)
20991 (setq org-agenda-redo-command
20992 (list 'org-search-view (if todo-only t nil) string
20993 '(if current-prefix-arg 1 nil)))
20994 (setq org-agenda-query-string string)
20996 (if (equal (string-to-char string) ?*)
20997 (setq hdl-only t
20998 words (substring string 1))
20999 (setq words string))
21000 (when (equal (string-to-char words) ?!)
21001 (setq todo-only t
21002 words (substring words 1)))
21003 (setq words (org-split-string words))
21004 (mapc (lambda (w)
21005 (setq c (string-to-char w))
21006 (if (equal c ?-)
21007 (setq neg t w (substring w 1))
21008 (if (equal c ?+)
21009 (setq neg nil w (substring w 1))
21010 (setq neg nil)))
21011 (if (string-match "\\`{.*}\\'" w)
21012 (setq re (substring w 1 -1))
21013 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21014 (if neg (push re regexps-) (push re regexps+)))
21015 words)
21016 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21017 (if (not regexps+)
21018 (setq regexp (concat "^" org-outline-regexp))
21019 (setq regexp (pop regexps+))
21020 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21021 regexp))))
21022 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21023 rtnall nil)
21024 (while (setq file (pop files))
21025 (setq ee nil)
21026 (catch 'nextfile
21027 (org-check-agenda-file file)
21028 (setq buffer (if (file-exists-p file)
21029 (org-get-agenda-file-buffer file)
21030 (error "No such file %s" file)))
21031 (if (not buffer)
21032 ;; If file does not exist, make sure an error message is sent
21033 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21034 file))))
21035 (with-current-buffer buffer
21036 (with-syntax-table (org-search-syntax-table)
21037 (unless (org-mode-p)
21038 (error "Agenda file %s is not in `org-mode'" file))
21039 (let ((case-fold-search t))
21040 (save-excursion
21041 (save-restriction
21042 (if org-agenda-restrict
21043 (narrow-to-region org-agenda-restrict-begin
21044 org-agenda-restrict-end)
21045 (widen))
21046 (goto-char (point-min))
21047 (unless (or (org-on-heading-p)
21048 (outline-next-heading))
21049 (throw 'nextfile t))
21050 (goto-char (max (point-min) (1- (point))))
21051 (while (re-search-forward regexp nil t)
21052 (org-back-to-heading t)
21053 (skip-chars-forward "* ")
21054 (setq beg (point-at-bol)
21055 beg1 (point)
21056 end (progn (outline-next-heading) (point)))
21057 (catch :skip
21058 (goto-char beg)
21059 (org-agenda-skip)
21060 (setq str (buffer-substring-no-properties
21061 (point-at-bol)
21062 (if hdl-only (point-at-eol) end)))
21063 (mapc (lambda (wr) (when (string-match wr str)
21064 (goto-char (1- end))
21065 (throw :skip t)))
21066 regexps-)
21067 (mapc (lambda (wr) (unless (string-match wr str)
21068 (goto-char (1- end))
21069 (throw :skip t)))
21070 (if todo-only
21071 (cons (concat "^\*+[ \t]+" org-not-done-regexp)
21072 regexps+)
21073 regexps+))
21074 (goto-char beg)
21075 (setq marker (org-agenda-new-marker (point))
21076 category (org-get-category)
21077 tags (org-get-tags-at (point))
21078 txt (org-format-agenda-item
21080 (buffer-substring-no-properties
21081 beg1 (point-at-eol))
21082 category tags))
21083 (org-add-props txt props
21084 'org-marker marker 'org-hd-marker marker
21085 'org-todo-regexp org-todo-regexp
21086 'priority 1000 'org-category category
21087 'type "search")
21088 (push txt ee)
21089 (goto-char (1- end))))))))))
21090 (setq rtn (nreverse ee))
21091 (setq rtnall (append rtnall rtn)))
21092 (if org-agenda-overriding-header
21093 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21094 nil 'face 'org-agenda-structure) "\n")
21095 (insert "Search words: ")
21096 (add-text-properties (point-min) (1- (point))
21097 (list 'face 'org-agenda-structure))
21098 (setq pos (point))
21099 (insert string "\n")
21100 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21101 (setq pos (point))
21102 (unless org-agenda-multi
21103 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21104 (add-text-properties pos (1- (point))
21105 (list 'face 'org-agenda-structure))))
21106 (when rtnall
21107 (insert (org-finalize-agenda-entries rtnall) "\n"))
21108 (goto-char (point-min))
21109 (org-fit-agenda-window)
21110 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21111 (org-finalize-agenda)
21112 (setq buffer-read-only t)))
21114 ;;; Agenda TODO list
21116 (defvar org-select-this-todo-keyword nil)
21117 (defvar org-last-arg nil)
21119 ;;;###autoload
21120 (defun org-todo-list (arg)
21121 "Show all TODO entries from all agenda file in a single list.
21122 The prefix arg can be used to select a specific TODO keyword and limit
21123 the list to these. When using \\[universal-argument], you will be prompted
21124 for a keyword. A numeric prefix directly selects the Nth keyword in
21125 `org-todo-keywords-1'."
21126 (interactive "P")
21127 (require 'calendar)
21128 (org-compile-prefix-format 'todo)
21129 (org-set-sorting-strategy 'todo)
21130 (org-prepare-agenda "TODO")
21131 (let* ((today (time-to-days (current-time)))
21132 (date (calendar-gregorian-from-absolute today))
21133 (kwds org-todo-keywords-for-agenda)
21134 (completion-ignore-case t)
21135 (org-select-this-todo-keyword
21136 (if (stringp arg) arg
21137 (and arg (integerp arg) (> arg 0)
21138 (nth (1- arg) kwds))))
21139 rtn rtnall files file pos)
21140 (when (equal arg '(4))
21141 (setq org-select-this-todo-keyword
21142 (completing-read "Keyword (or KWD1|K2D2|...): "
21143 (mapcar 'list kwds) nil nil)))
21144 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21145 (org-set-local 'org-last-arg arg)
21146 (setq org-agenda-redo-command
21147 '(org-todo-list (or current-prefix-arg org-last-arg)))
21148 (setq files (org-agenda-files)
21149 rtnall nil)
21150 (while (setq file (pop files))
21151 (catch 'nextfile
21152 (org-check-agenda-file file)
21153 (setq rtn (org-agenda-get-day-entries file date :todo))
21154 (setq rtnall (append rtnall rtn))))
21155 (if org-agenda-overriding-header
21156 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21157 nil 'face 'org-agenda-structure) "\n")
21158 (insert "Global list of TODO items of type: ")
21159 (add-text-properties (point-min) (1- (point))
21160 (list 'face 'org-agenda-structure))
21161 (setq pos (point))
21162 (insert (or org-select-this-todo-keyword "ALL") "\n")
21163 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21164 (setq pos (point))
21165 (unless org-agenda-multi
21166 (insert "Available with `N r': (0)ALL")
21167 (let ((n 0) s)
21168 (mapc (lambda (x)
21169 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21170 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21171 (insert "\n "))
21172 (insert " " s))
21173 kwds))
21174 (insert "\n"))
21175 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21176 (when rtnall
21177 (insert (org-finalize-agenda-entries rtnall) "\n"))
21178 (goto-char (point-min))
21179 (org-fit-agenda-window)
21180 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21181 (org-finalize-agenda)
21182 (setq buffer-read-only t)))
21184 ;;; Agenda tags match
21186 ;;;###autoload
21187 (defun org-tags-view (&optional todo-only match)
21188 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21189 The prefix arg TODO-ONLY limits the search to TODO entries."
21190 (interactive "P")
21191 (org-compile-prefix-format 'tags)
21192 (org-set-sorting-strategy 'tags)
21193 (let* ((org-tags-match-list-sublevels
21194 (if todo-only t org-tags-match-list-sublevels))
21195 (completion-ignore-case t)
21196 rtn rtnall files file pos matcher
21197 buffer)
21198 (setq matcher (org-make-tags-matcher match)
21199 match (car matcher) matcher (cdr matcher))
21200 (org-prepare-agenda (concat "TAGS " match))
21201 (setq org-agenda-query-string match)
21202 (setq org-agenda-redo-command
21203 (list 'org-tags-view (list 'quote todo-only)
21204 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21205 (setq files (org-agenda-files)
21206 rtnall nil)
21207 (while (setq file (pop files))
21208 (catch 'nextfile
21209 (org-check-agenda-file file)
21210 (setq buffer (if (file-exists-p file)
21211 (org-get-agenda-file-buffer file)
21212 (error "No such file %s" file)))
21213 (if (not buffer)
21214 ;; If file does not exist, merror message to agenda
21215 (setq rtn (list
21216 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21217 rtnall (append rtnall rtn))
21218 (with-current-buffer buffer
21219 (unless (org-mode-p)
21220 (error "Agenda file %s is not in `org-mode'" file))
21221 (save-excursion
21222 (save-restriction
21223 (if org-agenda-restrict
21224 (narrow-to-region org-agenda-restrict-begin
21225 org-agenda-restrict-end)
21226 (widen))
21227 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21228 (setq rtnall (append rtnall rtn))))))))
21229 (if org-agenda-overriding-header
21230 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21231 nil 'face 'org-agenda-structure) "\n")
21232 (insert "Headlines with TAGS match: ")
21233 (add-text-properties (point-min) (1- (point))
21234 (list 'face 'org-agenda-structure))
21235 (setq pos (point))
21236 (insert match "\n")
21237 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21238 (setq pos (point))
21239 (unless org-agenda-multi
21240 (insert "Press `C-u r' to search again with new search string\n"))
21241 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21242 (when rtnall
21243 (insert (org-finalize-agenda-entries rtnall) "\n"))
21244 (goto-char (point-min))
21245 (org-fit-agenda-window)
21246 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21247 (org-finalize-agenda)
21248 (setq buffer-read-only t)))
21250 ;;; Agenda Finding stuck projects
21252 (defvar org-agenda-skip-regexp nil
21253 "Regular expression used in skipping subtrees for the agenda.
21254 This is basically a temporary global variable that can be set and then
21255 used by user-defined selections using `org-agenda-skip-function'.")
21257 (defvar org-agenda-overriding-header nil
21258 "When this is set during todo and tags searches, will replace header.")
21260 (defun org-agenda-skip-subtree-when-regexp-matches ()
21261 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21262 If yes, it returns the end position of this tree, causing agenda commands
21263 to skip this subtree. This is a function that can be put into
21264 `org-agenda-skip-function' for the duration of a command."
21265 (let ((end (save-excursion (org-end-of-subtree t)))
21266 skip)
21267 (save-excursion
21268 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21269 (and skip end)))
21271 (defun org-agenda-skip-entry-if (&rest conditions)
21272 "Skip entry if any of CONDITIONS is true.
21273 See `org-agenda-skip-if' for details."
21274 (org-agenda-skip-if nil conditions))
21276 (defun org-agenda-skip-subtree-if (&rest conditions)
21277 "Skip entry if any of CONDITIONS is true.
21278 See `org-agenda-skip-if' for details."
21279 (org-agenda-skip-if t conditions))
21281 (defun org-agenda-skip-if (subtree conditions)
21282 "Checks current entity for CONDITIONS.
21283 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21284 the entry, i.e. the text before the next heading is checked.
21286 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21287 from different tests. Valid conditions are:
21289 scheduled Check if there is a scheduled cookie
21290 notscheduled Check if there is no scheduled cookie
21291 deadline Check if there is a deadline
21292 notdeadline Check if there is no deadline
21293 regexp Check if regexp matches
21294 notregexp Check if regexp does not match.
21296 The regexp is taken from the conditions list, it must come right after
21297 the `regexp' or `notregexp' element.
21299 If any of these conditions is met, this function returns the end point of
21300 the entity, causing the search to continue from there. This is a function
21301 that can be put into `org-agenda-skip-function' for the duration of a command."
21302 (let (beg end m)
21303 (org-back-to-heading t)
21304 (setq beg (point)
21305 end (if subtree
21306 (progn (org-end-of-subtree t) (point))
21307 (progn (outline-next-heading) (1- (point)))))
21308 (goto-char beg)
21309 (and
21311 (and (memq 'scheduled conditions)
21312 (re-search-forward org-scheduled-time-regexp end t))
21313 (and (memq 'notscheduled conditions)
21314 (not (re-search-forward org-scheduled-time-regexp end t)))
21315 (and (memq 'deadline conditions)
21316 (re-search-forward org-deadline-time-regexp end t))
21317 (and (memq 'notdeadline conditions)
21318 (not (re-search-forward org-deadline-time-regexp end t)))
21319 (and (setq m (memq 'regexp conditions))
21320 (stringp (nth 1 m))
21321 (re-search-forward (nth 1 m) end t))
21322 (and (setq m (memq 'notregexp conditions))
21323 (stringp (nth 1 m))
21324 (not (re-search-forward (nth 1 m) end t))))
21325 end)))
21327 ;;;###autoload
21328 (defun org-agenda-list-stuck-projects (&rest ignore)
21329 "Create agenda view for projects that are stuck.
21330 Stuck projects are project that have no next actions. For the definitions
21331 of what a project is and how to check if it stuck, customize the variable
21332 `org-stuck-projects'.
21333 MATCH is being ignored."
21334 (interactive)
21335 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21336 ;; FIXME: we could have used org-agenda-skip-if here.
21337 (org-agenda-overriding-header "List of stuck projects: ")
21338 (matcher (nth 0 org-stuck-projects))
21339 (todo (nth 1 org-stuck-projects))
21340 (todo-wds (if (member "*" todo)
21341 (progn
21342 (org-prepare-agenda-buffers (org-agenda-files))
21343 (org-delete-all
21344 org-done-keywords-for-agenda
21345 (copy-sequence org-todo-keywords-for-agenda)))
21346 todo))
21347 (todo-re (concat "^\\*+[ \t]+\\("
21348 (mapconcat 'identity todo-wds "\\|")
21349 "\\)\\>"))
21350 (tags (nth 2 org-stuck-projects))
21351 (tags-re (if (member "*" tags)
21352 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21353 (concat "^\\*+ .*:\\("
21354 (mapconcat 'identity tags "\\|")
21355 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21356 (gen-re (nth 3 org-stuck-projects))
21357 (re-list
21358 (delq nil
21359 (list
21360 (if todo todo-re)
21361 (if tags tags-re)
21362 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21363 gen-re)))))
21364 (setq org-agenda-skip-regexp
21365 (if re-list
21366 (mapconcat 'identity re-list "\\|")
21367 (error "No information how to identify unstuck projects")))
21368 (org-tags-view nil matcher)
21369 (with-current-buffer org-agenda-buffer-name
21370 (setq org-agenda-redo-command
21371 '(org-agenda-list-stuck-projects
21372 (or current-prefix-arg org-last-arg))))))
21374 ;;; Diary integration
21376 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21377 (defvar list-diary-entries-hook)
21379 (defun org-get-entries-from-diary (date)
21380 "Get the (Emacs Calendar) diary entries for DATE."
21381 (require 'diary-lib)
21382 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21383 (diary-display-hook '(fancy-diary-display))
21384 (pop-up-frames nil)
21385 (list-diary-entries-hook
21386 (cons 'org-diary-default-entry list-diary-entries-hook))
21387 (diary-file-name-prefix-function nil) ; turn this feature off
21388 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21389 entries
21390 (org-disable-agenda-to-diary t))
21391 (save-excursion
21392 (save-window-excursion
21393 (funcall (if (fboundp 'diary-list-entries)
21394 'diary-list-entries 'list-diary-entries)
21395 date 1)))
21396 (if (not (get-buffer fancy-diary-buffer))
21397 (setq entries nil)
21398 (with-current-buffer fancy-diary-buffer
21399 (setq buffer-read-only nil)
21400 (if (zerop (buffer-size))
21401 ;; No entries
21402 (setq entries nil)
21403 ;; Omit the date and other unnecessary stuff
21404 (org-agenda-cleanup-fancy-diary)
21405 ;; Add prefix to each line and extend the text properties
21406 (if (zerop (buffer-size))
21407 (setq entries nil)
21408 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21409 (set-buffer-modified-p nil)
21410 (kill-buffer fancy-diary-buffer)))
21411 (when entries
21412 (setq entries (org-split-string entries "\n"))
21413 (setq entries
21414 (mapcar
21415 (lambda (x)
21416 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21417 ;; Extend the text properties to the beginning of the line
21418 (org-add-props x (text-properties-at (1- (length x)) x)
21419 'type "diary" 'date date))
21420 entries)))))
21422 (defun org-agenda-cleanup-fancy-diary ()
21423 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21424 This gets rid of the date, the underline under the date, and
21425 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21426 date. It also removes lines that contain only whitespace."
21427 (goto-char (point-min))
21428 (if (looking-at ".*?:[ \t]*")
21429 (progn
21430 (replace-match "")
21431 (re-search-forward "\n=+$" nil t)
21432 (replace-match "")
21433 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21434 (re-search-forward "\n=+$" nil t)
21435 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21436 (goto-char (point-min))
21437 (while (re-search-forward "^ +\n" nil t)
21438 (replace-match ""))
21439 (goto-char (point-min))
21440 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21441 (replace-match "")))
21443 ;; Make sure entries from the diary have the right text properties.
21444 (eval-after-load "diary-lib"
21445 '(if (boundp 'diary-modify-entry-list-string-function)
21446 ;; We can rely on the hook, nothing to do
21448 ;; Hook not avaiable, must use advice to make this work
21449 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21450 "Make the position visible."
21451 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21452 (stringp string)
21453 buffer-file-name)
21454 (setq string (org-modify-diary-entry-string string))))))
21456 (defun org-modify-diary-entry-string (string)
21457 "Add text properties to string, allowing org-mode to act on it."
21458 (org-add-props string nil
21459 'mouse-face 'highlight
21460 'keymap org-agenda-keymap
21461 'help-echo (if buffer-file-name
21462 (format "mouse-2 or RET jump to diary file %s"
21463 (abbreviate-file-name buffer-file-name))
21465 'org-agenda-diary-link t
21466 'org-marker (org-agenda-new-marker (point-at-bol))))
21468 (defun org-diary-default-entry ()
21469 "Add a dummy entry to the diary.
21470 Needed to avoid empty dates which mess up holiday display."
21471 ;; Catch the error if dealing with the new add-to-diary-alist
21472 (when org-disable-agenda-to-diary
21473 (condition-case nil
21474 (add-to-diary-list original-date "Org-mode dummy" "")
21475 (error
21476 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21478 ;;;###autoload
21479 (defun org-diary (&rest args)
21480 "Return diary information from org-files.
21481 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21482 It accesses org files and extracts information from those files to be
21483 listed in the diary. The function accepts arguments specifying what
21484 items should be listed. The following arguments are allowed:
21486 :timestamp List the headlines of items containing a date stamp or
21487 date range matching the selected date. Deadlines will
21488 also be listed, on the expiration day.
21490 :sexp List entries resulting from diary-like sexps.
21492 :deadline List any deadlines past due, or due within
21493 `org-deadline-warning-days'. The listing occurs only
21494 in the diary for *today*, not at any other date. If
21495 an entry is marked DONE, it is no longer listed.
21497 :scheduled List all items which are scheduled for the given date.
21498 The diary for *today* also contains items which were
21499 scheduled earlier and are not yet marked DONE.
21501 :todo List all TODO items from the org-file. This may be a
21502 long list - so this is not turned on by default.
21503 Like deadlines, these entries only show up in the
21504 diary for *today*, not at any other date.
21506 The call in the diary file should look like this:
21508 &%%(org-diary) ~/path/to/some/orgfile.org
21510 Use a separate line for each org file to check. Or, if you omit the file name,
21511 all files listed in `org-agenda-files' will be checked automatically:
21513 &%%(org-diary)
21515 If you don't give any arguments (as in the example above), the default
21516 arguments (:deadline :scheduled :timestamp :sexp) are used.
21517 So the example above may also be written as
21519 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21521 The function expects the lisp variables `entry' and `date' to be provided
21522 by the caller, because this is how the calendar works. Don't use this
21523 function from a program - use `org-agenda-get-day-entries' instead."
21524 (when (> (- (time-to-seconds (current-time))
21525 org-agenda-last-marker-time)
21527 (org-agenda-reset-markers))
21528 (org-compile-prefix-format 'agenda)
21529 (org-set-sorting-strategy 'agenda)
21530 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21531 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21532 (list entry)
21533 (org-agenda-files t)))
21534 file rtn results)
21535 (org-prepare-agenda-buffers files)
21536 ;; If this is called during org-agenda, don't return any entries to
21537 ;; the calendar. Org Agenda will list these entries itself.
21538 (if org-disable-agenda-to-diary (setq files nil))
21539 (while (setq file (pop files))
21540 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21541 (setq results (append results rtn)))
21542 (if results
21543 (concat (org-finalize-agenda-entries results) "\n"))))
21545 ;;; Agenda entry finders
21547 (defun org-agenda-get-day-entries (file date &rest args)
21548 "Does the work for `org-diary' and `org-agenda'.
21549 FILE is the path to a file to be checked for entries. DATE is date like
21550 the one returned by `calendar-current-date'. ARGS are symbols indicating
21551 which kind of entries should be extracted. For details about these, see
21552 the documentation of `org-diary'."
21553 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21554 (let* ((org-startup-folded nil)
21555 (org-startup-align-all-tables nil)
21556 (buffer (if (file-exists-p file)
21557 (org-get-agenda-file-buffer file)
21558 (error "No such file %s" file)))
21559 arg results rtn)
21560 (if (not buffer)
21561 ;; If file does not exist, make sure an error message ends up in diary
21562 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21563 (with-current-buffer buffer
21564 (unless (org-mode-p)
21565 (error "Agenda file %s is not in `org-mode'" file))
21566 (let ((case-fold-search nil))
21567 (save-excursion
21568 (save-restriction
21569 (if org-agenda-restrict
21570 (narrow-to-region org-agenda-restrict-begin
21571 org-agenda-restrict-end)
21572 (widen))
21573 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21574 (while (setq arg (pop args))
21575 (cond
21576 ((and (eq arg :todo)
21577 (equal date (calendar-current-date)))
21578 (setq rtn (org-agenda-get-todos))
21579 (setq results (append results rtn)))
21580 ((eq arg :timestamp)
21581 (setq rtn (org-agenda-get-blocks))
21582 (setq results (append results rtn))
21583 (setq rtn (org-agenda-get-timestamps))
21584 (setq results (append results rtn)))
21585 ((eq arg :sexp)
21586 (setq rtn (org-agenda-get-sexps))
21587 (setq results (append results rtn)))
21588 ((eq arg :scheduled)
21589 (setq rtn (org-agenda-get-scheduled))
21590 (setq results (append results rtn)))
21591 ((eq arg :closed)
21592 (setq rtn (org-agenda-get-closed))
21593 (setq results (append results rtn)))
21594 ((eq arg :deadline)
21595 (setq rtn (org-agenda-get-deadlines))
21596 (setq results (append results rtn))))))))
21597 results))))
21599 (defun org-entry-is-todo-p ()
21600 (member (org-get-todo-state) org-not-done-keywords))
21602 (defun org-entry-is-done-p ()
21603 (member (org-get-todo-state) org-done-keywords))
21605 (defun org-get-todo-state ()
21606 (save-excursion
21607 (org-back-to-heading t)
21608 (and (looking-at org-todo-line-regexp)
21609 (match-end 2)
21610 (match-string 2))))
21612 (defun org-at-date-range-p (&optional inactive-ok)
21613 "Is the cursor inside a date range?"
21614 (interactive)
21615 (save-excursion
21616 (catch 'exit
21617 (let ((pos (point)))
21618 (skip-chars-backward "^[<\r\n")
21619 (skip-chars-backward "<[")
21620 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21621 (>= (match-end 0) pos)
21622 (throw 'exit t))
21623 (skip-chars-backward "^<[\r\n")
21624 (skip-chars-backward "<[")
21625 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21626 (>= (match-end 0) pos)
21627 (throw 'exit t)))
21628 nil)))
21630 (defun org-agenda-get-todos ()
21631 "Return the TODO information for agenda display."
21632 (let* ((props (list 'face nil
21633 'done-face 'org-done
21634 'org-not-done-regexp org-not-done-regexp
21635 'org-todo-regexp org-todo-regexp
21636 'mouse-face 'highlight
21637 'keymap org-agenda-keymap
21638 'help-echo
21639 (format "mouse-2 or RET jump to org file %s"
21640 (abbreviate-file-name buffer-file-name))))
21641 ;; FIXME: get rid of the \n at some point but watch out
21642 (regexp (concat "^\\*+[ \t]+\\("
21643 (if org-select-this-todo-keyword
21644 (if (equal org-select-this-todo-keyword "*")
21645 org-todo-regexp
21646 (concat "\\<\\("
21647 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21648 "\\)\\>"))
21649 org-not-done-regexp)
21650 "[^\n\r]*\\)"))
21651 marker priority category tags
21652 ee txt beg end)
21653 (goto-char (point-min))
21654 (while (re-search-forward regexp nil t)
21655 (catch :skip
21656 (save-match-data
21657 (beginning-of-line)
21658 (setq beg (point) end (progn (outline-next-heading) (point)))
21659 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21660 (re-search-forward org-ts-regexp end t))
21661 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21662 (re-search-forward org-scheduled-time-regexp end t))
21663 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21664 (re-search-forward org-deadline-time-regexp end t)
21665 (org-deadline-close (match-string 1))))
21666 (goto-char (1+ beg))
21667 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21668 (throw :skip nil)))
21669 (goto-char beg)
21670 (org-agenda-skip)
21671 (goto-char (match-beginning 1))
21672 (setq marker (org-agenda-new-marker (match-beginning 0))
21673 category (org-get-category)
21674 tags (org-get-tags-at (point))
21675 txt (org-format-agenda-item "" (match-string 1) category tags)
21676 priority (1+ (org-get-priority txt)))
21677 (org-add-props txt props
21678 'org-marker marker 'org-hd-marker marker
21679 'priority priority 'org-category category
21680 'type "todo")
21681 (push txt ee)
21682 (if org-agenda-todo-list-sublevels
21683 (goto-char (match-end 1))
21684 (org-end-of-subtree 'invisible))))
21685 (nreverse ee)))
21687 (defconst org-agenda-no-heading-message
21688 "No heading for this item in buffer or region.")
21690 (defun org-agenda-get-timestamps ()
21691 "Return the date stamp information for agenda display."
21692 (let* ((props (list 'face nil
21693 'org-not-done-regexp org-not-done-regexp
21694 'org-todo-regexp org-todo-regexp
21695 'mouse-face 'highlight
21696 'keymap org-agenda-keymap
21697 'help-echo
21698 (format "mouse-2 or RET jump to org file %s"
21699 (abbreviate-file-name buffer-file-name))))
21700 (d1 (calendar-absolute-from-gregorian date))
21701 (remove-re
21702 (concat
21703 (regexp-quote
21704 (format-time-string
21705 "<%Y-%m-%d"
21706 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21707 ".*?>"))
21708 (regexp
21709 (concat
21710 (regexp-quote
21711 (substring
21712 (format-time-string
21713 (car org-time-stamp-formats)
21714 (apply 'encode-time ; DATE bound by calendar
21715 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21716 0 11))
21717 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21718 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21719 marker hdmarker deadlinep scheduledp donep tmp priority category
21720 ee txt timestr tags b0 b3 e3 head)
21721 (goto-char (point-min))
21722 (while (re-search-forward regexp nil t)
21723 (setq b0 (match-beginning 0)
21724 b3 (match-beginning 3) e3 (match-end 3))
21725 (catch :skip
21726 (and (org-at-date-range-p) (throw :skip nil))
21727 (org-agenda-skip)
21728 (if (and (match-end 1)
21729 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21730 (throw :skip nil))
21731 (if (and e3
21732 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21733 (throw :skip nil))
21734 (setq marker (org-agenda-new-marker b0)
21735 category (org-get-category b0)
21736 tmp (buffer-substring (max (point-min)
21737 (- b0 org-ds-keyword-length))
21739 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21740 deadlinep (string-match org-deadline-regexp tmp)
21741 scheduledp (string-match org-scheduled-regexp tmp)
21742 donep (org-entry-is-done-p))
21743 (if (or scheduledp deadlinep) (throw :skip t))
21744 (if (string-match ">" timestr)
21745 ;; substring should only run to end of time stamp
21746 (setq timestr (substring timestr 0 (match-end 0))))
21747 (save-excursion
21748 (if (re-search-backward "^\\*+ " nil t)
21749 (progn
21750 (goto-char (match-beginning 0))
21751 (setq hdmarker (org-agenda-new-marker)
21752 tags (org-get-tags-at))
21753 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21754 (setq head (match-string 1))
21755 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21756 (setq txt (org-format-agenda-item
21757 nil head category tags timestr nil
21758 remove-re)))
21759 (setq txt org-agenda-no-heading-message))
21760 (setq priority (org-get-priority txt))
21761 (org-add-props txt props
21762 'org-marker marker 'org-hd-marker hdmarker)
21763 (org-add-props txt nil 'priority priority
21764 'org-category category 'date date
21765 'type "timestamp")
21766 (push txt ee))
21767 (outline-next-heading)))
21768 (nreverse ee)))
21770 (defun org-agenda-get-sexps ()
21771 "Return the sexp information for agenda display."
21772 (require 'diary-lib)
21773 (let* ((props (list 'face nil
21774 'mouse-face 'highlight
21775 'keymap org-agenda-keymap
21776 'help-echo
21777 (format "mouse-2 or RET jump to org file %s"
21778 (abbreviate-file-name buffer-file-name))))
21779 (regexp "^&?%%(")
21780 marker category ee txt tags entry result beg b sexp sexp-entry)
21781 (goto-char (point-min))
21782 (while (re-search-forward regexp nil t)
21783 (catch :skip
21784 (org-agenda-skip)
21785 (setq beg (match-beginning 0))
21786 (goto-char (1- (match-end 0)))
21787 (setq b (point))
21788 (forward-sexp 1)
21789 (setq sexp (buffer-substring b (point)))
21790 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21791 (org-trim (match-string 1))
21792 ""))
21793 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21794 (when result
21795 (setq marker (org-agenda-new-marker beg)
21796 category (org-get-category beg))
21798 (if (string-match "\\S-" result)
21799 (setq txt result)
21800 (setq txt "SEXP entry returned empty string"))
21802 (setq txt (org-format-agenda-item
21803 "" txt category tags 'time))
21804 (org-add-props txt props 'org-marker marker)
21805 (org-add-props txt nil
21806 'org-category category 'date date
21807 'type "sexp")
21808 (push txt ee))))
21809 (nreverse ee)))
21811 (defun org-agenda-get-closed ()
21812 "Return the logged TODO entries for agenda display."
21813 (let* ((props (list 'mouse-face 'highlight
21814 'org-not-done-regexp org-not-done-regexp
21815 'org-todo-regexp org-todo-regexp
21816 'keymap org-agenda-keymap
21817 'help-echo
21818 (format "mouse-2 or RET jump to org file %s"
21819 (abbreviate-file-name buffer-file-name))))
21820 (regexp (concat
21821 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21822 (regexp-quote
21823 (substring
21824 (format-time-string
21825 (car org-time-stamp-formats)
21826 (apply 'encode-time ; DATE bound by calendar
21827 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21828 1 11))))
21829 marker hdmarker priority category tags closedp
21830 ee txt timestr)
21831 (goto-char (point-min))
21832 (while (re-search-forward regexp nil t)
21833 (catch :skip
21834 (org-agenda-skip)
21835 (setq marker (org-agenda-new-marker (match-beginning 0))
21836 closedp (equal (match-string 1) org-closed-string)
21837 category (org-get-category (match-beginning 0))
21838 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21839 ;; donep (org-entry-is-done-p)
21841 (if (string-match "\\]" timestr)
21842 ;; substring should only run to end of time stamp
21843 (setq timestr (substring timestr 0 (match-end 0))))
21844 (save-excursion
21845 (if (re-search-backward "^\\*+ " nil t)
21846 (progn
21847 (goto-char (match-beginning 0))
21848 (setq hdmarker (org-agenda-new-marker)
21849 tags (org-get-tags-at))
21850 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21851 (setq txt (org-format-agenda-item
21852 (if closedp "Closed: " "Clocked: ")
21853 (match-string 1) category tags timestr)))
21854 (setq txt org-agenda-no-heading-message))
21855 (setq priority 100000)
21856 (org-add-props txt props
21857 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21858 'priority priority 'org-category category
21859 'type "closed" 'date date
21860 'undone-face 'org-warning 'done-face 'org-done)
21861 (push txt ee))
21862 (goto-char (point-at-eol))))
21863 (nreverse ee)))
21865 (defun org-agenda-get-deadlines ()
21866 "Return the deadline information for agenda display."
21867 (let* ((props (list 'mouse-face 'highlight
21868 'org-not-done-regexp org-not-done-regexp
21869 'org-todo-regexp org-todo-regexp
21870 'keymap org-agenda-keymap
21871 'help-echo
21872 (format "mouse-2 or RET jump to org file %s"
21873 (abbreviate-file-name buffer-file-name))))
21874 (regexp org-deadline-time-regexp)
21875 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21876 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21877 d2 diff dfrac wdays pos pos1 category tags
21878 ee txt head face s upcomingp donep timestr)
21879 (goto-char (point-min))
21880 (while (re-search-forward regexp nil t)
21881 (catch :skip
21882 (org-agenda-skip)
21883 (setq s (match-string 1)
21884 pos (1- (match-beginning 1))
21885 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21886 diff (- d2 d1)
21887 wdays (org-get-wdays s)
21888 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21889 upcomingp (and todayp (> diff 0)))
21890 ;; When to show a deadline in the calendar:
21891 ;; If the expiration is within wdays warning time.
21892 ;; Past-due deadlines are only shown on the current date
21893 (if (or (and (<= diff wdays)
21894 (and todayp (not org-agenda-only-exact-dates)))
21895 (= diff 0))
21896 (save-excursion
21897 (setq category (org-get-category))
21898 (if (re-search-backward "^\\*+[ \t]+" nil t)
21899 (progn
21900 (goto-char (match-end 0))
21901 (setq pos1 (match-beginning 0))
21902 (setq tags (org-get-tags-at pos1))
21903 (setq head (buffer-substring-no-properties
21904 (point)
21905 (progn (skip-chars-forward "^\r\n")
21906 (point))))
21907 (setq donep (string-match org-looking-at-done-regexp head))
21908 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21909 (setq timestr
21910 (concat (substring s (match-beginning 1)) " "))
21911 (setq timestr 'time))
21912 (if (and donep
21913 (or org-agenda-skip-deadline-if-done
21914 (not (= diff 0))))
21915 (setq txt nil)
21916 (setq txt (org-format-agenda-item
21917 (if (= diff 0)
21918 (car org-agenda-deadline-leaders)
21919 (format (nth 1 org-agenda-deadline-leaders)
21920 diff))
21921 head category tags timestr))))
21922 (setq txt org-agenda-no-heading-message))
21923 (when txt
21924 (setq face (org-agenda-deadline-face dfrac wdays))
21925 (org-add-props txt props
21926 'org-marker (org-agenda-new-marker pos)
21927 'org-hd-marker (org-agenda-new-marker pos1)
21928 'priority (+ (- diff)
21929 (org-get-priority txt))
21930 'org-category category
21931 'type (if upcomingp "upcoming-deadline" "deadline")
21932 'date (if upcomingp date d2)
21933 'face (if donep 'org-done face)
21934 'undone-face face 'done-face 'org-done)
21935 (push txt ee))))))
21936 (nreverse ee)))
21938 (defun org-agenda-deadline-face (fraction &optional wdays)
21939 "Return the face to displaying a deadline item.
21940 FRACTION is what fraction of the head-warning time has passed."
21941 (if (equal wdays 0) (setq fraction 1.))
21942 (let ((faces org-agenda-deadline-faces) f)
21943 (catch 'exit
21944 (while (setq f (pop faces))
21945 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21947 (defun org-agenda-get-scheduled ()
21948 "Return the scheduled information for agenda display."
21949 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21950 'org-todo-regexp org-todo-regexp
21951 'done-face 'org-done
21952 'mouse-face 'highlight
21953 'keymap org-agenda-keymap
21954 'help-echo
21955 (format "mouse-2 or RET jump to org file %s"
21956 (abbreviate-file-name buffer-file-name))))
21957 (regexp org-scheduled-time-regexp)
21958 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21959 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21960 d2 diff pos pos1 category tags
21961 ee txt head pastschedp donep face timestr s)
21962 (goto-char (point-min))
21963 (while (re-search-forward regexp nil t)
21964 (catch :skip
21965 (org-agenda-skip)
21966 (setq s (match-string 1)
21967 pos (1- (match-beginning 1))
21968 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21969 ;;; is this right?
21970 ;;; do we need to do this for deadleine too????
21971 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21972 diff (- d2 d1))
21973 (setq pastschedp (and todayp (< diff 0)))
21974 ;; When to show a scheduled item in the calendar:
21975 ;; If it is on or past the date.
21976 (if (or (and (< diff 0)
21977 (< (abs diff) org-scheduled-past-days)
21978 (and todayp (not org-agenda-only-exact-dates)))
21979 (= diff 0))
21980 (save-excursion
21981 (setq category (org-get-category))
21982 (if (re-search-backward "^\\*+[ \t]+" nil t)
21983 (progn
21984 (goto-char (match-end 0))
21985 (setq pos1 (match-beginning 0))
21986 (setq tags (org-get-tags-at))
21987 (setq head (buffer-substring-no-properties
21988 (point)
21989 (progn (skip-chars-forward "^\r\n") (point))))
21990 (setq donep (string-match org-looking-at-done-regexp head))
21991 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21992 (setq timestr
21993 (concat (substring s (match-beginning 1)) " "))
21994 (setq timestr 'time))
21995 (if (and donep
21996 (or org-agenda-skip-scheduled-if-done
21997 (not (= diff 0))))
21998 (setq txt nil)
21999 (setq txt (org-format-agenda-item
22000 (if (= diff 0)
22001 (car org-agenda-scheduled-leaders)
22002 (format (nth 1 org-agenda-scheduled-leaders)
22003 (- 1 diff)))
22004 head category tags timestr))))
22005 (setq txt org-agenda-no-heading-message))
22006 (when txt
22007 (setq face (if pastschedp
22008 'org-scheduled-previously
22009 'org-scheduled-today))
22010 (org-add-props txt props
22011 'undone-face face
22012 'face (if donep 'org-done face)
22013 'org-marker (org-agenda-new-marker pos)
22014 'org-hd-marker (org-agenda-new-marker pos1)
22015 'type (if pastschedp "past-scheduled" "scheduled")
22016 'date (if pastschedp d2 date)
22017 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22018 'org-category category)
22019 (push txt ee))))))
22020 (nreverse ee)))
22022 (defun org-agenda-get-blocks ()
22023 "Return the date-range information for agenda display."
22024 (let* ((props (list 'face nil
22025 'org-not-done-regexp org-not-done-regexp
22026 'org-todo-regexp org-todo-regexp
22027 'mouse-face 'highlight
22028 'keymap org-agenda-keymap
22029 'help-echo
22030 (format "mouse-2 or RET jump to org file %s"
22031 (abbreviate-file-name buffer-file-name))))
22032 (regexp org-tr-regexp)
22033 (d0 (calendar-absolute-from-gregorian date))
22034 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22035 donep head)
22036 (goto-char (point-min))
22037 (while (re-search-forward regexp nil t)
22038 (catch :skip
22039 (org-agenda-skip)
22040 (setq pos (point))
22041 (setq timestr (match-string 0)
22042 s1 (match-string 1)
22043 s2 (match-string 2)
22044 d1 (time-to-days (org-time-string-to-time s1))
22045 d2 (time-to-days (org-time-string-to-time s2)))
22046 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22047 ;; Only allow days between the limits, because the normal
22048 ;; date stamps will catch the limits.
22049 (save-excursion
22050 (setq marker (org-agenda-new-marker (point)))
22051 (setq category (org-get-category))
22052 (if (re-search-backward "^\\*+ " nil t)
22053 (progn
22054 (goto-char (match-beginning 0))
22055 (setq hdmarker (org-agenda-new-marker (point)))
22056 (setq tags (org-get-tags-at))
22057 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22058 (setq head (match-string 1))
22059 (and org-agenda-skip-timestamp-if-done
22060 (org-entry-is-done-p)
22061 (throw :skip t))
22062 (setq txt (org-format-agenda-item
22063 (format (if (= d1 d2) "" "(%d/%d): ")
22064 (1+ (- d0 d1)) (1+ (- d2 d1)))
22065 head category tags
22066 (if (= d0 d1) timestr))))
22067 (setq txt org-agenda-no-heading-message))
22068 (org-add-props txt props
22069 'org-marker marker 'org-hd-marker hdmarker
22070 'type "block" 'date date
22071 'priority (org-get-priority txt) 'org-category category)
22072 (push txt ee)))
22073 (goto-char pos)))
22074 ;; Sort the entries by expiration date.
22075 (nreverse ee)))
22077 ;;; Agenda presentation and sorting
22079 (defconst org-plain-time-of-day-regexp
22080 (concat
22081 "\\(\\<[012]?[0-9]"
22082 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22083 "\\(--?"
22084 "\\(\\<[012]?[0-9]"
22085 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22086 "\\)?")
22087 "Regular expression to match a plain time or time range.
22088 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22089 groups carry important information:
22090 0 the full match
22091 1 the first time, range or not
22092 8 the second time, if it is a range.")
22094 (defconst org-plain-time-extension-regexp
22095 (concat
22096 "\\(\\<[012]?[0-9]"
22097 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22098 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22099 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22100 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22101 groups carry important information:
22102 0 the full match
22103 7 hours of duration
22104 9 minutes of duration")
22106 (defconst org-stamp-time-of-day-regexp
22107 (concat
22108 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22109 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22110 "\\(--?"
22111 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22112 "Regular expression to match a timestamp time or time range.
22113 After a match, the following groups carry important information:
22114 0 the full match
22115 1 date plus weekday, for backreferencing to make sure both times on same day
22116 2 the first time, range or not
22117 4 the second time, if it is a range.")
22119 (defvar org-prefix-has-time nil
22120 "A flag, set by `org-compile-prefix-format'.
22121 The flag is set if the currently compiled format contains a `%t'.")
22122 (defvar org-prefix-has-tag nil
22123 "A flag, set by `org-compile-prefix-format'.
22124 The flag is set if the currently compiled format contains a `%T'.")
22126 (defun org-format-agenda-item (extra txt &optional category tags dotime
22127 noprefix remove-re)
22128 "Format TXT to be inserted into the agenda buffer.
22129 In particular, it adds the prefix and corresponding text properties. EXTRA
22130 must be a string and replaces the `%s' specifier in the prefix format.
22131 CATEGORY (string, symbol or nil) may be used to overrule the default
22132 category taken from local variable or file name. It will replace the `%c'
22133 specifier in the format. DOTIME, when non-nil, indicates that a
22134 time-of-day should be extracted from TXT for sorting of this entry, and for
22135 the `%t' specifier in the format. When DOTIME is a string, this string is
22136 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22137 only the correctly processes TXT should be returned - this is used by
22138 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22139 Any match of REMOVE-RE will be removed from TXT."
22140 (save-match-data
22141 ;; Diary entries sometimes have extra whitespace at the beginning
22142 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22143 (let* ((category (or category
22144 org-category
22145 (if buffer-file-name
22146 (file-name-sans-extension
22147 (file-name-nondirectory buffer-file-name))
22148 "")))
22149 (tag (if tags (nth (1- (length tags)) tags) ""))
22150 time ; time and tag are needed for the eval of the prefix format
22151 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22152 (time-of-day (and dotime (org-get-time-of-day ts)))
22153 stamp plain s0 s1 s2 rtn srp)
22154 (when (and dotime time-of-day org-prefix-has-time)
22155 ;; Extract starting and ending time and move them to prefix
22156 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22157 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22158 (setq s0 (match-string 0 ts)
22159 srp (and stamp (match-end 3))
22160 s1 (match-string (if plain 1 2) ts)
22161 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22163 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22164 ;; them, we might want to remove them there to avoid duplication.
22165 ;; The user can turn this off with a variable.
22166 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22167 (string-match (concat (regexp-quote s0) " *") txt)
22168 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22169 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22170 (= (match-beginning 0) 0)
22172 (setq txt (replace-match "" nil nil txt))))
22173 ;; Normalize the time(s) to 24 hour
22174 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22175 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22177 (when (and s1 (not s2) org-agenda-default-appointment-duration
22178 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22179 (let ((m (+ (string-to-number (match-string 2 s1))
22180 (* 60 (string-to-number (match-string 1 s1)))
22181 org-agenda-default-appointment-duration))
22183 (setq h (/ m 60) m (- m (* h 60)))
22184 (setq s2 (format "%02d:%02d" h m))))
22186 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22187 txt)
22188 ;; Tags are in the string
22189 (if (or (eq org-agenda-remove-tags t)
22190 (and org-agenda-remove-tags
22191 org-prefix-has-tag))
22192 (setq txt (replace-match "" t t txt))
22193 (setq txt (replace-match
22194 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22195 (match-string 2 txt))
22196 t t txt))))
22198 (when remove-re
22199 (while (string-match remove-re txt)
22200 (setq txt (replace-match "" t t txt))))
22202 ;; Create the final string
22203 (if noprefix
22204 (setq rtn txt)
22205 ;; Prepare the variables needed in the eval of the compiled format
22206 (setq time (cond (s2 (concat s1 "-" s2))
22207 (s1 (concat s1 "......"))
22208 (t ""))
22209 extra (or extra "")
22210 category (if (symbolp category) (symbol-name category) category))
22211 ;; Evaluate the compiled format
22212 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22214 ;; And finally add the text properties
22215 (org-add-props rtn nil
22216 'org-category (downcase category) 'tags tags
22217 'org-highest-priority org-highest-priority
22218 'org-lowest-priority org-lowest-priority
22219 'prefix-length (- (length rtn) (length txt))
22220 'time-of-day time-of-day
22221 'txt txt
22222 'time time
22223 'extra extra
22224 'dotime dotime))))
22226 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22227 (defvar org-agenda-sorting-strategy-selected nil)
22229 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22230 (catch 'exit
22231 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22232 ((and todayp (member 'today (car org-agenda-time-grid))))
22233 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22234 ((member 'weekly (car org-agenda-time-grid)))
22235 (t (throw 'exit list)))
22236 (let* ((have (delq nil (mapcar
22237 (lambda (x) (get-text-property 1 'time-of-day x))
22238 list)))
22239 (string (nth 1 org-agenda-time-grid))
22240 (gridtimes (nth 2 org-agenda-time-grid))
22241 (req (car org-agenda-time-grid))
22242 (remove (member 'remove-match req))
22243 new time)
22244 (if (and (member 'require-timed req) (not have))
22245 ;; don't show empty grid
22246 (throw 'exit list))
22247 (while (setq time (pop gridtimes))
22248 (unless (and remove (member time have))
22249 (setq time (int-to-string time))
22250 (push (org-format-agenda-item
22251 nil string "" nil
22252 (concat (substring time 0 -2) ":" (substring time -2)))
22253 new)
22254 (put-text-property
22255 1 (length (car new)) 'face 'org-time-grid (car new))))
22256 (if (member 'time-up org-agenda-sorting-strategy-selected)
22257 (append new list)
22258 (append list new)))))
22260 (defun org-compile-prefix-format (key)
22261 "Compile the prefix format into a Lisp form that can be evaluated.
22262 The resulting form is returned and stored in the variable
22263 `org-prefix-format-compiled'."
22264 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22265 (let ((s (cond
22266 ((stringp org-agenda-prefix-format)
22267 org-agenda-prefix-format)
22268 ((assq key org-agenda-prefix-format)
22269 (cdr (assq key org-agenda-prefix-format)))
22270 (t " %-12:c%?-12t% s")))
22271 (start 0)
22272 varform vars var e c f opt)
22273 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22274 s start)
22275 (setq var (cdr (assoc (match-string 4 s)
22276 '(("c" . category) ("t" . time) ("s" . extra)
22277 ("T" . tag))))
22278 c (or (match-string 3 s) "")
22279 opt (match-beginning 1)
22280 start (1+ (match-beginning 0)))
22281 (if (equal var 'time) (setq org-prefix-has-time t))
22282 (if (equal var 'tag) (setq org-prefix-has-tag t))
22283 (setq f (concat "%" (match-string 2 s) "s"))
22284 (if opt
22285 (setq varform
22286 `(if (equal "" ,var)
22288 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22289 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22290 (setq s (replace-match "%s" t nil s))
22291 (push varform vars))
22292 (setq vars (nreverse vars))
22293 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22295 (defun org-set-sorting-strategy (key)
22296 (if (symbolp (car org-agenda-sorting-strategy))
22297 ;; the old format
22298 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22299 (setq org-agenda-sorting-strategy-selected
22300 (or (cdr (assq key org-agenda-sorting-strategy))
22301 (cdr (assq 'agenda org-agenda-sorting-strategy))
22302 '(time-up category-keep priority-down)))))
22304 (defun org-get-time-of-day (s &optional string mod24)
22305 "Check string S for a time of day.
22306 If found, return it as a military time number between 0 and 2400.
22307 If not found, return nil.
22308 The optional STRING argument forces conversion into a 5 character wide string
22309 HH:MM."
22310 (save-match-data
22311 (when
22312 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22313 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22314 (let* ((h (string-to-number (match-string 1 s)))
22315 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22316 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22317 (am-p (equal ampm "am"))
22318 (h1 (cond ((not ampm) h)
22319 ((= h 12) (if am-p 0 12))
22320 (t (+ h (if am-p 0 12)))))
22321 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22322 (mod h1 24) h1))
22323 (t0 (+ (* 100 h2) m))
22324 (t1 (concat (if (>= h1 24) "+" " ")
22325 (if (< t0 100) "0" "")
22326 (if (< t0 10) "0" "")
22327 (int-to-string t0))))
22328 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22330 (defun org-finalize-agenda-entries (list &optional nosort)
22331 "Sort and concatenate the agenda items."
22332 (setq list (mapcar 'org-agenda-highlight-todo list))
22333 (if nosort
22334 list
22335 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22337 (defun org-agenda-highlight-todo (x)
22338 (let (re pl)
22339 (if (eq x 'line)
22340 (save-excursion
22341 (beginning-of-line 1)
22342 (setq re (get-text-property (point) 'org-todo-regexp))
22343 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22344 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22345 (add-text-properties (match-beginning 0) (match-end 0)
22346 (list 'face (org-get-todo-face 0)))
22347 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22348 (delete-region (match-beginning 1) (1- (match-end 0)))
22349 (goto-char (match-beginning 1))
22350 (insert (format org-agenda-todo-keyword-format s)))))
22351 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22352 pl (get-text-property 0 'prefix-length x))
22353 (when (and re
22354 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22355 x (or pl 0)) pl))
22356 (add-text-properties
22357 (or (match-end 1) (match-end 0)) (match-end 0)
22358 (list 'face (org-get-todo-face (match-string 2 x)))
22360 (setq x (concat (substring x 0 (match-end 1))
22361 (format org-agenda-todo-keyword-format
22362 (match-string 2 x))
22364 (substring x (match-end 3)))))
22365 x)))
22367 (defsubst org-cmp-priority (a b)
22368 "Compare the priorities of string A and B."
22369 (let ((pa (or (get-text-property 1 'priority a) 0))
22370 (pb (or (get-text-property 1 'priority b) 0)))
22371 (cond ((> pa pb) +1)
22372 ((< pa pb) -1)
22373 (t nil))))
22375 (defsubst org-cmp-category (a b)
22376 "Compare the string values of categories of strings A and B."
22377 (let ((ca (or (get-text-property 1 'org-category a) ""))
22378 (cb (or (get-text-property 1 'org-category b) "")))
22379 (cond ((string-lessp ca cb) -1)
22380 ((string-lessp cb ca) +1)
22381 (t nil))))
22383 (defsubst org-cmp-tag (a b)
22384 "Compare the string values of categories of strings A and B."
22385 (let ((ta (car (last (get-text-property 1 'tags a))))
22386 (tb (car (last (get-text-property 1 'tags b)))))
22387 (cond ((not ta) +1)
22388 ((not tb) -1)
22389 ((string-lessp ta tb) -1)
22390 ((string-lessp tb ta) +1)
22391 (t nil))))
22393 (defsubst org-cmp-time (a b)
22394 "Compare the time-of-day values of strings A and B."
22395 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22396 (ta (or (get-text-property 1 'time-of-day a) def))
22397 (tb (or (get-text-property 1 'time-of-day b) def)))
22398 (cond ((< ta tb) -1)
22399 ((< tb ta) +1)
22400 (t nil))))
22402 (defun org-entries-lessp (a b)
22403 "Predicate for sorting agenda entries."
22404 ;; The following variables will be used when the form is evaluated.
22405 ;; So even though the compiler complains, keep them.
22406 (let* ((time-up (org-cmp-time a b))
22407 (time-down (if time-up (- time-up) nil))
22408 (priority-up (org-cmp-priority a b))
22409 (priority-down (if priority-up (- priority-up) nil))
22410 (category-up (org-cmp-category a b))
22411 (category-down (if category-up (- category-up) nil))
22412 (category-keep (if category-up +1 nil))
22413 (tag-up (org-cmp-tag a b))
22414 (tag-down (if tag-up (- tag-up) nil)))
22415 (cdr (assoc
22416 (eval (cons 'or org-agenda-sorting-strategy-selected))
22417 '((-1 . t) (1 . nil) (nil . nil))))))
22419 ;;; Agenda restriction lock
22421 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22422 "Overlay to mark the headline to which arenda commands are restricted.")
22423 (org-overlay-put org-agenda-restriction-lock-overlay
22424 'face 'org-agenda-restriction-lock)
22425 (org-overlay-put org-agenda-restriction-lock-overlay
22426 'help-echo "Agendas are currently limited to this subtree.")
22427 (org-detach-overlay org-agenda-restriction-lock-overlay)
22428 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22429 "Overlay marking the agenda restriction line in speedbar.")
22430 (org-overlay-put org-speedbar-restriction-lock-overlay
22431 'face 'org-agenda-restriction-lock)
22432 (org-overlay-put org-speedbar-restriction-lock-overlay
22433 'help-echo "Agendas are currently limited to this item.")
22434 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22436 (defun org-agenda-set-restriction-lock (&optional type)
22437 "Set restriction lock for agenda, to current subtree or file.
22438 Restriction will be the file if TYPE is `file', or if type is the
22439 universal prefix '(4), or if the cursor is before the first headline
22440 in the file. Otherwise, restriction will be to the current subtree."
22441 (interactive "P")
22442 (and (equal type '(4)) (setq type 'file))
22443 (setq type (cond
22444 (type type)
22445 ((org-at-heading-p) 'subtree)
22446 ((condition-case nil (org-back-to-heading t) (error nil))
22447 'subtree)
22448 (t 'file)))
22449 (if (eq type 'subtree)
22450 (progn
22451 (setq org-agenda-restrict t)
22452 (setq org-agenda-overriding-restriction 'subtree)
22453 (put 'org-agenda-files 'org-restrict
22454 (list (buffer-file-name (buffer-base-buffer))))
22455 (org-back-to-heading t)
22456 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22457 (move-marker org-agenda-restrict-begin (point))
22458 (move-marker org-agenda-restrict-end
22459 (save-excursion (org-end-of-subtree t)))
22460 (message "Locking agenda restriction to subtree"))
22461 (put 'org-agenda-files 'org-restrict
22462 (list (buffer-file-name (buffer-base-buffer))))
22463 (setq org-agenda-restrict nil)
22464 (setq org-agenda-overriding-restriction 'file)
22465 (move-marker org-agenda-restrict-begin nil)
22466 (move-marker org-agenda-restrict-end nil)
22467 (message "Locking agenda restriction to file"))
22468 (setq current-prefix-arg nil)
22469 (org-agenda-maybe-redo))
22471 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22472 "Remove the agenda restriction lock."
22473 (interactive "P")
22474 (org-detach-overlay org-agenda-restriction-lock-overlay)
22475 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22476 (setq org-agenda-overriding-restriction nil)
22477 (setq org-agenda-restrict nil)
22478 (put 'org-agenda-files 'org-restrict nil)
22479 (move-marker org-agenda-restrict-begin nil)
22480 (move-marker org-agenda-restrict-end nil)
22481 (setq current-prefix-arg nil)
22482 (message "Agenda restriction lock removed")
22483 (or noupdate (org-agenda-maybe-redo)))
22485 (defun org-agenda-maybe-redo ()
22486 "If there is any window showing the agenda view, update it."
22487 (let ((w (get-buffer-window org-agenda-buffer-name t))
22488 (w0 (selected-window)))
22489 (when w
22490 (select-window w)
22491 (org-agenda-redo)
22492 (select-window w0)
22493 (if org-agenda-overriding-restriction
22494 (message "Agenda view shifted to new %s restriction"
22495 org-agenda-overriding-restriction)
22496 (message "Agenda restriction lock removed")))))
22498 ;;; Agenda commands
22500 (defun org-agenda-check-type (error &rest types)
22501 "Check if agenda buffer is of allowed type.
22502 If ERROR is non-nil, throw an error, otherwise just return nil."
22503 (if (memq org-agenda-type types)
22505 (if error
22506 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22507 nil)))
22509 (defun org-agenda-quit ()
22510 "Exit agenda by removing the window or the buffer."
22511 (interactive)
22512 (let ((buf (current-buffer)))
22513 (if (not (one-window-p)) (delete-window))
22514 (kill-buffer buf)
22515 (org-agenda-reset-markers)
22516 (org-columns-remove-overlays))
22517 ;; Maybe restore the pre-agenda window configuration.
22518 (and org-agenda-restore-windows-after-quit
22519 (not (eq org-agenda-window-setup 'other-frame))
22520 org-pre-agenda-window-conf
22521 (set-window-configuration org-pre-agenda-window-conf)))
22523 (defun org-agenda-exit ()
22524 "Exit agenda by removing the window or the buffer.
22525 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22526 Org-mode buffers visited directly by the user will not be touched."
22527 (interactive)
22528 (org-release-buffers org-agenda-new-buffers)
22529 (setq org-agenda-new-buffers nil)
22530 (org-agenda-quit))
22532 (defun org-agenda-execute (arg)
22533 "Execute another agenda command, keeping same window.\\<global-map>
22534 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22535 (interactive "P")
22536 (let ((org-agenda-window-setup 'current-window))
22537 (org-agenda arg)))
22539 (defun org-save-all-org-buffers ()
22540 "Save all Org-mode buffers without user confirmation."
22541 (interactive)
22542 (message "Saving all Org-mode buffers...")
22543 (save-some-buffers t 'org-mode-p)
22544 (message "Saving all Org-mode buffers... done"))
22546 (defun org-agenda-redo ()
22547 "Rebuild Agenda.
22548 When this is the global TODO list, a prefix argument will be interpreted."
22549 (interactive)
22550 (let* ((org-agenda-keep-modes t)
22551 (line (org-current-line))
22552 (window-line (- line (org-current-line (window-start))))
22553 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22554 (message "Rebuilding agenda buffer...")
22555 (org-let lprops '(eval org-agenda-redo-command))
22556 (setq org-agenda-undo-list nil
22557 org-agenda-pending-undo-list nil)
22558 (message "Rebuilding agenda buffer...done")
22559 (goto-line line)
22560 (recenter window-line)))
22562 (defun org-agenda-manipulate-query-add ()
22563 "Manipulate the query by adding a search term with positive selection.
22564 Positive selection means, the term must be matched for selection of an entry."
22565 (interactive)
22566 (org-agenda-manipulate-query ?\[))
22567 (defun org-agenda-manipulate-query-subtract ()
22568 "Manipulate the query by adding a search term with negative selection.
22569 Negative selection means, term must not be matched for selection of an entry."
22570 (interactive)
22571 (org-agenda-manipulate-query ?\]))
22572 (defun org-agenda-manipulate-query-add-re ()
22573 "Manipulate the query by adding a search regexp with positive selection.
22574 Positive selection means, the regexp must match for selection of an entry."
22575 (interactive)
22576 (org-agenda-manipulate-query ?\{))
22577 (defun org-agenda-manipulate-query-subtract-re ()
22578 "Manipulate the query by adding a search regexp with negative selection.
22579 Negative selection means, regexp must not match for selection of an entry."
22580 (interactive)
22581 (org-agenda-manipulate-query ?\}))
22582 (defun org-agenda-manipulate-query (char)
22583 (cond
22584 ((eq org-agenda-type 'search)
22585 (org-add-to-string
22586 'org-agenda-query-string
22587 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22588 (?\{ . " +{}") (?\} . " -{}")))))
22589 (setq org-agenda-redo-command
22590 (list 'org-search-view
22591 org-todo-only
22592 org-agenda-query-string
22593 (+ (length org-agenda-query-string)
22594 (if (member char '(?\{ ?\})) 0 1))))
22595 (set-register org-agenda-query-register org-agenda-query-string)
22596 (org-agenda-redo))
22597 (t (error "Canot manipulate query for %s-type agenda buffers"
22598 org-agenda-type))))
22600 (defun org-add-to-string (var string)
22601 (set var (concat (symbol-value var) string)))
22603 (defun org-agenda-goto-date (date)
22604 "Jump to DATE in agenda."
22605 (interactive (list (org-read-date)))
22606 (org-agenda-list nil date))
22608 (defun org-agenda-goto-today ()
22609 "Go to today."
22610 (interactive)
22611 (org-agenda-check-type t 'timeline 'agenda)
22612 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22613 (cond
22614 (tdpos (goto-char tdpos))
22615 ((eq org-agenda-type 'agenda)
22616 (let* ((sd (time-to-days
22617 (time-subtract (current-time)
22618 (list 0 (* 3600 org-extend-today-until) 0))))
22619 (comp (org-agenda-compute-time-span sd org-agenda-span))
22620 (org-agenda-overriding-arguments org-agenda-last-arguments))
22621 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22622 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22623 (org-agenda-redo)
22624 (org-agenda-find-same-or-today-or-agenda)))
22625 (t (error "Cannot find today")))))
22627 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22628 (goto-char
22629 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22630 (text-property-any (point-min) (point-max) 'org-today t)
22631 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22632 (point-min))))
22634 (defun org-agenda-later (arg)
22635 "Go forward in time by thee current span.
22636 With prefix ARG, go forward that many times the current span."
22637 (interactive "p")
22638 (org-agenda-check-type t 'agenda)
22639 (let* ((span org-agenda-span)
22640 (sd org-starting-day)
22641 (greg (calendar-gregorian-from-absolute sd))
22642 (cnt (get-text-property (point) 'org-day-cnt))
22643 greg2 nd)
22644 (cond
22645 ((eq span 'day)
22646 (setq sd (+ arg sd) nd 1))
22647 ((eq span 'week)
22648 (setq sd (+ (* 7 arg) sd) nd 7))
22649 ((eq span 'month)
22650 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22651 sd (calendar-absolute-from-gregorian greg2))
22652 (setcar greg2 (1+ (car greg2)))
22653 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22654 ((eq span 'year)
22655 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22656 sd (calendar-absolute-from-gregorian greg2))
22657 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22658 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22659 (let ((org-agenda-overriding-arguments
22660 (list (car org-agenda-last-arguments) sd nd t)))
22661 (org-agenda-redo)
22662 (org-agenda-find-same-or-today-or-agenda cnt))))
22664 (defun org-agenda-earlier (arg)
22665 "Go backward in time by the current span.
22666 With prefix ARG, go backward that many times the current span."
22667 (interactive "p")
22668 (org-agenda-later (- arg)))
22670 (defun org-agenda-day-view (&optional day-of-year)
22671 "Switch to daily view for agenda.
22672 With argument DAY-OF-YEAR, switch to that day of the year."
22673 (interactive "P")
22674 (setq org-agenda-ndays 1)
22675 (org-agenda-change-time-span 'day day-of-year))
22676 (defun org-agenda-week-view (&optional iso-week)
22677 "Switch to daily view for agenda.
22678 With argument ISO-WEEK, switch to the corresponding ISO week.
22679 If ISO-WEEK has more then 2 digits, only the last two encode the
22680 week. Any digits before this encode a year. So 200712 means
22681 week 12 of year 2007. Years in the range 1938-2037 can also be
22682 written as 2-digit years."
22683 (interactive "P")
22684 (setq org-agenda-ndays 7)
22685 (org-agenda-change-time-span 'week iso-week))
22686 (defun org-agenda-month-view (&optional month)
22687 "Switch to daily view for agenda.
22688 With argument MONTH, switch to that month."
22689 (interactive "P")
22690 ;; FIXME: allow month like 812 to mean 2008 december
22691 (org-agenda-change-time-span 'month month))
22692 (defun org-agenda-year-view (&optional year)
22693 "Switch to daily view for agenda.
22694 With argument YEAR, switch to that year.
22695 If MONTH has more then 2 digits, only the last two encode the
22696 month. Any digits before this encode a year. So 200712 means
22697 December year 2007. Years in the range 1938-2037 can also be
22698 written as 2-digit years."
22699 (interactive "P")
22700 (when year
22701 (setq year (org-small-year-to-year year)))
22702 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22703 (org-agenda-change-time-span 'year year)
22704 (error "Abort")))
22706 (defun org-agenda-change-time-span (span &optional n)
22707 "Change the agenda view to SPAN.
22708 SPAN may be `day', `week', `month', `year'."
22709 (org-agenda-check-type t 'agenda)
22710 (if (and (not n) (equal org-agenda-span span))
22711 (error "Viewing span is already \"%s\"" span))
22712 (let* ((sd (or (get-text-property (point) 'day)
22713 org-starting-day))
22714 (computed (org-agenda-compute-time-span sd span n))
22715 (org-agenda-overriding-arguments
22716 (list (car org-agenda-last-arguments)
22717 (car computed) (cdr computed) t)))
22718 (org-agenda-redo)
22719 (org-agenda-find-same-or-today-or-agenda))
22720 (org-agenda-set-mode-name)
22721 (message "Switched to %s view" span))
22723 (defun org-agenda-compute-time-span (sd span &optional n)
22724 "Compute starting date and number of days for agenda.
22725 SPAN may be `day', `week', `month', `year'. The return value
22726 is a cons cell with the starting date and the number of days,
22727 so that the date SD will be in that range."
22728 (let* ((greg (calendar-gregorian-from-absolute sd))
22729 (dg (nth 1 greg))
22730 (mg (car greg))
22731 (yg (nth 2 greg))
22732 nd w1 y1 m1 thisweek)
22733 (cond
22734 ((eq span 'day)
22735 (when n
22736 (setq sd (+ (calendar-absolute-from-gregorian
22737 (list mg 1 yg))
22738 n -1)))
22739 (setq nd 1))
22740 ((eq span 'week)
22741 (let* ((nt (calendar-day-of-week
22742 (calendar-gregorian-from-absolute sd)))
22743 (d (if org-agenda-start-on-weekday
22744 (- nt org-agenda-start-on-weekday)
22745 0)))
22746 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22747 (when n
22748 (require 'cal-iso)
22749 (setq thisweek (car (calendar-iso-from-absolute sd)))
22750 (when (> n 99)
22751 (setq y1 (org-small-year-to-year (/ n 100))
22752 n (mod n 100)))
22753 (setq sd
22754 (calendar-absolute-from-iso
22755 (list n 1
22756 (or y1 (nth 2 (calendar-iso-from-absolute sd)))))))
22757 (setq nd 7)))
22758 ((eq span 'month)
22759 (when (and n (> n 99))
22760 (setq y1 (org-small-year-to-year (/ n 100))
22761 n (mod n 100)))
22762 (setq sd (calendar-absolute-from-gregorian
22763 (list (or n mg) 1 (or y1 yg)))
22764 nd (- (calendar-absolute-from-gregorian
22765 (list (1+ (or n mg)) 1 (or y1 yg)))
22766 sd)))
22767 ((eq span 'year)
22768 (setq sd (calendar-absolute-from-gregorian
22769 (list 1 1 (or n yg)))
22770 nd (- (calendar-absolute-from-gregorian
22771 (list 1 1 (1+ (or n yg))))
22772 sd))))
22773 (cons sd nd)))
22775 (defun org-days-to-iso-week (days)
22776 "Return the iso week number."
22777 (require 'cal-iso)
22778 (car (calendar-iso-from-absolute days)))
22780 (defun org-small-year-to-year (year)
22781 "Convert 2-digit years into 4-digit years.
22782 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
22783 The year 2000 cannot be abbreviated. Any year lager than 99
22784 is retrned unchanged."
22785 (if (< year 38)
22786 (setq year (+ 2000 year))
22787 (if (< year 100)
22788 (setq year (+ 1900 year))))
22789 year)
22791 ;; FIXME: does not work if user makes date format that starts with a blank
22792 (defun org-agenda-next-date-line (&optional arg)
22793 "Jump to the next line indicating a date in agenda buffer."
22794 (interactive "p")
22795 (org-agenda-check-type t 'agenda 'timeline)
22796 (beginning-of-line 1)
22797 (if (looking-at "^\\S-") (forward-char 1))
22798 (if (not (re-search-forward "^\\S-" nil t arg))
22799 (progn
22800 (backward-char 1)
22801 (error "No next date after this line in this buffer")))
22802 (goto-char (match-beginning 0)))
22804 (defun org-agenda-previous-date-line (&optional arg)
22805 "Jump to the previous line indicating a date in agenda buffer."
22806 (interactive "p")
22807 (org-agenda-check-type t 'agenda 'timeline)
22808 (beginning-of-line 1)
22809 (if (not (re-search-backward "^\\S-" nil t arg))
22810 (error "No previous date before this line in this buffer")))
22812 ;; Initialize the highlight
22813 (defvar org-hl (org-make-overlay 1 1))
22814 (org-overlay-put org-hl 'face 'highlight)
22816 (defun org-highlight (begin end &optional buffer)
22817 "Highlight a region with overlay."
22818 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22819 org-hl begin end (or buffer (current-buffer))))
22821 (defun org-unhighlight ()
22822 "Detach overlay INDEX."
22823 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22825 ;; FIXME this is currently not used.
22826 (defun org-highlight-until-next-command (beg end &optional buffer)
22827 (org-highlight beg end buffer)
22828 (add-hook 'pre-command-hook 'org-unhighlight-once))
22829 (defun org-unhighlight-once ()
22830 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22831 (org-unhighlight))
22833 (defun org-agenda-follow-mode ()
22834 "Toggle follow mode in an agenda buffer."
22835 (interactive)
22836 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22837 (org-agenda-set-mode-name)
22838 (message "Follow mode is %s"
22839 (if org-agenda-follow-mode "on" "off")))
22841 (defun org-agenda-log-mode ()
22842 "Toggle log mode in an agenda buffer."
22843 (interactive)
22844 (org-agenda-check-type t 'agenda 'timeline)
22845 (setq org-agenda-show-log (not org-agenda-show-log))
22846 (org-agenda-set-mode-name)
22847 (org-agenda-redo)
22848 (message "Log mode is %s"
22849 (if org-agenda-show-log "on" "off")))
22851 (defun org-agenda-toggle-diary ()
22852 "Toggle diary inclusion in an agenda buffer."
22853 (interactive)
22854 (org-agenda-check-type t 'agenda)
22855 (setq org-agenda-include-diary (not org-agenda-include-diary))
22856 (org-agenda-redo)
22857 (org-agenda-set-mode-name)
22858 (message "Diary inclusion turned %s"
22859 (if org-agenda-include-diary "on" "off")))
22861 (defun org-agenda-toggle-time-grid ()
22862 "Toggle time grid in an agenda buffer."
22863 (interactive)
22864 (org-agenda-check-type t 'agenda)
22865 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22866 (org-agenda-redo)
22867 (org-agenda-set-mode-name)
22868 (message "Time-grid turned %s"
22869 (if org-agenda-use-time-grid "on" "off")))
22871 (defun org-agenda-set-mode-name ()
22872 "Set the mode name to indicate all the small mode settings."
22873 (setq mode-name
22874 (concat "Org-Agenda"
22875 (if (equal org-agenda-ndays 1) " Day" "")
22876 (if (equal org-agenda-ndays 7) " Week" "")
22877 (if org-agenda-follow-mode " Follow" "")
22878 (if org-agenda-include-diary " Diary" "")
22879 (if org-agenda-use-time-grid " Grid" "")
22880 (if org-agenda-show-log " Log" "")))
22881 (force-mode-line-update))
22883 (defun org-agenda-post-command-hook ()
22884 (and (eolp) (not (bolp)) (backward-char 1))
22885 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22886 (if (and org-agenda-follow-mode
22887 (get-text-property (point) 'org-marker))
22888 (org-agenda-show)))
22890 (defun org-agenda-show-priority ()
22891 "Show the priority of the current item.
22892 This priority is composed of the main priority given with the [#A] cookies,
22893 and by additional input from the age of a schedules or deadline entry."
22894 (interactive)
22895 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22896 (message "Priority is %d" (if pri pri -1000))))
22898 (defun org-agenda-show-tags ()
22899 "Show the tags applicable to the current item."
22900 (interactive)
22901 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22902 (if tags
22903 (message "Tags are :%s:"
22904 (org-no-properties (mapconcat 'identity tags ":")))
22905 (message "No tags associated with this line"))))
22907 (defun org-agenda-goto (&optional highlight)
22908 "Go to the Org-mode file which contains the item at point."
22909 (interactive)
22910 (let* ((marker (or (get-text-property (point) 'org-marker)
22911 (org-agenda-error)))
22912 (buffer (marker-buffer marker))
22913 (pos (marker-position marker)))
22914 (switch-to-buffer-other-window buffer)
22915 (widen)
22916 (goto-char pos)
22917 (when (org-mode-p)
22918 (org-show-context 'agenda)
22919 (save-excursion
22920 (and (outline-next-heading)
22921 (org-flag-heading nil)))) ; show the next heading
22922 (recenter (/ (window-height) 2))
22923 (run-hooks 'org-agenda-after-show-hook)
22924 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22926 (defvar org-agenda-after-show-hook nil
22927 "Normal hook run after an item has been shown from the agenda.
22928 Point is in the buffer where the item originated.")
22930 (defun org-agenda-kill ()
22931 "Kill the entry or subtree belonging to the current agenda entry."
22932 (interactive)
22933 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22934 (let* ((marker (or (get-text-property (point) 'org-marker)
22935 (org-agenda-error)))
22936 (buffer (marker-buffer marker))
22937 (pos (marker-position marker))
22938 (type (get-text-property (point) 'type))
22939 dbeg dend (n 0) conf)
22940 (org-with-remote-undo buffer
22941 (with-current-buffer buffer
22942 (save-excursion
22943 (goto-char pos)
22944 (if (and (org-mode-p) (not (member type '("sexp"))))
22945 (setq dbeg (progn (org-back-to-heading t) (point))
22946 dend (org-end-of-subtree t t))
22947 (setq dbeg (point-at-bol)
22948 dend (min (point-max) (1+ (point-at-eol)))))
22949 (goto-char dbeg)
22950 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22951 (setq conf (or (eq t org-agenda-confirm-kill)
22952 (and (numberp org-agenda-confirm-kill)
22953 (> n org-agenda-confirm-kill))))
22954 (and conf
22955 (not (y-or-n-p
22956 (format "Delete entry with %d lines in buffer \"%s\"? "
22957 n (buffer-name buffer))))
22958 (error "Abort"))
22959 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22960 (with-current-buffer buffer (delete-region dbeg dend))
22961 (message "Agenda item and source killed"))))
22963 (defun org-agenda-archive ()
22964 "Kill the entry or subtree belonging to the current agenda entry."
22965 (interactive)
22966 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22967 (let* ((marker (or (get-text-property (point) 'org-marker)
22968 (org-agenda-error)))
22969 (buffer (marker-buffer marker))
22970 (pos (marker-position marker)))
22971 (org-with-remote-undo buffer
22972 (with-current-buffer buffer
22973 (if (org-mode-p)
22974 (save-excursion
22975 (goto-char pos)
22976 (org-remove-subtree-entries-from-agenda)
22977 (org-back-to-heading t)
22978 (org-archive-subtree))
22979 (error "Archiving works only in Org-mode files"))))))
22981 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22982 "Remove all lines in the agenda that correspond to a given subtree.
22983 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22984 If this information is not given, the function uses the tree at point."
22985 (let ((buf (or buf (current-buffer))) m p)
22986 (save-excursion
22987 (unless (and beg end)
22988 (org-back-to-heading t)
22989 (setq beg (point))
22990 (org-end-of-subtree t)
22991 (setq end (point)))
22992 (set-buffer (get-buffer org-agenda-buffer-name))
22993 (save-excursion
22994 (goto-char (point-max))
22995 (beginning-of-line 1)
22996 (while (not (bobp))
22997 (when (and (setq m (get-text-property (point) 'org-marker))
22998 (equal buf (marker-buffer m))
22999 (setq p (marker-position m))
23000 (>= p beg)
23001 (<= p end))
23002 (let ((inhibit-read-only t))
23003 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23004 (beginning-of-line 0))))))
23006 (defun org-agenda-open-link ()
23007 "Follow the link in the current line, if any."
23008 (interactive)
23009 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23010 (save-excursion
23011 (save-restriction
23012 (narrow-to-region (point-at-bol) (point-at-eol))
23013 (org-open-at-point))))
23015 (defun org-agenda-copy-local-variable (var)
23016 "Get a variable from a referenced buffer and install it here."
23017 (let ((m (get-text-property (point) 'org-marker)))
23018 (when (and m (buffer-live-p (marker-buffer m)))
23019 (org-set-local var (with-current-buffer (marker-buffer m)
23020 (symbol-value var))))))
23022 (defun org-agenda-switch-to (&optional delete-other-windows)
23023 "Go to the Org-mode file which contains the item at point."
23024 (interactive)
23025 (let* ((marker (or (get-text-property (point) 'org-marker)
23026 (org-agenda-error)))
23027 (buffer (marker-buffer marker))
23028 (pos (marker-position marker)))
23029 (switch-to-buffer buffer)
23030 (and delete-other-windows (delete-other-windows))
23031 (widen)
23032 (goto-char pos)
23033 (when (org-mode-p)
23034 (org-show-context 'agenda)
23035 (save-excursion
23036 (and (outline-next-heading)
23037 (org-flag-heading nil)))))) ; show the next heading
23039 (defun org-agenda-goto-mouse (ev)
23040 "Go to the Org-mode file which contains the item at the mouse click."
23041 (interactive "e")
23042 (mouse-set-point ev)
23043 (org-agenda-goto))
23045 (defun org-agenda-show ()
23046 "Display the Org-mode file which contains the item at point."
23047 (interactive)
23048 (let ((win (selected-window)))
23049 (org-agenda-goto t)
23050 (select-window win)))
23052 (defun org-agenda-recenter (arg)
23053 "Display the Org-mode file which contains the item at point and recenter."
23054 (interactive "P")
23055 (let ((win (selected-window)))
23056 (org-agenda-goto t)
23057 (recenter arg)
23058 (select-window win)))
23060 (defun org-agenda-show-mouse (ev)
23061 "Display the Org-mode file which contains the item at the mouse click."
23062 (interactive "e")
23063 (mouse-set-point ev)
23064 (org-agenda-show))
23066 (defun org-agenda-check-no-diary ()
23067 "Check if the entry is a diary link and abort if yes."
23068 (if (get-text-property (point) 'org-agenda-diary-link)
23069 (org-agenda-error)))
23071 (defun org-agenda-error ()
23072 (error "Command not allowed in this line"))
23074 (defun org-agenda-tree-to-indirect-buffer ()
23075 "Show the subtree corresponding to the current entry in an indirect buffer.
23076 This calls the command `org-tree-to-indirect-buffer' from the original
23077 Org-mode buffer.
23078 With numerical prefix arg ARG, go up to this level and then take that tree.
23079 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23080 dedicated frame)."
23081 (interactive)
23082 (org-agenda-check-no-diary)
23083 (let* ((marker (or (get-text-property (point) 'org-marker)
23084 (org-agenda-error)))
23085 (buffer (marker-buffer marker))
23086 (pos (marker-position marker)))
23087 (with-current-buffer buffer
23088 (save-excursion
23089 (goto-char pos)
23090 (call-interactively 'org-tree-to-indirect-buffer)))))
23092 (defvar org-last-heading-marker (make-marker)
23093 "Marker pointing to the headline that last changed its TODO state
23094 by a remote command from the agenda.")
23096 (defun org-agenda-todo-nextset ()
23097 "Switch TODO entry to next sequence."
23098 (interactive)
23099 (org-agenda-todo 'nextset))
23101 (defun org-agenda-todo-previousset ()
23102 "Switch TODO entry to previous sequence."
23103 (interactive)
23104 (org-agenda-todo 'previousset))
23106 (defun org-agenda-todo (&optional arg)
23107 "Cycle TODO state of line at point, also in Org-mode file.
23108 This changes the line at point, all other lines in the agenda referring to
23109 the same tree node, and the headline of the tree node in the Org-mode file."
23110 (interactive "P")
23111 (org-agenda-check-no-diary)
23112 (let* ((col (current-column))
23113 (marker (or (get-text-property (point) 'org-marker)
23114 (org-agenda-error)))
23115 (buffer (marker-buffer marker))
23116 (pos (marker-position marker))
23117 (hdmarker (get-text-property (point) 'org-hd-marker))
23118 (inhibit-read-only t)
23119 newhead)
23120 (org-with-remote-undo buffer
23121 (with-current-buffer buffer
23122 (widen)
23123 (goto-char pos)
23124 (org-show-context 'agenda)
23125 (save-excursion
23126 (and (outline-next-heading)
23127 (org-flag-heading nil))) ; show the next heading
23128 (org-todo arg)
23129 (and (bolp) (forward-char 1))
23130 (setq newhead (org-get-heading))
23131 (save-excursion
23132 (org-back-to-heading)
23133 (move-marker org-last-heading-marker (point))))
23134 (beginning-of-line 1)
23135 (save-excursion
23136 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23137 (move-to-column col))))
23139 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23140 "Change all lines in the agenda buffer which match HDMARKER.
23141 The new content of the line will be NEWHEAD (as modified by
23142 `org-format-agenda-item'). HDMARKER is checked with
23143 `equal' against all `org-hd-marker' text properties in the file.
23144 If FIXFACE is non-nil, the face of each item is modified acording to
23145 the new TODO state."
23146 (let* ((inhibit-read-only t)
23147 props m pl undone-face done-face finish new dotime cat tags)
23148 (save-excursion
23149 (goto-char (point-max))
23150 (beginning-of-line 1)
23151 (while (not finish)
23152 (setq finish (bobp))
23153 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23154 (equal m hdmarker))
23155 (setq props (text-properties-at (point))
23156 dotime (get-text-property (point) 'dotime)
23157 cat (get-text-property (point) 'org-category)
23158 tags (get-text-property (point) 'tags)
23159 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23160 pl (get-text-property (point) 'prefix-length)
23161 undone-face (get-text-property (point) 'undone-face)
23162 done-face (get-text-property (point) 'done-face))
23163 (move-to-column pl)
23164 (cond
23165 ((equal new "")
23166 (beginning-of-line 1)
23167 (and (looking-at ".*\n?") (replace-match "")))
23168 ((looking-at ".*")
23169 (replace-match new t t)
23170 (beginning-of-line 1)
23171 (add-text-properties (point-at-bol) (point-at-eol) props)
23172 (when fixface
23173 (add-text-properties
23174 (point-at-bol) (point-at-eol)
23175 (list 'face
23176 (if org-last-todo-state-is-todo
23177 undone-face done-face))))
23178 (org-agenda-highlight-todo 'line)
23179 (beginning-of-line 1))
23180 (t (error "Line update did not work"))))
23181 (beginning-of-line 0)))
23182 (org-finalize-agenda)))
23184 (defun org-agenda-align-tags (&optional line)
23185 "Align all tags in agenda items to `org-agenda-tags-column'."
23186 (let ((inhibit-read-only t) l c)
23187 (save-excursion
23188 (goto-char (if line (point-at-bol) (point-min)))
23189 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23190 (if line (point-at-eol) nil) t)
23191 (add-text-properties
23192 (match-beginning 2) (match-end 2)
23193 (list 'face (delq nil (list 'org-tag (get-text-property
23194 (match-beginning 2) 'face)))))
23195 (setq l (- (match-end 2) (match-beginning 2))
23196 c (if (< org-agenda-tags-column 0)
23197 (- (abs org-agenda-tags-column) l)
23198 org-agenda-tags-column))
23199 (delete-region (match-beginning 1) (match-end 1))
23200 (goto-char (match-beginning 1))
23201 (insert (org-add-props
23202 (make-string (max 1 (- c (current-column))) ?\ )
23203 (text-properties-at (point))))))))
23205 (defun org-agenda-priority-up ()
23206 "Increase the priority of line at point, also in Org-mode file."
23207 (interactive)
23208 (org-agenda-priority 'up))
23210 (defun org-agenda-priority-down ()
23211 "Decrease the priority of line at point, also in Org-mode file."
23212 (interactive)
23213 (org-agenda-priority 'down))
23215 (defun org-agenda-priority (&optional force-direction)
23216 "Set the priority of line at point, also in Org-mode file.
23217 This changes the line at point, all other lines in the agenda referring to
23218 the same tree node, and the headline of the tree node in the Org-mode file."
23219 (interactive)
23220 (org-agenda-check-no-diary)
23221 (let* ((marker (or (get-text-property (point) 'org-marker)
23222 (org-agenda-error)))
23223 (hdmarker (get-text-property (point) 'org-hd-marker))
23224 (buffer (marker-buffer hdmarker))
23225 (pos (marker-position hdmarker))
23226 (inhibit-read-only t)
23227 newhead)
23228 (org-with-remote-undo buffer
23229 (with-current-buffer buffer
23230 (widen)
23231 (goto-char pos)
23232 (org-show-context 'agenda)
23233 (save-excursion
23234 (and (outline-next-heading)
23235 (org-flag-heading nil))) ; show the next heading
23236 (funcall 'org-priority force-direction)
23237 (end-of-line 1)
23238 (setq newhead (org-get-heading)))
23239 (org-agenda-change-all-lines newhead hdmarker)
23240 (beginning-of-line 1))))
23242 (defun org-get-tags-at (&optional pos)
23243 "Get a list of all headline tags applicable at POS.
23244 POS defaults to point. If tags are inherited, the list contains
23245 the targets in the same sequence as the headlines appear, i.e.
23246 sthe tags of the current headline come last."
23247 (interactive)
23248 (let (tags ltags lastpos parent)
23249 (save-excursion
23250 (save-restriction
23251 (widen)
23252 (goto-char (or pos (point)))
23253 (save-match-data
23254 (condition-case nil
23255 (progn
23256 (org-back-to-heading t)
23257 (while (not (equal lastpos (point)))
23258 (setq lastpos (point))
23259 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23260 (setq ltags (org-split-string
23261 (org-match-string-no-properties 1) ":"))
23262 (setq tags (append (org-remove-uniherited-tags ltags)
23263 tags)))
23264 (or org-use-tag-inheritance (error ""))
23265 (org-up-heading-all 1)
23266 (setq parent t)))
23267 (error nil))))
23268 tags)))
23270 ;; FIXME: should fix the tags property of the agenda line.
23271 (defun org-agenda-set-tags ()
23272 "Set tags for the current headline."
23273 (interactive)
23274 (org-agenda-check-no-diary)
23275 (if (and (org-region-active-p) (interactive-p))
23276 (call-interactively 'org-change-tag-in-region)
23277 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23278 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23279 (org-agenda-error)))
23280 (buffer (marker-buffer hdmarker))
23281 (pos (marker-position hdmarker))
23282 (inhibit-read-only t)
23283 newhead)
23284 (org-with-remote-undo buffer
23285 (with-current-buffer buffer
23286 (widen)
23287 (goto-char pos)
23288 (save-excursion
23289 (org-show-context 'agenda))
23290 (save-excursion
23291 (and (outline-next-heading)
23292 (org-flag-heading nil))) ; show the next heading
23293 (goto-char pos)
23294 (call-interactively 'org-set-tags)
23295 (end-of-line 1)
23296 (setq newhead (org-get-heading)))
23297 (org-agenda-change-all-lines newhead hdmarker)
23298 (beginning-of-line 1)))))
23300 (defun org-agenda-toggle-archive-tag ()
23301 "Toggle the archive tag for the current entry."
23302 (interactive)
23303 (org-agenda-check-no-diary)
23304 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23305 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23306 (org-agenda-error)))
23307 (buffer (marker-buffer hdmarker))
23308 (pos (marker-position hdmarker))
23309 (inhibit-read-only t)
23310 newhead)
23311 (org-with-remote-undo buffer
23312 (with-current-buffer buffer
23313 (widen)
23314 (goto-char pos)
23315 (org-show-context 'agenda)
23316 (save-excursion
23317 (and (outline-next-heading)
23318 (org-flag-heading nil))) ; show the next heading
23319 (call-interactively 'org-toggle-archive-tag)
23320 (end-of-line 1)
23321 (setq newhead (org-get-heading)))
23322 (org-agenda-change-all-lines newhead hdmarker)
23323 (beginning-of-line 1))))
23325 (defun org-agenda-date-later (arg &optional what)
23326 "Change the date of this item to one day later."
23327 (interactive "p")
23328 (org-agenda-check-type t 'agenda 'timeline)
23329 (org-agenda-check-no-diary)
23330 (let* ((marker (or (get-text-property (point) 'org-marker)
23331 (org-agenda-error)))
23332 (buffer (marker-buffer marker))
23333 (pos (marker-position marker)))
23334 (org-with-remote-undo buffer
23335 (with-current-buffer buffer
23336 (widen)
23337 (goto-char pos)
23338 (if (not (org-at-timestamp-p))
23339 (error "Cannot find time stamp"))
23340 (org-timestamp-change arg (or what 'day)))
23341 (org-agenda-show-new-time marker org-last-changed-timestamp))
23342 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23344 (defun org-agenda-date-earlier (arg &optional what)
23345 "Change the date of this item to one day earlier."
23346 (interactive "p")
23347 (org-agenda-date-later (- arg) what))
23349 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23350 "Show new date stamp via text properties."
23351 ;; We use text properties to make this undoable
23352 (let ((inhibit-read-only t))
23353 (setq stamp (concat " " prefix " => " stamp))
23354 (save-excursion
23355 (goto-char (point-max))
23356 (while (not (bobp))
23357 (when (equal marker (get-text-property (point) 'org-marker))
23358 (move-to-column (- (window-width) (length stamp)) t)
23359 (if (featurep 'xemacs)
23360 ;; Use `duplicable' property to trigger undo recording
23361 (let ((ex (make-extent nil nil))
23362 (gl (make-glyph stamp)))
23363 (set-glyph-face gl 'secondary-selection)
23364 (set-extent-properties
23365 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23366 (insert-extent ex (1- (point)) (point-at-eol)))
23367 (add-text-properties
23368 (1- (point)) (point-at-eol)
23369 (list 'display (org-add-props stamp nil
23370 'face 'secondary-selection))))
23371 (beginning-of-line 1))
23372 (beginning-of-line 0)))))
23374 (defun org-agenda-date-prompt (arg)
23375 "Change the date of this item. Date is prompted for, with default today.
23376 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23377 be used to request time specification in the time stamp."
23378 (interactive "P")
23379 (org-agenda-check-type t 'agenda 'timeline)
23380 (org-agenda-check-no-diary)
23381 (let* ((marker (or (get-text-property (point) 'org-marker)
23382 (org-agenda-error)))
23383 (buffer (marker-buffer marker))
23384 (pos (marker-position marker)))
23385 (org-with-remote-undo buffer
23386 (with-current-buffer buffer
23387 (widen)
23388 (goto-char pos)
23389 (if (not (org-at-timestamp-p))
23390 (error "Cannot find time stamp"))
23391 (org-time-stamp arg)
23392 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23394 (defun org-agenda-schedule (arg)
23395 "Schedule the item at point."
23396 (interactive "P")
23397 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23398 (org-agenda-check-no-diary)
23399 (let* ((marker (or (get-text-property (point) 'org-marker)
23400 (org-agenda-error)))
23401 (type (marker-insertion-type marker))
23402 (buffer (marker-buffer marker))
23403 (pos (marker-position marker))
23404 (org-insert-labeled-timestamps-at-point nil)
23406 (when type (message "%s" type) (sit-for 3))
23407 (set-marker-insertion-type marker t)
23408 (org-with-remote-undo buffer
23409 (with-current-buffer buffer
23410 (widen)
23411 (goto-char pos)
23412 (setq ts (org-schedule arg)))
23413 (org-agenda-show-new-time marker ts "S"))
23414 (message "Item scheduled for %s" ts)))
23416 (defun org-agenda-deadline (arg)
23417 "Schedule the item at point."
23418 (interactive "P")
23419 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23420 (org-agenda-check-no-diary)
23421 (let* ((marker (or (get-text-property (point) 'org-marker)
23422 (org-agenda-error)))
23423 (buffer (marker-buffer marker))
23424 (pos (marker-position marker))
23425 (org-insert-labeled-timestamps-at-point nil)
23427 (org-with-remote-undo buffer
23428 (with-current-buffer buffer
23429 (widen)
23430 (goto-char pos)
23431 (setq ts (org-deadline arg)))
23432 (org-agenda-show-new-time marker ts "S"))
23433 (message "Deadline for this item set to %s" ts)))
23435 (defun org-get-heading (&optional no-tags)
23436 "Return the heading of the current entry, without the stars."
23437 (save-excursion
23438 (org-back-to-heading t)
23439 (if (looking-at
23440 (if no-tags
23441 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23442 "\\*+[ \t]+\\([^\r\n]*\\)"))
23443 (match-string 1) "")))
23445 (defun org-agenda-clock-in (&optional arg)
23446 "Start the clock on the currently selected item."
23447 (interactive "P")
23448 (org-agenda-check-no-diary)
23449 (let* ((marker (or (get-text-property (point) 'org-marker)
23450 (org-agenda-error)))
23451 (pos (marker-position marker)))
23452 (org-with-remote-undo (marker-buffer marker)
23453 (with-current-buffer (marker-buffer marker)
23454 (widen)
23455 (goto-char pos)
23456 (org-clock-in)))))
23458 (defun org-agenda-clock-out (&optional arg)
23459 "Stop the currently running clock."
23460 (interactive "P")
23461 (unless (marker-buffer org-clock-marker)
23462 (error "No running clock"))
23463 (org-with-remote-undo (marker-buffer org-clock-marker)
23464 (org-clock-out)))
23466 (defun org-agenda-clock-cancel (&optional arg)
23467 "Cancel the currently running clock."
23468 (interactive "P")
23469 (unless (marker-buffer org-clock-marker)
23470 (error "No running clock"))
23471 (org-with-remote-undo (marker-buffer org-clock-marker)
23472 (org-clock-cancel)))
23474 (defun org-agenda-diary-entry ()
23475 "Make a diary entry, like the `i' command from the calendar.
23476 All the standard commands work: block, weekly etc."
23477 (interactive)
23478 (org-agenda-check-type t 'agenda 'timeline)
23479 (require 'diary-lib)
23480 (let* ((char (progn
23481 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23482 (read-char-exclusive)))
23483 (cmd (cdr (assoc char
23484 '((?d . insert-diary-entry)
23485 (?w . insert-weekly-diary-entry)
23486 (?m . insert-monthly-diary-entry)
23487 (?y . insert-yearly-diary-entry)
23488 (?a . insert-anniversary-diary-entry)
23489 (?b . insert-block-diary-entry)
23490 (?c . insert-cyclic-diary-entry)))))
23491 (oldf (symbol-function 'calendar-cursor-to-date))
23492 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23493 (point (point))
23494 (mark (or (mark t) (point))))
23495 (unless cmd
23496 (error "No command associated with <%c>" char))
23497 (unless (and (get-text-property point 'day)
23498 (or (not (equal ?b char))
23499 (get-text-property mark 'day)))
23500 (error "Don't know which date to use for diary entry"))
23501 ;; We implement this by hacking the `calendar-cursor-to-date' function
23502 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23503 (let ((calendar-mark-ring
23504 (list (calendar-gregorian-from-absolute
23505 (or (get-text-property mark 'day)
23506 (get-text-property point 'day))))))
23507 (unwind-protect
23508 (progn
23509 (fset 'calendar-cursor-to-date
23510 (lambda (&optional error)
23511 (calendar-gregorian-from-absolute
23512 (get-text-property point 'day))))
23513 (call-interactively cmd))
23514 (fset 'calendar-cursor-to-date oldf)))))
23517 (defun org-agenda-execute-calendar-command (cmd)
23518 "Execute a calendar command from the agenda, with the date associated to
23519 the cursor position."
23520 (org-agenda-check-type t 'agenda 'timeline)
23521 (require 'diary-lib)
23522 (unless (get-text-property (point) 'day)
23523 (error "Don't know which date to use for calendar command"))
23524 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23525 (point (point))
23526 (date (calendar-gregorian-from-absolute
23527 (get-text-property point 'day)))
23528 ;; the following 3 vars are needed in the calendar
23529 (displayed-day (extract-calendar-day date))
23530 (displayed-month (extract-calendar-month date))
23531 (displayed-year (extract-calendar-year date)))
23532 (unwind-protect
23533 (progn
23534 (fset 'calendar-cursor-to-date
23535 (lambda (&optional error)
23536 (calendar-gregorian-from-absolute
23537 (get-text-property point 'day))))
23538 (call-interactively cmd))
23539 (fset 'calendar-cursor-to-date oldf))))
23541 (defun org-agenda-phases-of-moon ()
23542 "Display the phases of the moon for the 3 months around the cursor date."
23543 (interactive)
23544 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23546 (defun org-agenda-holidays ()
23547 "Display the holidays for the 3 months around the cursor date."
23548 (interactive)
23549 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23551 (defvar calendar-longitude)
23552 (defvar calendar-latitude)
23553 (defvar calendar-location-name)
23555 (defun org-agenda-sunrise-sunset (arg)
23556 "Display sunrise and sunset for the cursor date.
23557 Latitude and longitude can be specified with the variables
23558 `calendar-latitude' and `calendar-longitude'. When called with prefix
23559 argument, latitude and longitude will be prompted for."
23560 (interactive "P")
23561 (require 'solar)
23562 (let ((calendar-longitude (if arg nil calendar-longitude))
23563 (calendar-latitude (if arg nil calendar-latitude))
23564 (calendar-location-name
23565 (if arg "the given coordinates" calendar-location-name)))
23566 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23568 (defun org-agenda-goto-calendar ()
23569 "Open the Emacs calendar with the date at the cursor."
23570 (interactive)
23571 (org-agenda-check-type t 'agenda 'timeline)
23572 (let* ((day (or (get-text-property (point) 'day)
23573 (error "Don't know which date to open in calendar")))
23574 (date (calendar-gregorian-from-absolute day))
23575 (calendar-move-hook nil)
23576 (view-calendar-holidays-initially nil)
23577 (view-diary-entries-initially nil))
23578 (calendar)
23579 (calendar-goto-date date)))
23581 (defun org-calendar-goto-agenda ()
23582 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23583 This is a command that has to be installed in `calendar-mode-map'."
23584 (interactive)
23585 (org-agenda-list nil (calendar-absolute-from-gregorian
23586 (calendar-cursor-to-date))
23587 nil))
23589 (defun org-agenda-convert-date ()
23590 (interactive)
23591 (org-agenda-check-type t 'agenda 'timeline)
23592 (let ((day (get-text-property (point) 'day))
23593 date s)
23594 (unless day
23595 (error "Don't know which date to convert"))
23596 (setq date (calendar-gregorian-from-absolute day))
23597 (setq s (concat
23598 "Gregorian: " (calendar-date-string date) "\n"
23599 "ISO: " (calendar-iso-date-string date) "\n"
23600 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23601 "Julian: " (calendar-julian-date-string date) "\n"
23602 "Astron. JD: " (calendar-astro-date-string date)
23603 " (Julian date number at noon UTC)\n"
23604 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23605 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23606 "French: " (calendar-french-date-string date) "\n"
23607 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23608 "Mayan: " (calendar-mayan-date-string date) "\n"
23609 "Coptic: " (calendar-coptic-date-string date) "\n"
23610 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23611 "Persian: " (calendar-persian-date-string date) "\n"
23612 "Chinese: " (calendar-chinese-date-string date) "\n"))
23613 (with-output-to-temp-buffer "*Dates*"
23614 (princ s))
23615 (if (fboundp 'fit-window-to-buffer)
23616 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23619 ;;;; Embedded LaTeX
23621 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23622 "Keymap for the minor `org-cdlatex-mode'.")
23624 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23625 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23626 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23627 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23628 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23630 (defvar org-cdlatex-texmathp-advice-is-done nil
23631 "Flag remembering if we have applied the advice to texmathp already.")
23633 (define-minor-mode org-cdlatex-mode
23634 "Toggle the minor `org-cdlatex-mode'.
23635 This mode supports entering LaTeX environment and math in LaTeX fragments
23636 in Org-mode.
23637 \\{org-cdlatex-mode-map}"
23638 nil " OCDL" nil
23639 (when org-cdlatex-mode (require 'cdlatex))
23640 (unless org-cdlatex-texmathp-advice-is-done
23641 (setq org-cdlatex-texmathp-advice-is-done t)
23642 (defadvice texmathp (around org-math-always-on activate)
23643 "Always return t in org-mode buffers.
23644 This is because we want to insert math symbols without dollars even outside
23645 the LaTeX math segments. If Orgmode thinks that point is actually inside
23646 en embedded LaTeX fragement, let texmathp do its job.
23647 \\[org-cdlatex-mode-map]"
23648 (interactive)
23649 (let (p)
23650 (cond
23651 ((not (org-mode-p)) ad-do-it)
23652 ((eq this-command 'cdlatex-math-symbol)
23653 (setq ad-return-value t
23654 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23656 (let ((p (org-inside-LaTeX-fragment-p)))
23657 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23658 (setq ad-return-value t
23659 texmathp-why '("Org-mode embedded math" . 0))
23660 (if p ad-do-it)))))))))
23662 (defun turn-on-org-cdlatex ()
23663 "Unconditionally turn on `org-cdlatex-mode'."
23664 (org-cdlatex-mode 1))
23666 (defun org-inside-LaTeX-fragment-p ()
23667 "Test if point is inside a LaTeX fragment.
23668 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23669 sequence appearing also before point.
23670 Even though the matchers for math are configurable, this function assumes
23671 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23672 delimiters are skipped when they have been removed by customization.
23673 The return value is nil, or a cons cell with the delimiter and
23674 and the position of this delimiter.
23676 This function does a reasonably good job, but can locally be fooled by
23677 for example currency specifications. For example it will assume being in
23678 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23679 fragments that are properly closed, but during editing, we have to live
23680 with the uncertainty caused by missing closing delimiters. This function
23681 looks only before point, not after."
23682 (catch 'exit
23683 (let ((pos (point))
23684 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23685 (lim (progn
23686 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23687 (point)))
23688 dd-on str (start 0) m re)
23689 (goto-char pos)
23690 (when dodollar
23691 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23692 re (nth 1 (assoc "$" org-latex-regexps)))
23693 (while (string-match re str start)
23694 (cond
23695 ((= (match-end 0) (length str))
23696 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23697 ((= (match-end 0) (- (length str) 5))
23698 (throw 'exit nil))
23699 (t (setq start (match-end 0))))))
23700 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23701 (goto-char pos)
23702 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23703 (and (match-beginning 2) (throw 'exit nil))
23704 ;; count $$
23705 (while (re-search-backward "\\$\\$" lim t)
23706 (setq dd-on (not dd-on)))
23707 (goto-char pos)
23708 (if dd-on (cons "$$" m))))))
23711 (defun org-try-cdlatex-tab ()
23712 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23713 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23714 - inside a LaTeX fragment, or
23715 - after the first word in a line, where an abbreviation expansion could
23716 insert a LaTeX environment."
23717 (when org-cdlatex-mode
23718 (cond
23719 ((save-excursion
23720 (skip-chars-backward "a-zA-Z0-9*")
23721 (skip-chars-backward " \t")
23722 (bolp))
23723 (cdlatex-tab) t)
23724 ((org-inside-LaTeX-fragment-p)
23725 (cdlatex-tab) t)
23726 (t nil))))
23728 (defun org-cdlatex-underscore-caret (&optional arg)
23729 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23730 Revert to the normal definition outside of these fragments."
23731 (interactive "P")
23732 (if (org-inside-LaTeX-fragment-p)
23733 (call-interactively 'cdlatex-sub-superscript)
23734 (let (org-cdlatex-mode)
23735 (call-interactively (key-binding (vector last-input-event))))))
23737 (defun org-cdlatex-math-modify (&optional arg)
23738 "Execute `cdlatex-math-modify' in LaTeX fragments.
23739 Revert to the normal definition outside of these fragments."
23740 (interactive "P")
23741 (if (org-inside-LaTeX-fragment-p)
23742 (call-interactively 'cdlatex-math-modify)
23743 (let (org-cdlatex-mode)
23744 (call-interactively (key-binding (vector last-input-event))))))
23746 (defvar org-latex-fragment-image-overlays nil
23747 "List of overlays carrying the images of latex fragments.")
23748 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23750 (defun org-remove-latex-fragment-image-overlays ()
23751 "Remove all overlays with LaTeX fragment images in current buffer."
23752 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23753 (setq org-latex-fragment-image-overlays nil))
23755 (defun org-preview-latex-fragment (&optional subtree)
23756 "Preview the LaTeX fragment at point, or all locally or globally.
23757 If the cursor is in a LaTeX fragment, create the image and overlay
23758 it over the source code. If there is no fragment at point, display
23759 all fragments in the current text, from one headline to the next. With
23760 prefix SUBTREE, display all fragments in the current subtree. With a
23761 double prefix `C-u C-u', or when the cursor is before the first headline,
23762 display all fragments in the buffer.
23763 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23764 (interactive "P")
23765 (org-remove-latex-fragment-image-overlays)
23766 (save-excursion
23767 (save-restriction
23768 (let (beg end at msg)
23769 (cond
23770 ((or (equal subtree '(16))
23771 (not (save-excursion
23772 (re-search-backward (concat "^" outline-regexp) nil t))))
23773 (setq beg (point-min) end (point-max)
23774 msg "Creating images for buffer...%s"))
23775 ((equal subtree '(4))
23776 (org-back-to-heading)
23777 (setq beg (point) end (org-end-of-subtree t)
23778 msg "Creating images for subtree...%s"))
23780 (if (setq at (org-inside-LaTeX-fragment-p))
23781 (goto-char (max (point-min) (- (cdr at) 2)))
23782 (org-back-to-heading))
23783 (setq beg (point) end (progn (outline-next-heading) (point))
23784 msg (if at "Creating image...%s"
23785 "Creating images for entry...%s"))))
23786 (message msg "")
23787 (narrow-to-region beg end)
23788 (goto-char beg)
23789 (org-format-latex
23790 (concat "ltxpng/" (file-name-sans-extension
23791 (file-name-nondirectory
23792 buffer-file-name)))
23793 default-directory 'overlays msg at 'forbuffer)
23794 (message msg "done. Use `C-c C-c' to remove images.")))))
23796 (defvar org-latex-regexps
23797 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23798 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23799 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23800 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23801 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23802 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23803 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23804 "Regular expressions for matching embedded LaTeX.")
23806 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23807 "Replace LaTeX fragments with links to an image, and produce images."
23808 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23809 (let* ((prefixnodir (file-name-nondirectory prefix))
23810 (absprefix (expand-file-name prefix dir))
23811 (todir (file-name-directory absprefix))
23812 (opt org-format-latex-options)
23813 (matchers (plist-get opt :matchers))
23814 (re-list org-latex-regexps)
23815 (cnt 0) txt link beg end re e checkdir
23816 m n block linkfile movefile ov)
23817 ;; Check if there are old images files with this prefix, and remove them
23818 (when (file-directory-p todir)
23819 (mapc 'delete-file
23820 (directory-files
23821 todir 'full
23822 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23823 ;; Check the different regular expressions
23824 (while (setq e (pop re-list))
23825 (setq m (car e) re (nth 1 e) n (nth 2 e)
23826 block (if (nth 3 e) "\n\n" ""))
23827 (when (member m matchers)
23828 (goto-char (point-min))
23829 (while (re-search-forward re nil t)
23830 (when (or (not at) (equal (cdr at) (match-beginning n)))
23831 (setq txt (match-string n)
23832 beg (match-beginning n) end (match-end n)
23833 cnt (1+ cnt)
23834 linkfile (format "%s_%04d.png" prefix cnt)
23835 movefile (format "%s_%04d.png" absprefix cnt)
23836 link (concat block "[[file:" linkfile "]]" block))
23837 (if msg (message msg cnt))
23838 (goto-char beg)
23839 (unless checkdir ; make sure the directory exists
23840 (setq checkdir t)
23841 (or (file-directory-p todir) (make-directory todir)))
23842 (org-create-formula-image
23843 txt movefile opt forbuffer)
23844 (if overlays
23845 (progn
23846 (setq ov (org-make-overlay beg end))
23847 (if (featurep 'xemacs)
23848 (progn
23849 (org-overlay-put ov 'invisible t)
23850 (org-overlay-put
23851 ov 'end-glyph
23852 (make-glyph (vector 'png :file movefile))))
23853 (org-overlay-put
23854 ov 'display
23855 (list 'image :type 'png :file movefile :ascent 'center)))
23856 (push ov org-latex-fragment-image-overlays)
23857 (goto-char end))
23858 (delete-region beg end)
23859 (insert link))))))))
23861 ;; This function borrows from Ganesh Swami's latex2png.el
23862 (defun org-create-formula-image (string tofile options buffer)
23863 (let* ((tmpdir (if (featurep 'xemacs)
23864 (temp-directory)
23865 temporary-file-directory))
23866 (texfilebase (make-temp-name
23867 (expand-file-name "orgtex" tmpdir)))
23868 (texfile (concat texfilebase ".tex"))
23869 (dvifile (concat texfilebase ".dvi"))
23870 (pngfile (concat texfilebase ".png"))
23871 (fnh (face-attribute 'default :height nil))
23872 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23873 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23874 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23875 "Black"))
23876 (bg (or (plist-get options (if buffer :background :html-background))
23877 "Transparent")))
23878 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23879 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23880 (with-temp-file texfile
23881 (insert org-format-latex-header
23882 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23883 (let ((dir default-directory))
23884 (condition-case nil
23885 (progn
23886 (cd tmpdir)
23887 (call-process "latex" nil nil nil texfile))
23888 (error nil))
23889 (cd dir))
23890 (if (not (file-exists-p dvifile))
23891 (progn (message "Failed to create dvi file from %s" texfile) nil)
23892 (call-process "dvipng" nil nil nil
23893 "-E" "-fg" fg "-bg" bg
23894 "-D" dpi
23895 ;;"-x" scale "-y" scale
23896 "-T" "tight"
23897 "-o" pngfile
23898 dvifile)
23899 (if (not (file-exists-p pngfile))
23900 (progn (message "Failed to create png file from %s" texfile) nil)
23901 ;; Use the requested file name and clean up
23902 (copy-file pngfile tofile 'replace)
23903 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23904 (delete-file (concat texfilebase e)))
23905 pngfile))))
23907 (defun org-dvipng-color (attr)
23908 "Return an rgb color specification for dvipng."
23909 (apply 'format "rgb %s %s %s"
23910 (mapcar 'org-normalize-color
23911 (color-values (face-attribute 'default attr nil)))))
23913 (defun org-normalize-color (value)
23914 "Return string to be used as color value for an RGB component."
23915 (format "%g" (/ value 65535.0)))
23917 ;;;; Exporting
23919 ;;; Variables, constants, and parameter plists
23921 (defconst org-level-max 20)
23923 (defvar org-export-html-preamble nil
23924 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23925 (defvar org-export-html-postamble nil
23926 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23927 (defvar org-export-html-auto-preamble t
23928 "Should default preamble be inserted? Set by publishing functions.")
23929 (defvar org-export-html-auto-postamble t
23930 "Should default postamble be inserted? Set by publishing functions.")
23931 (defvar org-current-export-file nil) ; dynamically scoped parameter
23932 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23935 (defconst org-export-plist-vars
23936 '((:language . org-export-default-language)
23937 (:customtime . org-display-custom-times)
23938 (:headline-levels . org-export-headline-levels)
23939 (:section-numbers . org-export-with-section-numbers)
23940 (:table-of-contents . org-export-with-toc)
23941 (:preserve-breaks . org-export-preserve-breaks)
23942 (:archived-trees . org-export-with-archived-trees)
23943 (:emphasize . org-export-with-emphasize)
23944 (:sub-superscript . org-export-with-sub-superscripts)
23945 (:special-strings . org-export-with-special-strings)
23946 (:footnotes . org-export-with-footnotes)
23947 (:drawers . org-export-with-drawers)
23948 (:tags . org-export-with-tags)
23949 (:TeX-macros . org-export-with-TeX-macros)
23950 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23951 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23952 (:fixed-width . org-export-with-fixed-width)
23953 (:timestamps . org-export-with-timestamps)
23954 (:author-info . org-export-author-info)
23955 (:time-stamp-file . org-export-time-stamp-file)
23956 (:tables . org-export-with-tables)
23957 (:table-auto-headline . org-export-highlight-first-table-line)
23958 (:style . org-export-html-style)
23959 (:agenda-style . org-agenda-export-html-style)
23960 (:convert-org-links . org-export-html-link-org-files-as-html)
23961 (:inline-images . org-export-html-inline-images)
23962 (:html-extension . org-export-html-extension)
23963 (:html-table-tag . org-export-html-table-tag)
23964 (:expand-quoted-html . org-export-html-expand)
23965 (:timestamp . org-export-html-with-timestamp)
23966 (:publishing-directory . org-export-publishing-directory)
23967 (:preamble . org-export-html-preamble)
23968 (:postamble . org-export-html-postamble)
23969 (:auto-preamble . org-export-html-auto-preamble)
23970 (:auto-postamble . org-export-html-auto-postamble)
23971 (:author . user-full-name)
23972 (:email . user-mail-address)))
23974 (defun org-default-export-plist ()
23975 "Return the property list with default settings for the export variables."
23976 (let ((l org-export-plist-vars) rtn e)
23977 (while (setq e (pop l))
23978 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23979 rtn))
23981 (defun org-infile-export-plist ()
23982 "Return the property list with file-local settings for export."
23983 (save-excursion
23984 (save-restriction
23985 (widen)
23986 (goto-char 0)
23987 (let ((re (org-make-options-regexp
23988 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23989 p key val text options)
23990 (while (re-search-forward re nil t)
23991 (setq key (org-match-string-no-properties 1)
23992 val (org-match-string-no-properties 2))
23993 (cond
23994 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23995 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23996 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23997 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23998 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23999 ((string-equal key "TEXT")
24000 (setq text (if text (concat text "\n" val) val)))
24001 ((string-equal key "OPTIONS") (setq options val))))
24002 (setq p (plist-put p :text text))
24003 (when options
24004 (let ((op '(("H" . :headline-levels)
24005 ("num" . :section-numbers)
24006 ("toc" . :table-of-contents)
24007 ("\\n" . :preserve-breaks)
24008 ("@" . :expand-quoted-html)
24009 (":" . :fixed-width)
24010 ("|" . :tables)
24011 ("^" . :sub-superscript)
24012 ("-" . :special-strings)
24013 ("f" . :footnotes)
24014 ("d" . :drawers)
24015 ("tags" . :tags)
24016 ("*" . :emphasize)
24017 ("TeX" . :TeX-macros)
24018 ("LaTeX" . :LaTeX-fragments)
24019 ("skip" . :skip-before-1st-heading)
24020 ("author" . :author-info)
24021 ("timestamp" . :time-stamp-file)))
24023 (while (setq o (pop op))
24024 (if (string-match (concat (regexp-quote (car o))
24025 ":\\([^ \t\n\r;,.]*\\)")
24026 options)
24027 (setq p (plist-put p (cdr o)
24028 (car (read-from-string
24029 (match-string 1 options)))))))))
24030 p))))
24032 (defun org-export-directory (type plist)
24033 (let* ((val (plist-get plist :publishing-directory))
24034 (dir (if (listp val)
24035 (or (cdr (assoc type val)) ".")
24036 val)))
24037 dir))
24039 (defun org-skip-comments (lines)
24040 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24041 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24042 (re2 "^\\(\\*+\\)[ \t\n\r]")
24043 (case-fold-search nil)
24044 rtn line level)
24045 (while (setq line (pop lines))
24046 (cond
24047 ((and (string-match re1 line)
24048 (setq level (- (match-end 1) (match-beginning 1))))
24049 ;; Beginning of a COMMENT subtree. Skip it.
24050 (while (and (setq line (pop lines))
24051 (or (not (string-match re2 line))
24052 (> (- (match-end 1) (match-beginning 1)) level))))
24053 (setq lines (cons line lines)))
24054 ((string-match "^#" line)
24055 ;; an ordinary comment line
24057 ((and org-export-table-remove-special-lines
24058 (string-match "^[ \t]*|" line)
24059 (or (string-match "^[ \t]*| *[!_^] *|" line)
24060 (and (string-match "| *<[0-9]+> *|" line)
24061 (not (string-match "| *[^ <|]" line)))))
24062 ;; a special table line that should be removed
24064 (t (setq rtn (cons line rtn)))))
24065 (nreverse rtn)))
24067 (defun org-export (&optional arg)
24068 (interactive)
24069 (let ((help "[t] insert the export option template
24070 \[v] limit export to visible part of outline tree
24072 \[a] export as ASCII
24074 \[h] export as HTML
24075 \[H] export as HTML to temporary buffer
24076 \[R] export region as HTML
24077 \[b] export as HTML and browse immediately
24078 \[x] export as XOXO
24080 \[l] export as LaTeX
24081 \[L] export as LaTeX to temporary buffer
24083 \[i] export current file as iCalendar file
24084 \[I] export all agenda files as iCalendar files
24085 \[c] export agenda files into combined iCalendar file
24087 \[F] publish current file
24088 \[P] publish current project
24089 \[X] publish... (project will be prompted for)
24090 \[A] publish all projects")
24091 (cmds
24092 '((?t . org-insert-export-options-template)
24093 (?v . org-export-visible)
24094 (?a . org-export-as-ascii)
24095 (?h . org-export-as-html)
24096 (?b . org-export-as-html-and-open)
24097 (?H . org-export-as-html-to-buffer)
24098 (?R . org-export-region-as-html)
24099 (?x . org-export-as-xoxo)
24100 (?l . org-export-as-latex)
24101 (?L . org-export-as-latex-to-buffer)
24102 (?i . org-export-icalendar-this-file)
24103 (?I . org-export-icalendar-all-agenda-files)
24104 (?c . org-export-icalendar-combine-agenda-files)
24105 (?F . org-publish-current-file)
24106 (?P . org-publish-current-project)
24107 (?X . org-publish)
24108 (?A . org-publish-all)))
24109 r1 r2 ass)
24110 (save-window-excursion
24111 (delete-other-windows)
24112 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24113 (princ help))
24114 (message "Select command: ")
24115 (setq r1 (read-char-exclusive)))
24116 (setq r2 (if (< r1 27) (+ r1 96) r1))
24117 (if (setq ass (assq r2 cmds))
24118 (call-interactively (cdr ass))
24119 (error "No command associated with key %c" r1))))
24121 (defconst org-html-entities
24122 '(("nbsp")
24123 ("iexcl")
24124 ("cent")
24125 ("pound")
24126 ("curren")
24127 ("yen")
24128 ("brvbar")
24129 ("vert" . "&#124;")
24130 ("sect")
24131 ("uml")
24132 ("copy")
24133 ("ordf")
24134 ("laquo")
24135 ("not")
24136 ("shy")
24137 ("reg")
24138 ("macr")
24139 ("deg")
24140 ("plusmn")
24141 ("sup2")
24142 ("sup3")
24143 ("acute")
24144 ("micro")
24145 ("para")
24146 ("middot")
24147 ("odot"."o")
24148 ("star"."*")
24149 ("cedil")
24150 ("sup1")
24151 ("ordm")
24152 ("raquo")
24153 ("frac14")
24154 ("frac12")
24155 ("frac34")
24156 ("iquest")
24157 ("Agrave")
24158 ("Aacute")
24159 ("Acirc")
24160 ("Atilde")
24161 ("Auml")
24162 ("Aring") ("AA"."&Aring;")
24163 ("AElig")
24164 ("Ccedil")
24165 ("Egrave")
24166 ("Eacute")
24167 ("Ecirc")
24168 ("Euml")
24169 ("Igrave")
24170 ("Iacute")
24171 ("Icirc")
24172 ("Iuml")
24173 ("ETH")
24174 ("Ntilde")
24175 ("Ograve")
24176 ("Oacute")
24177 ("Ocirc")
24178 ("Otilde")
24179 ("Ouml")
24180 ("times")
24181 ("Oslash")
24182 ("Ugrave")
24183 ("Uacute")
24184 ("Ucirc")
24185 ("Uuml")
24186 ("Yacute")
24187 ("THORN")
24188 ("szlig")
24189 ("agrave")
24190 ("aacute")
24191 ("acirc")
24192 ("atilde")
24193 ("auml")
24194 ("aring")
24195 ("aelig")
24196 ("ccedil")
24197 ("egrave")
24198 ("eacute")
24199 ("ecirc")
24200 ("euml")
24201 ("igrave")
24202 ("iacute")
24203 ("icirc")
24204 ("iuml")
24205 ("eth")
24206 ("ntilde")
24207 ("ograve")
24208 ("oacute")
24209 ("ocirc")
24210 ("otilde")
24211 ("ouml")
24212 ("divide")
24213 ("oslash")
24214 ("ugrave")
24215 ("uacute")
24216 ("ucirc")
24217 ("uuml")
24218 ("yacute")
24219 ("thorn")
24220 ("yuml")
24221 ("fnof")
24222 ("Alpha")
24223 ("Beta")
24224 ("Gamma")
24225 ("Delta")
24226 ("Epsilon")
24227 ("Zeta")
24228 ("Eta")
24229 ("Theta")
24230 ("Iota")
24231 ("Kappa")
24232 ("Lambda")
24233 ("Mu")
24234 ("Nu")
24235 ("Xi")
24236 ("Omicron")
24237 ("Pi")
24238 ("Rho")
24239 ("Sigma")
24240 ("Tau")
24241 ("Upsilon")
24242 ("Phi")
24243 ("Chi")
24244 ("Psi")
24245 ("Omega")
24246 ("alpha")
24247 ("beta")
24248 ("gamma")
24249 ("delta")
24250 ("epsilon")
24251 ("varepsilon"."&epsilon;")
24252 ("zeta")
24253 ("eta")
24254 ("theta")
24255 ("iota")
24256 ("kappa")
24257 ("lambda")
24258 ("mu")
24259 ("nu")
24260 ("xi")
24261 ("omicron")
24262 ("pi")
24263 ("rho")
24264 ("sigmaf") ("varsigma"."&sigmaf;")
24265 ("sigma")
24266 ("tau")
24267 ("upsilon")
24268 ("phi")
24269 ("chi")
24270 ("psi")
24271 ("omega")
24272 ("thetasym") ("vartheta"."&thetasym;")
24273 ("upsih")
24274 ("piv")
24275 ("bull") ("bullet"."&bull;")
24276 ("hellip") ("dots"."&hellip;")
24277 ("prime")
24278 ("Prime")
24279 ("oline")
24280 ("frasl")
24281 ("weierp")
24282 ("image")
24283 ("real")
24284 ("trade")
24285 ("alefsym")
24286 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24287 ("uarr") ("uparrow"."&uarr;")
24288 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24289 ("darr")("downarrow"."&darr;")
24290 ("harr") ("leftrightarrow"."&harr;")
24291 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24292 ("lArr") ("Leftarrow"."&lArr;")
24293 ("uArr") ("Uparrow"."&uArr;")
24294 ("rArr") ("Rightarrow"."&rArr;")
24295 ("dArr") ("Downarrow"."&dArr;")
24296 ("hArr") ("Leftrightarrow"."&hArr;")
24297 ("forall")
24298 ("part") ("partial"."&part;")
24299 ("exist") ("exists"."&exist;")
24300 ("empty") ("emptyset"."&empty;")
24301 ("nabla")
24302 ("isin") ("in"."&isin;")
24303 ("notin")
24304 ("ni")
24305 ("prod")
24306 ("sum")
24307 ("minus")
24308 ("lowast") ("ast"."&lowast;")
24309 ("radic")
24310 ("prop") ("proptp"."&prop;")
24311 ("infin") ("infty"."&infin;")
24312 ("ang") ("angle"."&ang;")
24313 ("and") ("wedge"."&and;")
24314 ("or") ("vee"."&or;")
24315 ("cap")
24316 ("cup")
24317 ("int")
24318 ("there4")
24319 ("sim")
24320 ("cong") ("simeq"."&cong;")
24321 ("asymp")("approx"."&asymp;")
24322 ("ne") ("neq"."&ne;")
24323 ("equiv")
24324 ("le")
24325 ("ge")
24326 ("sub") ("subset"."&sub;")
24327 ("sup") ("supset"."&sup;")
24328 ("nsub")
24329 ("sube")
24330 ("supe")
24331 ("oplus")
24332 ("otimes")
24333 ("perp")
24334 ("sdot") ("cdot"."&sdot;")
24335 ("lceil")
24336 ("rceil")
24337 ("lfloor")
24338 ("rfloor")
24339 ("lang")
24340 ("rang")
24341 ("loz") ("Diamond"."&loz;")
24342 ("spades") ("spadesuit"."&spades;")
24343 ("clubs") ("clubsuit"."&clubs;")
24344 ("hearts") ("diamondsuit"."&hearts;")
24345 ("diams") ("diamondsuit"."&diams;")
24346 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24347 ("quot")
24348 ("amp")
24349 ("lt")
24350 ("gt")
24351 ("OElig")
24352 ("oelig")
24353 ("Scaron")
24354 ("scaron")
24355 ("Yuml")
24356 ("circ")
24357 ("tilde")
24358 ("ensp")
24359 ("emsp")
24360 ("thinsp")
24361 ("zwnj")
24362 ("zwj")
24363 ("lrm")
24364 ("rlm")
24365 ("ndash")
24366 ("mdash")
24367 ("lsquo")
24368 ("rsquo")
24369 ("sbquo")
24370 ("ldquo")
24371 ("rdquo")
24372 ("bdquo")
24373 ("dagger")
24374 ("Dagger")
24375 ("permil")
24376 ("lsaquo")
24377 ("rsaquo")
24378 ("euro")
24380 ("arccos"."arccos")
24381 ("arcsin"."arcsin")
24382 ("arctan"."arctan")
24383 ("arg"."arg")
24384 ("cos"."cos")
24385 ("cosh"."cosh")
24386 ("cot"."cot")
24387 ("coth"."coth")
24388 ("csc"."csc")
24389 ("deg"."deg")
24390 ("det"."det")
24391 ("dim"."dim")
24392 ("exp"."exp")
24393 ("gcd"."gcd")
24394 ("hom"."hom")
24395 ("inf"."inf")
24396 ("ker"."ker")
24397 ("lg"."lg")
24398 ("lim"."lim")
24399 ("liminf"."liminf")
24400 ("limsup"."limsup")
24401 ("ln"."ln")
24402 ("log"."log")
24403 ("max"."max")
24404 ("min"."min")
24405 ("Pr"."Pr")
24406 ("sec"."sec")
24407 ("sin"."sin")
24408 ("sinh"."sinh")
24409 ("sup"."sup")
24410 ("tan"."tan")
24411 ("tanh"."tanh")
24413 "Entities for TeX->HTML translation.
24414 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24415 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24416 In that case, \"\\ent\" will be translated to \"&other;\".
24417 The list contains HTML entities for Latin-1, Greek and other symbols.
24418 It is supplemented by a number of commonly used TeX macros with appropriate
24419 translations. There is currently no way for users to extend this.")
24421 ;;; General functions for all backends
24423 (defun org-cleaned-string-for-export (string &rest parameters)
24424 "Cleanup a buffer STRING so that links can be created safely."
24425 (interactive)
24426 (let* ((re-radio (and org-target-link-regexp
24427 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24428 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24429 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24430 (re-archive (concat ":" org-archive-tag ":"))
24431 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24432 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24433 (htmlp (plist-get parameters :for-html))
24434 (asciip (plist-get parameters :for-ascii))
24435 (latexp (plist-get parameters :for-LaTeX))
24436 (commentsp (plist-get parameters :comments))
24437 (archived-trees (plist-get parameters :archived-trees))
24438 (inhibit-read-only t)
24439 (drawers org-drawers)
24440 (exp-drawers (plist-get parameters :drawers))
24441 (outline-regexp "\\*+ ")
24442 a b xx
24443 rtn p)
24444 (with-current-buffer (get-buffer-create " org-mode-tmp")
24445 (erase-buffer)
24446 (insert string)
24447 ;; Remove license-to-kill stuff
24448 (while (setq p (text-property-any (point-min) (point-max)
24449 :org-license-to-kill t))
24450 (delete-region p (next-single-property-change p :org-license-to-kill)))
24452 (let ((org-inhibit-startup t)) (org-mode))
24453 (untabify (point-min) (point-max))
24455 ;; Get rid of drawers
24456 (unless (eq t exp-drawers)
24457 (goto-char (point-min))
24458 (let ((re (concat "^[ \t]*:\\("
24459 (mapconcat
24460 'identity
24461 (org-delete-all exp-drawers
24462 (copy-sequence drawers))
24463 "\\|")
24464 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24465 (while (re-search-forward re nil t)
24466 (replace-match ""))))
24468 ;; Get the correct stuff before the first headline
24469 (when (plist-get parameters :skip-before-1st-heading)
24470 (goto-char (point-min))
24471 (when (re-search-forward "^\\*+[ \t]" nil t)
24472 (delete-region (point-min) (match-beginning 0))
24473 (goto-char (point-min))
24474 (insert "\n")))
24475 (when (plist-get parameters :add-text)
24476 (goto-char (point-min))
24477 (insert (plist-get parameters :add-text) "\n"))
24479 ;; Get rid of archived trees
24480 (when (not (eq archived-trees t))
24481 (goto-char (point-min))
24482 (while (re-search-forward re-archive nil t)
24483 (if (not (org-on-heading-p t))
24484 (org-end-of-subtree t)
24485 (beginning-of-line 1)
24486 (setq a (if archived-trees
24487 (1+ (point-at-eol)) (point))
24488 b (org-end-of-subtree t))
24489 (if (> b a) (delete-region a b)))))
24491 ;; Find targets in comments and move them out of comments,
24492 ;; but mark them as targets that should be invisible
24493 (goto-char (point-min))
24494 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24495 (replace-match "\\1(INVISIBLE)"))
24497 ;; Protect backend specific stuff, throw away the others.
24498 (let ((formatters
24499 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24500 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24501 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24502 fmt)
24503 (goto-char (point-min))
24504 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24505 (goto-char (match-end 0))
24506 (while (not (looking-at "#\\+END_EXAMPLE"))
24507 (insert ": ")
24508 (beginning-of-line 2)))
24509 (goto-char (point-min))
24510 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24511 (add-text-properties (match-beginning 0) (match-end 0)
24512 '(org-protected t)))
24513 (while formatters
24514 (setq fmt (pop formatters))
24515 (when (car fmt)
24516 (goto-char (point-min))
24517 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24518 ":[ \t]*\\(.*\\)") nil t)
24519 (replace-match "\\1" t)
24520 (add-text-properties
24521 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24522 '(org-protected t))))
24523 (goto-char (point-min))
24524 (while (re-search-forward
24525 (concat "^#\\+"
24526 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24527 (cadddr fmt) "\\>.*\n?") nil t)
24528 (if (car fmt)
24529 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24530 '(org-protected t))
24531 (delete-region (match-beginning 0) (match-end 0))))))
24533 ;; Protect quoted subtrees
24534 (goto-char (point-min))
24535 (while (re-search-forward re-quote nil t)
24536 (goto-char (match-beginning 0))
24537 (end-of-line 1)
24538 (add-text-properties (point) (org-end-of-subtree t)
24539 '(org-protected t)))
24541 ;; Protect verbatim elements
24542 (goto-char (point-min))
24543 (while (re-search-forward org-verbatim-re nil t)
24544 (add-text-properties (match-beginning 4) (match-end 4)
24545 '(org-protected t))
24546 (goto-char (1+ (match-end 4))))
24548 ;; Remove subtrees that are commented
24549 (goto-char (point-min))
24550 (while (re-search-forward re-commented nil t)
24551 (goto-char (match-beginning 0))
24552 (delete-region (point) (org-end-of-subtree t)))
24554 ;; Remove special table lines
24555 (when org-export-table-remove-special-lines
24556 (goto-char (point-min))
24557 (while (re-search-forward "^[ \t]*|" nil t)
24558 (beginning-of-line 1)
24559 (if (or (looking-at "[ \t]*| *[!_^] *|")
24560 (and (looking-at ".*?| *<[0-9]+> *|")
24561 (not (looking-at ".*?| *[^ <|]"))))
24562 (delete-region (max (point-min) (1- (point-at-bol)))
24563 (point-at-eol))
24564 (end-of-line 1))))
24566 ;; Specific LaTeX stuff
24567 (when latexp
24568 (require 'org-export-latex nil)
24569 (org-export-latex-cleaned-string))
24571 (when asciip
24572 (org-export-ascii-clean-string))
24574 ;; Specific HTML stuff
24575 (when htmlp
24576 ;; Convert LaTeX fragments to images
24577 (when (plist-get parameters :LaTeX-fragments)
24578 (org-format-latex
24579 (concat "ltxpng/" (file-name-sans-extension
24580 (file-name-nondirectory
24581 org-current-export-file)))
24582 org-current-export-dir nil "Creating LaTeX image %s"))
24583 (message "Exporting..."))
24585 ;; Remove or replace comments
24586 (goto-char (point-min))
24587 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24588 (if commentsp
24589 (progn (add-text-properties
24590 (match-beginning 0) (match-end 0) '(org-protected t))
24591 (replace-match (format commentsp (match-string 1)) t t))
24592 (replace-match "")))
24594 ;; Find matches for radio targets and turn them into internal links
24595 (goto-char (point-min))
24596 (when re-radio
24597 (while (re-search-forward re-radio nil t)
24598 (org-if-unprotected
24599 (replace-match "\\1[[\\2]]"))))
24601 ;; Find all links that contain a newline and put them into a single line
24602 (goto-char (point-min))
24603 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24604 (org-if-unprotected
24605 (replace-match "\\1 \\3")
24606 (goto-char (match-beginning 0))))
24609 ;; Normalize links: Convert angle and plain links into bracket links
24610 ;; Expand link abbreviations
24611 (goto-char (point-min))
24612 (while (re-search-forward re-plain-link nil t)
24613 (goto-char (1- (match-end 0)))
24614 (org-if-unprotected
24615 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24616 ":" (match-string 3) "]]")))
24617 ;; added 'org-link face to links
24618 (put-text-property 0 (length s) 'face 'org-link s)
24619 (replace-match s t t))))
24620 (goto-char (point-min))
24621 (while (re-search-forward re-angle-link nil t)
24622 (goto-char (1- (match-end 0)))
24623 (org-if-unprotected
24624 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24625 ":" (match-string 3) "]]")))
24626 (put-text-property 0 (length s) 'face 'org-link s)
24627 (replace-match s t t))))
24628 (goto-char (point-min))
24629 (while (re-search-forward org-bracket-link-regexp nil t)
24630 (org-if-unprotected
24631 (let* ((s (concat "[[" (setq xx (save-match-data
24632 (org-link-expand-abbrev (match-string 1))))
24634 (if (match-end 3)
24635 (match-string 2)
24636 (concat "[" xx "]"))
24637 "]")))
24638 (put-text-property 0 (length s) 'face 'org-link s)
24639 (replace-match s t t))))
24641 ;; Find multiline emphasis and put them into single line
24642 (when (plist-get parameters :emph-multiline)
24643 (goto-char (point-min))
24644 (while (re-search-forward org-emph-re nil t)
24645 (if (not (= (char-after (match-beginning 3))
24646 (char-after (match-beginning 4))))
24647 (org-if-unprotected
24648 (subst-char-in-region (match-beginning 0) (match-end 0)
24649 ?\n ?\ t)
24650 (goto-char (1- (match-end 0))))
24651 (goto-char (1+ (match-beginning 0))))))
24653 (setq rtn (buffer-string)))
24654 (kill-buffer " org-mode-tmp")
24655 rtn))
24657 (defun org-export-grab-title-from-buffer ()
24658 "Get a title for the current document, from looking at the buffer."
24659 (let ((inhibit-read-only t))
24660 (save-excursion
24661 (goto-char (point-min))
24662 (let ((end (save-excursion (outline-next-heading) (point))))
24663 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24664 ;; Mark the line so that it will not be exported as normal text.
24665 (org-unmodified
24666 (add-text-properties (match-beginning 0) (match-end 0)
24667 (list :org-license-to-kill t)))
24668 ;; Return the title string
24669 (org-trim (match-string 0)))))))
24671 (defun org-export-get-title-from-subtree ()
24672 "Return subtree title and exclude it from export."
24673 (let (title (m (mark)))
24674 (save-excursion
24675 (goto-char (region-beginning))
24676 (when (and (org-at-heading-p)
24677 (>= (org-end-of-subtree t t) (region-end)))
24678 ;; This is a subtree, we take the title from the first heading
24679 (goto-char (region-beginning))
24680 (looking-at org-todo-line-regexp)
24681 (setq title (match-string 3))
24682 (org-unmodified
24683 (add-text-properties (point) (1+ (point-at-eol))
24684 (list :org-license-to-kill t)))))
24685 title))
24687 (defun org-solidify-link-text (s &optional alist)
24688 "Take link text and make a safe target out of it."
24689 (save-match-data
24690 (let* ((rtn
24691 (mapconcat
24692 'identity
24693 (org-split-string s "[ \t\r\n]+") "--"))
24694 (a (assoc rtn alist)))
24695 (or (cdr a) rtn))))
24697 (defun org-get-min-level (lines)
24698 "Get the minimum level in LINES."
24699 (let ((re "^\\(\\*+\\) ") l min)
24700 (catch 'exit
24701 (while (setq l (pop lines))
24702 (if (string-match re l)
24703 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24704 1)))
24706 ;; Variable holding the vector with section numbers
24707 (defvar org-section-numbers (make-vector org-level-max 0))
24709 (defun org-init-section-numbers ()
24710 "Initialize the vector for the section numbers."
24711 (let* ((level -1)
24712 (numbers (nreverse (org-split-string "" "\\.")))
24713 (depth (1- (length org-section-numbers)))
24714 (i depth) number-string)
24715 (while (>= i 0)
24716 (if (> i level)
24717 (aset org-section-numbers i 0)
24718 (setq number-string (or (car numbers) "0"))
24719 (if (string-match "\\`[A-Z]\\'" number-string)
24720 (aset org-section-numbers i
24721 (- (string-to-char number-string) ?A -1))
24722 (aset org-section-numbers i (string-to-number number-string)))
24723 (pop numbers))
24724 (setq i (1- i)))))
24726 (defun org-section-number (&optional level)
24727 "Return a string with the current section number.
24728 When LEVEL is non-nil, increase section numbers on that level."
24729 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24730 (when level
24731 (when (> level -1)
24732 (aset org-section-numbers
24733 level (1+ (aref org-section-numbers level))))
24734 (setq idx (1+ level))
24735 (while (<= idx depth)
24736 (if (not (= idx 1))
24737 (aset org-section-numbers idx 0))
24738 (setq idx (1+ idx))))
24739 (setq idx 0)
24740 (while (<= idx depth)
24741 (setq n (aref org-section-numbers idx))
24742 (setq string (concat string (if (not (string= string "")) "." "")
24743 (int-to-string n)))
24744 (setq idx (1+ idx)))
24745 (save-match-data
24746 (if (string-match "\\`\\([@0]\\.\\)+" string)
24747 (setq string (replace-match "" t nil string)))
24748 (if (string-match "\\(\\.0\\)+\\'" string)
24749 (setq string (replace-match "" t nil string))))
24750 string))
24752 ;;; ASCII export
24754 (defvar org-last-level nil) ; dynamically scoped variable
24755 (defvar org-min-level nil) ; dynamically scoped variable
24756 (defvar org-levels-open nil) ; dynamically scoped parameter
24757 (defvar org-ascii-current-indentation nil) ; For communication
24759 (defun org-export-as-ascii (arg)
24760 "Export the outline as a pretty ASCII file.
24761 If there is an active region, export only the region.
24762 The prefix ARG specifies how many levels of the outline should become
24763 underlined headlines. The default is 3."
24764 (interactive "P")
24765 (setq-default org-todo-line-regexp org-todo-line-regexp)
24766 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24767 (org-infile-export-plist)))
24768 (region-p (org-region-active-p))
24769 (subtree-p
24770 (when region-p
24771 (save-excursion
24772 (goto-char (region-beginning))
24773 (and (org-at-heading-p)
24774 (>= (org-end-of-subtree t t) (region-end))))))
24775 (custom-times org-display-custom-times)
24776 (org-ascii-current-indentation '(0 . 0))
24777 (level 0) line txt
24778 (umax nil)
24779 (umax-toc nil)
24780 (case-fold-search nil)
24781 (filename (concat (file-name-as-directory
24782 (org-export-directory :ascii opt-plist))
24783 (file-name-sans-extension
24784 (or (and subtree-p
24785 (org-entry-get (region-beginning)
24786 "EXPORT_FILE_NAME" t))
24787 (file-name-nondirectory buffer-file-name)))
24788 ".txt"))
24789 (filename (if (equal (file-truename filename)
24790 (file-truename buffer-file-name))
24791 (concat filename ".txt")
24792 filename))
24793 (buffer (find-file-noselect filename))
24794 (org-levels-open (make-vector org-level-max nil))
24795 (odd org-odd-levels-only)
24796 (date (plist-get opt-plist :date))
24797 (author (plist-get opt-plist :author))
24798 (title (or (and subtree-p (org-export-get-title-from-subtree))
24799 (plist-get opt-plist :title)
24800 (and (not
24801 (plist-get opt-plist :skip-before-1st-heading))
24802 (org-export-grab-title-from-buffer))
24803 (file-name-sans-extension
24804 (file-name-nondirectory buffer-file-name))))
24805 (email (plist-get opt-plist :email))
24806 (language (plist-get opt-plist :language))
24807 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24808 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24809 (todo nil)
24810 (lang-words nil)
24811 (region
24812 (buffer-substring
24813 (if (org-region-active-p) (region-beginning) (point-min))
24814 (if (org-region-active-p) (region-end) (point-max))))
24815 (lines (org-split-string
24816 (org-cleaned-string-for-export
24817 region
24818 :for-ascii t
24819 :skip-before-1st-heading
24820 (plist-get opt-plist :skip-before-1st-heading)
24821 :drawers (plist-get opt-plist :drawers)
24822 :verbatim-multiline t
24823 :archived-trees
24824 (plist-get opt-plist :archived-trees)
24825 :add-text (plist-get opt-plist :text))
24826 "\n"))
24827 thetoc have-headings first-heading-pos
24828 table-open table-buffer)
24830 (let ((inhibit-read-only t))
24831 (org-unmodified
24832 (remove-text-properties (point-min) (point-max)
24833 '(:org-license-to-kill t))))
24835 (setq org-min-level (org-get-min-level lines))
24836 (setq org-last-level org-min-level)
24837 (org-init-section-numbers)
24839 (find-file-noselect filename)
24841 (setq lang-words (or (assoc language org-export-language-setup)
24842 (assoc "en" org-export-language-setup)))
24843 (switch-to-buffer-other-window buffer)
24844 (erase-buffer)
24845 (fundamental-mode)
24846 ;; create local variables for all options, to make sure all called
24847 ;; functions get the correct information
24848 (mapc (lambda (x)
24849 (set (make-local-variable (cdr x))
24850 (plist-get opt-plist (car x))))
24851 org-export-plist-vars)
24852 (org-set-local 'org-odd-levels-only odd)
24853 (setq umax (if arg (prefix-numeric-value arg)
24854 org-export-headline-levels))
24855 (setq umax-toc (if (integerp org-export-with-toc)
24856 (min org-export-with-toc umax)
24857 umax))
24859 ;; File header
24860 (if title (org-insert-centered title ?=))
24861 (insert "\n")
24862 (if (and (or author email)
24863 org-export-author-info)
24864 (insert (concat (nth 1 lang-words) ": " (or author "")
24865 (if email (concat " <" email ">") "")
24866 "\n")))
24868 (cond
24869 ((and date (string-match "%" date))
24870 (setq date (format-time-string date)))
24871 (date)
24872 (t (setq date (format-time-string "%Y/%m/%d %X"))))
24874 (if (and date org-export-time-stamp-file)
24875 (insert (concat (nth 2 lang-words) ": " date"\n")))
24877 (insert "\n\n")
24879 (if org-export-with-toc
24880 (progn
24881 (push (concat (nth 3 lang-words) "\n") thetoc)
24882 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24883 (mapc '(lambda (line)
24884 (if (string-match org-todo-line-regexp
24885 line)
24886 ;; This is a headline
24887 (progn
24888 (setq have-headings t)
24889 (setq level (- (match-end 1) (match-beginning 1))
24890 level (org-tr-level level)
24891 txt (match-string 3 line)
24892 todo
24893 (or (and org-export-mark-todo-in-toc
24894 (match-beginning 2)
24895 (not (member (match-string 2 line)
24896 org-done-keywords)))
24897 ; TODO, not DONE
24898 (and org-export-mark-todo-in-toc
24899 (= level umax-toc)
24900 (org-search-todo-below
24901 line lines level))))
24902 (setq txt (org-html-expand-for-ascii txt))
24904 (while (string-match org-bracket-link-regexp txt)
24905 (setq txt
24906 (replace-match
24907 (match-string (if (match-end 2) 3 1) txt)
24908 t t txt)))
24910 (if (and (memq org-export-with-tags '(not-in-toc nil))
24911 (string-match
24912 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24913 txt))
24914 (setq txt (replace-match "" t t txt)))
24915 (if (string-match quote-re0 txt)
24916 (setq txt (replace-match "" t t txt)))
24918 (if org-export-with-section-numbers
24919 (setq txt (concat (org-section-number level)
24920 " " txt)))
24921 (if (<= level umax-toc)
24922 (progn
24923 (push
24924 (concat
24925 (make-string
24926 (* (max 0 (- level org-min-level)) 4) ?\ )
24927 (format (if todo "%s (*)\n" "%s\n") txt))
24928 thetoc)
24929 (setq org-last-level level))
24930 ))))
24931 lines)
24932 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24934 (org-init-section-numbers)
24935 (while (setq line (pop lines))
24936 ;; Remove the quoted HTML tags.
24937 (setq line (org-html-expand-for-ascii line))
24938 ;; Remove targets
24939 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24940 (setq line (replace-match "" t t line)))
24941 ;; Replace internal links
24942 (while (string-match org-bracket-link-regexp line)
24943 (setq line (replace-match
24944 (if (match-end 3) "[\\3]" "[\\1]")
24945 t nil line)))
24946 (when custom-times
24947 (setq line (org-translate-time line)))
24948 (cond
24949 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24950 ;; a Headline
24951 (setq first-heading-pos (or first-heading-pos (point)))
24952 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24953 txt (match-string 2 line))
24954 (org-ascii-level-start level txt umax lines))
24956 ((and org-export-with-tables
24957 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24958 (if (not table-open)
24959 ;; New table starts
24960 (setq table-open t table-buffer nil))
24961 ;; Accumulate lines
24962 (setq table-buffer (cons line table-buffer))
24963 (when (or (not lines)
24964 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24965 (car lines))))
24966 (setq table-open nil
24967 table-buffer (nreverse table-buffer))
24968 (insert (mapconcat
24969 (lambda (x)
24970 (org-fix-indentation x org-ascii-current-indentation))
24971 (org-format-table-ascii table-buffer)
24972 "\n") "\n")))
24974 (setq line (org-fix-indentation line org-ascii-current-indentation))
24975 (if (and org-export-with-fixed-width
24976 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24977 (setq line (replace-match "\\1" nil nil line)))
24978 (insert line "\n"))))
24980 (normal-mode)
24982 ;; insert the table of contents
24983 (when thetoc
24984 (goto-char (point-min))
24985 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24986 (progn
24987 (goto-char (match-beginning 0))
24988 (replace-match ""))
24989 (goto-char first-heading-pos))
24990 (mapc 'insert thetoc)
24991 (or (looking-at "[ \t]*\n[ \t]*\n")
24992 (insert "\n\n")))
24994 ;; Convert whitespace place holders
24995 (goto-char (point-min))
24996 (let (beg end)
24997 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24998 (setq end (next-single-property-change beg 'org-whitespace))
24999 (goto-char beg)
25000 (delete-region beg end)
25001 (insert (make-string (- end beg) ?\ ))))
25003 (save-buffer)
25004 ;; remove display and invisible chars
25005 (let (beg end)
25006 (goto-char (point-min))
25007 (while (setq beg (next-single-property-change (point) 'display))
25008 (setq end (next-single-property-change beg 'display))
25009 (delete-region beg end)
25010 (goto-char beg)
25011 (insert "=>"))
25012 (goto-char (point-min))
25013 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25014 (setq end (next-single-property-change beg 'org-cwidth))
25015 (delete-region beg end)
25016 (goto-char beg)))
25017 (goto-char (point-min))))
25019 (defun org-export-ascii-clean-string ()
25020 "Do extra work for ASCII export"
25021 (goto-char (point-min))
25022 (while (re-search-forward org-verbatim-re nil t)
25023 (goto-char (match-end 2))
25024 (backward-delete-char 1) (insert "'")
25025 (goto-char (match-beginning 2))
25026 (delete-char 1) (insert "`")
25027 (goto-char (match-end 2))))
25029 (defun org-search-todo-below (line lines level)
25030 "Search the subtree below LINE for any TODO entries."
25031 (let ((rest (cdr (memq line lines)))
25032 (re org-todo-line-regexp)
25033 line lv todo)
25034 (catch 'exit
25035 (while (setq line (pop rest))
25036 (if (string-match re line)
25037 (progn
25038 (setq lv (- (match-end 1) (match-beginning 1))
25039 todo (and (match-beginning 2)
25040 (not (member (match-string 2 line)
25041 org-done-keywords))))
25042 ; TODO, not DONE
25043 (if (<= lv level) (throw 'exit nil))
25044 (if todo (throw 'exit t))))))))
25046 (defun org-html-expand-for-ascii (line)
25047 "Handle quoted HTML for ASCII export."
25048 (if org-export-html-expand
25049 (while (string-match "@<[^<>\n]*>" line)
25050 ;; We just remove the tags for now.
25051 (setq line (replace-match "" nil nil line))))
25052 line)
25054 (defun org-insert-centered (s &optional underline)
25055 "Insert the string S centered and underline it with character UNDERLINE."
25056 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25057 (insert (make-string ind ?\ ) s "\n")
25058 (if underline
25059 (insert (make-string ind ?\ )
25060 (make-string (string-width s) underline)
25061 "\n"))))
25063 (defun org-ascii-level-start (level title umax &optional lines)
25064 "Insert a new level in ASCII export."
25065 (let (char (n (- level umax 1)) (ind 0))
25066 (if (> level umax)
25067 (progn
25068 (insert (make-string (* 2 n) ?\ )
25069 (char-to-string (nth (% n (length org-export-ascii-bullets))
25070 org-export-ascii-bullets))
25071 " " title "\n")
25072 ;; find the indentation of the next non-empty line
25073 (catch 'stop
25074 (while lines
25075 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25076 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25077 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25078 (pop lines)))
25079 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25080 (if (or (not (equal (char-before) ?\n))
25081 (not (equal (char-before (1- (point))) ?\n)))
25082 (insert "\n"))
25083 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25084 (unless org-export-with-tags
25085 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25086 (setq title (replace-match "" t t title))))
25087 (if org-export-with-section-numbers
25088 (setq title (concat (org-section-number level) " " title)))
25089 (insert title "\n" (make-string (string-width title) char) "\n")
25090 (setq org-ascii-current-indentation '(0 . 0)))))
25092 (defun org-export-visible (type arg)
25093 "Create a copy of the visible part of the current buffer, and export it.
25094 The copy is created in a temporary buffer and removed after use.
25095 TYPE is the final key (as a string) that also select the export command in
25096 the `C-c C-e' export dispatcher.
25097 As a special case, if the you type SPC at the prompt, the temporary
25098 org-mode file will not be removed but presented to you so that you can
25099 continue to use it. The prefix arg ARG is passed through to the exporting
25100 command."
25101 (interactive
25102 (list (progn
25103 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25104 (read-char-exclusive))
25105 current-prefix-arg))
25106 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25107 (error "Invalid export key"))
25108 (let* ((binding (cdr (assoc type
25109 '((?a . org-export-as-ascii)
25110 (?\C-a . org-export-as-ascii)
25111 (?b . org-export-as-html-and-open)
25112 (?\C-b . org-export-as-html-and-open)
25113 (?h . org-export-as-html)
25114 (?H . org-export-as-html-to-buffer)
25115 (?R . org-export-region-as-html)
25116 (?x . org-export-as-xoxo)))))
25117 (keepp (equal type ?\ ))
25118 (file buffer-file-name)
25119 (buffer (get-buffer-create "*Org Export Visible*"))
25120 s e)
25121 ;; Need to hack the drawers here.
25122 (save-excursion
25123 (goto-char (point-min))
25124 (while (re-search-forward org-drawer-regexp nil t)
25125 (goto-char (match-beginning 1))
25126 (or (org-invisible-p) (org-flag-drawer nil))))
25127 (with-current-buffer buffer (erase-buffer))
25128 (save-excursion
25129 (setq s (goto-char (point-min)))
25130 (while (not (= (point) (point-max)))
25131 (goto-char (org-find-invisible))
25132 (append-to-buffer buffer s (point))
25133 (setq s (goto-char (org-find-visible))))
25134 (org-cycle-hide-drawers 'all)
25135 (goto-char (point-min))
25136 (unless keepp
25137 ;; Copy all comment lines to the end, to make sure #+ settings are
25138 ;; still available for the second export step. Kind of a hack, but
25139 ;; does do the trick.
25140 (if (looking-at "#[^\r\n]*")
25141 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25142 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25143 (append-to-buffer buffer (1+ (match-beginning 0))
25144 (min (point-max) (1+ (match-end 0))))))
25145 (set-buffer buffer)
25146 (let ((buffer-file-name file)
25147 (org-inhibit-startup t))
25148 (org-mode)
25149 (show-all)
25150 (unless keepp (funcall binding arg))))
25151 (if (not keepp)
25152 (kill-buffer buffer)
25153 (switch-to-buffer-other-window buffer)
25154 (goto-char (point-min)))))
25156 (defun org-find-visible ()
25157 (let ((s (point)))
25158 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25159 (get-char-property s 'invisible)))
25161 (defun org-find-invisible ()
25162 (let ((s (point)))
25163 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25164 (not (get-char-property s 'invisible))))
25167 ;;; HTML export
25169 (defun org-get-current-options ()
25170 "Return a string with current options as keyword options.
25171 Does include HTML export options as well as TODO and CATEGORY stuff."
25172 (format
25173 "#+TITLE: %s
25174 #+AUTHOR: %s
25175 #+EMAIL: %s
25176 #+DATE: %s
25177 #+LANGUAGE: %s
25178 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25179 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
25180 #+CATEGORY: %s
25181 #+SEQ_TODO: %s
25182 #+TYP_TODO: %s
25183 #+PRIORITIES: %c %c %c
25184 #+DRAWERS: %s
25185 #+STARTUP: %s %s %s %s %s
25186 #+TAGS: %s
25187 #+ARCHIVE: %s
25188 #+LINK: %s
25190 (buffer-name) (user-full-name) user-mail-address
25191 (format-time-string (car org-time-stamp-formats))
25192 org-export-default-language
25193 org-export-headline-levels
25194 org-export-with-section-numbers
25195 org-export-with-toc
25196 org-export-preserve-breaks
25197 org-export-html-expand
25198 org-export-with-fixed-width
25199 org-export-with-tables
25200 org-export-with-sub-superscripts
25201 org-export-with-special-strings
25202 org-export-with-footnotes
25203 org-export-with-emphasize
25204 org-export-with-TeX-macros
25205 org-export-with-LaTeX-fragments
25206 org-export-skip-text-before-1st-heading
25207 org-export-with-drawers
25208 org-export-with-tags
25209 (file-name-nondirectory buffer-file-name)
25210 "TODO FEEDBACK VERIFY DONE"
25211 "Me Jason Marie DONE"
25212 org-highest-priority org-lowest-priority org-default-priority
25213 (mapconcat 'identity org-drawers " ")
25214 (cdr (assoc org-startup-folded
25215 '((nil . "showall") (t . "overview") (content . "content"))))
25216 (if org-odd-levels-only "odd" "oddeven")
25217 (if org-hide-leading-stars "hidestars" "showstars")
25218 (if org-startup-align-all-tables "align" "noalign")
25219 (cond ((eq org-log-done t) "logdone")
25220 ((equal org-log-done 'note) "lognotedone")
25221 ((not org-log-done) "nologdone"))
25222 (or (mapconcat (lambda (x)
25223 (cond
25224 ((equal '(:startgroup) x) "{")
25225 ((equal '(:endgroup) x) "}")
25226 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25227 (t (car x))))
25228 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25229 org-archive-location
25230 "org file:~/org/%s.org"
25233 (defun org-insert-export-options-template ()
25234 "Insert into the buffer a template with information for exporting."
25235 (interactive)
25236 (if (not (bolp)) (newline))
25237 (let ((s (org-get-current-options)))
25238 (and (string-match "#\\+CATEGORY" s)
25239 (setq s (substring s 0 (match-beginning 0))))
25240 (insert s)))
25242 (defun org-toggle-fixed-width-section (arg)
25243 "Toggle the fixed-width export.
25244 If there is no active region, the QUOTE keyword at the current headline is
25245 inserted or removed. When present, it causes the text between this headline
25246 and the next to be exported as fixed-width text, and unmodified.
25247 If there is an active region, this command adds or removes a colon as the
25248 first character of this line. If the first character of a line is a colon,
25249 this line is also exported in fixed-width font."
25250 (interactive "P")
25251 (let* ((cc 0)
25252 (regionp (org-region-active-p))
25253 (beg (if regionp (region-beginning) (point)))
25254 (end (if regionp (region-end)))
25255 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25256 (case-fold-search nil)
25257 (re "[ \t]*\\(:\\)")
25258 off)
25259 (if regionp
25260 (save-excursion
25261 (goto-char beg)
25262 (setq cc (current-column))
25263 (beginning-of-line 1)
25264 (setq off (looking-at re))
25265 (while (> nlines 0)
25266 (setq nlines (1- nlines))
25267 (beginning-of-line 1)
25268 (cond
25269 (arg
25270 (move-to-column cc t)
25271 (insert ":\n")
25272 (forward-line -1))
25273 ((and off (looking-at re))
25274 (replace-match "" t t nil 1))
25275 ((not off) (move-to-column cc t) (insert ":")))
25276 (forward-line 1)))
25277 (save-excursion
25278 (org-back-to-heading)
25279 (if (looking-at (concat outline-regexp
25280 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25281 (replace-match "" t t nil 1)
25282 (if (looking-at outline-regexp)
25283 (progn
25284 (goto-char (match-end 0))
25285 (insert org-quote-string " "))))))))
25287 (defun org-export-as-html-and-open (arg)
25288 "Export the outline as HTML and immediately open it with a browser.
25289 If there is an active region, export only the region.
25290 The prefix ARG specifies how many levels of the outline should become
25291 headlines. The default is 3. Lower levels will become bulleted lists."
25292 (interactive "P")
25293 (org-export-as-html arg 'hidden)
25294 (org-open-file buffer-file-name))
25296 (defun org-export-as-html-batch ()
25297 "Call `org-export-as-html', may be used in batch processing as
25298 emacs --batch
25299 --load=$HOME/lib/emacs/org.el
25300 --eval \"(setq org-export-headline-levels 2)\"
25301 --visit=MyFile --funcall org-export-as-html-batch"
25302 (org-export-as-html org-export-headline-levels 'hidden))
25304 (defun org-export-as-html-to-buffer (arg)
25305 "Call `org-exort-as-html` with output to a temporary buffer.
25306 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25307 (interactive "P")
25308 (org-export-as-html arg nil nil "*Org HTML Export*")
25309 (switch-to-buffer-other-window "*Org HTML Export*"))
25311 (defun org-replace-region-by-html (beg end)
25312 "Assume the current region has org-mode syntax, and convert it to HTML.
25313 This can be used in any buffer. For example, you could write an
25314 itemized list in org-mode syntax in an HTML buffer and then use this
25315 command to convert it."
25316 (interactive "r")
25317 (let (reg html buf pop-up-frames)
25318 (save-window-excursion
25319 (if (org-mode-p)
25320 (setq html (org-export-region-as-html
25321 beg end t 'string))
25322 (setq reg (buffer-substring beg end)
25323 buf (get-buffer-create "*Org tmp*"))
25324 (with-current-buffer buf
25325 (erase-buffer)
25326 (insert reg)
25327 (org-mode)
25328 (setq html (org-export-region-as-html
25329 (point-min) (point-max) t 'string)))
25330 (kill-buffer buf)))
25331 (delete-region beg end)
25332 (insert html)))
25334 (defun org-export-region-as-html (beg end &optional body-only buffer)
25335 "Convert region from BEG to END in org-mode buffer to HTML.
25336 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25337 contents, and only produce the region of converted text, useful for
25338 cut-and-paste operations.
25339 If BUFFER is a buffer or a string, use/create that buffer as a target
25340 of the converted HTML. If BUFFER is the symbol `string', return the
25341 produced HTML as a string and leave not buffer behind. For example,
25342 a Lisp program could call this function in the following way:
25344 (setq html (org-export-region-as-html beg end t 'string))
25346 When called interactively, the output buffer is selected, and shown
25347 in a window. A non-interactive call will only retunr the buffer."
25348 (interactive "r\nP")
25349 (when (interactive-p)
25350 (setq buffer "*Org HTML Export*"))
25351 (let ((transient-mark-mode t) (zmacs-regions t)
25352 rtn)
25353 (goto-char end)
25354 (set-mark (point)) ;; to activate the region
25355 (goto-char beg)
25356 (setq rtn (org-export-as-html
25357 nil nil nil
25358 buffer body-only))
25359 (if (fboundp 'deactivate-mark) (deactivate-mark))
25360 (if (and (interactive-p) (bufferp rtn))
25361 (switch-to-buffer-other-window rtn)
25362 rtn)))
25364 (defvar html-table-tag nil) ; dynamically scoped into this.
25365 (defun org-export-as-html (arg &optional hidden ext-plist
25366 to-buffer body-only pub-dir)
25367 "Export the outline as a pretty HTML file.
25368 If there is an active region, export only the region. The prefix
25369 ARG specifies how many levels of the outline should become
25370 headlines. The default is 3. Lower levels will become bulleted
25371 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25372 EXT-PLIST is a property list with external parameters overriding
25373 org-mode's default settings, but still inferior to file-local
25374 settings. When TO-BUFFER is non-nil, create a buffer with that
25375 name and export to that buffer. If TO-BUFFER is the symbol
25376 `string', don't leave any buffer behind but just return the
25377 resulting HTML as a string. When BODY-ONLY is set, don't produce
25378 the file header and footer, simply return the content of
25379 <body>...</body>, without even the body tags themselves. When
25380 PUB-DIR is set, use this as the publishing directory."
25381 (interactive "P")
25383 ;; Make sure we have a file name when we need it.
25384 (when (and (not (or to-buffer body-only))
25385 (not buffer-file-name))
25386 (if (buffer-base-buffer)
25387 (org-set-local 'buffer-file-name
25388 (with-current-buffer (buffer-base-buffer)
25389 buffer-file-name))
25390 (error "Need a file name to be able to export.")))
25392 (message "Exporting...")
25393 (setq-default org-todo-line-regexp org-todo-line-regexp)
25394 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25395 (setq-default org-done-keywords org-done-keywords)
25396 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25397 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25398 ext-plist
25399 (org-infile-export-plist)))
25401 (style (plist-get opt-plist :style))
25402 (html-extension (plist-get opt-plist :html-extension))
25403 (link-validate (plist-get opt-plist :link-validation-function))
25404 valid thetoc have-headings first-heading-pos
25405 (odd org-odd-levels-only)
25406 (region-p (org-region-active-p))
25407 (subtree-p
25408 (when region-p
25409 (save-excursion
25410 (goto-char (region-beginning))
25411 (and (org-at-heading-p)
25412 (>= (org-end-of-subtree t t) (region-end))))))
25413 ;; The following two are dynamically scoped into other
25414 ;; routines below.
25415 (org-current-export-dir
25416 (or pub-dir (org-export-directory :html opt-plist)))
25417 (org-current-export-file buffer-file-name)
25418 (level 0) (line "") (origline "") txt todo
25419 (umax nil)
25420 (umax-toc nil)
25421 (filename (if to-buffer nil
25422 (expand-file-name
25423 (concat
25424 (file-name-sans-extension
25425 (or (and subtree-p
25426 (org-entry-get (region-beginning)
25427 "EXPORT_FILE_NAME" t))
25428 (file-name-nondirectory buffer-file-name)))
25429 "." html-extension)
25430 (file-name-as-directory
25431 (or pub-dir (org-export-directory :html opt-plist))))))
25432 (current-dir (if buffer-file-name
25433 (file-name-directory buffer-file-name)
25434 default-directory))
25435 (buffer (if to-buffer
25436 (cond
25437 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25438 (t (get-buffer-create to-buffer)))
25439 (find-file-noselect filename)))
25440 (org-levels-open (make-vector org-level-max nil))
25441 (date (plist-get opt-plist :date))
25442 (author (plist-get opt-plist :author))
25443 (title (or (and subtree-p (org-export-get-title-from-subtree))
25444 (plist-get opt-plist :title)
25445 (and (not
25446 (plist-get opt-plist :skip-before-1st-heading))
25447 (org-export-grab-title-from-buffer))
25448 (and buffer-file-name
25449 (file-name-sans-extension
25450 (file-name-nondirectory buffer-file-name)))
25451 "UNTITLED"))
25452 (html-table-tag (plist-get opt-plist :html-table-tag))
25453 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25454 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25455 (inquote nil)
25456 (infixed nil)
25457 (in-local-list nil)
25458 (local-list-num nil)
25459 (local-list-indent nil)
25460 (llt org-plain-list-ordered-item-terminator)
25461 (email (plist-get opt-plist :email))
25462 (language (plist-get opt-plist :language))
25463 (lang-words nil)
25464 (target-alist nil) tg
25465 (head-count 0) cnt
25466 (start 0)
25467 (coding-system (and (boundp 'buffer-file-coding-system)
25468 buffer-file-coding-system))
25469 (coding-system-for-write (or org-export-html-coding-system
25470 coding-system))
25471 (save-buffer-coding-system (or org-export-html-coding-system
25472 coding-system))
25473 (charset (and coding-system-for-write
25474 (fboundp 'coding-system-get)
25475 (coding-system-get coding-system-for-write
25476 'mime-charset)))
25477 (region
25478 (buffer-substring
25479 (if region-p (region-beginning) (point-min))
25480 (if region-p (region-end) (point-max))))
25481 (lines
25482 (org-split-string
25483 (org-cleaned-string-for-export
25484 region
25485 :emph-multiline t
25486 :for-html t
25487 :skip-before-1st-heading
25488 (plist-get opt-plist :skip-before-1st-heading)
25489 :drawers (plist-get opt-plist :drawers)
25490 :archived-trees
25491 (plist-get opt-plist :archived-trees)
25492 :add-text
25493 (plist-get opt-plist :text)
25494 :LaTeX-fragments
25495 (plist-get opt-plist :LaTeX-fragments))
25496 "[\r\n]"))
25497 table-open type
25498 table-buffer table-orig-buffer
25499 ind start-is-num starter didclose
25500 rpl path desc descp desc1 desc2 link
25501 snumber fnc
25504 (let ((inhibit-read-only t))
25505 (org-unmodified
25506 (remove-text-properties (point-min) (point-max)
25507 '(:org-license-to-kill t))))
25509 (message "Exporting...")
25511 (setq org-min-level (org-get-min-level lines))
25512 (setq org-last-level org-min-level)
25513 (org-init-section-numbers)
25515 (cond
25516 ((and date (string-match "%" date))
25517 (setq date (format-time-string date)))
25518 (date)
25519 (t (setq date (format-time-string "%Y/%m/%d %X"))))
25521 ;; Get the language-dependent settings
25522 (setq lang-words (or (assoc language org-export-language-setup)
25523 (assoc "en" org-export-language-setup)))
25525 ;; Switch to the output buffer
25526 (set-buffer buffer)
25527 (let ((inhibit-read-only t)) (erase-buffer))
25528 (fundamental-mode)
25530 (and (fboundp 'set-buffer-file-coding-system)
25531 (set-buffer-file-coding-system coding-system-for-write))
25533 (let ((case-fold-search nil)
25534 (org-odd-levels-only odd))
25535 ;; create local variables for all options, to make sure all called
25536 ;; functions get the correct information
25537 (mapc (lambda (x)
25538 (set (make-local-variable (cdr x))
25539 (plist-get opt-plist (car x))))
25540 org-export-plist-vars)
25541 (setq umax (if arg (prefix-numeric-value arg)
25542 org-export-headline-levels))
25543 (setq umax-toc (if (integerp org-export-with-toc)
25544 (min org-export-with-toc umax)
25545 umax))
25546 (unless body-only
25547 ;; File header
25548 (insert (format
25549 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25550 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25551 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25552 lang=\"%s\" xml:lang=\"%s\">
25553 <head>
25554 <title>%s</title>
25555 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25556 <meta name=\"generator\" content=\"Org-mode\"/>
25557 <meta name=\"generated\" content=\"%s\"/>
25558 <meta name=\"author\" content=\"%s\"/>
25560 </head><body>
25562 language language (org-html-expand title)
25563 (or charset "iso-8859-1") date author style))
25565 (insert (or (plist-get opt-plist :preamble) ""))
25567 (when (plist-get opt-plist :auto-preamble)
25568 (if title (insert (format org-export-html-title-format
25569 (org-html-expand title))))))
25571 (if (and org-export-with-toc (not body-only))
25572 (progn
25573 (push (format "<h%d>%s</h%d>\n"
25574 org-export-html-toplevel-hlevel
25575 (nth 3 lang-words)
25576 org-export-html-toplevel-hlevel)
25577 thetoc)
25578 (push "<div id=\"text-table-of-contents\">\n" thetoc)
25579 (push "<ul>\n<li>" thetoc)
25580 (setq lines
25581 (mapcar '(lambda (line)
25582 (if (string-match org-todo-line-regexp line)
25583 ;; This is a headline
25584 (progn
25585 (setq have-headings t)
25586 (setq level (- (match-end 1) (match-beginning 1))
25587 level (org-tr-level level)
25588 txt (save-match-data
25589 (org-html-expand
25590 (org-export-cleanup-toc-line
25591 (match-string 3 line))))
25592 todo
25593 (or (and org-export-mark-todo-in-toc
25594 (match-beginning 2)
25595 (not (member (match-string 2 line)
25596 org-done-keywords)))
25597 ; TODO, not DONE
25598 (and org-export-mark-todo-in-toc
25599 (= level umax-toc)
25600 (org-search-todo-below
25601 line lines level))))
25602 (if (string-match
25603 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25604 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25605 (if (string-match quote-re0 txt)
25606 (setq txt (replace-match "" t t txt)))
25607 (setq snumber (org-section-number level))
25608 (if org-export-with-section-numbers
25609 (setq txt (concat snumber " " txt)))
25610 (if (<= level (max umax umax-toc))
25611 (setq head-count (+ head-count 1)))
25612 (if (<= level umax-toc)
25613 (progn
25614 (if (> level org-last-level)
25615 (progn
25616 (setq cnt (- level org-last-level))
25617 (while (>= (setq cnt (1- cnt)) 0)
25618 (push "\n<ul>\n<li>" thetoc))
25619 (push "\n" thetoc)))
25620 (if (< level org-last-level)
25621 (progn
25622 (setq cnt (- org-last-level level))
25623 (while (>= (setq cnt (1- cnt)) 0)
25624 (push "</li>\n</ul>" thetoc))
25625 (push "\n" thetoc)))
25626 ;; Check for targets
25627 (while (string-match org-target-regexp line)
25628 (setq tg (match-string 1 line)
25629 line (replace-match
25630 (concat "@<span class=\"target\">" tg "@</span> ")
25631 t t line))
25632 (push (cons (org-solidify-link-text tg)
25633 (format "sec-%s" snumber))
25634 target-alist))
25635 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25636 (setq txt (replace-match "" t t txt)))
25637 (push
25638 (format
25639 (if todo
25640 "</li>\n<li><a href=\"#sec-%s\"><span class=\"todo\">%s</span></a>"
25641 "</li>\n<li><a href=\"#sec-%s\">%s</a>")
25642 snumber txt) thetoc)
25644 (setq org-last-level level))
25646 line)
25647 lines))
25648 (while (> org-last-level (1- org-min-level))
25649 (setq org-last-level (1- org-last-level))
25650 (push "</li>\n</ul>\n" thetoc))
25651 (push "</div>\n" thetoc)
25652 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25654 (setq head-count 0)
25655 (org-init-section-numbers)
25657 (while (setq line (pop lines) origline line)
25658 (catch 'nextline
25660 ;; end of quote section?
25661 (when (and inquote (string-match "^\\*+ " line))
25662 (insert "</pre>\n")
25663 (setq inquote nil))
25664 ;; inside a quote section?
25665 (when inquote
25666 (insert (org-html-protect line) "\n")
25667 (throw 'nextline nil))
25669 ;; verbatim lines
25670 (when (and org-export-with-fixed-width
25671 (string-match "^[ \t]*:\\(.*\\)" line))
25672 (when (not infixed)
25673 (setq infixed t)
25674 (insert "<pre>\n"))
25675 (insert (org-html-protect (match-string 1 line)) "\n")
25676 (when (and lines
25677 (not (string-match "^[ \t]*\\(:.*\\)"
25678 (car lines))))
25679 (setq infixed nil)
25680 (insert "</pre>\n"))
25681 (throw 'nextline nil))
25683 ;; Protected HTML
25684 (when (get-text-property 0 'org-protected line)
25685 (let (par)
25686 (when (re-search-backward
25687 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25688 (setq par (match-string 1))
25689 (replace-match "\\2\n"))
25690 (insert line "\n")
25691 (while (and lines
25692 (or (= (length (car lines)) 0)
25693 (get-text-property 0 'org-protected (car lines))))
25694 (insert (pop lines) "\n"))
25695 (and par (insert "<p>\n")))
25696 (throw 'nextline nil))
25698 ;; Horizontal line
25699 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25700 (insert "\n<hr/>\n")
25701 (throw 'nextline nil))
25703 ;; make targets to anchors
25704 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25705 (cond
25706 ((match-end 2)
25707 (setq line (replace-match
25708 (concat "@<a name=\""
25709 (org-solidify-link-text (match-string 1 line))
25710 "\">\\nbsp@</a>")
25711 t t line)))
25712 ((and org-export-with-toc (equal (string-to-char line) ?*))
25713 (setq line (replace-match
25714 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25715 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25716 t t line)))
25718 (setq line (replace-match
25719 (concat "@<a name=\""
25720 (org-solidify-link-text (match-string 1 line))
25721 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25722 t t line)))))
25724 (setq line (org-html-handle-time-stamps line))
25726 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25727 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25728 ;; Also handle sub_superscripts and checkboxes
25729 (or (string-match org-table-hline-regexp line)
25730 (setq line (org-html-expand line)))
25732 ;; Format the links
25733 (setq start 0)
25734 (while (string-match org-bracket-link-analytic-regexp line start)
25735 (setq start (match-beginning 0))
25736 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25737 (setq path (match-string 3 line))
25738 (setq desc1 (if (match-end 5) (match-string 5 line))
25739 desc2 (if (match-end 2) (concat type ":" path) path)
25740 descp (and desc1 (not (equal desc1 desc2)))
25741 desc (or desc1 desc2))
25742 ;; Make an image out of the description if that is so wanted
25743 (when (and descp (org-file-image-p desc))
25744 (save-match-data
25745 (if (string-match "^file:" desc)
25746 (setq desc (substring desc (match-end 0)))))
25747 (setq desc (concat "<img src=\"" desc "\"/>")))
25748 ;; FIXME: do we need to unescape here somewhere?
25749 (cond
25750 ((equal type "internal")
25751 (setq rpl
25752 (concat
25753 "<a href=\"#"
25754 (org-solidify-link-text
25755 (save-match-data (org-link-unescape path)) target-alist)
25756 "\">" desc "</a>")))
25757 ((member type '("http" "https"))
25758 ;; standard URL, just check if we need to inline an image
25759 (if (and (or (eq t org-export-html-inline-images)
25760 (and org-export-html-inline-images (not descp)))
25761 (org-file-image-p path))
25762 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25763 (setq link (concat type ":" path))
25764 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25765 ((member type '("ftp" "mailto" "news"))
25766 ;; standard URL
25767 (setq link (concat type ":" path))
25768 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25769 ((string= type "file")
25770 ;; FILE link
25771 (let* ((filename path)
25772 (abs-p (file-name-absolute-p filename))
25773 thefile file-is-image-p search)
25774 (save-match-data
25775 (if (string-match "::\\(.*\\)" filename)
25776 (setq search (match-string 1 filename)
25777 filename (replace-match "" t nil filename)))
25778 (setq valid
25779 (if (functionp link-validate)
25780 (funcall link-validate filename current-dir)
25782 (setq file-is-image-p (org-file-image-p filename))
25783 (setq thefile (if abs-p (expand-file-name filename) filename))
25784 (when (and org-export-html-link-org-files-as-html
25785 (string-match "\\.org$" thefile))
25786 (setq thefile (concat (substring thefile 0
25787 (match-beginning 0))
25788 "." html-extension))
25789 (if (and search
25790 ;; make sure this is can be used as target search
25791 (not (string-match "^[0-9]*$" search))
25792 (not (string-match "^\\*" search))
25793 (not (string-match "^/.*/$" search)))
25794 (setq thefile (concat thefile "#"
25795 (org-solidify-link-text
25796 (org-link-unescape search)))))
25797 (when (string-match "^file:" desc)
25798 (setq desc (replace-match "" t t desc))
25799 (if (string-match "\\.org$" desc)
25800 (setq desc (replace-match "" t t desc))))))
25801 (setq rpl (if (and file-is-image-p
25802 (or (eq t org-export-html-inline-images)
25803 (and org-export-html-inline-images
25804 (not descp))))
25805 (concat "<img src=\"" thefile "\"/>")
25806 (concat "<a href=\"" thefile "\">" desc "</a>")))
25807 (if (not valid) (setq rpl desc))))
25809 ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
25810 (setq rpl
25811 (save-match-data
25812 (funcall fnc (org-link-unescape path) desc1 'html))))
25815 ;; just publish the path, as default
25816 (setq rpl (concat "<i>&lt;" type ":"
25817 (save-match-data (org-link-unescape path))
25818 "&gt;</i>"))))
25819 (setq line (replace-match rpl t t line)
25820 start (+ start (length rpl))))
25822 ;; TODO items
25823 (if (and (string-match org-todo-line-regexp line)
25824 (match-beginning 2))
25826 (setq line
25827 (concat (substring line 0 (match-beginning 2))
25828 "<span class=\""
25829 (if (member (match-string 2 line)
25830 org-done-keywords)
25831 "done" "todo")
25832 "\">" (match-string 2 line)
25833 "</span>" (substring line (match-end 2)))))
25835 ;; Does this contain a reference to a footnote?
25836 (when org-export-with-footnotes
25837 (setq start 0)
25838 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25839 (if (get-text-property (match-beginning 2) 'org-protected line)
25840 (setq start (match-end 2))
25841 (let ((n (match-string 2 line)))
25842 (setq line
25843 (replace-match
25844 (format
25845 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25846 (match-string 1 line) n n n)
25847 t t line))))))
25849 (cond
25850 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25851 ;; This is a headline
25852 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25853 txt (match-string 2 line))
25854 (if (string-match quote-re0 txt)
25855 (setq txt (replace-match "" t t txt)))
25856 (if (<= level (max umax umax-toc))
25857 (setq head-count (+ head-count 1)))
25858 (when in-local-list
25859 ;; Close any local lists before inserting a new header line
25860 (while local-list-num
25861 (org-close-li)
25862 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25863 (pop local-list-num))
25864 (setq local-list-indent nil
25865 in-local-list nil))
25866 (setq first-heading-pos (or first-heading-pos (point)))
25867 (org-html-level-start level txt umax
25868 (and org-export-with-toc (<= level umax))
25869 head-count)
25870 ;; QUOTES
25871 (when (string-match quote-re line)
25872 (insert "<pre>")
25873 (setq inquote t)))
25875 ((and org-export-with-tables
25876 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25877 (if (not table-open)
25878 ;; New table starts
25879 (setq table-open t table-buffer nil table-orig-buffer nil))
25880 ;; Accumulate lines
25881 (setq table-buffer (cons line table-buffer)
25882 table-orig-buffer (cons origline table-orig-buffer))
25883 (when (or (not lines)
25884 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25885 (car lines))))
25886 (setq table-open nil
25887 table-buffer (nreverse table-buffer)
25888 table-orig-buffer (nreverse table-orig-buffer))
25889 (org-close-par-maybe)
25890 (insert (org-format-table-html table-buffer table-orig-buffer))))
25892 ;; Normal lines
25893 (when (string-match
25894 (cond
25895 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25896 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25897 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25898 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25899 line)
25900 (setq ind (org-get-string-indentation line)
25901 start-is-num (match-beginning 4)
25902 starter (if (match-beginning 2)
25903 (substring (match-string 2 line) 0 -1))
25904 line (substring line (match-beginning 5)))
25905 (unless (string-match "[^ \t]" line)
25906 ;; empty line. Pretend indentation is large.
25907 (setq ind (if org-empty-line-terminates-plain-lists
25909 (1+ (or (car local-list-indent) 1)))))
25910 (setq didclose nil)
25911 (while (and in-local-list
25912 (or (and (= ind (car local-list-indent))
25913 (not starter))
25914 (< ind (car local-list-indent))))
25915 (setq didclose t)
25916 (org-close-li)
25917 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25918 (pop local-list-num) (pop local-list-indent)
25919 (setq in-local-list local-list-indent))
25920 (cond
25921 ((and starter
25922 (or (not in-local-list)
25923 (> ind (car local-list-indent))))
25924 ;; Start new (level of) list
25925 (org-close-par-maybe)
25926 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25927 (push start-is-num local-list-num)
25928 (push ind local-list-indent)
25929 (setq in-local-list t))
25930 (starter
25931 ;; continue current list
25932 (org-close-li)
25933 (insert "<li>\n"))
25934 (didclose
25935 ;; we did close a list, normal text follows: need <p>
25936 (org-open-par)))
25937 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25938 (setq line
25939 (replace-match
25940 (if (equal (match-string 1 line) "X")
25941 "<b>[X]</b>"
25942 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25943 t t line))))
25945 ;; Empty lines start a new paragraph. If hand-formatted lists
25946 ;; are not fully interpreted, lines starting with "-", "+", "*"
25947 ;; also start a new paragraph.
25948 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25950 ;; Is this the start of a footnote?
25951 (when org-export-with-footnotes
25952 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25953 (org-close-par-maybe)
25954 (let ((n (match-string 1 line)))
25955 (setq line (replace-match
25956 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25958 ;; Check if the line break needs to be conserved
25959 (cond
25960 ((string-match "\\\\\\\\[ \t]*$" line)
25961 (setq line (replace-match "<br/>" t t line)))
25962 (org-export-preserve-breaks
25963 (setq line (concat line "<br/>"))))
25965 (insert line "\n")))))
25967 ;; Properly close all local lists and other lists
25968 (when inquote (insert "</pre>\n"))
25969 (when in-local-list
25970 ;; Close any local lists before inserting a new header line
25971 (while local-list-num
25972 (org-close-li)
25973 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25974 (pop local-list-num))
25975 (setq local-list-indent nil
25976 in-local-list nil))
25977 (org-html-level-start 1 nil umax
25978 (and org-export-with-toc (<= level umax))
25979 head-count)
25980 ;; the </div> to lose the last text-... div.
25981 (insert "</div>\n")
25983 (unless body-only
25984 (when (plist-get opt-plist :auto-postamble)
25985 (insert "<div id=\"postamble\">")
25986 (when (and org-export-author-info author)
25987 (insert "<p class=\"author\"> "
25988 (nth 1 lang-words) ": " author "\n")
25989 (when email
25990 (if (listp (split-string email ",+ *"))
25991 (mapc (lambda(e)
25992 (insert "<a href=\"mailto:" e "\">&lt;"
25993 e "&gt;</a>\n"))
25994 (split-string email ",+ *"))
25995 (insert "<a href=\"mailto:" email "\">&lt;"
25996 email "&gt;</a>\n")))
25997 (insert "</p>\n"))
25998 (when (and date org-export-time-stamp-file)
25999 (insert "<p class=\"date\"> "
26000 (nth 2 lang-words) ": "
26001 date "</p>\n"))
26002 (insert "</div>"))
26004 (if org-export-html-with-timestamp
26005 (insert org-export-html-html-helper-timestamp))
26006 (insert (or (plist-get opt-plist :postamble) ""))
26007 (insert "</body>\n</html>\n"))
26009 (normal-mode)
26010 (if (eq major-mode default-major-mode) (html-mode))
26012 ;; insert the table of contents
26013 (goto-char (point-min))
26014 (when thetoc
26015 (if (or (re-search-forward
26016 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26017 (re-search-forward
26018 "\\[TABLE-OF-CONTENTS\\]" nil t))
26019 (progn
26020 (goto-char (match-beginning 0))
26021 (replace-match ""))
26022 (goto-char first-heading-pos)
26023 (when (looking-at "\\s-*</p>")
26024 (goto-char (match-end 0))
26025 (insert "\n")))
26026 (insert "<div id=\"table-of-contents\">\n")
26027 (mapc 'insert thetoc)
26028 (insert "</div>\n"))
26029 ;; remove empty paragraphs and lists
26030 (goto-char (point-min))
26031 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26032 (replace-match ""))
26033 (goto-char (point-min))
26034 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26035 (replace-match ""))
26036 (goto-char (point-min))
26037 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26038 (replace-match ""))
26039 ;; Convert whitespace place holders
26040 (goto-char (point-min))
26041 (let (beg end n)
26042 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26043 (setq n (get-text-property beg 'org-whitespace)
26044 end (next-single-property-change beg 'org-whitespace))
26045 (goto-char beg)
26046 (delete-region beg end)
26047 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26048 (make-string n ?x)))))
26049 (or to-buffer (save-buffer))
26050 (goto-char (point-min))
26051 (message "Exporting... done")
26052 (if (eq to-buffer 'string)
26053 (prog1 (buffer-substring (point-min) (point-max))
26054 (kill-buffer (current-buffer)))
26055 (current-buffer)))))
26057 (defvar org-table-colgroup-info nil)
26058 (defun org-format-table-ascii (lines)
26059 "Format a table for ascii export."
26060 (if (stringp lines)
26061 (setq lines (org-split-string lines "\n")))
26062 (if (not (string-match "^[ \t]*|" (car lines)))
26063 ;; Table made by table.el - test for spanning
26064 lines
26066 ;; A normal org table
26067 ;; Get rid of hlines at beginning and end
26068 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26069 (setq lines (nreverse lines))
26070 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26071 (setq lines (nreverse lines))
26072 (when org-export-table-remove-special-lines
26073 ;; Check if the table has a marking column. If yes remove the
26074 ;; column and the special lines
26075 (setq lines (org-table-clean-before-export lines)))
26076 ;; Get rid of the vertical lines except for grouping
26077 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26078 rtn line vl1 start)
26079 (while (setq line (pop lines))
26080 (if (string-match org-table-hline-regexp line)
26081 (and (string-match "|\\(.*\\)|" line)
26082 (setq line (replace-match " \\1" t nil line)))
26083 (setq start 0 vl1 vl)
26084 (while (string-match "|" line start)
26085 (setq start (match-end 0))
26086 (or (pop vl1) (setq line (replace-match " " t t line)))))
26087 (push line rtn))
26088 (nreverse rtn))))
26090 (defun org-colgroup-info-to-vline-list (info)
26091 (let (vl new last)
26092 (while info
26093 (setq last new new (pop info))
26094 (if (or (memq last '(:end :startend))
26095 (memq new '(:start :startend)))
26096 (push t vl)
26097 (push nil vl)))
26098 (setq vl (nreverse vl))
26099 (and vl (setcar vl nil))
26100 vl))
26102 (defun org-format-table-html (lines olines)
26103 "Find out which HTML converter to use and return the HTML code."
26104 (if (stringp lines)
26105 (setq lines (org-split-string lines "\n")))
26106 (if (string-match "^[ \t]*|" (car lines))
26107 ;; A normal org table
26108 (org-format-org-table-html lines)
26109 ;; Table made by table.el - test for spanning
26110 (let* ((hlines (delq nil (mapcar
26111 (lambda (x)
26112 (if (string-match "^[ \t]*\\+-" x) x
26113 nil))
26114 lines)))
26115 (first (car hlines))
26116 (ll (and (string-match "\\S-+" first)
26117 (match-string 0 first)))
26118 (re (concat "^[ \t]*" (regexp-quote ll)))
26119 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26120 hlines))))
26121 (if (and (not spanning)
26122 (not org-export-prefer-native-exporter-for-tables))
26123 ;; We can use my own converter with HTML conversions
26124 (org-format-table-table-html lines)
26125 ;; Need to use the code generator in table.el, with the original text.
26126 (org-format-table-table-html-using-table-generate-source olines)))))
26128 (defun org-format-org-table-html (lines &optional splice)
26129 "Format a table into HTML."
26130 ;; Get rid of hlines at beginning and end
26131 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26132 (setq lines (nreverse lines))
26133 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26134 (setq lines (nreverse lines))
26135 (when org-export-table-remove-special-lines
26136 ;; Check if the table has a marking column. If yes remove the
26137 ;; column and the special lines
26138 (setq lines (org-table-clean-before-export lines)))
26140 (let ((head (and org-export-highlight-first-table-line
26141 (delq nil (mapcar
26142 (lambda (x) (string-match "^[ \t]*|-" x))
26143 (cdr lines)))))
26144 (nlines 0) fnum i
26145 tbopen line fields html gr colgropen)
26146 (if splice (setq head nil))
26147 (unless splice (push (if head "<thead>" "<tbody>") html))
26148 (setq tbopen t)
26149 (while (setq line (pop lines))
26150 (catch 'next-line
26151 (if (string-match "^[ \t]*|-" line)
26152 (progn
26153 (unless splice
26154 (push (if head "</thead>" "</tbody>") html)
26155 (if lines (push "<tbody>" html) (setq tbopen nil)))
26156 (setq head nil) ;; head ends here, first time around
26157 ;; ignore this line
26158 (throw 'next-line t)))
26159 ;; Break the line into fields
26160 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26161 (unless fnum (setq fnum (make-vector (length fields) 0)))
26162 (setq nlines (1+ nlines) i -1)
26163 (push (concat "<tr>"
26164 (mapconcat
26165 (lambda (x)
26166 (setq i (1+ i))
26167 (if (and (< i nlines)
26168 (string-match org-table-number-regexp x))
26169 (incf (aref fnum i)))
26170 (if head
26171 (concat (car org-export-table-header-tags) x
26172 (cdr org-export-table-header-tags))
26173 (concat (car org-export-table-data-tags) x
26174 (cdr org-export-table-data-tags))))
26175 fields "")
26176 "</tr>")
26177 html)))
26178 (unless splice (if tbopen (push "</tbody>" html)))
26179 (unless splice (push "</table>\n" html))
26180 (setq html (nreverse html))
26181 (unless splice
26182 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26183 (push (mapconcat
26184 (lambda (x)
26185 (setq gr (pop org-table-colgroup-info))
26186 (format "%s<col align=\"%s\"></col>%s"
26187 (if (memq gr '(:start :startend))
26188 (prog1
26189 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26190 (setq colgropen t))
26192 (if (> (/ (float x) nlines) org-table-number-fraction)
26193 "right" "left")
26194 (if (memq gr '(:end :startend))
26195 (progn (setq colgropen nil) "</colgroup>")
26196 "")))
26197 fnum "")
26198 html)
26199 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26200 (push html-table-tag html))
26201 (concat (mapconcat 'identity html "\n") "\n")))
26203 (defun org-table-clean-before-export (lines)
26204 "Check if the table has a marking column.
26205 If yes remove the column and the special lines."
26206 (setq org-table-colgroup-info nil)
26207 (if (memq nil
26208 (mapcar
26209 (lambda (x) (or (string-match "^[ \t]*|-" x)
26210 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26211 lines))
26212 (progn
26213 (setq org-table-clean-did-remove-column nil)
26214 (delq nil
26215 (mapcar
26216 (lambda (x)
26217 (cond
26218 ((string-match "^[ \t]*| */ *|" x)
26219 (setq org-table-colgroup-info
26220 (mapcar (lambda (x)
26221 (cond ((member x '("<" "&lt;")) :start)
26222 ((member x '(">" "&gt;")) :end)
26223 ((member x '("<>" "&lt;&gt;")) :startend)
26224 (t nil)))
26225 (org-split-string x "[ \t]*|[ \t]*")))
26226 nil)
26227 (t x)))
26228 lines)))
26229 (setq org-table-clean-did-remove-column t)
26230 (delq nil
26231 (mapcar
26232 (lambda (x)
26233 (cond
26234 ((string-match "^[ \t]*| */ *|" x)
26235 (setq org-table-colgroup-info
26236 (mapcar (lambda (x)
26237 (cond ((member x '("<" "&lt;")) :start)
26238 ((member x '(">" "&gt;")) :end)
26239 ((member x '("<>" "&lt;&gt;")) :startend)
26240 (t nil)))
26241 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26242 nil)
26243 ((string-match "^[ \t]*| *[!_^/] *|" x)
26244 nil) ; ignore this line
26245 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26246 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26247 ;; remove the first column
26248 (replace-match "\\1|" t nil x))))
26249 lines))))
26251 (defun org-format-table-table-html (lines)
26252 "Format a table generated by table.el into HTML.
26253 This conversion does *not* use `table-generate-source' from table.el.
26254 This has the advantage that Org-mode's HTML conversions can be used.
26255 But it has the disadvantage, that no cell- or row-spanning is allowed."
26256 (let (line field-buffer
26257 (head org-export-highlight-first-table-line)
26258 fields html empty)
26259 (setq html (concat html-table-tag "\n"))
26260 (while (setq line (pop lines))
26261 (setq empty "&nbsp;")
26262 (catch 'next-line
26263 (if (string-match "^[ \t]*\\+-" line)
26264 (progn
26265 (if field-buffer
26266 (progn
26267 (setq
26268 html
26269 (concat
26270 html
26271 "<tr>"
26272 (mapconcat
26273 (lambda (x)
26274 (if (equal x "") (setq x empty))
26275 (if head
26276 (concat (car org-export-table-header-tags) x
26277 (cdr org-export-table-header-tags))
26278 (concat (car org-export-table-data-tags) x
26279 (cdr org-export-table-data-tags))))
26280 field-buffer "\n")
26281 "</tr>\n"))
26282 (setq head nil)
26283 (setq field-buffer nil)))
26284 ;; Ignore this line
26285 (throw 'next-line t)))
26286 ;; Break the line into fields and store the fields
26287 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26288 (if field-buffer
26289 (setq field-buffer (mapcar
26290 (lambda (x)
26291 (concat x "<br/>" (pop fields)))
26292 field-buffer))
26293 (setq field-buffer fields))))
26294 (setq html (concat html "</table>\n"))
26295 html))
26297 (defun org-format-table-table-html-using-table-generate-source (lines)
26298 "Format a table into html, using `table-generate-source' from table.el.
26299 This has the advantage that cell- or row-spanning is allowed.
26300 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26301 (require 'table)
26302 (with-current-buffer (get-buffer-create " org-tmp1 ")
26303 (erase-buffer)
26304 (insert (mapconcat 'identity lines "\n"))
26305 (goto-char (point-min))
26306 (if (not (re-search-forward "|[^+]" nil t))
26307 (error "Error processing table"))
26308 (table-recognize-table)
26309 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26310 (table-generate-source 'html " org-tmp2 ")
26311 (set-buffer " org-tmp2 ")
26312 (buffer-substring (point-min) (point-max))))
26314 (defun org-html-handle-time-stamps (s)
26315 "Format time stamps in string S, or remove them."
26316 (catch 'exit
26317 (let (r b)
26318 (while (string-match org-maybe-keyword-time-regexp s)
26319 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26320 ;; never export CLOCK
26321 (throw 'exit ""))
26322 (or b (setq b (substring s 0 (match-beginning 0))))
26323 (if (not org-export-with-timestamps)
26324 (setq r (concat r (substring s 0 (match-beginning 0)))
26325 s (substring s (match-end 0)))
26326 (setq r (concat
26327 r (substring s 0 (match-beginning 0))
26328 (if (match-end 1)
26329 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26330 (match-string 1 s)))
26331 (format " @<span class=\"timestamp\">%s@</span>"
26332 (substring
26333 (org-translate-time (match-string 3 s)) 1 -1)))
26334 s (substring s (match-end 0)))))
26335 ;; Line break if line started and ended with time stamp stuff
26336 (if (not r)
26338 (setq r (concat r s))
26339 (unless (string-match "\\S-" (concat b s))
26340 (setq r (concat r "@<br/>")))
26341 r))))
26343 (defun org-html-protect (s)
26344 ;; convert & to &amp;, < to &lt; and > to &gt;
26345 (let ((start 0))
26346 (while (string-match "&" s start)
26347 (setq s (replace-match "&amp;" t t s)
26348 start (1+ (match-beginning 0))))
26349 (while (string-match "<" s)
26350 (setq s (replace-match "&lt;" t t s)))
26351 (while (string-match ">" s)
26352 (setq s (replace-match "&gt;" t t s))))
26355 (defun org-export-cleanup-toc-line (s)
26356 "Remove tags and time staps from lines going into the toc."
26357 (when (memq org-export-with-tags '(not-in-toc nil))
26358 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26359 (setq s (replace-match "" t t s))))
26360 (when org-export-remove-timestamps-from-toc
26361 (while (string-match org-maybe-keyword-time-regexp s)
26362 (setq s (replace-match "" t t s))))
26363 (while (string-match org-bracket-link-regexp s)
26364 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26365 t t s)))
26368 (defun org-html-expand (string)
26369 "Prepare STRING for HTML export. Applies all active conversions.
26370 If there are links in the string, don't modify these."
26371 (let* ((re (concat org-bracket-link-regexp "\\|"
26372 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26373 m s l res)
26374 (while (setq m (string-match re string))
26375 (setq s (substring string 0 m)
26376 l (match-string 0 string)
26377 string (substring string (match-end 0)))
26378 (push (org-html-do-expand s) res)
26379 (push l res))
26380 (push (org-html-do-expand string) res)
26381 (apply 'concat (nreverse res))))
26383 (defun org-html-do-expand (s)
26384 "Apply all active conversions to translate special ASCII to HTML."
26385 (setq s (org-html-protect s))
26386 (if org-export-html-expand
26387 (let ((start 0))
26388 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26389 (setq s (replace-match "<\\1>" t nil s)))))
26390 (if org-export-with-emphasize
26391 (setq s (org-export-html-convert-emphasize s)))
26392 (if org-export-with-special-strings
26393 (setq s (org-export-html-convert-special-strings s)))
26394 (if org-export-with-sub-superscripts
26395 (setq s (org-export-html-convert-sub-super s)))
26396 (if org-export-with-TeX-macros
26397 (let ((start 0) wd ass)
26398 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26399 (if (get-text-property (match-beginning 0) 'org-protected s)
26400 (setq start (match-end 0))
26401 (setq wd (match-string 1 s))
26402 (if (setq ass (assoc wd org-html-entities))
26403 (setq s (replace-match (or (cdr ass)
26404 (concat "&" (car ass) ";"))
26405 t t s))
26406 (setq start (+ start (length wd))))))))
26409 (defun org-create-multibrace-regexp (left right n)
26410 "Create a regular expression which will match a balanced sexp.
26411 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26412 as single character strings.
26413 The regexp returned will match the entire expression including the
26414 delimiters. It will also define a single group which contains the
26415 match except for the outermost delimiters. The maximum depth of
26416 stacked delimiters is N. Escaping delimiters is not possible."
26417 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26418 (or "\\|")
26419 (re nothing)
26420 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26421 (while (> n 1)
26422 (setq n (1- n)
26423 re (concat re or next)
26424 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26425 (concat left "\\(" re "\\)" right)))
26427 (defvar org-match-substring-regexp
26428 (concat
26429 "\\([^\\]\\)\\([_^]\\)\\("
26430 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26431 "\\|"
26432 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26433 "\\|"
26434 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26435 "The regular expression matching a sub- or superscript.")
26437 (defvar org-match-substring-with-braces-regexp
26438 (concat
26439 "\\([^\\]\\)\\([_^]\\)\\("
26440 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26441 "\\)")
26442 "The regular expression matching a sub- or superscript, forcing braces.")
26444 (defconst org-export-html-special-string-regexps
26445 '(("\\\\-" . "&shy;")
26446 ("---\\([^-]\\)" . "&mdash;\\1")
26447 ("--\\([^-]\\)" . "&ndash;\\1")
26448 ("\\.\\.\\." . "&hellip;"))
26449 "Regular expressions for special string conversion.")
26451 (defun org-export-html-convert-special-strings (string)
26452 "Convert special characters in STRING to HTML."
26453 (let ((all org-export-html-special-string-regexps)
26454 e a re rpl start)
26455 (while (setq a (pop all))
26456 (setq re (car a) rpl (cdr a) start 0)
26457 (while (string-match re string start)
26458 (if (get-text-property (match-beginning 0) 'org-protected string)
26459 (setq start (match-end 0))
26460 (setq string (replace-match rpl t nil string)))))
26461 string))
26463 (defun org-export-html-convert-sub-super (string)
26464 "Convert sub- and superscripts in STRING to HTML."
26465 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26466 (while (string-match org-match-substring-regexp string s)
26467 (cond
26468 ((and requireb (match-end 8)) (setq s (match-end 2)))
26469 ((get-text-property (match-beginning 2) 'org-protected string)
26470 (setq s (match-end 2)))
26472 (setq s (match-end 1)
26473 key (if (string= (match-string 2 string) "_") "sub" "sup")
26474 c (or (match-string 8 string)
26475 (match-string 6 string)
26476 (match-string 5 string))
26477 string (replace-match
26478 (concat (match-string 1 string)
26479 "<" key ">" c "</" key ">")
26480 t t string)))))
26481 (while (string-match "\\\\\\([_^]\\)" string)
26482 (setq string (replace-match (match-string 1 string) t t string)))
26483 string))
26485 (defun org-export-html-convert-emphasize (string)
26486 "Apply emphasis."
26487 (let ((s 0) rpl)
26488 (while (string-match org-emph-re string s)
26489 (if (not (equal
26490 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26491 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26492 (setq s (match-beginning 0)
26494 (concat
26495 (match-string 1 string)
26496 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26497 (match-string 4 string)
26498 (nth 3 (assoc (match-string 3 string)
26499 org-emphasis-alist))
26500 (match-string 5 string))
26501 string (replace-match rpl t t string)
26502 s (+ s (- (length rpl) 2)))
26503 (setq s (1+ s))))
26504 string))
26506 (defvar org-par-open nil)
26507 (defun org-open-par ()
26508 "Insert <p>, but first close previous paragraph if any."
26509 (org-close-par-maybe)
26510 (insert "\n<p>")
26511 (setq org-par-open t))
26512 (defun org-close-par-maybe ()
26513 "Close paragraph if there is one open."
26514 (when org-par-open
26515 (insert "</p>")
26516 (setq org-par-open nil)))
26517 (defun org-close-li ()
26518 "Close <li> if necessary."
26519 (org-close-par-maybe)
26520 (insert "</li>\n"))
26522 (defvar body-only) ; dynamically scoped into this.
26523 (defun org-html-level-start (level title umax with-toc head-count)
26524 "Insert a new level in HTML export.
26525 When TITLE is nil, just close all open levels."
26526 (org-close-par-maybe)
26527 (let ((l org-level-max) snumber)
26528 (while (>= l level)
26529 (if (aref org-levels-open (1- l))
26530 (progn
26531 (org-html-level-close l umax)
26532 (aset org-levels-open (1- l) nil)))
26533 (setq l (1- l)))
26534 (when title
26535 ;; If title is nil, this means this function is called to close
26536 ;; all levels, so the rest is done only if title is given
26537 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26538 (setq title (replace-match
26539 (if org-export-with-tags
26540 (save-match-data
26541 (concat
26542 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26543 (mapconcat 'identity (org-split-string
26544 (match-string 1 title) ":")
26545 "&nbsp;")
26546 "</span>"))
26548 t t title)))
26549 (if (> level umax)
26550 (progn
26551 (if (aref org-levels-open (1- level))
26552 (progn
26553 (org-close-li)
26554 (insert "<li>" title "<br/>\n"))
26555 (aset org-levels-open (1- level) t)
26556 (org-close-par-maybe)
26557 (insert "<ul>\n<li>" title "<br/>\n")))
26558 (aset org-levels-open (1- level) t)
26559 (setq snumber (org-section-number level))
26560 (if (and org-export-with-section-numbers (not body-only))
26561 (setq title (concat snumber " " title)))
26562 (setq level (+ level org-export-html-toplevel-hlevel -1))
26563 (unless (= head-count 1) (insert "\n</div>\n"))
26564 (insert (format "\n<div id=\"outline-container-%s\" class=\"outline-%d\">\n<h%d id=\"sec-%s\">%s</h%d>\n<div id=\"text-%s\">\n"
26565 snumber level level snumber title level snumber))
26566 (org-open-par)))))
26568 (defun org-html-level-close (level max-outline-level)
26569 "Terminate one level in HTML export."
26570 (if (<= level max-outline-level)
26571 (insert "</div>\n")
26572 (org-close-li)
26573 (insert "</ul>\n")))
26575 ;;; iCalendar export
26577 ;;;###autoload
26578 (defun org-export-icalendar-this-file ()
26579 "Export current file as an iCalendar file.
26580 The iCalendar file will be located in the same directory as the Org-mode
26581 file, but with extension `.ics'."
26582 (interactive)
26583 (org-export-icalendar nil buffer-file-name))
26585 ;;;###autoload
26586 (defun org-export-icalendar-all-agenda-files ()
26587 "Export all files in `org-agenda-files' to iCalendar .ics files.
26588 Each iCalendar file will be located in the same directory as the Org-mode
26589 file, but with extension `.ics'."
26590 (interactive)
26591 (apply 'org-export-icalendar nil (org-agenda-files t)))
26593 ;;;###autoload
26594 (defun org-export-icalendar-combine-agenda-files ()
26595 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26596 The file is stored under the name `org-combined-agenda-icalendar-file'."
26597 (interactive)
26598 (apply 'org-export-icalendar t (org-agenda-files t)))
26600 (defun org-export-icalendar (combine &rest files)
26601 "Create iCalendar files for all elements of FILES.
26602 If COMBINE is non-nil, combine all calendar entries into a single large
26603 file and store it under the name `org-combined-agenda-icalendar-file'."
26604 (save-excursion
26605 (org-prepare-agenda-buffers files)
26606 (let* ((dir (org-export-directory
26607 :ical (list :publishing-directory
26608 org-export-publishing-directory)))
26609 file ical-file ical-buffer category started org-agenda-new-buffers)
26610 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26611 (when combine
26612 (setq ical-file
26613 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26614 org-combined-agenda-icalendar-file
26615 (expand-file-name org-combined-agenda-icalendar-file dir))
26616 ical-buffer (org-get-agenda-file-buffer ical-file))
26617 (set-buffer ical-buffer) (erase-buffer))
26618 (while (setq file (pop files))
26619 (catch 'nextfile
26620 (org-check-agenda-file file)
26621 (set-buffer (org-get-agenda-file-buffer file))
26622 (unless combine
26623 (setq ical-file (concat (file-name-as-directory dir)
26624 (file-name-sans-extension
26625 (file-name-nondirectory buffer-file-name))
26626 ".ics"))
26627 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26628 (with-current-buffer ical-buffer (erase-buffer)))
26629 (setq category (or org-category
26630 (file-name-sans-extension
26631 (file-name-nondirectory buffer-file-name))))
26632 (if (symbolp category) (setq category (symbol-name category)))
26633 (let ((standard-output ical-buffer))
26634 (if combine
26635 (and (not started) (setq started t)
26636 (org-start-icalendar-file org-icalendar-combined-name))
26637 (org-start-icalendar-file category))
26638 (org-print-icalendar-entries combine)
26639 (when (or (and combine (not files)) (not combine))
26640 (org-finish-icalendar-file)
26641 (set-buffer ical-buffer)
26642 (save-buffer)
26643 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26644 (org-release-buffers org-agenda-new-buffers))))
26646 (defvar org-after-save-iCalendar-file-hook nil
26647 "Hook run after an iCalendar file has been saved.
26648 The iCalendar buffer is still current when this hook is run.
26649 A good way to use this is to tell a desktop calenndar application to re-read
26650 the iCalendar file.")
26652 (defun org-print-icalendar-entries (&optional combine)
26653 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26654 When COMBINE is non nil, add the category to each line."
26655 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26656 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26657 (dts (org-ical-ts-to-string
26658 (format-time-string (cdr org-time-stamp-formats) (current-time))
26659 "DTSTART"))
26660 hd ts ts2 state status (inc t) pos b sexp rrule
26661 scheduledp deadlinep tmp pri category entry location summary desc
26662 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26663 (org-refresh-category-properties)
26664 (save-excursion
26665 (goto-char (point-min))
26666 (while (re-search-forward re1 nil t)
26667 (catch :skip
26668 (org-agenda-skip)
26669 (when (boundp 'org-icalendar-verify-function)
26670 (unless (funcall org-icalendar-verify-function)
26671 (outline-next-heading)
26672 (backward-char 1)
26673 (throw :skip nil)))
26674 (setq pos (match-beginning 0)
26675 ts (match-string 0)
26676 inc t
26677 hd (org-get-heading)
26678 summary (org-icalendar-cleanup-string
26679 (org-entry-get nil "SUMMARY"))
26680 desc (org-icalendar-cleanup-string
26681 (or (org-entry-get nil "DESCRIPTION")
26682 (and org-icalendar-include-body (org-get-entry)))
26683 t org-icalendar-include-body)
26684 location (org-icalendar-cleanup-string
26685 (org-entry-get nil "LOCATION"))
26686 category (org-get-category))
26687 (if (looking-at re2)
26688 (progn
26689 (goto-char (match-end 0))
26690 (setq ts2 (match-string 1) inc nil))
26691 (setq tmp (buffer-substring (max (point-min)
26692 (- pos org-ds-keyword-length))
26693 pos)
26694 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26695 (progn
26696 (setq inc nil)
26697 (replace-match "\\1" t nil ts))
26699 deadlinep (string-match org-deadline-regexp tmp)
26700 scheduledp (string-match org-scheduled-regexp tmp)
26701 ;; donep (org-entry-is-done-p)
26703 (if (or (string-match org-tr-regexp hd)
26704 (string-match org-ts-regexp hd))
26705 (setq hd (replace-match "" t t hd)))
26706 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26707 (setq rrule
26708 (concat "\nRRULE:FREQ="
26709 (cdr (assoc
26710 (match-string 2 ts)
26711 '(("d" . "DAILY")("w" . "WEEKLY")
26712 ("m" . "MONTHLY")("y" . "YEARLY"))))
26713 ";INTERVAL=" (match-string 1 ts)))
26714 (setq rrule ""))
26715 (setq summary (or summary hd))
26716 (if (string-match org-bracket-link-regexp summary)
26717 (setq summary
26718 (replace-match (if (match-end 3)
26719 (match-string 3 summary)
26720 (match-string 1 summary))
26721 t t summary)))
26722 (if deadlinep (setq summary (concat "DL: " summary)))
26723 (if scheduledp (setq summary (concat "S: " summary)))
26724 (if (string-match "\\`<%%" ts)
26725 (with-current-buffer sexp-buffer
26726 (insert (substring ts 1 -1) " " summary "\n"))
26727 (princ (format "BEGIN:VEVENT
26729 %s%s
26730 SUMMARY:%s%s%s
26731 CATEGORIES:%s
26732 END:VEVENT\n"
26733 (org-ical-ts-to-string ts "DTSTART")
26734 (org-ical-ts-to-string ts2 "DTEND" inc)
26735 rrule summary
26736 (if (and desc (string-match "\\S-" desc))
26737 (concat "\nDESCRIPTION: " desc) "")
26738 (if (and location (string-match "\\S-" location))
26739 (concat "\nLOCATION: " location) "")
26740 category)))))
26742 (when (and org-icalendar-include-sexps
26743 (condition-case nil (require 'icalendar) (error nil))
26744 (fboundp 'icalendar-export-region))
26745 ;; Get all the literal sexps
26746 (goto-char (point-min))
26747 (while (re-search-forward "^&?%%(" nil t)
26748 (catch :skip
26749 (org-agenda-skip)
26750 (setq b (match-beginning 0))
26751 (goto-char (1- (match-end 0)))
26752 (forward-sexp 1)
26753 (end-of-line 1)
26754 (setq sexp (buffer-substring b (point)))
26755 (with-current-buffer sexp-buffer
26756 (insert sexp "\n"))
26757 (princ (org-diary-to-ical-string sexp-buffer)))))
26759 (when org-icalendar-include-todo
26760 (goto-char (point-min))
26761 (while (re-search-forward org-todo-line-regexp nil t)
26762 (catch :skip
26763 (org-agenda-skip)
26764 (when (boundp 'org-icalendar-verify-function)
26765 (unless (funcall org-icalendar-verify-function)
26766 (outline-next-heading)
26767 (backward-char 1)
26768 (throw :skip nil)))
26769 (setq state (match-string 2))
26770 (setq status (if (member state org-done-keywords)
26771 "COMPLETED" "NEEDS-ACTION"))
26772 (when (and state
26773 (or (not (member state org-done-keywords))
26774 (eq org-icalendar-include-todo 'all))
26775 (not (member org-archive-tag (org-get-tags-at)))
26777 (setq hd (match-string 3)
26778 summary (org-icalendar-cleanup-string
26779 (org-entry-get nil "SUMMARY"))
26780 desc (org-icalendar-cleanup-string
26781 (or (org-entry-get nil "DESCRIPTION")
26782 (and org-icalendar-include-body (org-get-entry)))
26783 t org-icalendar-include-body)
26784 location (org-icalendar-cleanup-string
26785 (org-entry-get nil "LOCATION")))
26786 (if (string-match org-bracket-link-regexp hd)
26787 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26788 (match-string 1 hd))
26789 t t hd)))
26790 (if (string-match org-priority-regexp hd)
26791 (setq pri (string-to-char (match-string 2 hd))
26792 hd (concat (substring hd 0 (match-beginning 1))
26793 (substring hd (match-end 1))))
26794 (setq pri org-default-priority))
26795 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26796 (- org-lowest-priority org-highest-priority))))))
26798 (princ (format "BEGIN:VTODO
26800 SUMMARY:%s%s%s
26801 CATEGORIES:%s
26802 SEQUENCE:1
26803 PRIORITY:%d
26804 STATUS:%s
26805 END:VTODO\n"
26807 (or summary hd)
26808 (if (and location (string-match "\\S-" location))
26809 (concat "\nLOCATION: " location) "")
26810 (if (and desc (string-match "\\S-" desc))
26811 (concat "\nDESCRIPTION: " desc) "")
26812 category pri status)))))))))
26814 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26815 "Take out stuff and quote what needs to be quoted.
26816 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26817 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26818 characters."
26819 (if (not s)
26821 (when is-body
26822 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26823 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26824 (while (string-match re s) (setq s (replace-match "" t t s)))
26825 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26826 (let ((start 0))
26827 (while (string-match "\\([,;\\]\\)" s start)
26828 (setq start (+ (match-beginning 0) 2)
26829 s (replace-match "\\\\\\1" nil nil s))))
26830 (when is-body
26831 (while (string-match "[ \t]*\n[ \t]*" s)
26832 (setq s (replace-match "\\n" t t s))))
26833 (setq s (org-trim s))
26834 (if is-body
26835 (if maxlength
26836 (if (and (numberp maxlength)
26837 (> (length s) maxlength))
26838 (setq s (substring s 0 maxlength)))))
26841 (defun org-get-entry ()
26842 "Clean-up description string."
26843 (save-excursion
26844 (org-back-to-heading t)
26845 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26847 (defun org-start-icalendar-file (name)
26848 "Start an iCalendar file by inserting the header."
26849 (let ((user user-full-name)
26850 (name (or name "unknown"))
26851 (timezone (cadr (current-time-zone))))
26852 (princ
26853 (format "BEGIN:VCALENDAR
26854 VERSION:2.0
26855 X-WR-CALNAME:%s
26856 PRODID:-//%s//Emacs with Org-mode//EN
26857 X-WR-TIMEZONE:%s
26858 CALSCALE:GREGORIAN\n" name user timezone))))
26860 (defun org-finish-icalendar-file ()
26861 "Finish an iCalendar file by inserting the END statement."
26862 (princ "END:VCALENDAR\n"))
26864 (defun org-ical-ts-to-string (s keyword &optional inc)
26865 "Take a time string S and convert it to iCalendar format.
26866 KEYWORD is added in front, to make a complete line like DTSTART....
26867 When INC is non-nil, increase the hour by two (if time string contains
26868 a time), or the day by one (if it does not contain a time)."
26869 (let ((t1 (org-parse-time-string s 'nodefault))
26870 t2 fmt have-time time)
26871 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26872 (setq t2 t1 have-time t)
26873 (setq t2 (org-parse-time-string s)))
26874 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26875 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26876 (when inc
26877 (if have-time
26878 (if org-agenda-default-appointment-duration
26879 (setq mi (+ org-agenda-default-appointment-duration mi))
26880 (setq h (+ 2 h)))
26881 (setq d (1+ d))))
26882 (setq time (encode-time s mi h d m y)))
26883 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26884 (concat keyword (format-time-string fmt time))))
26886 ;;; XOXO export
26888 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26889 (with-current-buffer buffer
26890 (apply 'insert output)))
26891 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26893 (defun org-export-as-xoxo (&optional buffer)
26894 "Export the org buffer as XOXO.
26895 The XOXO buffer is named *xoxo-<source buffer name>*"
26896 (interactive (list (current-buffer)))
26897 ;; A quickie abstraction
26899 ;; Output everything as XOXO
26900 (with-current-buffer (get-buffer buffer)
26901 (let* ((pos (point))
26902 (opt-plist (org-combine-plists (org-default-export-plist)
26903 (org-infile-export-plist)))
26904 (filename (concat (file-name-as-directory
26905 (org-export-directory :xoxo opt-plist))
26906 (file-name-sans-extension
26907 (file-name-nondirectory buffer-file-name))
26908 ".html"))
26909 (out (find-file-noselect filename))
26910 (last-level 1)
26911 (hanging-li nil))
26912 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26913 ;; Check the output buffer is empty.
26914 (with-current-buffer out (erase-buffer))
26915 ;; Kick off the output
26916 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26917 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26918 (let* ((hd (match-string-no-properties 1))
26919 (level (length hd))
26920 (text (concat
26921 (match-string-no-properties 2)
26922 (save-excursion
26923 (goto-char (match-end 0))
26924 (let ((str ""))
26925 (catch 'loop
26926 (while 't
26927 (forward-line)
26928 (if (looking-at "^[ \t]\\(.*\\)")
26929 (setq str (concat str (match-string-no-properties 1)))
26930 (throw 'loop str)))))))))
26932 ;; Handle level rendering
26933 (cond
26934 ((> level last-level)
26935 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26937 ((< level last-level)
26938 (dotimes (- (- last-level level) 1)
26939 (if hanging-li
26940 (org-export-as-xoxo-insert-into out "</li>\n"))
26941 (org-export-as-xoxo-insert-into out "</ol>\n"))
26942 (when hanging-li
26943 (org-export-as-xoxo-insert-into out "</li>\n")
26944 (setq hanging-li nil)))
26946 ((equal level last-level)
26947 (if hanging-li
26948 (org-export-as-xoxo-insert-into out "</li>\n")))
26951 (setq last-level level)
26953 ;; And output the new li
26954 (setq hanging-li 't)
26955 (if (equal ?+ (elt text 0))
26956 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26957 (org-export-as-xoxo-insert-into out "<li>" text))))
26959 ;; Finally finish off the ol
26960 (dotimes (- last-level 1)
26961 (if hanging-li
26962 (org-export-as-xoxo-insert-into out "</li>\n"))
26963 (org-export-as-xoxo-insert-into out "</ol>\n"))
26965 (goto-char pos)
26966 ;; Finish the buffer off and clean it up.
26967 (switch-to-buffer-other-window out)
26968 (indent-region (point-min) (point-max) nil)
26969 (save-buffer)
26970 (goto-char (point-min))
26974 ;;;; Key bindings
26976 ;; Make `C-c C-x' a prefix key
26977 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26979 ;; TAB key with modifiers
26980 (org-defkey org-mode-map "\C-i" 'org-cycle)
26981 (org-defkey org-mode-map [(tab)] 'org-cycle)
26982 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26983 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26984 (org-defkey org-mode-map "\M-\t" 'org-complete)
26985 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26986 ;; The following line is necessary under Suse GNU/Linux
26987 (unless (featurep 'xemacs)
26988 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26989 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26990 (define-key org-mode-map [backtab] 'org-shifttab)
26992 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26993 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26994 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26996 ;; Cursor keys with modifiers
26997 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26998 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26999 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27000 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27002 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27003 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27004 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27005 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27007 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27008 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27009 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27010 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27012 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27013 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27015 ;;; Extra keys for tty access.
27016 ;; We only set them when really needed because otherwise the
27017 ;; menus don't show the simple keys
27019 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27020 (not window-system))
27021 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27022 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27023 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27024 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27025 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27026 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27027 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27028 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27029 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27030 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27031 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27032 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27033 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27034 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27035 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27036 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27037 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27038 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27039 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27040 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27041 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27042 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27044 ;; All the other keys
27046 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27047 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27048 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27049 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27050 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27051 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27052 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27053 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27054 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27055 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27056 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27057 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27058 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27059 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27060 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27061 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27062 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27063 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27064 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27065 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27066 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27067 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27068 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27069 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27070 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27071 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27072 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27073 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27074 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27075 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27076 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27077 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27078 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27079 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27080 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27081 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27082 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27083 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27084 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27085 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27086 (org-defkey org-mode-map "\C-c^" 'org-sort)
27087 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27088 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27089 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27090 (org-defkey org-mode-map "\C-m" 'org-return)
27091 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27092 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27093 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27094 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27095 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27096 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27097 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27098 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27099 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27100 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27101 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27102 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27103 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27104 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27105 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27106 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27108 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27109 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27110 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27111 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27113 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27114 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27115 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27116 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27117 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27118 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27119 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27120 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27121 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27122 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27123 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27124 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27126 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27128 (when (featurep 'xemacs)
27129 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27131 (defsubst org-table-p () (org-at-table-p))
27133 (defun org-self-insert-command (N)
27134 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27135 If the cursor is in a table looking at whitespace, the whitespace is
27136 overwritten, and the table is not marked as requiring realignment."
27137 (interactive "p")
27138 (if (and (org-table-p)
27139 (progn
27140 ;; check if we blank the field, and if that triggers align
27141 (and org-table-auto-blank-field
27142 (member last-command
27143 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27144 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27145 ;; got extra space, this field does not determine column width
27146 (let (org-table-may-need-update) (org-table-blank-field))
27147 ;; no extra space, this field may determine column width
27148 (org-table-blank-field)))
27150 (eq N 1)
27151 (looking-at "[^|\n]* |"))
27152 (let (org-table-may-need-update)
27153 (goto-char (1- (match-end 0)))
27154 (delete-backward-char 1)
27155 (goto-char (match-beginning 0))
27156 (self-insert-command N))
27157 (setq org-table-may-need-update t)
27158 (self-insert-command N)
27159 (org-fix-tags-on-the-fly)))
27161 (defun org-fix-tags-on-the-fly ()
27162 (when (and (equal (char-after (point-at-bol)) ?*)
27163 (org-on-heading-p))
27164 (org-align-tags-here org-tags-column)))
27166 (defun org-delete-backward-char (N)
27167 "Like `delete-backward-char', insert whitespace at field end in tables.
27168 When deleting backwards, in tables this function will insert whitespace in
27169 front of the next \"|\" separator, to keep the table aligned. The table will
27170 still be marked for re-alignment if the field did fill the entire column,
27171 because, in this case the deletion might narrow the column."
27172 (interactive "p")
27173 (if (and (org-table-p)
27174 (eq N 1)
27175 (string-match "|" (buffer-substring (point-at-bol) (point)))
27176 (looking-at ".*?|"))
27177 (let ((pos (point))
27178 (noalign (looking-at "[^|\n\r]* |"))
27179 (c org-table-may-need-update))
27180 (backward-delete-char N)
27181 (skip-chars-forward "^|")
27182 (insert " ")
27183 (goto-char (1- pos))
27184 ;; noalign: if there were two spaces at the end, this field
27185 ;; does not determine the width of the column.
27186 (if noalign (setq org-table-may-need-update c)))
27187 (backward-delete-char N)
27188 (org-fix-tags-on-the-fly)))
27190 (defun org-delete-char (N)
27191 "Like `delete-char', but insert whitespace at field end in tables.
27192 When deleting characters, in tables this function will insert whitespace in
27193 front of the next \"|\" separator, to keep the table aligned. The table will
27194 still be marked for re-alignment if the field did fill the entire column,
27195 because, in this case the deletion might narrow the column."
27196 (interactive "p")
27197 (if (and (org-table-p)
27198 (not (bolp))
27199 (not (= (char-after) ?|))
27200 (eq N 1))
27201 (if (looking-at ".*?|")
27202 (let ((pos (point))
27203 (noalign (looking-at "[^|\n\r]* |"))
27204 (c org-table-may-need-update))
27205 (replace-match (concat
27206 (substring (match-string 0) 1 -1)
27207 " |"))
27208 (goto-char pos)
27209 ;; noalign: if there were two spaces at the end, this field
27210 ;; does not determine the width of the column.
27211 (if noalign (setq org-table-may-need-update c)))
27212 (delete-char N))
27213 (delete-char N)
27214 (org-fix-tags-on-the-fly)))
27216 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27217 (put 'org-self-insert-command 'delete-selection t)
27218 (put 'orgtbl-self-insert-command 'delete-selection t)
27219 (put 'org-delete-char 'delete-selection 'supersede)
27220 (put 'org-delete-backward-char 'delete-selection 'supersede)
27222 ;; Make `flyspell-mode' delay after some commands
27223 (put 'org-self-insert-command 'flyspell-delayed t)
27224 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27225 (put 'org-delete-char 'flyspell-delayed t)
27226 (put 'org-delete-backward-char 'flyspell-delayed t)
27228 ;; Make pabbrev-mode expand after org-mode commands
27229 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27230 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27232 ;; How to do this: Measure non-white length of current string
27233 ;; If equal to column width, we should realign.
27235 (defun org-remap (map &rest commands)
27236 "In MAP, remap the functions given in COMMANDS.
27237 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27238 (let (new old)
27239 (while commands
27240 (setq old (pop commands) new (pop commands))
27241 (if (fboundp 'command-remapping)
27242 (org-defkey map (vector 'remap old) new)
27243 (substitute-key-definition old new map global-map)))))
27245 (when (eq org-enable-table-editor 'optimized)
27246 ;; If the user wants maximum table support, we need to hijack
27247 ;; some standard editing functions
27248 (org-remap org-mode-map
27249 'self-insert-command 'org-self-insert-command
27250 'delete-char 'org-delete-char
27251 'delete-backward-char 'org-delete-backward-char)
27252 (org-defkey org-mode-map "|" 'org-force-self-insert))
27254 (defun org-shiftcursor-error ()
27255 "Throw an error because Shift-Cursor command was applied in wrong context."
27256 (error "This command is active in special context like tables, headlines or timestamps"))
27258 (defun org-shifttab (&optional arg)
27259 "Global visibility cycling or move to previous table field.
27260 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27261 on context.
27262 See the individual commands for more information."
27263 (interactive "P")
27264 (cond
27265 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27266 (arg (message "Content view to level: ")
27267 (org-content (prefix-numeric-value arg))
27268 (setq org-cycle-global-status 'overview))
27269 (t (call-interactively 'org-global-cycle))))
27271 (defun org-shiftmetaleft ()
27272 "Promote subtree or delete table column.
27273 Calls `org-promote-subtree', `org-outdent-item',
27274 or `org-table-delete-column', depending on context.
27275 See the individual commands for more information."
27276 (interactive)
27277 (cond
27278 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27279 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27280 ((org-at-item-p) (call-interactively 'org-outdent-item))
27281 (t (org-shiftcursor-error))))
27283 (defun org-shiftmetaright ()
27284 "Demote subtree or insert table column.
27285 Calls `org-demote-subtree', `org-indent-item',
27286 or `org-table-insert-column', depending on context.
27287 See the individual commands for more information."
27288 (interactive)
27289 (cond
27290 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27291 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27292 ((org-at-item-p) (call-interactively 'org-indent-item))
27293 (t (org-shiftcursor-error))))
27295 (defun org-shiftmetaup (&optional arg)
27296 "Move subtree up or kill table row.
27297 Calls `org-move-subtree-up' or `org-table-kill-row' or
27298 `org-move-item-up' depending on context. See the individual commands
27299 for more information."
27300 (interactive "P")
27301 (cond
27302 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27303 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27304 ((org-at-item-p) (call-interactively 'org-move-item-up))
27305 (t (org-shiftcursor-error))))
27306 (defun org-shiftmetadown (&optional arg)
27307 "Move subtree down or insert table row.
27308 Calls `org-move-subtree-down' or `org-table-insert-row' or
27309 `org-move-item-down', depending on context. See the individual
27310 commands for more information."
27311 (interactive "P")
27312 (cond
27313 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27314 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27315 ((org-at-item-p) (call-interactively 'org-move-item-down))
27316 (t (org-shiftcursor-error))))
27318 (defun org-metaleft (&optional arg)
27319 "Promote heading or move table column to left.
27320 Calls `org-do-promote' or `org-table-move-column', depending on context.
27321 With no specific context, calls the Emacs default `backward-word'.
27322 See the individual commands for more information."
27323 (interactive "P")
27324 (cond
27325 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27326 ((or (org-on-heading-p) (org-region-active-p))
27327 (call-interactively 'org-do-promote))
27328 ((org-at-item-p) (call-interactively 'org-outdent-item))
27329 (t (call-interactively 'backward-word))))
27331 (defun org-metaright (&optional arg)
27332 "Demote subtree or move table column to right.
27333 Calls `org-do-demote' or `org-table-move-column', depending on context.
27334 With no specific context, calls the Emacs default `forward-word'.
27335 See the individual commands for more information."
27336 (interactive "P")
27337 (cond
27338 ((org-at-table-p) (call-interactively 'org-table-move-column))
27339 ((or (org-on-heading-p) (org-region-active-p))
27340 (call-interactively 'org-do-demote))
27341 ((org-at-item-p) (call-interactively 'org-indent-item))
27342 (t (call-interactively 'forward-word))))
27344 (defun org-metaup (&optional arg)
27345 "Move subtree up or move table row up.
27346 Calls `org-move-subtree-up' or `org-table-move-row' or
27347 `org-move-item-up', depending on context. See the individual commands
27348 for more information."
27349 (interactive "P")
27350 (cond
27351 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27352 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27353 ((org-at-item-p) (call-interactively 'org-move-item-up))
27354 (t (transpose-lines 1) (beginning-of-line -1))))
27356 (defun org-metadown (&optional arg)
27357 "Move subtree down or move table row down.
27358 Calls `org-move-subtree-down' or `org-table-move-row' or
27359 `org-move-item-down', depending on context. See the individual
27360 commands for more information."
27361 (interactive "P")
27362 (cond
27363 ((org-at-table-p) (call-interactively 'org-table-move-row))
27364 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27365 ((org-at-item-p) (call-interactively 'org-move-item-down))
27366 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27368 (defun org-shiftup (&optional arg)
27369 "Increase item in timestamp or increase priority of current headline.
27370 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27371 depending on context. See the individual commands for more information."
27372 (interactive "P")
27373 (cond
27374 ((org-at-timestamp-p t)
27375 (call-interactively (if org-edit-timestamp-down-means-later
27376 'org-timestamp-down 'org-timestamp-up)))
27377 ((org-on-heading-p) (call-interactively 'org-priority-up))
27378 ((org-at-item-p) (call-interactively 'org-previous-item))
27379 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27381 (defun org-shiftdown (&optional arg)
27382 "Decrease item in timestamp or decrease priority of current headline.
27383 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27384 depending on context. See the individual commands for more information."
27385 (interactive "P")
27386 (cond
27387 ((org-at-timestamp-p t)
27388 (call-interactively (if org-edit-timestamp-down-means-later
27389 'org-timestamp-up 'org-timestamp-down)))
27390 ((org-on-heading-p) (call-interactively 'org-priority-down))
27391 (t (call-interactively 'org-next-item))))
27393 (defun org-shiftright ()
27394 "Next TODO keyword or timestamp one day later, depending on context."
27395 (interactive)
27396 (cond
27397 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27398 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27399 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27400 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27401 (t (org-shiftcursor-error))))
27403 (defun org-shiftleft ()
27404 "Previous TODO keyword or timestamp one day earlier, depending on context."
27405 (interactive)
27406 (cond
27407 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27408 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27409 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27410 ((org-at-property-p)
27411 (call-interactively 'org-property-previous-allowed-value))
27412 (t (org-shiftcursor-error))))
27414 (defun org-shiftcontrolright ()
27415 "Switch to next TODO set."
27416 (interactive)
27417 (cond
27418 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27419 (t (org-shiftcursor-error))))
27421 (defun org-shiftcontrolleft ()
27422 "Switch to previous TODO set."
27423 (interactive)
27424 (cond
27425 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27426 (t (org-shiftcursor-error))))
27428 (defun org-ctrl-c-ret ()
27429 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27430 (interactive)
27431 (cond
27432 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27433 (t (call-interactively 'org-insert-heading))))
27435 (defun org-copy-special ()
27436 "Copy region in table or copy current subtree.
27437 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27438 See the individual commands for more information."
27439 (interactive)
27440 (call-interactively
27441 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27443 (defun org-cut-special ()
27444 "Cut region in table or cut current subtree.
27445 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27446 See the individual commands for more information."
27447 (interactive)
27448 (call-interactively
27449 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27451 (defun org-paste-special (arg)
27452 "Paste rectangular region into table, or past subtree relative to level.
27453 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27454 See the individual commands for more information."
27455 (interactive "P")
27456 (if (org-at-table-p)
27457 (org-table-paste-rectangle)
27458 (org-paste-subtree arg)))
27460 (defun org-ctrl-c-ctrl-c (&optional arg)
27461 "Set tags in headline, or update according to changed information at point.
27463 This command does many different things, depending on context:
27465 - If the cursor is in a headline, prompt for tags and insert them
27466 into the current line, aligned to `org-tags-column'. When called
27467 with prefix arg, realign all tags in the current buffer.
27469 - If the cursor is in one of the special #+KEYWORD lines, this
27470 triggers scanning the buffer for these lines and updating the
27471 information.
27473 - If the cursor is inside a table, realign the table. This command
27474 works even if the automatic table editor has been turned off.
27476 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27477 the entire table.
27479 - If the cursor is a the beginning of a dynamic block, update it.
27481 - If the cursor is inside a table created by the table.el package,
27482 activate that table.
27484 - If the current buffer is a remember buffer, close note and file it.
27485 with a prefix argument, file it without further interaction to the default
27486 location.
27488 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27489 links in this buffer.
27491 - If the cursor is on a numbered item in a plain list, renumber the
27492 ordered list.
27494 - If the cursor is on a checkbox, toggle it."
27495 (interactive "P")
27496 (let ((org-enable-table-editor t))
27497 (cond
27498 ((or org-clock-overlays
27499 org-occur-highlights
27500 org-latex-fragment-image-overlays)
27501 (org-remove-clock-overlays)
27502 (org-remove-occur-highlights)
27503 (org-remove-latex-fragment-image-overlays)
27504 (message "Temporary highlights/overlays removed from current buffer"))
27505 ((and (local-variable-p 'org-finish-function (current-buffer))
27506 (fboundp org-finish-function))
27507 (funcall org-finish-function))
27508 ((org-at-property-p)
27509 (call-interactively 'org-property-action))
27510 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27511 ((org-on-heading-p) (call-interactively 'org-set-tags))
27512 ((org-at-table.el-p)
27513 (require 'table)
27514 (beginning-of-line 1)
27515 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27516 (call-interactively 'table-recognize-table))
27517 ((org-at-table-p)
27518 (org-table-maybe-eval-formula)
27519 (if arg
27520 (call-interactively 'org-table-recalculate)
27521 (org-table-maybe-recalculate-line))
27522 (call-interactively 'org-table-align))
27523 ((org-at-item-checkbox-p)
27524 (call-interactively 'org-toggle-checkbox))
27525 ((org-at-item-p)
27526 (call-interactively 'org-maybe-renumber-ordered-list))
27527 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27528 ;; Dynamic block
27529 (beginning-of-line 1)
27530 (org-update-dblock))
27531 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27532 (cond
27533 ((equal (match-string 1) "TBLFM")
27534 ;; Recalculate the table before this line
27535 (save-excursion
27536 (beginning-of-line 1)
27537 (skip-chars-backward " \r\n\t")
27538 (if (org-at-table-p)
27539 (org-call-with-arg 'org-table-recalculate t))))
27541 (call-interactively 'org-mode-restart))))
27542 (t (error "C-c C-c can do nothing useful at this location.")))))
27544 (defun org-mode-restart ()
27545 "Restart Org-mode, to scan again for special lines.
27546 Also updates the keyword regular expressions."
27547 (interactive)
27548 (let ((org-inhibit-startup t)) (org-mode))
27549 (message "Org-mode restarted to refresh keyword and special line setup"))
27551 (defun org-kill-note-or-show-branches ()
27552 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27553 (interactive)
27554 (if (not org-finish-function)
27555 (call-interactively 'show-branches)
27556 (let ((org-note-abort t))
27557 (funcall org-finish-function))))
27559 (defun org-return (&optional indent)
27560 "Goto next table row or insert a newline.
27561 Calls `org-table-next-row' or `newline', depending on context.
27562 See the individual commands for more information."
27563 (interactive)
27564 (cond
27565 ((bobp) (if indent (newline-and-indent) (newline)))
27566 ((and (org-at-heading-p)
27567 (looking-at
27568 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27569 (org-show-entry)
27570 (end-of-line 1)
27571 (newline))
27572 ((org-at-table-p)
27573 (org-table-justify-field-maybe)
27574 (call-interactively 'org-table-next-row))
27575 (t (if indent (newline-and-indent) (newline)))))
27577 (defun org-return-indent ()
27578 "Goto next table row or insert a newline and indent.
27579 Calls `org-table-next-row' or `newline-and-indent', depending on
27580 context. See the individual commands for more information."
27581 (interactive)
27582 (org-return t))
27584 (defun org-ctrl-c-star ()
27585 "Compute table, or change heading status of lines.
27586 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27587 depending on context. This will also turn a plain list item or a normal
27588 line into a subheading."
27589 (interactive)
27590 (cond
27591 ((org-at-table-p)
27592 (call-interactively 'org-table-recalculate))
27593 ((org-region-active-p)
27594 ;; Convert all lines in region to list items
27595 (call-interactively 'org-toggle-region-headings))
27596 ((org-on-heading-p)
27597 (org-toggle-region-headings (point-at-bol)
27598 (min (1+ (point-at-eol)) (point-max))))
27599 ((org-at-item-p)
27600 ;; Convert to heading
27601 (let ((level (save-match-data
27602 (save-excursion
27603 (condition-case nil
27604 (progn
27605 (org-back-to-heading t)
27606 (funcall outline-level))
27607 (error 0))))))
27608 (replace-match
27609 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27610 (t (org-toggle-region-headings (point-at-bol)
27611 (min (1+ (point-at-eol)) (point-max))))))
27613 (defun org-ctrl-c-minus ()
27614 "Insert separator line in table or modify bullet status of line.
27615 Also turns a plain line or a region of lines into list items.
27616 Calls `org-table-insert-hline', `org-toggle-region-items', or
27617 `org-cycle-list-bullet', depending on context."
27618 (interactive)
27619 (cond
27620 ((org-at-table-p)
27621 (call-interactively 'org-table-insert-hline))
27622 ((org-on-heading-p)
27623 ;; Convert to item
27624 (save-excursion
27625 (beginning-of-line 1)
27626 (if (looking-at "\\*+ ")
27627 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27628 ((org-region-active-p)
27629 ;; Convert all lines in region to list items
27630 (call-interactively 'org-toggle-region-items))
27631 ((org-in-item-p)
27632 (call-interactively 'org-cycle-list-bullet))
27633 (t (org-toggle-region-items (point-at-bol)
27634 (min (1+ (point-at-eol)) (point-max))))))
27636 (defun org-toggle-region-items (beg end)
27637 "Convert all lines in region to list items.
27638 If the first line is already an item, convert all list items in the region
27639 to normal lines."
27640 (interactive "r")
27641 (let (l2 l)
27642 (save-excursion
27643 (goto-char end)
27644 (setq l2 (org-current-line))
27645 (goto-char beg)
27646 (beginning-of-line 1)
27647 (setq l (1- (org-current-line)))
27648 (if (org-at-item-p)
27649 ;; We already have items, de-itemize
27650 (while (< (setq l (1+ l)) l2)
27651 (when (org-at-item-p)
27652 (goto-char (match-beginning 2))
27653 (delete-region (match-beginning 2) (match-end 2))
27654 (and (looking-at "[ \t]+") (replace-match "")))
27655 (beginning-of-line 2))
27656 (while (< (setq l (1+ l)) l2)
27657 (unless (org-at-item-p)
27658 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27659 (replace-match "\\1- \\2")))
27660 (beginning-of-line 2))))))
27662 (defun org-toggle-region-headings (beg end)
27663 "Convert all lines in region to list items.
27664 If the first line is already an item, convert all list items in the region
27665 to normal lines."
27666 (interactive "r")
27667 (let (l2 l)
27668 (save-excursion
27669 (goto-char end)
27670 (setq l2 (org-current-line))
27671 (goto-char beg)
27672 (beginning-of-line 1)
27673 (setq l (1- (org-current-line)))
27674 (if (org-on-heading-p)
27675 ;; We already have headlines, de-star them
27676 (while (< (setq l (1+ l)) l2)
27677 (when (org-on-heading-p t)
27678 (and (looking-at outline-regexp) (replace-match "")))
27679 (beginning-of-line 2))
27680 (let* ((stars (save-excursion
27681 (re-search-backward org-complex-heading-regexp nil t)
27682 (or (match-string 1) "*")))
27683 (add-stars (if org-odd-levels-only "**" "*"))
27684 (rpl (concat stars add-stars " \\2")))
27685 (while (< (setq l (1+ l)) l2)
27686 (unless (org-on-heading-p)
27687 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27688 (replace-match rpl)))
27689 (beginning-of-line 2)))))))
27691 (defun org-meta-return (&optional arg)
27692 "Insert a new heading or wrap a region in a table.
27693 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27694 See the individual commands for more information."
27695 (interactive "P")
27696 (cond
27697 ((org-at-table-p)
27698 (call-interactively 'org-table-wrap-region))
27699 (t (call-interactively 'org-insert-heading))))
27701 ;;; Menu entries
27703 ;; Define the Org-mode menus
27704 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27705 '("Tbl"
27706 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27707 ["Next Field" org-cycle (org-at-table-p)]
27708 ["Previous Field" org-shifttab (org-at-table-p)]
27709 ["Next Row" org-return (org-at-table-p)]
27710 "--"
27711 ["Blank Field" org-table-blank-field (org-at-table-p)]
27712 ["Edit Field" org-table-edit-field (org-at-table-p)]
27713 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27714 "--"
27715 ("Column"
27716 ["Move Column Left" org-metaleft (org-at-table-p)]
27717 ["Move Column Right" org-metaright (org-at-table-p)]
27718 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27719 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27720 ("Row"
27721 ["Move Row Up" org-metaup (org-at-table-p)]
27722 ["Move Row Down" org-metadown (org-at-table-p)]
27723 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27724 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27725 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27726 "--"
27727 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27728 ("Rectangle"
27729 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27730 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27731 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27732 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27733 "--"
27734 ("Calculate"
27735 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27736 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27737 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27738 "--"
27739 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27740 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27741 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27742 "--"
27743 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27744 "--"
27745 ["Sum Column/Rectangle" org-table-sum
27746 (or (org-at-table-p) (org-region-active-p))]
27747 ["Which Column?" org-table-current-column (org-at-table-p)])
27748 ["Debug Formulas"
27749 org-table-toggle-formula-debugger
27750 :style toggle :selected org-table-formula-debug]
27751 ["Show Col/Row Numbers"
27752 org-table-toggle-coordinate-overlays
27753 :style toggle :selected org-table-overlay-coordinates]
27754 "--"
27755 ["Create" org-table-create (and (not (org-at-table-p))
27756 org-enable-table-editor)]
27757 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27758 ["Import from File" org-table-import (not (org-at-table-p))]
27759 ["Export to File" org-table-export (org-at-table-p)]
27760 "--"
27761 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27763 (easy-menu-define org-org-menu org-mode-map "Org menu"
27764 '("Org"
27765 ("Show/Hide"
27766 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27767 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27768 ["Sparse Tree" org-occur t]
27769 ["Reveal Context" org-reveal t]
27770 ["Show All" show-all t]
27771 "--"
27772 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27773 "--"
27774 ["New Heading" org-insert-heading t]
27775 ("Navigate Headings"
27776 ["Up" outline-up-heading t]
27777 ["Next" outline-next-visible-heading t]
27778 ["Previous" outline-previous-visible-heading t]
27779 ["Next Same Level" outline-forward-same-level t]
27780 ["Previous Same Level" outline-backward-same-level t]
27781 "--"
27782 ["Jump" org-goto t])
27783 ("Edit Structure"
27784 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27785 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27786 "--"
27787 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27788 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27789 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27790 "--"
27791 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27792 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27793 ["Demote Heading" org-metaright (not (org-at-table-p))]
27794 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27795 "--"
27796 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27797 "--"
27798 ["Convert to odd levels" org-convert-to-odd-levels t]
27799 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27800 ("Editing"
27801 ["Emphasis..." org-emphasize t])
27802 ("Archive"
27803 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27804 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27805 ; :active t :keys "C-u C-c C-x C-a"]
27806 ["Sparse trees open ARCHIVE trees"
27807 (setq org-sparse-tree-open-archived-trees
27808 (not org-sparse-tree-open-archived-trees))
27809 :style toggle :selected org-sparse-tree-open-archived-trees]
27810 ["Cycling opens ARCHIVE trees"
27811 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27812 :style toggle :selected org-cycle-open-archived-trees]
27813 ["Agenda includes ARCHIVE trees"
27814 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27815 :style toggle :selected (not org-agenda-skip-archived-trees)]
27816 "--"
27817 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27818 ; ["Check and Move Children" (org-archive-subtree '(4))
27819 ; :active t :keys "C-u C-c C-x C-s"]
27821 "--"
27822 ("TODO Lists"
27823 ["TODO/DONE/-" org-todo t]
27824 ("Select keyword"
27825 ["Next keyword" org-shiftright (org-on-heading-p)]
27826 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27827 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27828 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27829 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27830 ["Show TODO Tree" org-show-todo-tree t]
27831 ["Global TODO list" org-todo-list t]
27832 "--"
27833 ["Set Priority" org-priority t]
27834 ["Priority Up" org-shiftup t]
27835 ["Priority Down" org-shiftdown t])
27836 ("TAGS and Properties"
27837 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27838 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27839 "--"
27840 ["Set property" 'org-set-property t]
27841 ["Column view of properties" org-columns t]
27842 ["Insert Column View DBlock" org-insert-columns-dblock t])
27843 ("Dates and Scheduling"
27844 ["Timestamp" org-time-stamp t]
27845 ["Timestamp (inactive)" org-time-stamp-inactive t]
27846 ("Change Date"
27847 ["1 Day Later" org-shiftright t]
27848 ["1 Day Earlier" org-shiftleft t]
27849 ["1 ... Later" org-shiftup t]
27850 ["1 ... Earlier" org-shiftdown t])
27851 ["Compute Time Range" org-evaluate-time-range t]
27852 ["Schedule Item" org-schedule t]
27853 ["Deadline" org-deadline t]
27854 "--"
27855 ["Custom time format" org-toggle-time-stamp-overlays
27856 :style radio :selected org-display-custom-times]
27857 "--"
27858 ["Goto Calendar" org-goto-calendar t]
27859 ["Date from Calendar" org-date-from-calendar t])
27860 ("Logging work"
27861 ["Clock in" org-clock-in t]
27862 ["Clock out" org-clock-out t]
27863 ["Clock cancel" org-clock-cancel t]
27864 ["Goto running clock" org-clock-goto t]
27865 ["Display times" org-clock-display t]
27866 ["Create clock table" org-clock-report t]
27867 "--"
27868 ["Record DONE time"
27869 (progn (setq org-log-done (not org-log-done))
27870 (message "Switching to %s will %s record a timestamp"
27871 (car org-done-keywords)
27872 (if org-log-done "automatically" "not")))
27873 :style toggle :selected org-log-done])
27874 "--"
27875 ["Agenda Command..." org-agenda t]
27876 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27877 ("File List for Agenda")
27878 ("Special views current file"
27879 ["TODO Tree" org-show-todo-tree t]
27880 ["Check Deadlines" org-check-deadlines t]
27881 ["Timeline" org-timeline t]
27882 ["Tags Tree" org-tags-sparse-tree t])
27883 "--"
27884 ("Hyperlinks"
27885 ["Store Link (Global)" org-store-link t]
27886 ["Insert Link" org-insert-link t]
27887 ["Follow Link" org-open-at-point t]
27888 "--"
27889 ["Next link" org-next-link t]
27890 ["Previous link" org-previous-link t]
27891 "--"
27892 ["Descriptive Links"
27893 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27894 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27895 ["Literal Links"
27896 (progn
27897 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27898 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27899 "--"
27900 ["Export/Publish..." org-export t]
27901 ("LaTeX"
27902 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27903 :selected org-cdlatex-mode]
27904 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27905 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27906 ["Modify math symbol" org-cdlatex-math-modify
27907 (org-inside-LaTeX-fragment-p)]
27908 ["Export LaTeX fragments as images"
27909 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27910 :style toggle :selected org-export-with-LaTeX-fragments])
27911 "--"
27912 ("Documentation"
27913 ["Show Version" org-version t]
27914 ["Info Documentation" org-info t])
27915 ("Customize"
27916 ["Browse Org Group" org-customize t]
27917 "--"
27918 ["Expand This Menu" org-create-customize-menu
27919 (fboundp 'customize-menu-create)])
27920 "--"
27921 ["Refresh setup" org-mode-restart t]
27924 (defun org-info (&optional node)
27925 "Read documentation for Org-mode in the info system.
27926 With optional NODE, go directly to that node."
27927 (interactive)
27928 (info (format "(org)%s" (or node ""))))
27930 (defun org-install-agenda-files-menu ()
27931 (let ((bl (buffer-list)))
27932 (save-excursion
27933 (while bl
27934 (set-buffer (pop bl))
27935 (if (org-mode-p) (setq bl nil)))
27936 (when (org-mode-p)
27937 (easy-menu-change
27938 '("Org") "File List for Agenda"
27939 (append
27940 (list
27941 ["Edit File List" (org-edit-agenda-file-list) t]
27942 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27943 ["Remove Current File from List" org-remove-file t]
27944 ["Cycle through agenda files" org-cycle-agenda-files t]
27945 ["Occur in all agenda files" org-occur-in-agenda-files t]
27946 "--")
27947 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27949 ;;;; Documentation
27951 (defun org-customize ()
27952 "Call the customize function with org as argument."
27953 (interactive)
27954 (customize-browse 'org))
27956 (defun org-create-customize-menu ()
27957 "Create a full customization menu for Org-mode, insert it into the menu."
27958 (interactive)
27959 (if (fboundp 'customize-menu-create)
27960 (progn
27961 (easy-menu-change
27962 '("Org") "Customize"
27963 `(["Browse Org group" org-customize t]
27964 "--"
27965 ,(customize-menu-create 'org)
27966 ["Set" Custom-set t]
27967 ["Save" Custom-save t]
27968 ["Reset to Current" Custom-reset-current t]
27969 ["Reset to Saved" Custom-reset-saved t]
27970 ["Reset to Standard Settings" Custom-reset-standard t]))
27971 (message "\"Org\"-menu now contains full customization menu"))
27972 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27974 ;;;; Miscellaneous stuff
27977 ;;; Generally useful functions
27979 (defun org-context ()
27980 "Return a list of contexts of the current cursor position.
27981 If several contexts apply, all are returned.
27982 Each context entry is a list with a symbol naming the context, and
27983 two positions indicating start and end of the context. Possible
27984 contexts are:
27986 :headline anywhere in a headline
27987 :headline-stars on the leading stars in a headline
27988 :todo-keyword on a TODO keyword (including DONE) in a headline
27989 :tags on the TAGS in a headline
27990 :priority on the priority cookie in a headline
27991 :item on the first line of a plain list item
27992 :item-bullet on the bullet/number of a plain list item
27993 :checkbox on the checkbox in a plain list item
27994 :table in an org-mode table
27995 :table-special on a special filed in a table
27996 :table-table in a table.el table
27997 :link on a hyperlink
27998 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27999 :target on a <<target>>
28000 :radio-target on a <<<radio-target>>>
28001 :latex-fragment on a LaTeX fragment
28002 :latex-preview on a LaTeX fragment with overlayed preview image
28004 This function expects the position to be visible because it uses font-lock
28005 faces as a help to recognize the following contexts: :table-special, :link,
28006 and :keyword."
28007 (let* ((f (get-text-property (point) 'face))
28008 (faces (if (listp f) f (list f)))
28009 (p (point)) clist o)
28010 ;; First the large context
28011 (cond
28012 ((org-on-heading-p t)
28013 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28014 (when (progn
28015 (beginning-of-line 1)
28016 (looking-at org-todo-line-tags-regexp))
28017 (push (org-point-in-group p 1 :headline-stars) clist)
28018 (push (org-point-in-group p 2 :todo-keyword) clist)
28019 (push (org-point-in-group p 4 :tags) clist))
28020 (goto-char p)
28021 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28022 (if (looking-at "\\[#[A-Z0-9]\\]")
28023 (push (org-point-in-group p 0 :priority) clist)))
28025 ((org-at-item-p)
28026 (push (org-point-in-group p 2 :item-bullet) clist)
28027 (push (list :item (point-at-bol)
28028 (save-excursion (org-end-of-item) (point)))
28029 clist)
28030 (and (org-at-item-checkbox-p)
28031 (push (org-point-in-group p 0 :checkbox) clist)))
28033 ((org-at-table-p)
28034 (push (list :table (org-table-begin) (org-table-end)) clist)
28035 (if (memq 'org-formula faces)
28036 (push (list :table-special
28037 (previous-single-property-change p 'face)
28038 (next-single-property-change p 'face)) clist)))
28039 ((org-at-table-p 'any)
28040 (push (list :table-table) clist)))
28041 (goto-char p)
28043 ;; Now the small context
28044 (cond
28045 ((org-at-timestamp-p)
28046 (push (org-point-in-group p 0 :timestamp) clist))
28047 ((memq 'org-link faces)
28048 (push (list :link
28049 (previous-single-property-change p 'face)
28050 (next-single-property-change p 'face)) clist))
28051 ((memq 'org-special-keyword faces)
28052 (push (list :keyword
28053 (previous-single-property-change p 'face)
28054 (next-single-property-change p 'face)) clist))
28055 ((org-on-target-p)
28056 (push (org-point-in-group p 0 :target) clist)
28057 (goto-char (1- (match-beginning 0)))
28058 (if (looking-at org-radio-target-regexp)
28059 (push (org-point-in-group p 0 :radio-target) clist))
28060 (goto-char p))
28061 ((setq o (car (delq nil
28062 (mapcar
28063 (lambda (x)
28064 (if (memq x org-latex-fragment-image-overlays) x))
28065 (org-overlays-at (point))))))
28066 (push (list :latex-fragment
28067 (org-overlay-start o) (org-overlay-end o)) clist)
28068 (push (list :latex-preview
28069 (org-overlay-start o) (org-overlay-end o)) clist))
28070 ((org-inside-LaTeX-fragment-p)
28071 ;; FIXME: positions wrong.
28072 (push (list :latex-fragment (point) (point)) clist)))
28074 (setq clist (nreverse (delq nil clist)))
28075 clist))
28077 ;; FIXME: Compare with at-regexp-p Do we need both?
28078 (defun org-in-regexp (re &optional nlines visually)
28079 "Check if point is inside a match of regexp.
28080 Normally only the current line is checked, but you can include NLINES extra
28081 lines both before and after point into the search.
28082 If VISUALLY is set, require that the cursor is not after the match but
28083 really on, so that the block visually is on the match."
28084 (catch 'exit
28085 (let ((pos (point))
28086 (eol (point-at-eol (+ 1 (or nlines 0))))
28087 (inc (if visually 1 0)))
28088 (save-excursion
28089 (beginning-of-line (- 1 (or nlines 0)))
28090 (while (re-search-forward re eol t)
28091 (if (and (<= (match-beginning 0) pos)
28092 (>= (+ inc (match-end 0)) pos))
28093 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28095 (defun org-at-regexp-p (regexp)
28096 "Is point inside a match of REGEXP in the current line?"
28097 (catch 'exit
28098 (save-excursion
28099 (let ((pos (point)) (end (point-at-eol)))
28100 (beginning-of-line 1)
28101 (while (re-search-forward regexp end t)
28102 (if (and (<= (match-beginning 0) pos)
28103 (>= (match-end 0) pos))
28104 (throw 'exit t)))
28105 nil))))
28107 (defun org-occur-in-agenda-files (regexp &optional nlines)
28108 "Call `multi-occur' with buffers for all agenda files."
28109 (interactive "sOrg-files matching: \np")
28110 (let* ((files (org-agenda-files))
28111 (tnames (mapcar 'file-truename files))
28112 (extra org-agenda-text-search-extra-files)
28114 (while (setq f (pop extra))
28115 (unless (member (file-truename f) tnames)
28116 (add-to-list 'files f 'append)
28117 (add-to-list 'tnames (file-truename f) 'append)))
28118 (multi-occur
28119 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28120 regexp)))
28122 (if (boundp 'occur-mode-find-occurrence-hook)
28123 ;; Emacs 23
28124 (add-hook 'occur-mode-find-occurrence-hook
28125 (lambda ()
28126 (when (org-mode-p)
28127 (org-reveal))))
28128 ;; Emacs 22
28129 (defadvice occur-mode-goto-occurrence
28130 (after org-occur-reveal activate)
28131 (and (org-mode-p) (org-reveal)))
28132 (defadvice occur-mode-goto-occurrence-other-window
28133 (after org-occur-reveal activate)
28134 (and (org-mode-p) (org-reveal)))
28135 (defadvice occur-mode-display-occurrence
28136 (after org-occur-reveal activate)
28137 (when (org-mode-p)
28138 (let ((pos (occur-mode-find-occurrence)))
28139 (with-current-buffer (marker-buffer pos)
28140 (save-excursion
28141 (goto-char pos)
28142 (org-reveal)))))))
28144 (defun org-uniquify (list)
28145 "Remove duplicate elements from LIST."
28146 (let (res)
28147 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28148 res))
28150 (defun org-delete-all (elts list)
28151 "Remove all elements in ELTS from LIST."
28152 (while elts
28153 (setq list (delete (pop elts) list)))
28154 list)
28156 (defun org-back-over-empty-lines ()
28157 "Move backwards over witespace, to the beginning of the first empty line.
28158 Returns the number of empty lines passed."
28159 (let ((pos (point)))
28160 (skip-chars-backward " \t\n\r")
28161 (beginning-of-line 2)
28162 (goto-char (min (point) pos))
28163 (count-lines (point) pos)))
28165 (defun org-skip-whitespace ()
28166 (skip-chars-forward " \t\n\r"))
28168 (defun org-point-in-group (point group &optional context)
28169 "Check if POINT is in match-group GROUP.
28170 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28171 match. If the match group does ot exist or point is not inside it,
28172 return nil."
28173 (and (match-beginning group)
28174 (>= point (match-beginning group))
28175 (<= point (match-end group))
28176 (if context
28177 (list context (match-beginning group) (match-end group))
28178 t)))
28180 (defun org-switch-to-buffer-other-window (&rest args)
28181 "Switch to buffer in a second window on the current frame.
28182 In particular, do not allow pop-up frames."
28183 (let (pop-up-frames special-display-buffer-names special-display-regexps
28184 special-display-function)
28185 (apply 'switch-to-buffer-other-window args)))
28187 (defun org-combine-plists (&rest plists)
28188 "Create a single property list from all plists in PLISTS.
28189 The process starts by copying the first list, and then setting properties
28190 from the other lists. Settings in the last list are the most significant
28191 ones and overrule settings in the other lists."
28192 (let ((rtn (copy-sequence (pop plists)))
28193 p v ls)
28194 (while plists
28195 (setq ls (pop plists))
28196 (while ls
28197 (setq p (pop ls) v (pop ls))
28198 (setq rtn (plist-put rtn p v))))
28199 rtn))
28201 (defun org-move-line-down (arg)
28202 "Move the current line down. With prefix argument, move it past ARG lines."
28203 (interactive "p")
28204 (let ((col (current-column))
28205 beg end pos)
28206 (beginning-of-line 1) (setq beg (point))
28207 (beginning-of-line 2) (setq end (point))
28208 (beginning-of-line (+ 1 arg))
28209 (setq pos (move-marker (make-marker) (point)))
28210 (insert (delete-and-extract-region beg end))
28211 (goto-char pos)
28212 (move-to-column col)))
28214 (defun org-move-line-up (arg)
28215 "Move the current line up. With prefix argument, move it past ARG lines."
28216 (interactive "p")
28217 (let ((col (current-column))
28218 beg end pos)
28219 (beginning-of-line 1) (setq beg (point))
28220 (beginning-of-line 2) (setq end (point))
28221 (beginning-of-line (- arg))
28222 (setq pos (move-marker (make-marker) (point)))
28223 (insert (delete-and-extract-region beg end))
28224 (goto-char pos)
28225 (move-to-column col)))
28227 (defun org-replace-escapes (string table)
28228 "Replace %-escapes in STRING with values in TABLE.
28229 TABLE is an association list with keys like \"%a\" and string values.
28230 The sequences in STRING may contain normal field width and padding information,
28231 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28232 so values can contain further %-escapes if they are define later in TABLE."
28233 (let ((case-fold-search nil)
28234 e re rpl)
28235 (while (setq e (pop table))
28236 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28237 (while (string-match re string)
28238 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28239 (cdr e)))
28240 (setq string (replace-match rpl t t string))))
28241 string))
28244 (defun org-sublist (list start end)
28245 "Return a section of LIST, from START to END.
28246 Counting starts at 1."
28247 (let (rtn (c start))
28248 (setq list (nthcdr (1- start) list))
28249 (while (and list (<= c end))
28250 (push (pop list) rtn)
28251 (setq c (1+ c)))
28252 (nreverse rtn)))
28254 (defun org-find-base-buffer-visiting (file)
28255 "Like `find-buffer-visiting' but alway return the base buffer and
28256 not an indirect buffer."
28257 (let ((buf (find-buffer-visiting file)))
28258 (if buf
28259 (or (buffer-base-buffer buf) buf)
28260 nil)))
28262 (defun org-image-file-name-regexp ()
28263 "Return regexp matching the file names of images."
28264 (if (fboundp 'image-file-name-regexp)
28265 (image-file-name-regexp)
28266 (let ((image-file-name-extensions
28267 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28268 "xbm" "xpm" "pbm" "pgm" "ppm")))
28269 (concat "\\."
28270 (regexp-opt (nconc (mapcar 'upcase
28271 image-file-name-extensions)
28272 image-file-name-extensions)
28274 "\\'"))))
28276 (defun org-file-image-p (file)
28277 "Return non-nil if FILE is an image."
28278 (save-match-data
28279 (string-match (org-image-file-name-regexp) file)))
28281 ;;; Paragraph filling stuff.
28282 ;; We want this to be just right, so use the full arsenal.
28284 (defun org-indent-line-function ()
28285 "Indent line like previous, but further if previous was headline or item."
28286 (interactive)
28287 (let* ((pos (point))
28288 (itemp (org-at-item-p))
28289 column bpos bcol tpos tcol bullet btype bullet-type)
28290 ;; Find the previous relevant line
28291 (beginning-of-line 1)
28292 (cond
28293 ((looking-at "#") (setq column 0))
28294 ((looking-at "\\*+ ") (setq column 0))
28296 (beginning-of-line 0)
28297 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28298 (beginning-of-line 0))
28299 (cond
28300 ((looking-at "\\*+[ \t]+")
28301 (goto-char (match-end 0))
28302 (setq column (current-column)))
28303 ((org-in-item-p)
28304 (org-beginning-of-item)
28305 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28306 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28307 (setq bpos (match-beginning 1) tpos (match-end 0)
28308 bcol (progn (goto-char bpos) (current-column))
28309 tcol (progn (goto-char tpos) (current-column))
28310 bullet (match-string 1)
28311 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28312 (if (not itemp)
28313 (setq column tcol)
28314 (goto-char pos)
28315 (beginning-of-line 1)
28316 (if (looking-at "\\S-")
28317 (progn
28318 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28319 (setq bullet (match-string 1)
28320 btype (if (string-match "[0-9]" bullet) "n" bullet))
28321 (setq column (if (equal btype bullet-type) bcol tcol)))
28322 (setq column (org-get-indentation)))))
28323 (t (setq column (org-get-indentation))))))
28324 (goto-char pos)
28325 (if (<= (current-column) (current-indentation))
28326 (indent-line-to column)
28327 (save-excursion (indent-line-to column)))
28328 (setq column (current-column))
28329 (beginning-of-line 1)
28330 (if (looking-at
28331 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28332 (replace-match (concat "\\1" (format org-property-format
28333 (match-string 2) (match-string 3)))
28334 t nil))
28335 (move-to-column column)))
28337 (defun org-set-autofill-regexps ()
28338 (interactive)
28339 ;; In the paragraph separator we include headlines, because filling
28340 ;; text in a line directly attached to a headline would otherwise
28341 ;; fill the headline as well.
28342 (org-set-local 'comment-start-skip "^#+[ \t]*")
28343 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28344 ;; The paragraph starter includes hand-formatted lists.
28345 (org-set-local 'paragraph-start
28346 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28347 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28348 ;; But only if the user has not turned off tables or fixed-width regions
28349 (org-set-local
28350 'auto-fill-inhibit-regexp
28351 (concat "\\*+ \\|#\\+"
28352 "\\|[ \t]*" org-keyword-time-regexp
28353 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28354 (concat
28355 "\\|[ \t]*["
28356 (if org-enable-table-editor "|" "")
28357 (if org-enable-fixed-width-editor ":" "")
28358 "]"))))
28359 ;; We use our own fill-paragraph function, to make sure that tables
28360 ;; and fixed-width regions are not wrapped. That function will pass
28361 ;; through to `fill-paragraph' when appropriate.
28362 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28363 ; Adaptive filling: To get full control, first make sure that
28364 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28365 (org-set-local 'adaptive-fill-regexp "\000")
28366 (org-set-local 'adaptive-fill-function
28367 'org-adaptive-fill-function)
28368 (org-set-local
28369 'align-mode-rules-list
28370 '((org-in-buffer-settings
28371 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28372 (modes . '(org-mode))))))
28374 (defun org-fill-paragraph (&optional justify)
28375 "Re-align a table, pass through to fill-paragraph if no table."
28376 (let ((table-p (org-at-table-p))
28377 (table.el-p (org-at-table.el-p)))
28378 (cond ((and (equal (char-after (point-at-bol)) ?*)
28379 (save-excursion (goto-char (point-at-bol))
28380 (looking-at outline-regexp)))
28381 t) ; skip headlines
28382 (table.el-p t) ; skip table.el tables
28383 (table-p (org-table-align) t) ; align org-mode tables
28384 (t nil)))) ; call paragraph-fill
28386 ;; For reference, this is the default value of adaptive-fill-regexp
28387 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28389 (defun org-adaptive-fill-function ()
28390 "Return a fill prefix for org-mode files.
28391 In particular, this makes sure hanging paragraphs for hand-formatted lists
28392 work correctly."
28393 (cond ((looking-at "#[ \t]+")
28394 (match-string 0))
28395 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28396 (save-excursion
28397 (goto-char (match-end 0))
28398 (make-string (current-column) ?\ )))
28399 (t nil)))
28401 ;;;; Functions extending outline functionality
28403 (defun org-beginning-of-line (&optional arg)
28404 "Go to the beginning of the current line. If that is invisible, continue
28405 to a visible line beginning. This makes the function of C-a more intuitive.
28406 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28407 first attempt, and only move to after the tags when the cursor is already
28408 beyond the end of the headline."
28409 (interactive "P")
28410 (let ((pos (point)))
28411 (beginning-of-line 1)
28412 (if (bobp)
28414 (backward-char 1)
28415 (if (org-invisible-p)
28416 (while (and (not (bobp)) (org-invisible-p))
28417 (backward-char 1)
28418 (beginning-of-line 1))
28419 (forward-char 1)))
28420 (when org-special-ctrl-a/e
28421 (cond
28422 ((and (looking-at org-todo-line-regexp)
28423 (= (char-after (match-end 1)) ?\ ))
28424 (goto-char
28425 (if (eq org-special-ctrl-a/e t)
28426 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28427 ((= pos (point)) (match-beginning 3))
28428 (t (point)))
28429 (cond ((> pos (point)) (point))
28430 ((not (eq last-command this-command)) (point))
28431 (t (match-beginning 3))))))
28432 ((org-at-item-p)
28433 (goto-char
28434 (if (eq org-special-ctrl-a/e t)
28435 (cond ((> pos (match-end 4)) (match-end 4))
28436 ((= pos (point)) (match-end 4))
28437 (t (point)))
28438 (cond ((> pos (point)) (point))
28439 ((not (eq last-command this-command)) (point))
28440 (t (match-end 4))))))))))
28442 (defun org-end-of-line (&optional arg)
28443 "Go to the end of the line.
28444 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28445 first attempt, and only move to after the tags when the cursor is already
28446 beyond the end of the headline."
28447 (interactive "P")
28448 (if (or (not org-special-ctrl-a/e)
28449 (not (org-on-heading-p)))
28450 (end-of-line arg)
28451 (let ((pos (point)))
28452 (beginning-of-line 1)
28453 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28454 (if (eq org-special-ctrl-a/e t)
28455 (if (or (< pos (match-beginning 1))
28456 (= pos (match-end 0)))
28457 (goto-char (match-beginning 1))
28458 (goto-char (match-end 0)))
28459 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28460 (goto-char (match-end 0))
28461 (goto-char (match-beginning 1))))
28462 (end-of-line arg)))))
28464 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28465 (define-key org-mode-map "\C-e" 'org-end-of-line)
28467 (defun org-kill-line (&optional arg)
28468 "Kill line, to tags or end of line."
28469 (interactive "P")
28470 (cond
28471 ((or (not org-special-ctrl-k)
28472 (bolp)
28473 (not (org-on-heading-p)))
28474 (call-interactively 'kill-line))
28475 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28476 (kill-region (point) (match-beginning 1))
28477 (org-set-tags nil t))
28478 (t (kill-region (point) (point-at-eol)))))
28480 (define-key org-mode-map "\C-k" 'org-kill-line)
28482 (defun org-invisible-p ()
28483 "Check if point is at a character currently not visible."
28484 ;; Early versions of noutline don't have `outline-invisible-p'.
28485 (if (fboundp 'outline-invisible-p)
28486 (outline-invisible-p)
28487 (get-char-property (point) 'invisible)))
28489 (defun org-invisible-p2 ()
28490 "Check if point is at a character currently not visible."
28491 (save-excursion
28492 (if (and (eolp) (not (bobp))) (backward-char 1))
28493 ;; Early versions of noutline don't have `outline-invisible-p'.
28494 (if (fboundp 'outline-invisible-p)
28495 (outline-invisible-p)
28496 (get-char-property (point) 'invisible))))
28498 (defalias 'org-back-to-heading 'outline-back-to-heading)
28499 (defalias 'org-on-heading-p 'outline-on-heading-p)
28500 (defalias 'org-at-heading-p 'outline-on-heading-p)
28501 (defun org-at-heading-or-item-p ()
28502 (or (org-on-heading-p) (org-at-item-p)))
28504 (defun org-on-target-p ()
28505 (or (org-in-regexp org-radio-target-regexp)
28506 (org-in-regexp org-target-regexp)))
28508 (defun org-up-heading-all (arg)
28509 "Move to the heading line of which the present line is a subheading.
28510 This function considers both visible and invisible heading lines.
28511 With argument, move up ARG levels."
28512 (if (fboundp 'outline-up-heading-all)
28513 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28514 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28516 (defun org-up-heading-safe ()
28517 "Move to the heading line of which the present line is a subheading.
28518 This version will not throw an error. It will return the level of the
28519 headline found, or nil if no higher level is found."
28520 (let ((pos (point)) start-level level
28521 (re (concat "^" outline-regexp)))
28522 (catch 'exit
28523 (outline-back-to-heading t)
28524 (setq start-level (funcall outline-level))
28525 (if (equal start-level 1) (throw 'exit nil))
28526 (while (re-search-backward re nil t)
28527 (setq level (funcall outline-level))
28528 (if (< level start-level) (throw 'exit level)))
28529 nil)))
28531 (defun org-first-sibling-p ()
28532 "Is this heading the first child of its parents?"
28533 (interactive)
28534 (let ((re (concat "^" outline-regexp))
28535 level l)
28536 (unless (org-at-heading-p t)
28537 (error "Not at a heading"))
28538 (setq level (funcall outline-level))
28539 (save-excursion
28540 (if (not (re-search-backward re nil t))
28542 (setq l (funcall outline-level))
28543 (< l level)))))
28545 (defun org-goto-sibling (&optional previous)
28546 "Goto the next sibling, even if it is invisible.
28547 When PREVIOUS is set, go to the previous sibling instead. Returns t
28548 when a sibling was found. When none is found, return nil and don't
28549 move point."
28550 (let ((fun (if previous 're-search-backward 're-search-forward))
28551 (pos (point))
28552 (re (concat "^" outline-regexp))
28553 level l)
28554 (when (condition-case nil (org-back-to-heading t) (error nil))
28555 (setq level (funcall outline-level))
28556 (catch 'exit
28557 (or previous (forward-char 1))
28558 (while (funcall fun re nil t)
28559 (setq l (funcall outline-level))
28560 (when (< l level) (goto-char pos) (throw 'exit nil))
28561 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28562 (goto-char pos)
28563 nil))))
28565 (defun org-show-siblings ()
28566 "Show all siblings of the current headline."
28567 (save-excursion
28568 (while (org-goto-sibling) (org-flag-heading nil)))
28569 (save-excursion
28570 (while (org-goto-sibling 'previous)
28571 (org-flag-heading nil))))
28573 (defun org-show-hidden-entry ()
28574 "Show an entry where even the heading is hidden."
28575 (save-excursion
28576 (org-show-entry)))
28578 (defun org-flag-heading (flag &optional entry)
28579 "Flag the current heading. FLAG non-nil means make invisible.
28580 When ENTRY is non-nil, show the entire entry."
28581 (save-excursion
28582 (org-back-to-heading t)
28583 ;; Check if we should show the entire entry
28584 (if entry
28585 (progn
28586 (org-show-entry)
28587 (save-excursion
28588 (and (outline-next-heading)
28589 (org-flag-heading nil))))
28590 (outline-flag-region (max (point-min) (1- (point)))
28591 (save-excursion (outline-end-of-heading) (point))
28592 flag))))
28594 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28595 ;; This is an exact copy of the original function, but it uses
28596 ;; `org-back-to-heading', to make it work also in invisible
28597 ;; trees. And is uses an invisible-OK argument.
28598 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28599 (org-back-to-heading invisible-OK)
28600 (let ((first t)
28601 (level (funcall outline-level)))
28602 (while (and (not (eobp))
28603 (or first (> (funcall outline-level) level)))
28604 (setq first nil)
28605 (outline-next-heading))
28606 (unless to-heading
28607 (if (memq (preceding-char) '(?\n ?\^M))
28608 (progn
28609 ;; Go to end of line before heading
28610 (forward-char -1)
28611 (if (memq (preceding-char) '(?\n ?\^M))
28612 ;; leave blank line before heading
28613 (forward-char -1))))))
28614 (point))
28616 (defun org-show-subtree ()
28617 "Show everything after this heading at deeper levels."
28618 (outline-flag-region
28619 (point)
28620 (save-excursion
28621 (outline-end-of-subtree) (outline-next-heading) (point))
28622 nil))
28624 (defun org-show-entry ()
28625 "Show the body directly following this heading.
28626 Show the heading too, if it is currently invisible."
28627 (interactive)
28628 (save-excursion
28629 (condition-case nil
28630 (progn
28631 (org-back-to-heading t)
28632 (outline-flag-region
28633 (max (point-min) (1- (point)))
28634 (save-excursion
28635 (re-search-forward
28636 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28637 (or (match-beginning 1) (point-max)))
28638 nil))
28639 (error nil))))
28641 (defun org-make-options-regexp (kwds)
28642 "Make a regular expression for keyword lines."
28643 (concat
28645 "#?[ \t]*\\+\\("
28646 (mapconcat 'regexp-quote kwds "\\|")
28647 "\\):[ \t]*"
28648 "\\(.+\\)"))
28650 ;; Make isearch reveal the necessary context
28651 (defun org-isearch-end ()
28652 "Reveal context after isearch exits."
28653 (when isearch-success ; only if search was successful
28654 (if (featurep 'xemacs)
28655 ;; Under XEmacs, the hook is run in the correct place,
28656 ;; we directly show the context.
28657 (org-show-context 'isearch)
28658 ;; In Emacs the hook runs *before* restoring the overlays.
28659 ;; So we have to use a one-time post-command-hook to do this.
28660 ;; (Emacs 22 has a special variable, see function `org-mode')
28661 (unless (and (boundp 'isearch-mode-end-hook-quit)
28662 isearch-mode-end-hook-quit)
28663 ;; Only when the isearch was not quitted.
28664 (org-add-hook 'post-command-hook 'org-isearch-post-command
28665 'append 'local)))))
28667 (defun org-isearch-post-command ()
28668 "Remove self from hook, and show context."
28669 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28670 (org-show-context 'isearch))
28673 ;;;; Integration with and fixes for other packages
28675 ;;; Imenu support
28677 (defvar org-imenu-markers nil
28678 "All markers currently used by Imenu.")
28679 (make-variable-buffer-local 'org-imenu-markers)
28681 (defun org-imenu-new-marker (&optional pos)
28682 "Return a new marker for use by Imenu, and remember the marker."
28683 (let ((m (make-marker)))
28684 (move-marker m (or pos (point)))
28685 (push m org-imenu-markers)
28688 (defun org-imenu-get-tree ()
28689 "Produce the index for Imenu."
28690 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28691 (setq org-imenu-markers nil)
28692 (let* ((n org-imenu-depth)
28693 (re (concat "^" outline-regexp))
28694 (subs (make-vector (1+ n) nil))
28695 (last-level 0)
28696 m tree level head)
28697 (save-excursion
28698 (save-restriction
28699 (widen)
28700 (goto-char (point-max))
28701 (while (re-search-backward re nil t)
28702 (setq level (org-reduced-level (funcall outline-level)))
28703 (when (<= level n)
28704 (looking-at org-complex-heading-regexp)
28705 (setq head (org-match-string-no-properties 4)
28706 m (org-imenu-new-marker))
28707 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28708 (if (>= level last-level)
28709 (push (cons head m) (aref subs level))
28710 (push (cons head (aref subs (1+ level))) (aref subs level))
28711 (loop for i from (1+ level) to n do (aset subs i nil)))
28712 (setq last-level level)))))
28713 (aref subs 1)))
28715 (eval-after-load "imenu"
28716 '(progn
28717 (add-hook 'imenu-after-jump-hook
28718 (lambda () (org-show-context 'org-goto)))))
28720 ;; Speedbar support
28722 (defun org-speedbar-set-agenda-restriction ()
28723 "Restrict future agenda commands to the location at point in speedbar.
28724 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28725 (interactive)
28726 (let (p m tp np dir txt w)
28727 (cond
28728 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28729 'org-imenu t))
28730 (setq m (get-text-property p 'org-imenu-marker))
28731 (save-excursion
28732 (save-restriction
28733 (set-buffer (marker-buffer m))
28734 (goto-char m)
28735 (org-agenda-set-restriction-lock 'subtree))))
28736 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28737 'speedbar-function 'speedbar-find-file))
28738 (setq tp (previous-single-property-change
28739 (1+ p) 'speedbar-function)
28740 np (next-single-property-change
28741 tp 'speedbar-function)
28742 dir (speedbar-line-directory)
28743 txt (buffer-substring-no-properties (or tp (point-min))
28744 (or np (point-max))))
28745 (save-excursion
28746 (save-restriction
28747 (set-buffer (find-file-noselect
28748 (let ((default-directory dir))
28749 (expand-file-name txt))))
28750 (unless (org-mode-p)
28751 (error "Cannot restrict to non-Org-mode file"))
28752 (org-agenda-set-restriction-lock 'file))))
28753 (t (error "Don't know how to restrict Org-mode's agenda")))
28754 (org-move-overlay org-speedbar-restriction-lock-overlay
28755 (point-at-bol) (point-at-eol))
28756 (setq current-prefix-arg nil)
28757 (org-agenda-maybe-redo)))
28759 (eval-after-load "speedbar"
28760 '(progn
28761 (speedbar-add-supported-extension ".org")
28762 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28763 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28764 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28765 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28766 (add-hook 'speedbar-visiting-tag-hook
28767 (lambda () (org-show-context 'org-goto)))))
28770 ;;; Fixes and Hacks
28772 ;; Make flyspell not check words in links, to not mess up our keymap
28773 (defun org-mode-flyspell-verify ()
28774 "Don't let flyspell put overlays at active buttons."
28775 (not (get-text-property (point) 'keymap)))
28777 ;; Make `bookmark-jump' show the jump location if it was hidden.
28778 (eval-after-load "bookmark"
28779 '(if (boundp 'bookmark-after-jump-hook)
28780 ;; We can use the hook
28781 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28782 ;; Hook not available, use advice
28783 (defadvice bookmark-jump (after org-make-visible activate)
28784 "Make the position visible."
28785 (org-bookmark-jump-unhide))))
28787 (defun org-bookmark-jump-unhide ()
28788 "Unhide the current position, to show the bookmark location."
28789 (and (org-mode-p)
28790 (or (org-invisible-p)
28791 (save-excursion (goto-char (max (point-min) (1- (point))))
28792 (org-invisible-p)))
28793 (org-show-context 'bookmark-jump)))
28795 ;; Make session.el ignore our circular variable
28796 (eval-after-load "session"
28797 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28799 ;;;; Experimental code
28801 (defun org-closed-in-range ()
28802 "Sparse tree of items closed in a certain time range.
28803 Still experimental, may disappear in the future."
28804 (interactive)
28805 ;; Get the time interval from the user.
28806 (let* ((time1 (time-to-seconds
28807 (org-read-date nil 'to-time nil "Starting date: ")))
28808 (time2 (time-to-seconds
28809 (org-read-date nil 'to-time nil "End date:")))
28810 ;; callback function
28811 (callback (lambda ()
28812 (let ((time
28813 (time-to-seconds
28814 (apply 'encode-time
28815 (org-parse-time-string
28816 (match-string 1))))))
28817 ;; check if time in interval
28818 (and (>= time time1) (<= time time2))))))
28819 ;; make tree, check each match with the callback
28820 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28823 ;;;; Finish up
28825 (provide 'org)
28827 (run-hooks 'org-load-hook)
28829 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28830 ;;; org.el ends here