Use `org-scheduled-past-days'.
[org-mode.git] / org.el
blobe9d035fc131c96da2892e55138959ae88846bce5
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-test
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-test"
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. The fourth element is optional and can
1566 specify a destination file for remember items created with this template.
1567 The default file is given by `org-default-notes-file'. An optional fifth
1568 element can specify the headline in that file that should be offered
1569 first when the user is asked to file the entry. The default headline is
1570 given in the variable `org-remember-default-headline'.
1572 An optional sixth element specifies the contexts in which the user can
1573 select the template. This element can be either a list of major modes
1574 or a function. `org-remember' will first check whether the function
1575 returns `t' or if we are in any of the listed major mode, and select
1576 the template accordingly.
1578 The template specifies the structure of the remember buffer. It should have
1579 a first line starting with a star, to act as the org-mode headline.
1580 Furthermore, the following %-escapes will be replaced with content:
1582 %^{prompt} Prompt the user for a string and replace this sequence with it.
1583 A default value and a completion table ca be specified like this:
1584 %^{prompt|default|completion2|completion3|...}
1585 %t time stamp, date only
1586 %T time stamp with date and time
1587 %u, %U like the above, but inactive time stamps
1588 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1589 You may define a prompt like %^{Please specify birthday}t
1590 %n user name (taken from `user-full-name')
1591 %a annotation, normally the link created with org-store-link
1592 %i initial content, the region active. If %i is indented,
1593 the entire inserted text will be indented as well.
1594 %c content of the clipboard, or current kill ring head
1595 %^g prompt for tags, with completion on tags in target file
1596 %^G prompt for tags, with completion all tags in all agenda files
1597 %:keyword specific information for certain link types, see below
1598 %[pathname] insert the contents of the file given by `pathname'
1599 %(sexp) evaluate elisp `(sexp)' and replace with the result
1600 %! Store this note immediately after filling the template
1602 %? After completing the template, position cursor here.
1604 Apart from these general escapes, you can access information specific to the
1605 link type that is created. For example, calling `remember' in emails or gnus
1606 will record the author and the subject of the message, which you can access
1607 with %:author and %:subject, respectively. Here is a complete list of what
1608 is recorded for each link type.
1610 Link type | Available information
1611 -------------------+------------------------------------------------------
1612 bbdb | %:type %:name %:company
1613 vm, wl, mh, rmail | %:type %:subject %:message-id
1614 | %:from %:fromname %:fromaddress
1615 | %:to %:toname %:toaddress
1616 | %:fromto (either \"to NAME\" or \"from NAME\")
1617 gnus | %:group, for messages also all email fields
1618 w3, w3m | %:type %:url
1619 info | %:type %:file %:node
1620 calendar | %:type %:date"
1621 :group 'org-remember
1622 :get (lambda (var) ; Make sure all entries have at least 5 elements
1623 (mapcar (lambda (x)
1624 (if (not (stringp (car x))) (setq x (cons "" x)))
1625 (cond ((= (length x) 4) (append x '("")))
1626 ((= (length x) 3) (append x '("" "")))
1627 (t x)))
1628 (default-value var)))
1629 :type '(repeat
1630 :tag "enabled"
1631 (list :value ("" ?a "\n" nil nil nil)
1632 (string :tag "Name")
1633 (character :tag "Selection Key")
1634 (string :tag "Template")
1635 (choice
1636 (file :tag "Destination file")
1637 (const :tag "Prompt for file" nil))
1638 (choice
1639 (string :tag "Destination headline")
1640 (const :tag "Selection interface for heading"))
1641 (choice
1642 (const :tag "Use by default" nil)
1643 (const :tag "Use in all contexts" t)
1644 (repeat :tag "Use only if in major mode"
1645 (symbol :tag "Major mode"))
1646 (function :tag "Perform a check against function")))))
1648 (defcustom org-reverse-note-order nil
1649 "Non-nil means, store new notes at the beginning of a file or entry.
1650 When nil, new notes will be filed to the end of a file or entry.
1651 This can also be a list with cons cells of regular expressions that
1652 are matched against file names, and values."
1653 :group 'org-remember
1654 :type '(choice
1655 (const :tag "Reverse always" t)
1656 (const :tag "Reverse never" nil)
1657 (repeat :tag "By file name regexp"
1658 (cons regexp boolean))))
1660 (defcustom org-refile-targets nil
1661 "Targets for refiling entries with \\[org-refile].
1662 This is list of cons cells. Each cell contains:
1663 - a specification of the files to be considered, either a list of files,
1664 or a symbol whose function or value fields will be used to retrieve
1665 a file name or a list of file names. Nil means, refile to a different
1666 heading in the current buffer.
1667 - A specification of how to find candidate refile targets. This may be
1668 any of
1669 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1670 This tag has to be present in all target headlines, inheritance will
1671 not be considered.
1672 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1673 todo keyword.
1674 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1675 headlines that are refiling targets.
1676 - a cons cell (:level . N). Any headline of level N is considered a target.
1677 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1678 ;; FIXME: what if there are a var and func with same name???
1679 :group 'org-remember
1680 :type '(repeat
1681 (cons
1682 (choice :value org-agenda-files
1683 (const :tag "All agenda files" org-agenda-files)
1684 (const :tag "Current buffer" nil)
1685 (function) (variable) (file))
1686 (choice :tag "Identify target headline by"
1687 (cons :tag "Specific tag" (const :tag) (string))
1688 (cons :tag "TODO keyword" (const :todo) (string))
1689 (cons :tag "Regular expression" (const :regexp) (regexp))
1690 (cons :tag "Level number" (const :level) (integer))
1691 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1693 (defcustom org-refile-use-outline-path nil
1694 "Non-nil means, provide refile targets as paths.
1695 So a level 3 headline will be available as level1/level2/level3.
1696 When the value is `file', also include the file name (without directory)
1697 into the path. When `full-file-path', include the full file path."
1698 :group 'org-remember
1699 :type '(choice
1700 (const :tag "Not" nil)
1701 (const :tag "Yes" t)
1702 (const :tag "Start with file name" file)
1703 (const :tag "Start with full file path" full-file-path)))
1705 (defgroup org-todo nil
1706 "Options concerning TODO items in Org-mode."
1707 :tag "Org TODO"
1708 :group 'org)
1710 (defgroup org-progress nil
1711 "Options concerning Progress logging in Org-mode."
1712 :tag "Org Progress"
1713 :group 'org-time)
1715 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1716 "List of TODO entry keyword sequences and their interpretation.
1717 \\<org-mode-map>This is a list of sequences.
1719 Each sequence starts with a symbol, either `sequence' or `type',
1720 indicating if the keywords should be interpreted as a sequence of
1721 action steps, or as different types of TODO items. The first
1722 keywords are states requiring action - these states will select a headline
1723 for inclusion into the global TODO list Org-mode produces. If one of
1724 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1725 signify that no further action is necessary. If \"|\" is not found,
1726 the last keyword is treated as the only DONE state of the sequence.
1728 The command \\[org-todo] cycles an entry through these states, and one
1729 additional state where no keyword is present. For details about this
1730 cycling, see the manual.
1732 TODO keywords and interpretation can also be set on a per-file basis with
1733 the special #+SEQ_TODO and #+TYP_TODO lines.
1735 Each keyword can optionally specify a character for fast state selection
1736 \(in combination with the variable `org-use-fast-todo-selection')
1737 and specifiers for state change logging, using the same syntax
1738 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1739 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1740 indicates to record a time stamp each time this state is selected.
1742 Each keyword may also specify if a timestamp or a note should be
1743 recorded when entering or leaving the state, by adding additional
1744 characters in the parenthesis after the keyword. This looks like this:
1745 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1746 record only the time of the state change. With X and Y being either
1747 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1748 Y when leaving the state if and only if the *target* state does not
1749 define X. You may omit any of the fast-selection key or X or /Y,
1750 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1752 For backward compatibility, this variable may also be just a list
1753 of keywords - in this case the interptetation (sequence or type) will be
1754 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1755 :group 'org-todo
1756 :group 'org-keywords
1757 :type '(choice
1758 (repeat :tag "Old syntax, just keywords"
1759 (string :tag "Keyword"))
1760 (repeat :tag "New syntax"
1761 (cons
1762 (choice
1763 :tag "Interpretation"
1764 (const :tag "Sequence (cycling hits every state)" sequence)
1765 (const :tag "Type (cycling directly to DONE)" type))
1766 (repeat
1767 (string :tag "Keyword"))))))
1769 (defvar org-todo-keywords-1 nil
1770 "All TODO and DONE keywords active in a buffer.")
1771 (make-variable-buffer-local 'org-todo-keywords-1)
1772 (defvar org-todo-keywords-for-agenda nil)
1773 (defvar org-done-keywords-for-agenda nil)
1774 (defvar org-not-done-keywords nil)
1775 (make-variable-buffer-local 'org-not-done-keywords)
1776 (defvar org-done-keywords nil)
1777 (make-variable-buffer-local 'org-done-keywords)
1778 (defvar org-todo-heads nil)
1779 (make-variable-buffer-local 'org-todo-heads)
1780 (defvar org-todo-sets nil)
1781 (make-variable-buffer-local 'org-todo-sets)
1782 (defvar org-todo-log-states nil)
1783 (make-variable-buffer-local 'org-todo-log-states)
1784 (defvar org-todo-kwd-alist nil)
1785 (make-variable-buffer-local 'org-todo-kwd-alist)
1786 (defvar org-todo-key-alist nil)
1787 (make-variable-buffer-local 'org-todo-key-alist)
1788 (defvar org-todo-key-trigger nil)
1789 (make-variable-buffer-local 'org-todo-key-trigger)
1791 (defcustom org-todo-interpretation 'sequence
1792 "Controls how TODO keywords are interpreted.
1793 This variable is in principle obsolete and is only used for
1794 backward compatibility, if the interpretation of todo keywords is
1795 not given already in `org-todo-keywords'. See that variable for
1796 more information."
1797 :group 'org-todo
1798 :group 'org-keywords
1799 :type '(choice (const sequence)
1800 (const type)))
1802 (defcustom org-use-fast-todo-selection 'prefix
1803 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1804 This variable describes if and under what circumstances the cycling
1805 mechanism for TODO keywords will be replaced by a single-key, direct
1806 selection scheme.
1808 When nil, fast selection is never used.
1810 When the symbol `prefix', it will be used when `org-todo' is called with
1811 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1812 in an agenda buffer.
1814 When t, fast selection is used by default. In this case, the prefix
1815 argument forces cycling instead.
1817 In all cases, the special interface is only used if access keys have actually
1818 been assigned by the user, i.e. if keywords in the configuration are followed
1819 by a letter in parenthesis, like TODO(t)."
1820 :group 'org-todo
1821 :type '(choice
1822 (const :tag "Never" nil)
1823 (const :tag "By default" t)
1824 (const :tag "Only with C-u C-c C-t" prefix)))
1826 (defcustom org-after-todo-state-change-hook nil
1827 "Hook which is run after the state of a TODO item was changed.
1828 The new state (a string with a TODO keyword, or nil) is available in the
1829 Lisp variable `state'."
1830 :group 'org-todo
1831 :type 'hook)
1833 (defcustom org-log-done nil
1834 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1835 When equal to the list (done), also prompt for a closing note.
1836 This can also be configured on a per-file basis by adding one of
1837 the following lines anywhere in the buffer:
1839 #+STARTUP: logdone
1840 #+STARTUP: lognotedone
1841 #+STARTUP: nologdone"
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "No logging" nil)
1846 (const :tag "Record CLOSED timestamp" time)
1847 (const :tag "Record CLOSED timestamp with closing note." note)))
1849 ;; Normalize old uses of org-log-done.
1850 (cond
1851 ((eq org-log-done t) (setq org-log-done 'time))
1852 ((and (listp org-log-done) (memq 'done org-log-done))
1853 (setq org-log-done 'note)))
1855 ;; FIXME: document
1856 (defcustom org-log-note-clock-out nil
1857 "Non-nil means, recored a note when clocking out of an item.
1858 This can also be configured on a per-file basis by adding one of
1859 the following lines anywhere in the buffer:
1861 #+STARTUP: lognoteclock-out
1862 #+STARTUP: nolognoteclock-out"
1863 :group 'org-todo
1864 :group 'org-progress
1865 :type 'boolean)
1867 (defcustom org-log-done-with-time t
1868 "Non-nil means, the CLOSED time stamp will contain date and time.
1869 When nil, only the date will be recorded."
1870 :group 'org-progress
1871 :type 'boolean)
1873 (defcustom org-log-note-headings
1874 '((done . "CLOSING NOTE %t")
1875 (state . "State %-12s %t")
1876 (clock-out . ""))
1877 "Headings for notes added when clocking out or closing TODO items.
1878 The value is an alist, with the car being a symbol indicating the note
1879 context, and the cdr is the heading to be used. The heading may also be the
1880 empty string.
1881 %t in the heading will be replaced by a time stamp.
1882 %s will be replaced by the new TODO state, in double quotes.
1883 %u will be replaced by the user name.
1884 %U will be replaced by the full user name."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type '(list :greedy t
1888 (cons (const :tag "Heading when closing an item" done) string)
1889 (cons (const :tag
1890 "Heading when changing todo state (todo sequence only)"
1891 state) string)
1892 (cons (const :tag "Heading when clocking out" clock-out) string)))
1894 (defcustom org-log-states-order-reversed t
1895 "Non-nil means, the latest state change note will be directly after heading.
1896 When nil, the notes will be orderer according to time."
1897 :group 'org-todo
1898 :group 'org-progress
1899 :type 'boolean)
1901 (defcustom org-log-repeat 'time
1902 "Non-nil means, record moving through the DONE state when triggering repeat.
1903 An auto-repeating tasks is immediately switched back to TODO when marked
1904 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1905 the TODO keyword definition, or recording a cloing note by setting
1906 `org-log-done', there will be no record of the task moving trhough DONE.
1907 This variable forces taking a note anyway. Possible values are:
1909 nil Don't force a record
1910 time Record a time stamp
1911 note Record a note
1913 This option can also be set with on a per-file-basis with
1915 #+STARTUP: logrepeat
1916 #+STARTUP: lognoterepeat
1917 #+STARTUP: nologrepeat
1919 You can have local logging settings for a subtree by setting the LOGGING
1920 property to one or more of these keywords."
1921 :group 'org-todo
1922 :group 'org-progress
1923 :type '(choice
1924 (const :tag "Don't force a record" nil)
1925 (const :tag "Force recording the DONE state" time)
1926 (const :tag "Force recording a note with the DONE state" note)))
1928 (defcustom org-clock-into-drawer 2
1929 "Should clocking info be wrapped into a drawer?
1930 When t, clocking info will always be inserted into a :CLOCK: drawer.
1931 If necessary, the drawer will be created.
1932 When nil, the drawer will not be created, but used when present.
1933 When an integer and the number of clocking entries in an item
1934 reaches or exceeds this number, a drawer will be created."
1935 :group 'org-todo
1936 :group 'org-progress
1937 :type '(choice
1938 (const :tag "Always" t)
1939 (const :tag "Only when drawer exists" nil)
1940 (integer :tag "When at least N clock entries")))
1942 (defcustom org-clock-out-when-done t
1943 "When t, the clock will be stopped when the relevant entry is marked DONE.
1944 Nil means, clock will keep running until stopped explicitly with
1945 `C-c C-x C-o', or until the clock is started in a different item."
1946 :group 'org-progress
1947 :type 'boolean)
1949 (defcustom org-clock-in-switch-to-state nil
1950 "Set task to a special todo state while clocking it.
1951 The value should be the state to which the entry should be switched."
1952 :group 'org-progress
1953 :group 'org-todo
1954 :type '(choice
1955 (const :tag "Don't force a state" nil)
1956 (string :tag "State")))
1958 (defgroup org-priorities nil
1959 "Priorities in Org-mode."
1960 :tag "Org Priorities"
1961 :group 'org-todo)
1963 (defcustom org-highest-priority ?A
1964 "The highest priority of TODO items. A character like ?A, ?B etc.
1965 Must have a smaller ASCII number than `org-lowest-priority'."
1966 :group 'org-priorities
1967 :type 'character)
1969 (defcustom org-lowest-priority ?C
1970 "The lowest priority of TODO items. A character like ?A, ?B etc.
1971 Must have a larger ASCII number than `org-highest-priority'."
1972 :group 'org-priorities
1973 :type 'character)
1975 (defcustom org-default-priority ?B
1976 "The default priority of TODO items.
1977 This is the priority an item get if no explicit priority is given."
1978 :group 'org-priorities
1979 :type 'character)
1981 (defcustom org-priority-start-cycle-with-default t
1982 "Non-nil means, start with default priority when starting to cycle.
1983 When this is nil, the first step in the cycle will be (depending on the
1984 command used) one higher or lower that the default priority."
1985 :group 'org-priorities
1986 :type 'boolean)
1988 (defgroup org-time nil
1989 "Options concerning time stamps and deadlines in Org-mode."
1990 :tag "Org Time"
1991 :group 'org)
1993 (defcustom org-insert-labeled-timestamps-at-point nil
1994 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1995 When nil, these labeled time stamps are forces into the second line of an
1996 entry, just after the headline. When scheduling from the global TODO list,
1997 the time stamp will always be forced into the second line."
1998 :group 'org-time
1999 :type 'boolean)
2001 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2002 "Formats for `format-time-string' which are used for time stamps.
2003 It is not recommended to change this constant.")
2005 (defcustom org-time-stamp-rounding-minutes '(0 5)
2006 "Number of minutes to round time stamps to.
2007 These are two values, the first applies when first creating a time stamp.
2008 The second applies when changing it with the commands `S-up' and `S-down'.
2009 When changing the time stamp, this means that it will change in steps
2010 of N minues, as given by the second value.
2012 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2013 numbers should be factors of 60, so for example 5, 10, 15.
2015 When this is larger than 1, you can still force an exact time-stamp by using
2016 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2017 and by using a prefix arg to `S-up/down' to specify the exact number
2018 of minutes to shift."
2019 :group 'org-time
2020 :get '(lambda (var) ; Make sure all entries have 5 elements
2021 (if (integerp (default-value var))
2022 (list (default-value var) 5)
2023 (default-value var)))
2024 :type '(list
2025 (integer :tag "when inserting times")
2026 (integer :tag "when modifying times")))
2028 ;; Make sure old customizations of this variable don't lead to problems.
2029 (when (integerp org-time-stamp-rounding-minutes)
2030 (setq org-time-stamp-rounding-minutes
2031 (list org-time-stamp-rounding-minutes
2032 org-time-stamp-rounding-minutes)))
2034 (defcustom org-display-custom-times nil
2035 "Non-nil means, overlay custom formats over all time stamps.
2036 The formats are defined through the variable `org-time-stamp-custom-formats'.
2037 To turn this on on a per-file basis, insert anywhere in the file:
2038 #+STARTUP: customtime"
2039 :group 'org-time
2040 :set 'set-default
2041 :type 'sexp)
2042 (make-variable-buffer-local 'org-display-custom-times)
2044 (defcustom org-time-stamp-custom-formats
2045 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2046 "Custom formats for time stamps. See `format-time-string' for the syntax.
2047 These are overlayed over the default ISO format if the variable
2048 `org-display-custom-times' is set. Time like %H:%M should be at the
2049 end of the second format."
2050 :group 'org-time
2051 :type 'sexp)
2053 (defun org-time-stamp-format (&optional long inactive)
2054 "Get the right format for a time string."
2055 (let ((f (if long (cdr org-time-stamp-formats)
2056 (car org-time-stamp-formats))))
2057 (if inactive
2058 (concat "[" (substring f 1 -1) "]")
2059 f)))
2061 (defcustom org-read-date-prefer-future t
2062 "Non-nil means, assume future for incomplete date input from user.
2063 This affects the following situations:
2064 1. The user gives a day, but no month.
2065 For example, if today is the 15th, and you enter \"3\", Org-mode will
2066 read this as the third of *next* month. However, if you enter \"17\",
2067 it will be considered as *this* month.
2068 2. The user gives a month but not a year.
2069 For example, if it is april and you enter \"feb 2\", this will be read
2070 as feb 2, *next* year. \"May 5\", however, will be this year.
2072 When this option is nil, the current month and year will always be used
2073 as defaults."
2074 :group 'org-time
2075 :type 'boolean)
2077 (defcustom org-read-date-display-live t
2078 "Non-nil means, display current interpretation of date prompt live.
2079 This display will be in an overlay, in the minibuffer."
2080 :group 'org-time
2081 :type 'boolean)
2083 (defcustom org-read-date-popup-calendar t
2084 "Non-nil means, pop up a calendar when prompting for a date.
2085 In the calendar, the date can be selected with mouse-1. However, the
2086 minibuffer will also be active, and you can simply enter the date as well.
2087 When nil, only the minibuffer will be available."
2088 :group 'org-time
2089 :type 'boolean)
2090 (if (fboundp 'defvaralias)
2091 (defvaralias 'org-popup-calendar-for-date-prompt
2092 'org-read-date-popup-calendar))
2094 (defcustom org-extend-today-until 0
2095 "The hour when your day really ends.
2096 This has influence for the following applications:
2097 - When switching the agenda to \"today\". It it is still earlier than
2098 the time given here, the day recognized as TODAY is actually yesterday.
2099 - When a date is read from the user and it is still before the time given
2100 here, the current date and time will be assumed to be yesterday, 23:59.
2102 FIXME:
2103 IMPORTANT: This is still a very experimental feature, it may disappear
2104 again or it may be extended to mean more things."
2105 :group 'org-time
2106 :type 'number)
2108 (defcustom org-edit-timestamp-down-means-later nil
2109 "Non-nil means, S-down will increase the time in a time stamp.
2110 When nil, S-up will increase."
2111 :group 'org-time
2112 :type 'boolean)
2114 (defcustom org-calendar-follow-timestamp-change t
2115 "Non-nil means, make the calendar window follow timestamp changes.
2116 When a timestamp is modified and the calendar window is visible, it will be
2117 moved to the new date."
2118 :group 'org-time
2119 :type 'boolean)
2121 (defcustom org-clock-heading-function nil
2122 "When non-nil, should be a function to create `org-clock-heading'.
2123 This is the string shown in the mode line when a clock is running.
2124 The function is called with point at the beginning of the headline."
2125 :group 'org-time ; FIXME: Should we have a separate group????
2126 :type 'function)
2128 (defgroup org-tags nil
2129 "Options concerning tags in Org-mode."
2130 :tag "Org Tags"
2131 :group 'org)
2133 (defcustom org-tag-alist nil
2134 "List of tags allowed in Org-mode files.
2135 When this list is nil, Org-mode will base TAG input on what is already in the
2136 buffer.
2137 The value of this variable is an alist, the car of each entry must be a
2138 keyword as a string, the cdr may be a character that is used to select
2139 that tag through the fast-tag-selection interface.
2140 See the manual for details."
2141 :group 'org-tags
2142 :type '(repeat
2143 (choice
2144 (cons (string :tag "Tag name")
2145 (character :tag "Access char"))
2146 (const :tag "Start radio group" (:startgroup))
2147 (const :tag "End radio group" (:endgroup)))))
2149 (defcustom org-use-fast-tag-selection 'auto
2150 "Non-nil means, use fast tag selection scheme.
2151 This is a special interface to select and deselect tags with single keys.
2152 When nil, fast selection is never used.
2153 When the symbol `auto', fast selection is used if and only if selection
2154 characters for tags have been configured, either through the variable
2155 `org-tag-alist' or through a #+TAGS line in the buffer.
2156 When t, fast selection is always used and selection keys are assigned
2157 automatically if necessary."
2158 :group 'org-tags
2159 :type '(choice
2160 (const :tag "Always" t)
2161 (const :tag "Never" nil)
2162 (const :tag "When selection characters are configured" 'auto)))
2164 (defcustom org-fast-tag-selection-single-key nil
2165 "Non-nil means, fast tag selection exits after first change.
2166 When nil, you have to press RET to exit it.
2167 During fast tag selection, you can toggle this flag with `C-c'.
2168 This variable can also have the value `expert'. In this case, the window
2169 displaying the tags menu is not even shown, until you press C-c again."
2170 :group 'org-tags
2171 :type '(choice
2172 (const :tag "No" nil)
2173 (const :tag "Yes" t)
2174 (const :tag "Expert" expert)))
2176 (defvar org-fast-tag-selection-include-todo nil
2177 "Non-nil means, fast tags selection interface will also offer TODO states.
2178 This is an undocumented feature, you should not rely on it.")
2180 (defcustom org-tags-column -80
2181 "The column to which tags should be indented in a headline.
2182 If this number is positive, it specifies the column. If it is negative,
2183 it means that the tags should be flushright to that column. For example,
2184 -80 works well for a normal 80 character screen."
2185 :group 'org-tags
2186 :type 'integer)
2188 (defcustom org-auto-align-tags t
2189 "Non-nil means, realign tags after pro/demotion of TODO state change.
2190 These operations change the length of a headline and therefore shift
2191 the tags around. With this options turned on, after each such operation
2192 the tags are again aligned to `org-tags-column'."
2193 :group 'org-tags
2194 :type 'boolean)
2196 (defcustom org-use-tag-inheritance t
2197 "Non-nil means, tags in levels apply also for sublevels.
2198 When nil, only the tags directly given in a specific line apply there.
2199 If you turn off this option, you very likely want to turn on the
2200 companion option `org-tags-match-list-sublevels'."
2201 :group 'org-tags
2202 :type 'boolean)
2204 (defcustom org-tags-match-list-sublevels nil
2205 "Non-nil means list also sublevels of headlines matching tag search.
2206 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2207 the sublevels of a headline matching a tag search often also match
2208 the same search. Listing all of them can create very long lists.
2209 Setting this variable to nil causes subtrees of a match to be skipped.
2210 This option is off by default, because inheritance in on. If you turn
2211 inheritance off, you very likely want to turn this option on.
2213 As a special case, if the tag search is restricted to TODO items, the
2214 value of this variable is ignored and sublevels are always checked, to
2215 make sure all corresponding TODO items find their way into the list."
2216 :group 'org-tags
2217 :type 'boolean)
2219 (defvar org-tags-history nil
2220 "History of minibuffer reads for tags.")
2221 (defvar org-last-tags-completion-table nil
2222 "The last used completion table for tags.")
2223 (defvar org-after-tags-change-hook nil
2224 "Hook that is run after the tags in a line have changed.")
2226 (defgroup org-properties nil
2227 "Options concerning properties in Org-mode."
2228 :tag "Org Properties"
2229 :group 'org)
2231 (defcustom org-property-format "%-10s %s"
2232 "How property key/value pairs should be formatted by `indent-line'.
2233 When `indent-line' hits a property definition, it will format the line
2234 according to this format, mainly to make sure that the values are
2235 lined-up with respect to each other."
2236 :group 'org-properties
2237 :type 'string)
2239 (defcustom org-use-property-inheritance nil
2240 "Non-nil means, properties apply also for sublevels.
2241 This setting is only relevant during property searches, not when querying
2242 an entry with `org-entry-get'. To retrieve a property with inheritance,
2243 you need to call `org-entry-get' with the inheritance flag.
2244 Turning this on can cause significant overhead when doing a search, so
2245 this is turned off by default.
2246 When nil, only the properties directly given in the current entry count.
2247 The value may also be a list of properties that shouldhave inheritance.
2249 However, note that some special properties use inheritance under special
2250 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2251 and the properties ending in \"_ALL\" when they are used as descriptor
2252 for valid values of a property."
2253 :group 'org-properties
2254 :type '(choice
2255 (const :tag "Not" nil)
2256 (const :tag "Always" nil)
2257 (repeat :tag "Specific properties" (string :tag "Property"))))
2259 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2260 "The default column format, if no other format has been defined.
2261 This variable can be set on the per-file basis by inserting a line
2263 #+COLUMNS: %25ITEM ....."
2264 :group 'org-properties
2265 :type 'string)
2267 (defcustom org-global-properties nil
2268 "List of property/value pairs that can be inherited by any entry.
2269 You can set buffer-local values for this by adding lines like
2271 #+PROPERTY: NAME VALUE"
2272 :group 'org-properties
2273 :type '(repeat
2274 (cons (string :tag "Property")
2275 (string :tag "Value"))))
2277 (defvar org-local-properties nil
2278 "List of property/value pairs that can be inherited by any entry.
2279 Valid for the current buffer.
2280 This variable is populated from #+PROPERTY lines.")
2282 (defgroup org-agenda nil
2283 "Options concerning agenda views in Org-mode."
2284 :tag "Org Agenda"
2285 :group 'org)
2287 (defvar org-category nil
2288 "Variable used by org files to set a category for agenda display.
2289 Such files should use a file variable to set it, for example
2291 # -*- mode: org; org-category: \"ELisp\"
2293 or contain a special line
2295 #+CATEGORY: ELisp
2297 If the file does not specify a category, then file's base name
2298 is used instead.")
2299 (make-variable-buffer-local 'org-category)
2301 (defcustom org-agenda-files nil
2302 "The files to be used for agenda display.
2303 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2304 \\[org-remove-file]. You can also use customize to edit the list.
2306 If an entry is a directory, all files in that directory that are matched by
2307 `org-agenda-file-regexp' will be part of the file list.
2309 If the value of the variable is not a list but a single file name, then
2310 the list of agenda files is actually stored and maintained in that file, one
2311 agenda file per line."
2312 :group 'org-agenda
2313 :type '(choice
2314 (repeat :tag "List of files and directories" file)
2315 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2317 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2318 "Regular expression to match files for `org-agenda-files'.
2319 If any element in the list in that variable contains a directory instead
2320 of a normal file, all files in that directory that are matched by this
2321 regular expression will be included."
2322 :group 'org-agenda
2323 :type 'regexp)
2325 (defcustom org-agenda-skip-unavailable-files nil
2326 "t means to just skip non-reachable files in `org-agenda-files'.
2327 Nil means to remove them, after a query, from the list."
2328 :group 'org-agenda
2329 :type 'boolean)
2331 (defcustom org-agenda-text-search-extra-files nil
2332 "List of extra files to be searched by text search commands.
2333 These files will be search in addition to the agenda files bu the
2334 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2335 Note that these files will only be searched for text search commands,
2336 not for the other agenda views like todo lists, tag earches or the weekly
2337 agenda. This variable is intended to list notes and possibly archive files
2338 that should also be searched by these two commands."
2339 :group 'org-agenda
2340 :type '(repeat file))
2342 (if (fboundp 'defvaralias)
2343 (defvaralias 'org-agenda-multi-occur-extra-files
2344 'org-agenda-text-search-extra-files))
2346 (defcustom org-agenda-confirm-kill 1
2347 "When set, remote killing from the agenda buffer needs confirmation.
2348 When t, a confirmation is always needed. When a number N, confirmation is
2349 only needed when the text to be killed contains more than N non-white lines."
2350 :group 'org-agenda
2351 :type '(choice
2352 (const :tag "Never" nil)
2353 (const :tag "Always" t)
2354 (number :tag "When more than N lines")))
2356 (defcustom org-calendar-to-agenda-key [?c]
2357 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2358 The command `org-calendar-goto-agenda' will be bound to this key. The
2359 default is the character `c' because then `c' can be used to switch back and
2360 forth between agenda and calendar."
2361 :group 'org-agenda
2362 :type 'sexp)
2364 (defcustom org-agenda-compact-blocks nil
2365 "Non-nil means, make the block agenda more compact.
2366 This is done by leaving out unnecessary lines."
2367 :group 'org-agenda
2368 :type nil)
2370 (defgroup org-agenda-export nil
2371 "Options concerning exporting agenda views in Org-mode."
2372 :tag "Org Agenda Export"
2373 :group 'org-agenda)
2375 (defcustom org-agenda-with-colors t
2376 "Non-nil means, use colors in agenda views."
2377 :group 'org-agenda-export
2378 :type 'boolean)
2380 (defcustom org-agenda-exporter-settings nil
2381 "Alist of variable/value pairs that should be active during agenda export.
2382 This is a good place to set uptions for ps-print and for htmlize."
2383 :group 'org-agenda-export
2384 :type '(repeat
2385 (list
2386 (variable)
2387 (sexp :tag "Value"))))
2389 (defcustom org-agenda-export-html-style ""
2390 "The style specification for exported HTML Agenda files.
2391 If this variable contains a string, it will replace the default <style>
2392 section as produced by `htmlize'.
2393 Since there are different ways of setting style information, this variable
2394 needs to contain the full HTML structure to provide a style, including the
2395 surrounding HTML tags. The style specifications should include definitions
2396 the fonts used by the agenda, here is an example:
2398 <style type=\"text/css\">
2399 p { font-weight: normal; color: gray; }
2400 .org-agenda-structure {
2401 font-size: 110%;
2402 color: #003399;
2403 font-weight: 600;
2405 .org-todo {
2406 color: #cc6666;
2407 font-weight: bold;
2409 .org-done {
2410 color: #339933;
2412 .title { text-align: center; }
2413 .todo, .deadline { color: red; }
2414 .done { color: green; }
2415 </style>
2417 or, if you want to keep the style in a file,
2419 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2421 As the value of this option simply gets inserted into the HTML <head> header,
2422 you can \"misuse\" it to also add other text to the header. However,
2423 <style>...</style> is required, if not present the variable will be ignored."
2424 :group 'org-agenda-export
2425 :group 'org-export-html
2426 :type 'string)
2428 (defgroup org-agenda-custom-commands nil
2429 "Options concerning agenda views in Org-mode."
2430 :tag "Org Agenda Custom Commands"
2431 :group 'org-agenda)
2433 (defconst org-sorting-choice
2434 '(choice
2435 (const time-up) (const time-down)
2436 (const category-keep) (const category-up) (const category-down)
2437 (const tag-down) (const tag-up)
2438 (const priority-up) (const priority-down))
2439 "Sorting choices.")
2441 (defconst org-agenda-custom-commands-local-options
2442 `(repeat :tag "Local settings for this command. Remember to quote values"
2443 (choice :tag "Setting"
2444 (list :tag "Any variable"
2445 (variable :tag "Variable")
2446 (sexp :tag "Value"))
2447 (list :tag "Files to be searched"
2448 (const org-agenda-files)
2449 (list
2450 (const :format "" quote)
2451 (repeat
2452 (file))))
2453 (list :tag "Sorting strategy"
2454 (const org-agenda-sorting-strategy)
2455 (list
2456 (const :format "" quote)
2457 (repeat
2458 ,org-sorting-choice)))
2459 (list :tag "Prefix format"
2460 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2461 (string))
2462 (list :tag "Number of days in agenda"
2463 (const org-agenda-ndays)
2464 (integer :value 1))
2465 (list :tag "Fixed starting date"
2466 (const org-agenda-start-day)
2467 (string :value "2007-11-01"))
2468 (list :tag "Start on day of week"
2469 (const org-agenda-start-on-weekday)
2470 (choice :value 1
2471 (const :tag "Today" nil)
2472 (number :tag "Weekday No.")))
2473 (list :tag "Include data from diary"
2474 (const org-agenda-include-diary)
2475 (boolean))
2476 (list :tag "Deadline Warning days"
2477 (const org-deadline-warning-days)
2478 (integer :value 1))
2479 (list :tag "Standard skipping condition"
2480 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2481 (const org-agenda-skip-function)
2482 (list
2483 (const :format "" quote)
2484 (list
2485 (choice
2486 :tag "Skiping range"
2487 (const :tag "Skip entry" org-agenda-skip-entry-if)
2488 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2489 (repeat :inline t :tag "Conditions for skipping"
2490 (choice
2491 :tag "Condition type"
2492 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2493 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2494 (const :tag "scheduled" 'scheduled)
2495 (const :tag "not scheduled" 'notscheduled)
2496 (const :tag "deadline" 'deadline)
2497 (const :tag "no deadline" 'notdeadline))))))
2498 (list :tag "Non-standard skipping condition"
2499 :value (org-agenda-skip-function)
2500 (list
2501 (const org-agenda-skip-function)
2502 (sexp :tag "Function or form (quoted!)")))))
2503 "Selection of examples for agenda command settings.
2504 This will be spliced into the custom type of
2505 `org-agenda-custom-commands'.")
2508 (defcustom org-agenda-custom-commands nil
2509 "Custom commands for the agenda.
2510 These commands will be offered on the splash screen displayed by the
2511 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2513 (key desc type match settings files)
2515 key The key (one or more characters as a string) to be associated
2516 with the command.
2517 desc A description of the command, when omitted or nil, a default
2518 description is built using MATCH.
2519 type The command type, any of the following symbols:
2520 agenda The daily/weekly agenda.
2521 todo Entries with a specific TODO keyword, in all agenda files.
2522 search Entries containing search words entry or headline.
2523 tags Tags/Property/TODO match in all agenda files.
2524 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2525 todo-tree Sparse tree of specific TODO keyword in *current* file.
2526 tags-tree Sparse tree with all tags matches in *current* file.
2527 occur-tree Occur sparse tree for *current* file.
2528 ... A user-defined function.
2529 match What to search for:
2530 - a single keyword for TODO keyword searches
2531 - a tags match expression for tags searches
2532 - a word search expression for text searches.
2533 - a regular expression for occur searches
2534 For all other commands, this should be the empty string.
2535 settings A list of option settings, similar to that in a let form, so like
2536 this: ((opt1 val1) (opt2 val2) ...). The values will be
2537 evaluated at the moment of execution, so quote them when needed.
2538 files A list of files file to write the produced agenda buffer to
2539 with the command `org-store-agenda-views'.
2540 If a file name ends in \".html\", an HTML version of the buffer
2541 is written out. If it ends in \".ps\", a postscript version is
2542 produced. Otherwide, only the plain text is written to the file.
2544 You can also define a set of commands, to create a composite agenda buffer.
2545 In this case, an entry looks like this:
2547 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2549 where
2551 desc A description string to be displayed in the dispatcher menu.
2552 cmd An agenda command, similar to the above. However, tree commands
2553 are no allowed, but instead you can get agenda and global todo list.
2554 So valid commands for a set are:
2555 (agenda \"\" settings)
2556 (alltodo \"\" settings)
2557 (stuck \"\" settings)
2558 (todo \"match\" settings files)
2559 (search \"match\" settings files)
2560 (tags \"match\" settings files)
2561 (tags-todo \"match\" settings files)
2563 Each command can carry a list of options, and another set of options can be
2564 given for the whole set of commands. Individual command options take
2565 precedence over the general options.
2567 When using several characters as key to a command, the first characters
2568 are prefix commands. For the dispatcher to display useful information, you
2569 should provide a description for the prefix, like
2571 (setq org-agenda-custom-commands
2572 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2573 (\"hl\" tags \"+HOME+Lisa\")
2574 (\"hp\" tags \"+HOME+Peter\")
2575 (\"hk\" tags \"+HOME+Kim\")))"
2576 :group 'org-agenda-custom-commands
2577 :type `(repeat
2578 (choice :value ("x" "Describe command here" tags "" nil)
2579 (list :tag "Single command"
2580 (string :tag "Access Key(s) ")
2581 (option (string :tag "Description"))
2582 (choice
2583 (const :tag "Agenda" agenda)
2584 (const :tag "TODO list" alltodo)
2585 (const :tag "Search words" search)
2586 (const :tag "Stuck projects" stuck)
2587 (const :tag "Tags search (all agenda files)" tags)
2588 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2589 (const :tag "TODO keyword search (all agenda files)" todo)
2590 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2591 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2592 (const :tag "Occur tree (current buffer)" occur-tree)
2593 (sexp :tag "Other, user-defined function"))
2594 (string :tag "Match (only for some commands)")
2595 ,org-agenda-custom-commands-local-options
2596 (option (repeat :tag "Export" (file :tag "Export to"))))
2597 (list :tag "Command series, all agenda files"
2598 (string :tag "Access Key(s)")
2599 (string :tag "Description ")
2600 (repeat :tag "Component"
2601 (choice
2602 (list :tag "Agenda"
2603 (const :format "" agenda)
2604 (const :tag "" :format "" "")
2605 ,org-agenda-custom-commands-local-options)
2606 (list :tag "TODO list (all keywords)"
2607 (const :format "" alltodo)
2608 (const :tag "" :format "" "")
2609 ,org-agenda-custom-commands-local-options)
2610 (list :tag "Search words"
2611 (const :format "" search)
2612 (string :tag "Match")
2613 ,org-agenda-custom-commands-local-options)
2614 (list :tag "Stuck projects"
2615 (const :format "" stuck)
2616 (const :tag "" :format "" "")
2617 ,org-agenda-custom-commands-local-options)
2618 (list :tag "Tags search"
2619 (const :format "" tags)
2620 (string :tag "Match")
2621 ,org-agenda-custom-commands-local-options)
2622 (list :tag "Tags search, TODO entries only"
2623 (const :format "" tags-todo)
2624 (string :tag "Match")
2625 ,org-agenda-custom-commands-local-options)
2626 (list :tag "TODO keyword search"
2627 (const :format "" todo)
2628 (string :tag "Match")
2629 ,org-agenda-custom-commands-local-options)
2630 (list :tag "Other, user-defined function"
2631 (symbol :tag "function")
2632 (string :tag "Match")
2633 ,org-agenda-custom-commands-local-options)))
2635 (repeat :tag "Settings for entire command set"
2636 (list (variable :tag "Any variable")
2637 (sexp :tag "Value")))
2638 (option (repeat :tag "Export" (file :tag "Export to"))))
2639 (cons :tag "Prefix key documentation"
2640 (string :tag "Access Key(s)")
2641 (string :tag "Description ")))))
2643 (defcustom org-agenda-query-register ?o
2644 "The register holding the current query string.
2645 The prupose of this is that if you construct a query string interactively,
2646 you can then use it to define a custom command."
2647 :group 'org-agenda-custom-commands
2648 :type 'character)
2650 (defcustom org-stuck-projects
2651 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2652 "How to identify stuck projects.
2653 This is a list of four items:
2654 1. A tags/todo matcher string that is used to identify a project.
2655 The entire tree below a headline matched by this is considered one project.
2656 2. A list of TODO keywords identifying non-stuck projects.
2657 If the project subtree contains any headline with one of these todo
2658 keywords, the project is considered to be not stuck. If you specify
2659 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2660 3. A list of tags identifying non-stuck projects.
2661 If the project subtree contains any headline with one of these tags,
2662 the project is considered to be not stuck. If you specify \"*\" as
2663 a tag, any tag will mark the project unstuck.
2664 4. An arbitrary regular expression matching non-stuck projects.
2666 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2667 or `C-c a #' to produce the list."
2668 :group 'org-agenda-custom-commands
2669 :type '(list
2670 (string :tag "Tags/TODO match to identify a project")
2671 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2672 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2673 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2676 (defgroup org-agenda-skip nil
2677 "Options concerning skipping parts of agenda files."
2678 :tag "Org Agenda Skip"
2679 :group 'org-agenda)
2681 (defcustom org-agenda-todo-list-sublevels t
2682 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2683 When nil, the sublevels of a TODO entry are not checked, resulting in
2684 potentially much shorter TODO lists."
2685 :group 'org-agenda-skip
2686 :group 'org-todo
2687 :type 'boolean)
2689 (defcustom org-agenda-todo-ignore-with-date nil
2690 "Non-nil means, don't show entries with a date in the global todo list.
2691 You can use this if you prefer to mark mere appointments with a TODO keyword,
2692 but don't want them to show up in the TODO list.
2693 When this is set, it also covers deadlines and scheduled items, the settings
2694 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2695 will be ignored."
2696 :group 'org-agenda-skip
2697 :group 'org-todo
2698 :type 'boolean)
2700 (defcustom org-agenda-todo-ignore-scheduled nil
2701 "Non-nil means, don't show scheduled entries in the global todo list.
2702 The idea behind this is that by scheduling it, you have already taken care
2703 of this item.
2704 See also `org-agenda-todo-ignore-with-date'."
2705 :group 'org-agenda-skip
2706 :group 'org-todo
2707 :type 'boolean)
2709 (defcustom org-agenda-todo-ignore-deadlines nil
2710 "Non-nil means, don't show near deadline entries in the global todo list.
2711 Near means closer than `org-deadline-warning-days' days.
2712 The idea behind this is that such items will appear in the agenda anyway.
2713 See also `org-agenda-todo-ignore-with-date'."
2714 :group 'org-agenda-skip
2715 :group 'org-todo
2716 :type 'boolean)
2718 (defcustom org-agenda-skip-scheduled-if-done nil
2719 "Non-nil means don't show scheduled items in agenda when they are done.
2720 This is relevant for the daily/weekly agenda, not for the TODO list. And
2721 it applies only to the actual date of the scheduling. Warnings about
2722 an item with a past scheduling dates are always turned off when the item
2723 is DONE."
2724 :group 'org-agenda-skip
2725 :type 'boolean)
2727 (defcustom org-agenda-skip-deadline-if-done nil
2728 "Non-nil means don't show deadines when the corresponding item is done.
2729 When nil, the deadline is still shown and should give you a happy feeling.
2730 This is relevant for the daily/weekly agenda. And it applied only to the
2731 actualy date of the deadline. Warnings about approching and past-due
2732 deadlines are always turned off when the item is DONE."
2733 :group 'org-agenda-skip
2734 :type 'boolean)
2736 (defcustom org-agenda-skip-timestamp-if-done nil
2737 "Non-nil means don't select item by timestamp or -range if it is DONE."
2738 :group 'org-agenda-skip
2739 :type 'boolean)
2741 (defcustom org-timeline-show-empty-dates 3
2742 "Non-nil means, `org-timeline' also shows dates without an entry.
2743 When nil, only the days which actually have entries are shown.
2744 When t, all days between the first and the last date are shown.
2745 When an integer, show also empty dates, but if there is a gap of more than
2746 N days, just insert a special line indicating the size of the gap."
2747 :group 'org-agenda-skip
2748 :type '(choice
2749 (const :tag "None" nil)
2750 (const :tag "All" t)
2751 (number :tag "at most")))
2754 (defgroup org-agenda-startup nil
2755 "Options concerning initial settings in the Agenda in Org Mode."
2756 :tag "Org Agenda Startup"
2757 :group 'org-agenda)
2759 (defcustom org-finalize-agenda-hook nil
2760 "Hook run just before displaying an agenda buffer."
2761 :group 'org-agenda-startup
2762 :type 'hook)
2764 (defcustom org-agenda-mouse-1-follows-link nil
2765 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2766 A longer mouse click will still set point. Does not work on XEmacs.
2767 Needs to be set before org.el is loaded."
2768 :group 'org-agenda-startup
2769 :type 'boolean)
2771 (defcustom org-agenda-start-with-follow-mode nil
2772 "The initial value of follow-mode in a newly created agenda window."
2773 :group 'org-agenda-startup
2774 :type 'boolean)
2776 (defgroup org-agenda-windows nil
2777 "Options concerning the windows used by the Agenda in Org Mode."
2778 :tag "Org Agenda Windows"
2779 :group 'org-agenda)
2781 (defcustom org-agenda-window-setup 'reorganize-frame
2782 "How the agenda buffer should be displayed.
2783 Possible values for this option are:
2785 current-window Show agenda in the current window, keeping all other windows.
2786 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2787 other-window Use `switch-to-buffer-other-window' to display agenda.
2788 reorganize-frame Show only two windows on the current frame, the current
2789 window and the agenda.
2790 See also the variable `org-agenda-restore-windows-after-quit'."
2791 :group 'org-agenda-windows
2792 :type '(choice
2793 (const current-window)
2794 (const other-frame)
2795 (const other-window)
2796 (const reorganize-frame)))
2798 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2799 "The min and max height of the agenda window as a fraction of frame height.
2800 The value of the variable is a cons cell with two numbers between 0 and 1.
2801 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2802 :group 'org-agenda-windows
2803 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2805 (defcustom org-agenda-restore-windows-after-quit nil
2806 "Non-nil means, restore window configuration open exiting agenda.
2807 Before the window configuration is changed for displaying the agenda,
2808 the current status is recorded. When the agenda is exited with
2809 `q' or `x' and this option is set, the old state is restored. If
2810 `org-agenda-window-setup' is `other-frame', the value of this
2811 option will be ignored.."
2812 :group 'org-agenda-windows
2813 :type 'boolean)
2815 (defcustom org-indirect-buffer-display 'other-window
2816 "How should indirect tree buffers be displayed?
2817 This applies to indirect buffers created with the commands
2818 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2819 Valid values are:
2820 current-window Display in the current window
2821 other-window Just display in another window.
2822 dedicated-frame Create one new frame, and re-use it each time.
2823 new-frame Make a new frame each time. Note that in this case
2824 previously-made indirect buffers are kept, and you need to
2825 kill these buffers yourself."
2826 :group 'org-structure
2827 :group 'org-agenda-windows
2828 :type '(choice
2829 (const :tag "In current window" current-window)
2830 (const :tag "In current frame, other window" other-window)
2831 (const :tag "Each time a new frame" new-frame)
2832 (const :tag "One dedicated frame" dedicated-frame)))
2834 (defgroup org-agenda-daily/weekly nil
2835 "Options concerning the daily/weekly agenda."
2836 :tag "Org Agenda Daily/Weekly"
2837 :group 'org-agenda)
2839 (defcustom org-agenda-ndays 7
2840 "Number of days to include in overview display.
2841 Should be 1 or 7."
2842 :group 'org-agenda-daily/weekly
2843 :type 'number)
2845 (defcustom org-agenda-start-on-weekday 1
2846 "Non-nil means, start the overview always on the specified weekday.
2847 0 denotes Sunday, 1 denotes Monday etc.
2848 When nil, always start on the current day."
2849 :group 'org-agenda-daily/weekly
2850 :type '(choice (const :tag "Today" nil)
2851 (number :tag "Weekday No.")))
2853 (defcustom org-agenda-show-all-dates t
2854 "Non-nil means, `org-agenda' shows every day in the selected range.
2855 When nil, only the days which actually have entries are shown."
2856 :group 'org-agenda-daily/weekly
2857 :type 'boolean)
2859 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2860 "Format string for displaying dates in the agenda.
2861 Used by the daily/weekly agenda and by the timeline. This should be
2862 a format string understood by `format-time-string', or a function returning
2863 the formatted date as a string. The function must take a single argument,
2864 a calendar-style date list like (month day year)."
2865 :group 'org-agenda-daily/weekly
2866 :type '(choice
2867 (string :tag "Format string")
2868 (function :tag "Function")))
2870 (defun org-agenda-format-date-aligned (date)
2871 "Format a date string for display in the daily/weekly agenda, or timeline.
2872 This function makes sure that dates are aligned for easy reading."
2873 (format "%-9s %2d %s %4d"
2874 (calendar-day-name date)
2875 (extract-calendar-day date)
2876 (calendar-month-name (extract-calendar-month date))
2877 (extract-calendar-year date)))
2879 (defcustom org-agenda-include-diary nil
2880 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2881 :group 'org-agenda-daily/weekly
2882 :type 'boolean)
2884 (defcustom org-agenda-include-all-todo nil
2885 "Set means weekly/daily agenda will always contain all TODO entries.
2886 The TODO entries will be listed at the top of the agenda, before
2887 the entries for specific days."
2888 :group 'org-agenda-daily/weekly
2889 :type 'boolean)
2891 (defcustom org-agenda-repeating-timestamp-show-all t
2892 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2893 When nil, only one occurence is shown, either today or the
2894 nearest into the future."
2895 :group 'org-agenda-daily/weekly
2896 :type 'boolean)
2898 (defcustom org-deadline-warning-days 14
2899 "No. of days before expiration during which a deadline becomes active.
2900 This variable governs the display in sparse trees and in the agenda.
2901 When 0 or negative, it means use this number (the absolute value of it)
2902 even if a deadline has a different individual lead time specified."
2903 :group 'org-time
2904 :group 'org-agenda-daily/weekly
2905 :type 'number)
2907 (defcustom org-scheduled-past-days 10000
2908 "No. of days to continue listing scheduled items that are not marked DONE.
2909 When an item is scheduled on a date, it shows up in the agenda on this
2910 day and will be listed until it is marked done for the number of days
2911 given here."
2912 :group 'org-agenda-daily/weekly
2913 :type 'number)
2915 (defgroup org-agenda-time-grid nil
2916 "Options concerning the time grid in the Org-mode Agenda."
2917 :tag "Org Agenda Time Grid"
2918 :group 'org-agenda)
2920 (defcustom org-agenda-use-time-grid t
2921 "Non-nil means, show a time grid in the agenda schedule.
2922 A time grid is a set of lines for specific times (like every two hours between
2923 8:00 and 20:00). The items scheduled for a day at specific times are
2924 sorted in between these lines.
2925 For details about when the grid will be shown, and what it will look like, see
2926 the variable `org-agenda-time-grid'."
2927 :group 'org-agenda-time-grid
2928 :type 'boolean)
2930 (defcustom org-agenda-time-grid
2931 '((daily today require-timed)
2932 "----------------"
2933 (800 1000 1200 1400 1600 1800 2000))
2935 "The settings for time grid for agenda display.
2936 This is a list of three items. The first item is again a list. It contains
2937 symbols specifying conditions when the grid should be displayed:
2939 daily if the agenda shows a single day
2940 weekly if the agenda shows an entire week
2941 today show grid on current date, independent of daily/weekly display
2942 require-timed show grid only if at least one item has a time specification
2944 The second item is a string which will be places behing the grid time.
2946 The third item is a list of integers, indicating the times that should have
2947 a grid line."
2948 :group 'org-agenda-time-grid
2949 :type
2950 '(list
2951 (set :greedy t :tag "Grid Display Options"
2952 (const :tag "Show grid in single day agenda display" daily)
2953 (const :tag "Show grid in weekly agenda display" weekly)
2954 (const :tag "Always show grid for today" today)
2955 (const :tag "Show grid only if any timed entries are present"
2956 require-timed)
2957 (const :tag "Skip grid times already present in an entry"
2958 remove-match))
2959 (string :tag "Grid String")
2960 (repeat :tag "Grid Times" (integer :tag "Time"))))
2962 (defgroup org-agenda-sorting nil
2963 "Options concerning sorting in the Org-mode Agenda."
2964 :tag "Org Agenda Sorting"
2965 :group 'org-agenda)
2967 (defcustom org-agenda-sorting-strategy
2968 '((agenda time-up category-keep priority-down)
2969 (todo category-keep priority-down)
2970 (tags category-keep priority-down)
2971 (search category-keep))
2972 "Sorting structure for the agenda items of a single day.
2973 This is a list of symbols which will be used in sequence to determine
2974 if an entry should be listed before another entry. The following
2975 symbols are recognized:
2977 time-up Put entries with time-of-day indications first, early first
2978 time-down Put entries with time-of-day indications first, late first
2979 category-keep Keep the default order of categories, corresponding to the
2980 sequence in `org-agenda-files'.
2981 category-up Sort alphabetically by category, A-Z.
2982 category-down Sort alphabetically by category, Z-A.
2983 tag-up Sort alphabetically by last tag, A-Z.
2984 tag-down Sort alphabetically by last tag, Z-A.
2985 priority-up Sort numerically by priority, high priority last.
2986 priority-down Sort numerically by priority, high priority first.
2988 The different possibilities will be tried in sequence, and testing stops
2989 if one comparison returns a \"not-equal\". For example, the default
2990 '(time-up category-keep priority-down)
2991 means: Pull out all entries having a specified time of day and sort them,
2992 in order to make a time schedule for the current day the first thing in the
2993 agenda listing for the day. Of the entries without a time indication, keep
2994 the grouped in categories, don't sort the categories, but keep them in
2995 the sequence given in `org-agenda-files'. Within each category sort by
2996 priority.
2998 Leaving out `category-keep' would mean that items will be sorted across
2999 categories by priority.
3001 Instead of a single list, this can also be a set of list for specific
3002 contents, with a context symbol in the car of the list, any of
3003 `agenda', `todo', `tags' for the corresponding agenda views."
3004 :group 'org-agenda-sorting
3005 :type `(choice
3006 (repeat :tag "General" ,org-sorting-choice)
3007 (list :tag "Individually"
3008 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
3009 (repeat ,org-sorting-choice))
3010 (cons (const :tag "Strategy for TODO lists" todo)
3011 (repeat ,org-sorting-choice))
3012 (cons (const :tag "Strategy for Tags matches" tags)
3013 (repeat ,org-sorting-choice)))))
3015 (defcustom org-sort-agenda-notime-is-late t
3016 "Non-nil means, items without time are considered late.
3017 This is only relevant for sorting. When t, items which have no explicit
3018 time like 15:30 will be considered as 99:01, i.e. later than any items which
3019 do have a time. When nil, the default time is before 0:00. You can use this
3020 option to decide if the schedule for today should come before or after timeless
3021 agenda entries."
3022 :group 'org-agenda-sorting
3023 :type 'boolean)
3025 (defgroup org-agenda-line-format nil
3026 "Options concerning the entry prefix in the Org-mode agenda display."
3027 :tag "Org Agenda Line Format"
3028 :group 'org-agenda)
3030 (defcustom org-agenda-prefix-format
3031 '((agenda . " %-12:c%?-12t% s")
3032 (timeline . " % s")
3033 (todo . " %-12:c")
3034 (tags . " %-12:c")
3035 (search . " %-12:c"))
3036 "Format specifications for the prefix of items in the agenda views.
3037 An alist with four entries, for the different agenda types. The keys to the
3038 sublists are `agenda', `timeline', `todo', and `tags'. The values
3039 are format strings.
3040 This format works similar to a printf format, with the following meaning:
3042 %c the category of the item, \"Diary\" for entries from the diary, or
3043 as given by the CATEGORY keyword or derived from the file name.
3044 %T the *last* tag of the item. Last because inherited tags come
3045 first in the list.
3046 %t the time-of-day specification if one applies to the entry, in the
3047 format HH:MM
3048 %s Scheduling/Deadline information, a short string
3050 All specifiers work basically like the standard `%s' of printf, but may
3051 contain two additional characters: A question mark just after the `%' and
3052 a whitespace/punctuation character just before the final letter.
3054 If the first character after `%' is a question mark, the entire field
3055 will only be included if the corresponding value applies to the
3056 current entry. This is useful for fields which should have fixed
3057 width when present, but zero width when absent. For example,
3058 \"%?-12t\" will result in a 12 character time field if a time of the
3059 day is specified, but will completely disappear in entries which do
3060 not contain a time.
3062 If there is punctuation or whitespace character just before the final
3063 format letter, this character will be appended to the field value if
3064 the value is not empty. For example, the format \"%-12:c\" leads to
3065 \"Diary: \" if the category is \"Diary\". If the category were be
3066 empty, no additional colon would be interted.
3068 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3069 - Indent the line with two space characters
3070 - Give the category in a 12 chars wide field, padded with whitespace on
3071 the right (because of `-'). Append a colon if there is a category
3072 (because of `:').
3073 - If there is a time-of-day, put it into a 12 chars wide field. If no
3074 time, don't put in an empty field, just skip it (because of '?').
3075 - Finally, put the scheduling information and append a whitespace.
3077 As another example, if you don't want the time-of-day of entries in
3078 the prefix, you could use:
3080 (setq org-agenda-prefix-format \" %-11:c% s\")
3082 See also the variables `org-agenda-remove-times-when-in-prefix' and
3083 `org-agenda-remove-tags'."
3084 :type '(choice
3085 (string :tag "General format")
3086 (list :greedy t :tag "View dependent"
3087 (cons (const agenda) (string :tag "Format"))
3088 (cons (const timeline) (string :tag "Format"))
3089 (cons (const todo) (string :tag "Format"))
3090 (cons (const tags) (string :tag "Format"))
3091 (cons (const search) (string :tag "Format"))))
3092 :group 'org-agenda-line-format)
3094 (defvar org-prefix-format-compiled nil
3095 "The compiled version of the most recently used prefix format.
3096 See the variable `org-agenda-prefix-format'.")
3098 (defcustom org-agenda-todo-keyword-format "%-1s"
3099 "Format for the TODO keyword in agenda lines.
3100 Set this to something like \"%-12s\" if you want all TODO keywords
3101 to occupy a fixed space in the agenda display."
3102 :group 'org-agenda-line-format
3103 :type 'string)
3105 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3106 "Text preceeding scheduled items in the agenda view.
3107 This is a list with two strings. The first applies when the item is
3108 scheduled on the current day. The second applies when it has been scheduled
3109 previously, it may contain a %d to capture how many days ago the item was
3110 scheduled."
3111 :group 'org-agenda-line-format
3112 :type '(list
3113 (string :tag "Scheduled today ")
3114 (string :tag "Scheduled previously")))
3116 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3117 "Text preceeding deadline items in the agenda view.
3118 This is a list with two strings. The first applies when the item has its
3119 deadline on the current day. The second applies when it is in the past or
3120 in the future, it may contain %d to capture how many days away the deadline
3121 is (was)."
3122 :group 'org-agenda-line-format
3123 :type '(list
3124 (string :tag "Deadline today ")
3125 (string :tag "Deadline relative")))
3127 (defcustom org-agenda-remove-times-when-in-prefix t
3128 "Non-nil means, remove duplicate time specifications in agenda items.
3129 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3130 time-of-day specification in a headline or diary entry is extracted and
3131 placed into the prefix. If this option is non-nil, the original specification
3132 \(a timestamp or -range, or just a plain time(range) specification like
3133 11:30-4pm) will be removed for agenda display. This makes the agenda less
3134 cluttered.
3135 The option can be t or nil. It may also be the symbol `beg', indicating
3136 that the time should only be removed what it is located at the beginning of
3137 the headline/diary entry."
3138 :group 'org-agenda-line-format
3139 :type '(choice
3140 (const :tag "Always" t)
3141 (const :tag "Never" nil)
3142 (const :tag "When at beginning of entry" beg)))
3145 (defcustom org-agenda-default-appointment-duration nil
3146 "Default duration for appointments that only have a starting time.
3147 When nil, no duration is specified in such cases.
3148 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3149 :group 'org-agenda-line-format
3150 :type '(choice
3151 (integer :tag "Minutes")
3152 (const :tag "No default duration")))
3155 (defcustom org-agenda-remove-tags nil
3156 "Non-nil means, remove the tags from the headline copy in the agenda.
3157 When this is the symbol `prefix', only remove tags when
3158 `org-agenda-prefix-format' contains a `%T' specifier."
3159 :group 'org-agenda-line-format
3160 :type '(choice
3161 (const :tag "Always" t)
3162 (const :tag "Never" nil)
3163 (const :tag "When prefix format contains %T" prefix)))
3165 (if (fboundp 'defvaralias)
3166 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3167 'org-agenda-remove-tags))
3169 (defcustom org-agenda-tags-column -80
3170 "Shift tags in agenda items to this column.
3171 If this number is positive, it specifies the column. If it is negative,
3172 it means that the tags should be flushright to that column. For example,
3173 -80 works well for a normal 80 character screen."
3174 :group 'org-agenda-line-format
3175 :type 'integer)
3177 (if (fboundp 'defvaralias)
3178 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3180 (defcustom org-agenda-fontify-priorities t
3181 "Non-nil means, highlight low and high priorities in agenda.
3182 When t, the highest priority entries are bold, lowest priority italic.
3183 This may also be an association list of priority faces. The face may be
3184 a names face, or a list like `(:background \"Red\")'."
3185 :group 'org-agenda-line-format
3186 :type '(choice
3187 (const :tag "Never" nil)
3188 (const :tag "Defaults" t)
3189 (repeat :tag "Specify"
3190 (list (character :tag "Priority" :value ?A)
3191 (sexp :tag "face")))))
3193 (defgroup org-latex nil
3194 "Options for embedding LaTeX code into Org-mode"
3195 :tag "Org LaTeX"
3196 :group 'org)
3198 (defcustom org-format-latex-options
3199 '(:foreground default :background default :scale 1.0
3200 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3201 :matchers ("begin" "$" "$$" "\\(" "\\["))
3202 "Options for creating images from LaTeX fragments.
3203 This is a property list with the following properties:
3204 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3205 `default' means use the forground of the default face.
3206 :background the background color, or \"Transparent\".
3207 `default' means use the background of the default face.
3208 :scale a scaling factor for the size of the images
3209 :html-foreground, :html-background, :html-scale
3210 The same numbers for HTML export.
3211 :matchers a list indicating which matchers should be used to
3212 find LaTeX fragments. Valid members of this list are:
3213 \"begin\" find environments
3214 \"$\" find math expressions surrounded by $...$
3215 \"$$\" find math expressions surrounded by $$....$$
3216 \"\\(\" find math expressions surrounded by \\(...\\)
3217 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3218 :group 'org-latex
3219 :type 'plist)
3221 (defcustom org-format-latex-header "\\documentclass{article}
3222 \\usepackage{fullpage} % do not remove
3223 \\usepackage{amssymb}
3224 \\usepackage[usenames]{color}
3225 \\usepackage{amsmath}
3226 \\usepackage{latexsym}
3227 \\usepackage[mathscr]{eucal}
3228 \\pagestyle{empty} % do not remove"
3229 "The document header used for processing LaTeX fragments."
3230 :group 'org-latex
3231 :type 'string)
3233 (defgroup org-export nil
3234 "Options for exporting org-listings."
3235 :tag "Org Export"
3236 :group 'org)
3238 (defgroup org-export-general nil
3239 "General options for exporting Org-mode files."
3240 :tag "Org Export General"
3241 :group 'org-export)
3243 ;; FIXME
3244 (defvar org-export-publishing-directory nil)
3246 (defcustom org-export-with-special-strings t
3247 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3248 When this option is turned on, these strings will be exported as:
3250 Org HTML LaTeX
3251 -----+----------+--------
3252 \\- &shy; \\-
3253 -- &ndash; --
3254 --- &mdash; ---
3255 ... &hellip; \ldots
3257 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3258 :group 'org-export-translation
3259 :type 'boolean)
3261 (defcustom org-export-language-setup
3262 '(("en" "Author" "Date" "Table of Contents")
3263 ("cs" "Autor" "Datum" "Obsah")
3264 ("da" "Ophavsmand" "Dato" "Indhold")
3265 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3266 ("es" "Autor" "Fecha" "\xcdndice")
3267 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3268 ("it" "Autore" "Data" "Indice")
3269 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3270 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3271 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3272 "Terms used in export text, translated to different languages.
3273 Use the variable `org-export-default-language' to set the language,
3274 or use the +OPTION lines for a per-file setting."
3275 :group 'org-export-general
3276 :type '(repeat
3277 (list
3278 (string :tag "HTML language tag")
3279 (string :tag "Author")
3280 (string :tag "Date")
3281 (string :tag "Table of Contents"))))
3283 (defcustom org-export-default-language "en"
3284 "The default language of HTML export, as a string.
3285 This should have an association in `org-export-language-setup'."
3286 :group 'org-export-general
3287 :type 'string)
3289 (defcustom org-export-skip-text-before-1st-heading t
3290 "Non-nil means, skip all text before the first headline when exporting.
3291 When nil, that text is exported as well."
3292 :group 'org-export-general
3293 :type 'boolean)
3295 (defcustom org-export-headline-levels 3
3296 "The last level which is still exported as a headline.
3297 Inferior levels will produce itemize lists when exported.
3298 Note that a numeric prefix argument to an exporter function overrides
3299 this setting.
3301 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3302 :group 'org-export-general
3303 :type 'number)
3305 (defcustom org-export-with-section-numbers t
3306 "Non-nil means, add section numbers to headlines when exporting.
3308 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3309 :group 'org-export-general
3310 :type 'boolean)
3312 (defcustom org-export-with-toc t
3313 "Non-nil means, create a table of contents in exported files.
3314 The TOC contains headlines with levels up to`org-export-headline-levels'.
3315 When an integer, include levels up to N in the toc, this may then be
3316 different from `org-export-headline-levels', but it will not be allowed
3317 to be larger than the number of headline levels.
3318 When nil, no table of contents is made.
3320 Headlines which contain any TODO items will be marked with \"(*)\" in
3321 ASCII export, and with red color in HTML output, if the option
3322 `org-export-mark-todo-in-toc' is set.
3324 In HTML output, the TOC will be clickable.
3326 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3327 or \"toc:3\"."
3328 :group 'org-export-general
3329 :type '(choice
3330 (const :tag "No Table of Contents" nil)
3331 (const :tag "Full Table of Contents" t)
3332 (integer :tag "TOC to level")))
3334 (defcustom org-export-mark-todo-in-toc nil
3335 "Non-nil means, mark TOC lines that contain any open TODO items."
3336 :group 'org-export-general
3337 :type 'boolean)
3339 (defcustom org-export-preserve-breaks nil
3340 "Non-nil means, preserve all line breaks when exporting.
3341 Normally, in HTML output paragraphs will be reformatted. In ASCII
3342 export, line breaks will always be preserved, regardless of this variable.
3344 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3345 :group 'org-export-general
3346 :type 'boolean)
3348 (defcustom org-export-with-archived-trees 'headline
3349 "Whether subtrees with the ARCHIVE tag should be exported.
3350 This can have three different values
3351 nil Do not export, pretend this tree is not present
3352 t Do export the entire tree
3353 headline Only export the headline, but skip the tree below it."
3354 :group 'org-export-general
3355 :group 'org-archive
3356 :type '(choice
3357 (const :tag "not at all" nil)
3358 (const :tag "headline only" 'headline)
3359 (const :tag "entirely" t)))
3361 (defcustom org-export-author-info t
3362 "Non-nil means, insert author name and email into the exported file.
3364 This option can also be set with the +OPTIONS line,
3365 e.g. \"author-info:nil\"."
3366 :group 'org-export-general
3367 :type 'boolean)
3369 (defcustom org-export-time-stamp-file t
3370 "Non-nil means, insert a time stamp into the exported file.
3371 The time stamp shows when the file was created.
3373 This option can also be set with the +OPTIONS line,
3374 e.g. \"timestamp:nil\"."
3375 :group 'org-export-general
3376 :type 'boolean)
3378 (defcustom org-export-with-timestamps t
3379 "If nil, do not export time stamps and associated keywords."
3380 :group 'org-export-general
3381 :type 'boolean)
3383 (defcustom org-export-remove-timestamps-from-toc t
3384 "If nil, remove timestamps from the table of contents entries."
3385 :group 'org-export-general
3386 :type 'boolean)
3388 (defcustom org-export-with-tags 'not-in-toc
3389 "If nil, do not export tags, just remove them from headlines.
3390 If this is the symbol `not-in-toc', tags will be removed from table of
3391 contents entries, but still be shown in the headlines of the document.
3393 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3394 :group 'org-export-general
3395 :type '(choice
3396 (const :tag "Off" nil)
3397 (const :tag "Not in TOC" not-in-toc)
3398 (const :tag "On" t)))
3400 (defcustom org-export-with-drawers nil
3401 "Non-nil means, export with drawers like the property drawer.
3402 When t, all drawers are exported. This may also be a list of
3403 drawer names to export."
3404 :group 'org-export-general
3405 :type '(choice
3406 (const :tag "All drawers" t)
3407 (const :tag "None" nil)
3408 (repeat :tag "Selected drawers"
3409 (string :tag "Drawer name"))))
3411 (defgroup org-export-translation nil
3412 "Options for translating special ascii sequences for the export backends."
3413 :tag "Org Export Translation"
3414 :group 'org-export)
3416 (defcustom org-export-with-emphasize t
3417 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3418 If the export target supports emphasizing text, the word will be
3419 typeset in bold, italic, or underlined, respectively. Works only for
3420 single words, but you can say: I *really* *mean* *this*.
3421 Not all export backends support this.
3423 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3424 :group 'org-export-translation
3425 :type 'boolean)
3427 (defcustom org-export-with-footnotes t
3428 "If nil, export [1] as a footnote marker.
3429 Lines starting with [1] will be formatted as footnotes.
3431 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3432 :group 'org-export-translation
3433 :type 'boolean)
3435 (defcustom org-export-with-sub-superscripts t
3436 "Non-nil means, interpret \"_\" and \"^\" for export.
3437 When this option is turned on, you can use TeX-like syntax for sub- and
3438 superscripts. Several characters after \"_\" or \"^\" will be
3439 considered as a single item - so grouping with {} is normally not
3440 needed. For example, the following things will be parsed as single
3441 sub- or superscripts.
3443 10^24 or 10^tau several digits will be considered 1 item.
3444 10^-12 or 10^-tau a leading sign with digits or a word
3445 x^2-y^3 will be read as x^2 - y^3, because items are
3446 terminated by almost any nonword/nondigit char.
3447 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3449 Still, ambiguity is possible - so when in doubt use {} to enclose the
3450 sub/superscript. If you set this variable to the symbol `{}',
3451 the braces are *required* in order to trigger interpretations as
3452 sub/superscript. This can be helpful in documents that need \"_\"
3453 frequently in plain text.
3455 Not all export backends support this, but HTML does.
3457 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3458 :group 'org-export-translation
3459 :type '(choice
3460 (const :tag "Always interpret" t)
3461 (const :tag "Only with braces" {})
3462 (const :tag "Never interpret" nil)))
3464 (defcustom org-export-with-special-strings t
3465 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3466 When this option is turned on, these strings will be exported as:
3468 \\- : &shy;
3469 -- : &ndash;
3470 --- : &mdash;
3472 Not all export backends support this, but HTML does.
3474 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3475 :group 'org-export-translation
3476 :type 'boolean)
3478 (defcustom org-export-with-TeX-macros t
3479 "Non-nil means, interpret simple TeX-like macros when exporting.
3480 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3481 No only real TeX macros will work here, but the standard HTML entities
3482 for math can be used as macro names as well. For a list of supported
3483 names in HTML export, see the constant `org-html-entities'.
3484 Not all export backends support this.
3486 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3487 :group 'org-export-translation
3488 :group 'org-export-latex
3489 :type 'boolean)
3491 (defcustom org-export-with-LaTeX-fragments nil
3492 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3493 When set, the exporter will find LaTeX environments if the \\begin line is
3494 the first non-white thing on a line. It will also find the math delimiters
3495 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3496 display math.
3498 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3499 :group 'org-export-translation
3500 :group 'org-export-latex
3501 :type 'boolean)
3503 (defcustom org-export-with-fixed-width t
3504 "Non-nil means, lines starting with \":\" will be in fixed width font.
3505 This can be used to have pre-formatted text, fragments of code etc. For
3506 example:
3507 : ;; Some Lisp examples
3508 : (while (defc cnt)
3509 : (ding))
3510 will be looking just like this in also HTML. See also the QUOTE keyword.
3511 Not all export backends support this.
3513 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3514 :group 'org-export-translation
3515 :type 'boolean)
3517 (defcustom org-match-sexp-depth 3
3518 "Number of stacked braces for sub/superscript matching.
3519 This has to be set before loading org.el to be effective."
3520 :group 'org-export-translation
3521 :type 'integer)
3523 (defgroup org-export-tables nil
3524 "Options for exporting tables in Org-mode."
3525 :tag "Org Export Tables"
3526 :group 'org-export)
3528 (defcustom org-export-with-tables t
3529 "If non-nil, lines starting with \"|\" define a table.
3530 For example:
3532 | Name | Address | Birthday |
3533 |-------------+----------+-----------|
3534 | Arthur Dent | England | 29.2.2100 |
3536 Not all export backends support this.
3538 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3539 :group 'org-export-tables
3540 :type 'boolean)
3542 (defcustom org-export-highlight-first-table-line t
3543 "Non-nil means, highlight the first table line.
3544 In HTML export, this means use <th> instead of <td>.
3545 In tables created with table.el, this applies to the first table line.
3546 In Org-mode tables, all lines before the first horizontal separator
3547 line will be formatted with <th> tags."
3548 :group 'org-export-tables
3549 :type 'boolean)
3551 (defcustom org-export-table-remove-special-lines t
3552 "Remove special lines and marking characters in calculating tables.
3553 This removes the special marking character column from tables that are set
3554 up for spreadsheet calculations. It also removes the entire lines
3555 marked with `!', `_', or `^'. The lines with `$' are kept, because
3556 the values of constants may be useful to have."
3557 :group 'org-export-tables
3558 :type 'boolean)
3560 (defcustom org-export-prefer-native-exporter-for-tables nil
3561 "Non-nil means, always export tables created with table.el natively.
3562 Natively means, use the HTML code generator in table.el.
3563 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3564 the table does not use row- or column-spanning). This has the
3565 advantage, that the automatic HTML conversions for math symbols and
3566 sub/superscripts can be applied. Org-mode's HTML generator is also
3567 much faster."
3568 :group 'org-export-tables
3569 :type 'boolean)
3571 (defgroup org-export-ascii nil
3572 "Options specific for ASCII export of Org-mode files."
3573 :tag "Org Export ASCII"
3574 :group 'org-export)
3576 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3577 "Characters for underlining headings in ASCII export.
3578 In the given sequence, these characters will be used for level 1, 2, ..."
3579 :group 'org-export-ascii
3580 :type '(repeat character))
3582 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3583 "Bullet characters for headlines converted to lists in ASCII export.
3584 The first character is used for the first lest level generated in this
3585 way, and so on. If there are more levels than characters given here,
3586 the list will be repeated.
3587 Note that plain lists will keep the same bullets as the have in the
3588 Org-mode file."
3589 :group 'org-export-ascii
3590 :type '(repeat character))
3592 (defgroup org-export-xml nil
3593 "Options specific for XML export of Org-mode files."
3594 :tag "Org Export XML"
3595 :group 'org-export)
3597 (defgroup org-export-html nil
3598 "Options specific for HTML export of Org-mode files."
3599 :tag "Org Export HTML"
3600 :group 'org-export)
3602 (defcustom org-export-html-coding-system nil
3604 :group 'org-export-html
3605 :type 'coding-system)
3607 (defcustom org-export-html-extension "html"
3608 "The extension for exported HTML files."
3609 :group 'org-export-html
3610 :type 'string)
3612 (defcustom org-export-html-style
3613 "<style type=\"text/css\">
3614 html {
3615 font-family: Times, serif;
3616 font-size: 12pt;
3618 .title { text-align: center; }
3619 .todo { color: red; }
3620 .done { color: green; }
3621 .timestamp { color: grey }
3622 .timestamp-kwd { color: CadetBlue }
3623 .tag { background-color:lightblue; font-weight:normal }
3624 .target { background-color: lavender; }
3625 pre {
3626 border: 1pt solid #AEBDCC;
3627 background-color: #F3F5F7;
3628 padding: 5pt;
3629 font-family: courier, monospace;
3631 table { border-collapse: collapse; }
3632 td, th {
3633 vertical-align: top;
3634 <!--border: 1pt solid #ADB9CC;-->
3636 </style>"
3637 "The default style specification for exported HTML files.
3638 Since there are different ways of setting style information, this variable
3639 needs to contain the full HTML structure to provide a style, including the
3640 surrounding HTML tags. The style specifications should include definitions
3641 for new classes todo, done, title, and deadline. For example, valid values
3642 would be:
3644 <style type=\"text/css\">
3645 p { font-weight: normal; color: gray; }
3646 h1 { color: black; }
3647 .title { text-align: center; }
3648 .todo, .deadline { color: red; }
3649 .done { color: green; }
3650 </style>
3652 or, if you want to keep the style in a file,
3654 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3656 As the value of this option simply gets inserted into the HTML <head> header,
3657 you can \"misuse\" it to add arbitrary text to the header."
3658 :group 'org-export-html
3659 :type 'string)
3662 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3663 "Format for typesetting the document title in HTML export."
3664 :group 'org-export-html
3665 :type 'string)
3667 (defcustom org-export-html-toplevel-hlevel 2
3668 "The <H> level for level 1 headings in HTML export."
3669 :group 'org-export-html
3670 :type 'string)
3672 (defcustom org-export-html-link-org-files-as-html t
3673 "Non-nil means, make file links to `file.org' point to `file.html'.
3674 When org-mode is exporting an org-mode file to HTML, links to
3675 non-html files are directly put into a href tag in HTML.
3676 However, links to other Org-mode files (recognized by the
3677 extension `.org.) should become links to the corresponding html
3678 file, assuming that the linked org-mode file will also be
3679 converted to HTML.
3680 When nil, the links still point to the plain `.org' file."
3681 :group 'org-export-html
3682 :type 'boolean)
3684 (defcustom org-export-html-inline-images 'maybe
3685 "Non-nil means, inline images into exported HTML pages.
3686 This is done using an <img> tag. When nil, an anchor with href is used to
3687 link to the image. If this option is `maybe', then images in links with
3688 an empty description will be inlined, while images with a description will
3689 be linked only."
3690 :group 'org-export-html
3691 :type '(choice (const :tag "Never" nil)
3692 (const :tag "Always" t)
3693 (const :tag "When there is no description" maybe)))
3695 ;; FIXME: rename
3696 (defcustom org-export-html-expand t
3697 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3698 When nil, these tags will be exported as plain text and therefore
3699 not be interpreted by a browser.
3701 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3702 :group 'org-export-html
3703 :type 'boolean)
3705 (defcustom org-export-html-table-tag
3706 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3707 "The HTML tag that is used to start a table.
3708 This must be a <table> tag, but you may change the options like
3709 borders and spacing."
3710 :group 'org-export-html
3711 :type 'string)
3713 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3714 "The opening tag for table header fields.
3715 This is customizable so that alignment options can be specified."
3716 :group 'org-export-tables
3717 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3719 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3720 "The opening tag for table data fields.
3721 This is customizable so that alignment options can be specified."
3722 :group 'org-export-tables
3723 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3725 (defcustom org-export-html-with-timestamp nil
3726 "If non-nil, write `org-export-html-html-helper-timestamp'
3727 into the exported HTML text. Otherwise, the buffer will just be saved
3728 to a file."
3729 :group 'org-export-html
3730 :type 'boolean)
3732 (defcustom org-export-html-html-helper-timestamp
3733 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3734 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3735 :group 'org-export-html
3736 :type 'string)
3738 (defgroup org-export-icalendar nil
3739 "Options specific for iCalendar export of Org-mode files."
3740 :tag "Org Export iCalendar"
3741 :group 'org-export)
3743 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3744 "The file name for the iCalendar file covering all agenda files.
3745 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3746 The file name should be absolute, the file will be overwritten without warning."
3747 :group 'org-export-icalendar
3748 :type 'file)
3750 (defcustom org-icalendar-include-todo nil
3751 "Non-nil means, export to iCalendar files should also cover TODO items."
3752 :group 'org-export-icalendar
3753 :type '(choice
3754 (const :tag "None" nil)
3755 (const :tag "Unfinished" t)
3756 (const :tag "All" all)))
3758 (defcustom org-icalendar-include-sexps t
3759 "Non-nil means, export to iCalendar files should also cover sexp entries.
3760 These are entries like in the diary, but directly in an Org-mode file."
3761 :group 'org-export-icalendar
3762 :type 'boolean)
3764 (defcustom org-icalendar-include-body 100
3765 "Amount of text below headline to be included in iCalendar export.
3766 This is a number of characters that should maximally be included.
3767 Properties, scheduling and clocking lines will always be removed.
3768 The text will be inserted into the DESCRIPTION field."
3769 :group 'org-export-icalendar
3770 :type '(choice
3771 (const :tag "Nothing" nil)
3772 (const :tag "Everything" t)
3773 (integer :tag "Max characters")))
3775 (defcustom org-icalendar-combined-name "OrgMode"
3776 "Calendar name for the combined iCalendar representing all agenda files."
3777 :group 'org-export-icalendar
3778 :type 'string)
3780 (defgroup org-font-lock nil
3781 "Font-lock settings for highlighting in Org-mode."
3782 :tag "Org Font Lock"
3783 :group 'org)
3785 (defcustom org-level-color-stars-only nil
3786 "Non-nil means fontify only the stars in each headline.
3787 When nil, the entire headline is fontified.
3788 Changing it requires restart of `font-lock-mode' to become effective
3789 also in regions already fontified."
3790 :group 'org-font-lock
3791 :type 'boolean)
3793 (defcustom org-hide-leading-stars nil
3794 "Non-nil means, hide the first N-1 stars in a headline.
3795 This works by using the face `org-hide' for these stars. This
3796 face is white for a light background, and black for a dark
3797 background. You may have to customize the face `org-hide' to
3798 make this work.
3799 Changing it requires restart of `font-lock-mode' to become effective
3800 also in regions already fontified.
3801 You may also set this on a per-file basis by adding one of the following
3802 lines to the buffer:
3804 #+STARTUP: hidestars
3805 #+STARTUP: showstars"
3806 :group 'org-font-lock
3807 :type 'boolean)
3809 (defcustom org-fontify-done-headline nil
3810 "Non-nil means, change the face of a headline if it is marked DONE.
3811 Normally, only the TODO/DONE keyword indicates the state of a headline.
3812 When this is non-nil, the headline after the keyword is set to the
3813 `org-headline-done' as an additional indication."
3814 :group 'org-font-lock
3815 :type 'boolean)
3817 (defcustom org-fontify-emphasized-text t
3818 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3819 Changing this variable requires a restart of Emacs to take effect."
3820 :group 'org-font-lock
3821 :type 'boolean)
3823 (defcustom org-highlight-latex-fragments-and-specials nil
3824 "Non-nil means, fontify what is treated specially by the exporters."
3825 :group 'org-font-lock
3826 :type 'boolean)
3828 (defcustom org-hide-emphasis-markers nil
3829 "Non-nil mean font-lock should hide the emphasis marker characters."
3830 :group 'org-font-lock
3831 :type 'boolean)
3833 (defvar org-emph-re nil
3834 "Regular expression for matching emphasis.")
3835 (defvar org-verbatim-re nil
3836 "Regular expression for matching verbatim text.")
3837 (defvar org-emphasis-regexp-components) ; defined just below
3838 (defvar org-emphasis-alist) ; defined just below
3839 (defun org-set-emph-re (var val)
3840 "Set variable and compute the emphasis regular expression."
3841 (set var val)
3842 (when (and (boundp 'org-emphasis-alist)
3843 (boundp 'org-emphasis-regexp-components)
3844 org-emphasis-alist org-emphasis-regexp-components)
3845 (let* ((e org-emphasis-regexp-components)
3846 (pre (car e))
3847 (post (nth 1 e))
3848 (border (nth 2 e))
3849 (body (nth 3 e))
3850 (nl (nth 4 e))
3851 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3852 (body1 (concat body "*?"))
3853 (markers (mapconcat 'car org-emphasis-alist ""))
3854 (vmarkers (mapconcat
3855 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3856 org-emphasis-alist "")))
3857 ;; make sure special characters appear at the right position in the class
3858 (if (string-match "\\^" markers)
3859 (setq markers (concat (replace-match "" t t markers) "^")))
3860 (if (string-match "-" markers)
3861 (setq markers (concat (replace-match "" t t markers) "-")))
3862 (if (string-match "\\^" vmarkers)
3863 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3864 (if (string-match "-" vmarkers)
3865 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3866 (if (> nl 0)
3867 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3868 (int-to-string nl) "\\}")))
3869 ;; Make the regexp
3870 (setq org-emph-re
3871 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3872 "\\("
3873 "\\([" markers "]\\)"
3874 "\\("
3875 "[^" border "]\\|"
3876 "[^" border (if (and nil stacked) markers) "]"
3877 body1
3878 "[^" border (if (and nil stacked) markers) "]"
3879 "\\)"
3880 "\\3\\)"
3881 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3882 (setq org-verbatim-re
3883 (concat "\\([" pre "]\\|^\\)"
3884 "\\("
3885 "\\([" vmarkers "]\\)"
3886 "\\("
3887 "[^" border "]\\|"
3888 "[^" border "]"
3889 body1
3890 "[^" border "]"
3891 "\\)"
3892 "\\3\\)"
3893 "\\([" post "]\\|$\\)")))))
3895 (defcustom org-emphasis-regexp-components
3896 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3897 "Components used to build the regular expression for emphasis.
3898 This is a list with 6 entries. Terminology: In an emphasis string
3899 like \" *strong word* \", we call the initial space PREMATCH, the final
3900 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3901 and \"trong wor\" is the body. The different components in this variable
3902 specify what is allowed/forbidden in each part:
3904 pre Chars allowed as prematch. Beginning of line will be allowed too.
3905 post Chars allowed as postmatch. End of line will be allowed too.
3906 border The chars *forbidden* as border characters.
3907 body-regexp A regexp like \".\" to match a body character. Don't use
3908 non-shy groups here, and don't allow newline here.
3909 newline The maximum number of newlines allowed in an emphasis exp.
3911 Use customize to modify this, or restart Emacs after changing it."
3912 :group 'org-font-lock
3913 :set 'org-set-emph-re
3914 :type '(list
3915 (sexp :tag "Allowed chars in pre ")
3916 (sexp :tag "Allowed chars in post ")
3917 (sexp :tag "Forbidden chars in border ")
3918 (sexp :tag "Regexp for body ")
3919 (integer :tag "number of newlines allowed")
3920 (option (boolean :tag "Stacking (DISABLED) "))))
3922 (defcustom org-emphasis-alist
3923 '(("*" bold "<b>" "</b>")
3924 ("/" italic "<i>" "</i>")
3925 ("_" underline "<u>" "</u>")
3926 ("=" org-code "<code>" "</code>" verbatim)
3927 ("~" org-verbatim "" "" verbatim)
3928 ("+" (:strike-through t) "<del>" "</del>")
3930 "Special syntax for emphasized text.
3931 Text starting and ending with a special character will be emphasized, for
3932 example *bold*, _underlined_ and /italic/. This variable sets the marker
3933 characters, the face to be used by font-lock for highlighting in Org-mode
3934 Emacs buffers, and the HTML tags to be used for this.
3935 Use customize to modify this, or restart Emacs after changing it."
3936 :group 'org-font-lock
3937 :set 'org-set-emph-re
3938 :type '(repeat
3939 (list
3940 (string :tag "Marker character")
3941 (choice
3942 (face :tag "Font-lock-face")
3943 (plist :tag "Face property list"))
3944 (string :tag "HTML start tag")
3945 (string :tag "HTML end tag")
3946 (option (const verbatim)))))
3948 ;;; The faces
3950 (defgroup org-faces nil
3951 "Faces in Org-mode."
3952 :tag "Org Faces"
3953 :group 'org-font-lock)
3955 (defun org-compatible-face (inherits specs)
3956 "Make a compatible face specification.
3957 If INHERITS is an existing face and if the Emacs version supports it,
3958 just inherit the face. If not, use SPECS to define the face.
3959 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3960 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3961 to the top of the list. The `min-colors' attribute will be removed from
3962 any other entries, and any resulting duplicates will be removed entirely."
3963 (cond
3964 ((and inherits (facep inherits)
3965 (not (featurep 'xemacs)) (> emacs-major-version 22))
3966 ;; In Emacs 23, we use inheritance where possible.
3967 ;; We only do this in Emacs 23, because only there the outline
3968 ;; faces have been changed to the original org-mode-level-faces.
3969 (list (list t :inherit inherits)))
3970 ((or (featurep 'xemacs) (< emacs-major-version 22))
3971 ;; These do not understand the `min-colors' attribute.
3972 (let (r e a)
3973 (while (setq e (pop specs))
3974 (cond
3975 ((memq (car e) '(t default)) (push e r))
3976 ((setq a (member '(min-colors 8) (car e)))
3977 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3978 (cdr e)))))
3979 ((setq a (assq 'min-colors (car e)))
3980 (setq e (cons (delq a (car e)) (cdr e)))
3981 (or (assoc (car e) r) (push e r)))
3982 (t (or (assoc (car e) r) (push e r)))))
3983 (nreverse r)))
3984 (t specs)))
3985 (put 'org-compatible-face 'lisp-indent-function 1)
3987 (defface org-hide
3988 '((((background light)) (:foreground "white"))
3989 (((background dark)) (:foreground "black")))
3990 "Face used to hide leading stars in headlines.
3991 The forground color of this face should be equal to the background
3992 color of the frame."
3993 :group 'org-faces)
3995 (defface org-level-1 ;; font-lock-function-name-face
3996 (org-compatible-face 'outline-1
3997 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3998 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3999 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4000 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4001 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4002 (t (:bold t))))
4003 "Face used for level 1 headlines."
4004 :group 'org-faces)
4006 (defface org-level-2 ;; font-lock-variable-name-face
4007 (org-compatible-face 'outline-2
4008 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4009 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4010 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
4011 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
4012 (t (:bold t))))
4013 "Face used for level 2 headlines."
4014 :group 'org-faces)
4016 (defface org-level-3 ;; font-lock-keyword-face
4017 (org-compatible-face 'outline-3
4018 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
4019 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
4020 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4021 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4022 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4023 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4024 (t (:bold t))))
4025 "Face used for level 3 headlines."
4026 :group 'org-faces)
4028 (defface org-level-4 ;; font-lock-comment-face
4029 (org-compatible-face 'outline-4
4030 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4031 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4032 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4033 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4034 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4035 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4036 (t (:bold t))))
4037 "Face used for level 4 headlines."
4038 :group 'org-faces)
4040 (defface org-level-5 ;; font-lock-type-face
4041 (org-compatible-face 'outline-5
4042 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4043 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4044 (((class color) (min-colors 8)) (:foreground "green"))))
4045 "Face used for level 5 headlines."
4046 :group 'org-faces)
4048 (defface org-level-6 ;; font-lock-constant-face
4049 (org-compatible-face 'outline-6
4050 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4051 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4052 (((class color) (min-colors 8)) (:foreground "magenta"))))
4053 "Face used for level 6 headlines."
4054 :group 'org-faces)
4056 (defface org-level-7 ;; font-lock-builtin-face
4057 (org-compatible-face 'outline-7
4058 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4059 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4060 (((class color) (min-colors 8)) (:foreground "blue"))))
4061 "Face used for level 7 headlines."
4062 :group 'org-faces)
4064 (defface org-level-8 ;; font-lock-string-face
4065 (org-compatible-face 'outline-8
4066 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4067 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4068 (((class color) (min-colors 8)) (:foreground "green"))))
4069 "Face used for level 8 headlines."
4070 :group 'org-faces)
4072 (defface org-special-keyword ;; font-lock-string-face
4073 (org-compatible-face nil
4074 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4075 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4076 (t (:italic t))))
4077 "Face used for special keywords."
4078 :group 'org-faces)
4080 (defface org-drawer ;; font-lock-function-name-face
4081 (org-compatible-face nil
4082 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4083 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4084 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4085 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4086 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4087 (t (:bold t))))
4088 "Face used for drawers."
4089 :group 'org-faces)
4091 (defface org-property-value nil
4092 "Face used for the value of a property."
4093 :group 'org-faces)
4095 (defface org-column
4096 (org-compatible-face nil
4097 '((((class color) (min-colors 16) (background light))
4098 (:background "grey90"))
4099 (((class color) (min-colors 16) (background dark))
4100 (:background "grey30"))
4101 (((class color) (min-colors 8))
4102 (:background "cyan" :foreground "black"))
4103 (t (:inverse-video t))))
4104 "Face for column display of entry properties."
4105 :group 'org-faces)
4107 (when (fboundp 'set-face-attribute)
4108 ;; Make sure that a fixed-width face is used when we have a column table.
4109 (set-face-attribute 'org-column nil
4110 :height (face-attribute 'default :height)
4111 :family (face-attribute 'default :family)))
4113 (defface org-warning
4114 (org-compatible-face 'font-lock-warning-face
4115 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4116 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4117 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4118 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4119 (t (:bold t))))
4120 "Face for deadlines and TODO keywords."
4121 :group 'org-faces)
4123 (defface org-archived ; similar to shadow
4124 (org-compatible-face 'shadow
4125 '((((class color grayscale) (min-colors 88) (background light))
4126 (:foreground "grey50"))
4127 (((class color grayscale) (min-colors 88) (background dark))
4128 (:foreground "grey70"))
4129 (((class color) (min-colors 8) (background light))
4130 (:foreground "green"))
4131 (((class color) (min-colors 8) (background dark))
4132 (:foreground "yellow"))))
4133 "Face for headline with the ARCHIVE tag."
4134 :group 'org-faces)
4136 (defface org-link
4137 '((((class color) (background light)) (:foreground "Purple" :underline t))
4138 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4139 (t (:underline t)))
4140 "Face for links."
4141 :group 'org-faces)
4143 (defface org-ellipsis
4144 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4145 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4146 (t (:strike-through t)))
4147 "Face for the ellipsis in folded text."
4148 :group 'org-faces)
4150 (defface org-target
4151 '((((class color) (background light)) (:underline t))
4152 (((class color) (background dark)) (:underline t))
4153 (t (:underline t)))
4154 "Face for links."
4155 :group 'org-faces)
4157 (defface org-date
4158 '((((class color) (background light)) (:foreground "Purple" :underline t))
4159 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4160 (t (:underline t)))
4161 "Face for links."
4162 :group 'org-faces)
4164 (defface org-sexp-date
4165 '((((class color) (background light)) (:foreground "Purple"))
4166 (((class color) (background dark)) (:foreground "Cyan"))
4167 (t (:underline t)))
4168 "Face for links."
4169 :group 'org-faces)
4171 (defface org-tag
4172 '((t (:bold t)))
4173 "Face for tags."
4174 :group 'org-faces)
4176 (defface org-todo ; font-lock-warning-face
4177 (org-compatible-face nil
4178 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4179 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4180 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4181 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4182 (t (:inverse-video t :bold t))))
4183 "Face for TODO keywords."
4184 :group 'org-faces)
4186 (defface org-done ;; font-lock-type-face
4187 (org-compatible-face nil
4188 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4189 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4190 (((class color) (min-colors 8)) (:foreground "green"))
4191 (t (:bold t))))
4192 "Face used for todo keywords that indicate DONE items."
4193 :group 'org-faces)
4195 (defface org-headline-done ;; font-lock-string-face
4196 (org-compatible-face nil
4197 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4198 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4199 (((class color) (min-colors 8) (background light)) (:bold nil))))
4200 "Face used to indicate that a headline is DONE.
4201 This face is only used if `org-fontify-done-headline' is set. If applies
4202 to the part of the headline after the DONE keyword."
4203 :group 'org-faces)
4205 (defcustom org-todo-keyword-faces nil
4206 "Faces for specific TODO keywords.
4207 This is a list of cons cells, with TODO keywords in the car
4208 and faces in the cdr. The face can be a symbol, or a property
4209 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4210 :group 'org-faces
4211 :group 'org-todo
4212 :type '(repeat
4213 (cons
4214 (string :tag "keyword")
4215 (sexp :tag "face"))))
4217 (defface org-table ;; font-lock-function-name-face
4218 (org-compatible-face nil
4219 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4220 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4221 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4222 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4223 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4224 (((class color) (min-colors 8) (background dark)))))
4225 "Face used for tables."
4226 :group 'org-faces)
4228 (defface org-formula
4229 (org-compatible-face nil
4230 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4231 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4232 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4233 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4234 (t (:bold t :italic t))))
4235 "Face for formulas."
4236 :group 'org-faces)
4238 (defface org-code
4239 (org-compatible-face nil
4240 '((((class color grayscale) (min-colors 88) (background light))
4241 (:foreground "grey50"))
4242 (((class color grayscale) (min-colors 88) (background dark))
4243 (:foreground "grey70"))
4244 (((class color) (min-colors 8) (background light))
4245 (:foreground "green"))
4246 (((class color) (min-colors 8) (background dark))
4247 (:foreground "yellow"))))
4248 "Face for fixed-with text like code snippets."
4249 :group 'org-faces
4250 :version "22.1")
4252 (defface org-verbatim
4253 (org-compatible-face nil
4254 '((((class color grayscale) (min-colors 88) (background light))
4255 (:foreground "grey50" :underline t))
4256 (((class color grayscale) (min-colors 88) (background dark))
4257 (:foreground "grey70" :underline t))
4258 (((class color) (min-colors 8) (background light))
4259 (:foreground "green" :underline t))
4260 (((class color) (min-colors 8) (background dark))
4261 (:foreground "yellow" :underline t))))
4262 "Face for fixed-with text like code snippets."
4263 :group 'org-faces
4264 :version "22.1")
4266 (defface org-agenda-structure ;; font-lock-function-name-face
4267 (org-compatible-face nil
4268 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4269 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4270 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4271 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4272 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4273 (t (:bold t))))
4274 "Face used in agenda for captions and dates."
4275 :group 'org-faces)
4277 (defface org-scheduled-today
4278 (org-compatible-face nil
4279 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4280 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4281 (((class color) (min-colors 8)) (:foreground "green"))
4282 (t (:bold t :italic t))))
4283 "Face for items scheduled for a certain day."
4284 :group 'org-faces)
4286 (defface org-scheduled-previously
4287 (org-compatible-face nil
4288 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4289 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4290 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4291 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4292 (t (:bold t))))
4293 "Face for items scheduled previously, and not yet done."
4294 :group 'org-faces)
4296 (defface org-upcoming-deadline
4297 (org-compatible-face nil
4298 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4299 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4300 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4301 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4302 (t (:bold t))))
4303 "Face for items scheduled previously, and not yet done."
4304 :group 'org-faces)
4306 (defcustom org-agenda-deadline-faces
4307 '((1.0 . org-warning)
4308 (0.5 . org-upcoming-deadline)
4309 (0.0 . default))
4310 "Faces for showing deadlines in the agenda.
4311 This is a list of cons cells. The cdr of each cell is a face to be used,
4312 and it can also just be like '(:foreground \"yellow\").
4313 Each car is a fraction of the head-warning time that must have passed for
4314 this the face in the cdr to be used for display. The numbers must be
4315 given in descending order. The head-warning time is normally taken
4316 from `org-deadline-warning-days', but can also be specified in the deadline
4317 timestamp itself, like this:
4319 DEADLINE: <2007-08-13 Mon -8d>
4321 You may use d for days, w for weeks, m for months and y for years. Months
4322 and years will only be treated in an approximate fashion (30.4 days for a
4323 month and 365.24 days for a year)."
4324 :group 'org-faces
4325 :group 'org-agenda-daily/weekly
4326 :type '(repeat
4327 (cons
4328 (number :tag "Fraction of head-warning time passed")
4329 (sexp :tag "Face"))))
4331 ;; FIXME: this is not a good face yet.
4332 (defface org-agenda-restriction-lock
4333 (org-compatible-face nil
4334 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4335 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4336 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4337 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4338 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4339 (t (:inverse-video t))))
4340 "Face for showing the agenda restriction lock."
4341 :group 'org-faces)
4343 (defface org-time-grid ;; font-lock-variable-name-face
4344 (org-compatible-face nil
4345 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4346 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4347 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4348 "Face used for time grids."
4349 :group 'org-faces)
4351 (defconst org-level-faces
4352 '(org-level-1 org-level-2 org-level-3 org-level-4
4353 org-level-5 org-level-6 org-level-7 org-level-8
4356 (defcustom org-n-level-faces (length org-level-faces)
4357 "The number of different faces to be used for headlines.
4358 Org-mode defines 8 different headline faces, so this can be at most 8.
4359 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4360 :type 'number
4361 :group 'org-faces)
4363 ;;; Functions and variables from ther packages
4364 ;; Declared here to avoid compiler warnings
4366 (eval-and-compile
4367 (unless (fboundp 'declare-function)
4368 (defmacro declare-function (fn file &optional arglist fileonly))))
4370 ;; XEmacs only
4371 (defvar outline-mode-menu-heading)
4372 (defvar outline-mode-menu-show)
4373 (defvar outline-mode-menu-hide)
4374 (defvar zmacs-regions) ; XEmacs regions
4376 ;; Emacs only
4377 (defvar mark-active)
4379 ;; Various packages
4380 ;; FIXME: get the argument lists for the UNKNOWN stuff
4381 (declare-function add-to-diary-list "diary-lib"
4382 (date string specifier &optional marker globcolor literal))
4383 (declare-function table--at-cell-p "table" (position &optional object at-column))
4384 (declare-function bibtex-beginning-of-entry "bibtex" ())
4385 (declare-function bibtex-generate-autokey "bibtex" ())
4386 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4387 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4388 (defvar calc-embedded-close-formula)
4389 (defvar calc-embedded-open-formula)
4390 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4391 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4392 (declare-function calendar-check-holidays "holidays" (date))
4393 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4394 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4395 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4396 (declare-function calendar-forward-day "cal-move" (arg))
4397 (declare-function calendar-french-date-string "cal-french" (&optional date))
4398 (declare-function calendar-goto-date "cal-move" (date))
4399 (declare-function calendar-goto-today "cal-move" ())
4400 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4401 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4402 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4403 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4404 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4405 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4406 (defvar calendar-mode-map)
4407 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4408 (declare-function cdlatex-tab "ext:cdlatex" ())
4409 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4410 (defvar font-lock-unfontify-region-function)
4411 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4412 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4413 (declare-function parse-time-string "parse-time" (string))
4414 (declare-function remember "remember" (&optional initial))
4415 (declare-function remember-buffer-desc "remember" ())
4416 (declare-function remember-finalize "remember" ())
4417 (defvar remember-save-after-remembering)
4418 (defvar remember-data-file)
4419 (defvar remember-register)
4420 (defvar remember-buffer)
4421 (defvar remember-handler-functions)
4422 (defvar remember-annotation-functions)
4423 (defvar texmathp-why)
4424 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4426 (defvar w3m-current-url)
4427 (defvar w3m-current-title)
4429 (defvar org-latex-regexps)
4430 (defvar constants-unit-system)
4432 ;;; Variables for pre-computed regular expressions, all buffer local
4434 (defvar org-drawer-regexp nil
4435 "Matches first line of a hidden block.")
4436 (make-variable-buffer-local 'org-drawer-regexp)
4437 (defvar org-todo-regexp nil
4438 "Matches any of the TODO state keywords.")
4439 (make-variable-buffer-local 'org-todo-regexp)
4440 (defvar org-not-done-regexp nil
4441 "Matches any of the TODO state keywords except the last one.")
4442 (make-variable-buffer-local 'org-not-done-regexp)
4443 (defvar org-todo-line-regexp nil
4444 "Matches a headline and puts TODO state into group 2 if present.")
4445 (make-variable-buffer-local 'org-todo-line-regexp)
4446 (defvar org-complex-heading-regexp nil
4447 "Matches a headline and puts everything into groups:
4448 group 1: the stars
4449 group 2: The todo keyword, maybe
4450 group 3: Priority cookie
4451 group 4: True headline
4452 group 5: Tags")
4453 (make-variable-buffer-local 'org-complex-heading-regexp)
4454 (defvar org-todo-line-tags-regexp nil
4455 "Matches a headline and puts TODO state into group 2 if present.
4456 Also put tags into group 4 if tags are present.")
4457 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4458 (defvar org-nl-done-regexp nil
4459 "Matches newline followed by a headline with the DONE keyword.")
4460 (make-variable-buffer-local 'org-nl-done-regexp)
4461 (defvar org-looking-at-done-regexp nil
4462 "Matches the DONE keyword a point.")
4463 (make-variable-buffer-local 'org-looking-at-done-regexp)
4464 (defvar org-ds-keyword-length 12
4465 "Maximum length of the Deadline and SCHEDULED keywords.")
4466 (make-variable-buffer-local 'org-ds-keyword-length)
4467 (defvar org-deadline-regexp nil
4468 "Matches the DEADLINE keyword.")
4469 (make-variable-buffer-local 'org-deadline-regexp)
4470 (defvar org-deadline-time-regexp nil
4471 "Matches the DEADLINE keyword together with a time stamp.")
4472 (make-variable-buffer-local 'org-deadline-time-regexp)
4473 (defvar org-deadline-line-regexp nil
4474 "Matches the DEADLINE keyword and the rest of the line.")
4475 (make-variable-buffer-local 'org-deadline-line-regexp)
4476 (defvar org-scheduled-regexp nil
4477 "Matches the SCHEDULED keyword.")
4478 (make-variable-buffer-local 'org-scheduled-regexp)
4479 (defvar org-scheduled-time-regexp nil
4480 "Matches the SCHEDULED keyword together with a time stamp.")
4481 (make-variable-buffer-local 'org-scheduled-time-regexp)
4482 (defvar org-closed-time-regexp nil
4483 "Matches the CLOSED keyword together with a time stamp.")
4484 (make-variable-buffer-local 'org-closed-time-regexp)
4486 (defvar org-keyword-time-regexp nil
4487 "Matches any of the 4 keywords, together with the time stamp.")
4488 (make-variable-buffer-local 'org-keyword-time-regexp)
4489 (defvar org-keyword-time-not-clock-regexp nil
4490 "Matches any of the 3 keywords, together with the time stamp.")
4491 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4492 (defvar org-maybe-keyword-time-regexp nil
4493 "Matches a timestamp, possibly preceeded by a keyword.")
4494 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4495 (defvar org-planning-or-clock-line-re nil
4496 "Matches a line with planning or clock info.")
4497 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4499 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4500 rear-nonsticky t mouse-map t fontified t)
4501 "Properties to remove when a string without properties is wanted.")
4503 (defsubst org-match-string-no-properties (num &optional string)
4504 (if (featurep 'xemacs)
4505 (let ((s (match-string num string)))
4506 (remove-text-properties 0 (length s) org-rm-props s)
4508 (match-string-no-properties num string)))
4510 (defsubst org-no-properties (s)
4511 (if (fboundp 'set-text-properties)
4512 (set-text-properties 0 (length s) nil s)
4513 (remove-text-properties 0 (length s) org-rm-props s))
4516 (defsubst org-get-alist-option (option key)
4517 (cond ((eq key t) t)
4518 ((eq option t) t)
4519 ((assoc key option) (cdr (assoc key option)))
4520 (t (cdr (assq 'default option)))))
4522 (defsubst org-inhibit-invisibility ()
4523 "Modified `buffer-invisibility-spec' for Emacs 21.
4524 Some ops with invisible text do not work correctly on Emacs 21. For these
4525 we turn off invisibility temporarily. Use this in a `let' form."
4526 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4528 (defsubst org-set-local (var value)
4529 "Make VAR local in current buffer and set it to VALUE."
4530 (set (make-variable-buffer-local var) value))
4532 (defsubst org-mode-p ()
4533 "Check if the current buffer is in Org-mode."
4534 (eq major-mode 'org-mode))
4536 (defsubst org-last (list)
4537 "Return the last element of LIST."
4538 (car (last list)))
4540 (defun org-let (list &rest body)
4541 (eval (cons 'let (cons list body))))
4542 (put 'org-let 'lisp-indent-function 1)
4544 (defun org-let2 (list1 list2 &rest body)
4545 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4546 (put 'org-let2 'lisp-indent-function 2)
4547 (defconst org-startup-options
4548 '(("fold" org-startup-folded t)
4549 ("overview" org-startup-folded t)
4550 ("nofold" org-startup-folded nil)
4551 ("showall" org-startup-folded nil)
4552 ("content" org-startup-folded content)
4553 ("hidestars" org-hide-leading-stars t)
4554 ("showstars" org-hide-leading-stars nil)
4555 ("odd" org-odd-levels-only t)
4556 ("oddeven" org-odd-levels-only nil)
4557 ("align" org-startup-align-all-tables t)
4558 ("noalign" org-startup-align-all-tables nil)
4559 ("customtime" org-display-custom-times t)
4560 ("logdone" org-log-done time)
4561 ("lognotedone" org-log-done note)
4562 ("nologdone" org-log-done nil)
4563 ("lognoteclock-out" org-log-note-clock-out t)
4564 ("nolognoteclock-out" org-log-note-clock-out nil)
4565 ("logrepeat" org-log-repeat state)
4566 ("lognoterepeat" org-log-repeat note)
4567 ("nologrepeat" org-log-repeat nil)
4568 ("constcgs" constants-unit-system cgs)
4569 ("constSI" constants-unit-system SI))
4570 "Variable associated with STARTUP options for org-mode.
4571 Each element is a list of three items: The startup options as written
4572 in the #+STARTUP line, the corresponding variable, and the value to
4573 set this variable to if the option is found. An optional forth element PUSH
4574 means to push this value onto the list in the variable.")
4576 (defun org-set-regexps-and-options ()
4577 "Precompute regular expressions for current buffer."
4578 (when (org-mode-p)
4579 (org-set-local 'org-todo-kwd-alist nil)
4580 (org-set-local 'org-todo-key-alist nil)
4581 (org-set-local 'org-todo-key-trigger nil)
4582 (org-set-local 'org-todo-keywords-1 nil)
4583 (org-set-local 'org-done-keywords nil)
4584 (org-set-local 'org-todo-heads nil)
4585 (org-set-local 'org-todo-sets nil)
4586 (org-set-local 'org-todo-log-states nil)
4587 (let ((re (org-make-options-regexp
4588 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4589 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4590 "CONSTANTS" "PROPERTY" "DRAWERS")))
4591 (splitre "[ \t]+")
4592 kwds kws0 kwsa key log value cat arch tags const links hw dws
4593 tail sep kws1 prio props drawers)
4594 (save-excursion
4595 (save-restriction
4596 (widen)
4597 (goto-char (point-min))
4598 (while (re-search-forward re nil t)
4599 (setq key (match-string 1) value (org-match-string-no-properties 2))
4600 (cond
4601 ((equal key "CATEGORY")
4602 (if (string-match "[ \t]+$" value)
4603 (setq value (replace-match "" t t value)))
4604 (setq cat value))
4605 ((member key '("SEQ_TODO" "TODO"))
4606 (push (cons 'sequence (org-split-string value splitre)) kwds))
4607 ((equal key "TYP_TODO")
4608 (push (cons 'type (org-split-string value splitre)) kwds))
4609 ((equal key "TAGS")
4610 (setq tags (append tags (org-split-string value splitre))))
4611 ((equal key "COLUMNS")
4612 (org-set-local 'org-columns-default-format value))
4613 ((equal key "LINK")
4614 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4615 (push (cons (match-string 1 value)
4616 (org-trim (match-string 2 value)))
4617 links)))
4618 ((equal key "PRIORITIES")
4619 (setq prio (org-split-string value " +")))
4620 ((equal key "PROPERTY")
4621 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4622 (push (cons (match-string 1 value) (match-string 2 value))
4623 props)))
4624 ((equal key "DRAWERS")
4625 (setq drawers (org-split-string value splitre)))
4626 ((equal key "CONSTANTS")
4627 (setq const (append const (org-split-string value splitre))))
4628 ((equal key "STARTUP")
4629 (let ((opts (org-split-string value splitre))
4630 l var val)
4631 (while (setq l (pop opts))
4632 (when (setq l (assoc l org-startup-options))
4633 (setq var (nth 1 l) val (nth 2 l))
4634 (if (not (nth 3 l))
4635 (set (make-local-variable var) val)
4636 (if (not (listp (symbol-value var)))
4637 (set (make-local-variable var) nil))
4638 (set (make-local-variable var) (symbol-value var))
4639 (add-to-list var val))))))
4640 ((equal key "ARCHIVE")
4641 (string-match " *$" value)
4642 (setq arch (replace-match "" t t value))
4643 (remove-text-properties 0 (length arch)
4644 '(face t fontified t) arch)))
4646 (when cat
4647 (org-set-local 'org-category (intern cat))
4648 (push (cons "CATEGORY" cat) props))
4649 (when prio
4650 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4651 (setq prio (mapcar 'string-to-char prio))
4652 (org-set-local 'org-highest-priority (nth 0 prio))
4653 (org-set-local 'org-lowest-priority (nth 1 prio))
4654 (org-set-local 'org-default-priority (nth 2 prio)))
4655 (and props (org-set-local 'org-local-properties (nreverse props)))
4656 (and drawers (org-set-local 'org-drawers drawers))
4657 (and arch (org-set-local 'org-archive-location arch))
4658 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4659 ;; Process the TODO keywords
4660 (unless kwds
4661 ;; Use the global values as if they had been given locally.
4662 (setq kwds (default-value 'org-todo-keywords))
4663 (if (stringp (car kwds))
4664 (setq kwds (list (cons org-todo-interpretation
4665 (default-value 'org-todo-keywords)))))
4666 (setq kwds (reverse kwds)))
4667 (setq kwds (nreverse kwds))
4668 (let (inter kws kw)
4669 (while (setq kws (pop kwds))
4670 (setq inter (pop kws) sep (member "|" kws)
4671 kws0 (delete "|" (copy-sequence kws))
4672 kwsa nil
4673 kws1 (mapcar
4674 (lambda (x)
4675 ;; 1 2
4676 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4677 (progn
4678 (setq kw (match-string 1 x)
4679 key (and (match-end 2) (match-string 2 x))
4680 log (org-extract-log-state-settings x))
4681 (push (cons kw (and key (string-to-char key))) kwsa)
4682 (and log (push log org-todo-log-states))
4684 (error "Invalid TODO keyword %s" x)))
4685 kws0)
4686 kwsa (if kwsa (append '((:startgroup))
4687 (nreverse kwsa)
4688 '((:endgroup))))
4689 hw (car kws1)
4690 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4691 tail (list inter hw (car dws) (org-last dws)))
4692 (add-to-list 'org-todo-heads hw 'append)
4693 (push kws1 org-todo-sets)
4694 (setq org-done-keywords (append org-done-keywords dws nil))
4695 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4696 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4697 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4698 (setq org-todo-sets (nreverse org-todo-sets)
4699 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4700 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4701 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4702 ;; Process the constants
4703 (when const
4704 (let (e cst)
4705 (while (setq e (pop const))
4706 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4707 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4708 (setq org-table-formula-constants-local cst)))
4710 ;; Process the tags.
4711 (when tags
4712 (let (e tgs)
4713 (while (setq e (pop tags))
4714 (cond
4715 ((equal e "{") (push '(:startgroup) tgs))
4716 ((equal e "}") (push '(:endgroup) tgs))
4717 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4718 (push (cons (match-string 1 e)
4719 (string-to-char (match-string 2 e)))
4720 tgs))
4721 (t (push (list e) tgs))))
4722 (org-set-local 'org-tag-alist nil)
4723 (while (setq e (pop tgs))
4724 (or (and (stringp (car e))
4725 (assoc (car e) org-tag-alist))
4726 (push e org-tag-alist))))))
4728 ;; Compute the regular expressions and other local variables
4729 (if (not org-done-keywords)
4730 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4731 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4732 (length org-scheduled-string)))
4733 org-drawer-regexp
4734 (concat "^[ \t]*:\\("
4735 (mapconcat 'regexp-quote org-drawers "\\|")
4736 "\\):[ \t]*$")
4737 org-not-done-keywords
4738 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4739 org-todo-regexp
4740 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4741 "\\|") "\\)\\>")
4742 org-not-done-regexp
4743 (concat "\\<\\("
4744 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4745 "\\)\\>")
4746 org-todo-line-regexp
4747 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4748 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4749 "\\)\\>\\)?[ \t]*\\(.*\\)")
4750 org-complex-heading-regexp
4751 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4752 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4753 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4754 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4755 org-nl-done-regexp
4756 (concat "\n\\*+[ \t]+"
4757 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4758 "\\)" "\\>")
4759 org-todo-line-tags-regexp
4760 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4761 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4762 (org-re
4763 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4764 org-looking-at-done-regexp
4765 (concat "^" "\\(?:"
4766 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4767 "\\>")
4768 org-deadline-regexp (concat "\\<" org-deadline-string)
4769 org-deadline-time-regexp
4770 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4771 org-deadline-line-regexp
4772 (concat "\\<\\(" org-deadline-string "\\).*")
4773 org-scheduled-regexp
4774 (concat "\\<" org-scheduled-string)
4775 org-scheduled-time-regexp
4776 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4777 org-closed-time-regexp
4778 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4779 org-keyword-time-regexp
4780 (concat "\\<\\(" org-scheduled-string
4781 "\\|" org-deadline-string
4782 "\\|" org-closed-string
4783 "\\|" org-clock-string "\\)"
4784 " *[[<]\\([^]>]+\\)[]>]")
4785 org-keyword-time-not-clock-regexp
4786 (concat "\\<\\(" org-scheduled-string
4787 "\\|" org-deadline-string
4788 "\\|" org-closed-string
4789 "\\)"
4790 " *[[<]\\([^]>]+\\)[]>]")
4791 org-maybe-keyword-time-regexp
4792 (concat "\\(\\<\\(" org-scheduled-string
4793 "\\|" org-deadline-string
4794 "\\|" org-closed-string
4795 "\\|" org-clock-string "\\)\\)?"
4796 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4797 org-planning-or-clock-line-re
4798 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4799 "\\|" org-deadline-string
4800 "\\|" org-closed-string "\\|" org-clock-string
4801 "\\)\\>\\)")
4803 (org-compute-latex-and-specials-regexp)
4804 (org-set-font-lock-defaults)))
4806 (defun org-extract-log-state-settings (x)
4807 "Extract the log state setting from a TODO keyword string.
4808 This will extract info from a string like \"WAIT(w@/!)\"."
4809 (let (kw key log1 log2)
4810 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4811 (setq kw (match-string 1 x)
4812 key (and (match-end 2) (match-string 2 x))
4813 log1 (and (match-end 3) (match-string 3 x))
4814 log2 (and (match-end 4) (match-string 4 x)))
4815 (and (or log1 log2)
4816 (list kw
4817 (and log1 (if (equal log1 "!") 'time 'note))
4818 (and log2 (if (equal log2 "!") 'time 'note)))))))
4820 (defun org-remove-keyword-keys (list)
4821 "Remove a pair of parenthesis at the end of each string in LIST."
4822 (mapcar (lambda (x)
4823 (if (string-match "(.*)$" x)
4824 (substring x 0 (match-beginning 0))
4826 list))
4828 ;; FIXME: this could be done much better, using second characters etc.
4829 (defun org-assign-fast-keys (alist)
4830 "Assign fast keys to a keyword-key alist.
4831 Respect keys that are already there."
4832 (let (new e k c c1 c2 (char ?a))
4833 (while (setq e (pop alist))
4834 (cond
4835 ((equal e '(:startgroup)) (push e new))
4836 ((equal e '(:endgroup)) (push e new))
4838 (setq k (car e) c2 nil)
4839 (if (cdr e)
4840 (setq c (cdr e))
4841 ;; automatically assign a character.
4842 (setq c1 (string-to-char
4843 (downcase (substring
4844 k (if (= (string-to-char k) ?@) 1 0)))))
4845 (if (or (rassoc c1 new) (rassoc c1 alist))
4846 (while (or (rassoc char new) (rassoc char alist))
4847 (setq char (1+ char)))
4848 (setq c2 c1))
4849 (setq c (or c2 char)))
4850 (push (cons k c) new))))
4851 (nreverse new)))
4853 ;;; Some variables ujsed in various places
4855 (defvar org-window-configuration nil
4856 "Used in various places to store a window configuration.")
4857 (defvar org-finish-function nil
4858 "Function to be called when `C-c C-c' is used.
4859 This is for getting out of special buffers like remember.")
4862 ;; FIXME: Occasionally check by commenting these, to make sure
4863 ;; no other functions uses these, forgetting to let-bind them.
4864 (defvar entry)
4865 (defvar state)
4866 (defvar last-state)
4867 (defvar date)
4868 (defvar description)
4870 ;; Defined somewhere in this file, but used before definition.
4871 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4872 (defvar org-agenda-buffer-name)
4873 (defvar org-agenda-undo-list)
4874 (defvar org-agenda-pending-undo-list)
4875 (defvar org-agenda-overriding-header)
4876 (defvar orgtbl-mode)
4877 (defvar org-html-entities)
4878 (defvar org-struct-menu)
4879 (defvar org-org-menu)
4880 (defvar org-tbl-menu)
4881 (defvar org-agenda-keymap)
4883 ;;;; Emacs/XEmacs compatibility
4885 ;; Overlay compatibility functions
4886 (defun org-make-overlay (beg end &optional buffer)
4887 (if (featurep 'xemacs)
4888 (make-extent beg end buffer)
4889 (make-overlay beg end buffer)))
4890 (defun org-delete-overlay (ovl)
4891 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4892 (defun org-detach-overlay (ovl)
4893 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4894 (defun org-move-overlay (ovl beg end &optional buffer)
4895 (if (featurep 'xemacs)
4896 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4897 (move-overlay ovl beg end buffer)))
4898 (defun org-overlay-put (ovl prop value)
4899 (if (featurep 'xemacs)
4900 (set-extent-property ovl prop value)
4901 (overlay-put ovl prop value)))
4902 (defun org-overlay-display (ovl text &optional face evap)
4903 "Make overlay OVL display TEXT with face FACE."
4904 (if (featurep 'xemacs)
4905 (let ((gl (make-glyph text)))
4906 (and face (set-glyph-face gl face))
4907 (set-extent-property ovl 'invisible t)
4908 (set-extent-property ovl 'end-glyph gl))
4909 (overlay-put ovl 'display text)
4910 (if face (overlay-put ovl 'face face))
4911 (if evap (overlay-put ovl 'evaporate t))))
4912 (defun org-overlay-before-string (ovl text &optional face evap)
4913 "Make overlay OVL display TEXT with face FACE."
4914 (if (featurep 'xemacs)
4915 (let ((gl (make-glyph text)))
4916 (and face (set-glyph-face gl face))
4917 (set-extent-property ovl 'begin-glyph gl))
4918 (if face (org-add-props text nil 'face face))
4919 (overlay-put ovl 'before-string text)
4920 (if evap (overlay-put ovl 'evaporate t))))
4921 (defun org-overlay-get (ovl prop)
4922 (if (featurep 'xemacs)
4923 (extent-property ovl prop)
4924 (overlay-get ovl prop)))
4925 (defun org-overlays-at (pos)
4926 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4927 (defun org-overlays-in (&optional start end)
4928 (if (featurep 'xemacs)
4929 (extent-list nil start end)
4930 (overlays-in start end)))
4931 (defun org-overlay-start (o)
4932 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4933 (defun org-overlay-end (o)
4934 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4935 (defun org-find-overlays (prop &optional pos delete)
4936 "Find all overlays specifying PROP at POS or point.
4937 If DELETE is non-nil, delete all those overlays."
4938 (let ((overlays (org-overlays-at (or pos (point))))
4939 ov found)
4940 (while (setq ov (pop overlays))
4941 (if (org-overlay-get ov prop)
4942 (if delete (org-delete-overlay ov) (push ov found))))
4943 found))
4945 ;; Region compatibility
4947 (defun org-add-hook (hook function &optional append local)
4948 "Add-hook, compatible with both Emacsen."
4949 (if (and local (featurep 'xemacs))
4950 (add-local-hook hook function append)
4951 (add-hook hook function append local)))
4953 (defvar org-ignore-region nil
4954 "To temporarily disable the active region.")
4956 (defun org-region-active-p ()
4957 "Is `transient-mark-mode' on and the region active?
4958 Works on both Emacs and XEmacs."
4959 (if org-ignore-region
4961 (if (featurep 'xemacs)
4962 (and zmacs-regions (region-active-p))
4963 (if (fboundp 'use-region-p)
4964 (use-region-p)
4965 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4967 ;; Invisibility compatibility
4969 (defun org-add-to-invisibility-spec (arg)
4970 "Add elements to `buffer-invisibility-spec'.
4971 See documentation for `buffer-invisibility-spec' for the kind of elements
4972 that can be added."
4973 (cond
4974 ((fboundp 'add-to-invisibility-spec)
4975 (add-to-invisibility-spec arg))
4976 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4977 (setq buffer-invisibility-spec (list arg)))
4979 (setq buffer-invisibility-spec
4980 (cons arg buffer-invisibility-spec)))))
4982 (defun org-remove-from-invisibility-spec (arg)
4983 "Remove elements from `buffer-invisibility-spec'."
4984 (if (fboundp 'remove-from-invisibility-spec)
4985 (remove-from-invisibility-spec arg)
4986 (if (consp buffer-invisibility-spec)
4987 (setq buffer-invisibility-spec
4988 (delete arg buffer-invisibility-spec)))))
4990 (defun org-in-invisibility-spec-p (arg)
4991 "Is ARG a member of `buffer-invisibility-spec'?"
4992 (if (consp buffer-invisibility-spec)
4993 (member arg buffer-invisibility-spec)
4994 nil))
4996 ;;;; Define the Org-mode
4998 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4999 (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."))
5002 ;; We use a before-change function to check if a table might need
5003 ;; an update.
5004 (defvar org-table-may-need-update t
5005 "Indicates that a table might need an update.
5006 This variable is set by `org-before-change-function'.
5007 `org-table-align' sets it back to nil.")
5008 (defvar org-mode-map)
5009 (defvar org-mode-hook nil)
5010 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5011 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5012 (defvar org-table-buffer-is-an nil)
5013 (defconst org-outline-regexp "\\*+ ")
5015 ;;;###autoload
5016 (define-derived-mode org-mode outline-mode "Org"
5017 "Outline-based notes management and organizer, alias
5018 \"Carsten's outline-mode for keeping track of everything.\"
5020 Org-mode develops organizational tasks around a NOTES file which
5021 contains information about projects as plain text. Org-mode is
5022 implemented on top of outline-mode, which is ideal to keep the content
5023 of large files well structured. It supports ToDo items, deadlines and
5024 time stamps, which magically appear in the diary listing of the Emacs
5025 calendar. Tables are easily created with a built-in table editor.
5026 Plain text URL-like links connect to websites, emails (VM), Usenet
5027 messages (Gnus), BBDB entries, and any files related to the project.
5028 For printing and sharing of notes, an Org-mode file (or a part of it)
5029 can be exported as a structured ASCII or HTML file.
5031 The following commands are available:
5033 \\{org-mode-map}"
5035 ;; Get rid of Outline menus, they are not needed
5036 ;; Need to do this here because define-derived-mode sets up
5037 ;; the keymap so late. Still, it is a waste to call this each time
5038 ;; we switch another buffer into org-mode.
5039 (if (featurep 'xemacs)
5040 (when (boundp 'outline-mode-menu-heading)
5041 ;; Assume this is Greg's port, it used easymenu
5042 (easy-menu-remove outline-mode-menu-heading)
5043 (easy-menu-remove outline-mode-menu-show)
5044 (easy-menu-remove outline-mode-menu-hide))
5045 (define-key org-mode-map [menu-bar headings] 'undefined)
5046 (define-key org-mode-map [menu-bar hide] 'undefined)
5047 (define-key org-mode-map [menu-bar show] 'undefined))
5049 (org-load-modules-maybe)
5050 (easy-menu-add org-org-menu)
5051 (easy-menu-add org-tbl-menu)
5052 (org-install-agenda-files-menu)
5053 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5054 (org-add-to-invisibility-spec '(org-cwidth))
5055 (when (featurep 'xemacs)
5056 (org-set-local 'line-move-ignore-invisible t))
5057 (org-set-local 'outline-regexp org-outline-regexp)
5058 (org-set-local 'outline-level 'org-outline-level)
5059 (when (and org-ellipsis
5060 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5061 (fboundp 'make-glyph-code))
5062 (unless org-display-table
5063 (setq org-display-table (make-display-table)))
5064 (set-display-table-slot
5065 org-display-table 4
5066 (vconcat (mapcar
5067 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5068 org-ellipsis)))
5069 (if (stringp org-ellipsis) org-ellipsis "..."))))
5070 (setq buffer-display-table org-display-table))
5071 (org-set-regexps-and-options)
5072 ;; Calc embedded
5073 (org-set-local 'calc-embedded-open-mode "# ")
5074 (modify-syntax-entry ?# "<")
5075 (modify-syntax-entry ?@ "w")
5076 (if org-startup-truncated (setq truncate-lines t))
5077 (org-set-local 'font-lock-unfontify-region-function
5078 'org-unfontify-region)
5079 ;; Activate before-change-function
5080 (org-set-local 'org-table-may-need-update t)
5081 (org-add-hook 'before-change-functions 'org-before-change-function nil
5082 'local)
5083 ;; Check for running clock before killing a buffer
5084 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5085 ;; Paragraphs and auto-filling
5086 (org-set-autofill-regexps)
5087 (setq indent-line-function 'org-indent-line-function)
5088 (org-update-radio-target-regexp)
5090 ;; Comment characters
5091 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5092 (org-set-local 'comment-padding " ")
5094 ;; Align options lines
5095 (org-set-local
5096 'align-mode-rules-list
5097 '((org-in-buffer-settings
5098 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5099 (modes . '(org-mode)))))
5101 ;; Imenu
5102 (org-set-local 'imenu-create-index-function
5103 'org-imenu-get-tree)
5105 ;; Make isearch reveal context
5106 (if (or (featurep 'xemacs)
5107 (not (boundp 'outline-isearch-open-invisible-function)))
5108 ;; Emacs 21 and XEmacs make use of the hook
5109 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5110 ;; Emacs 22 deals with this through a special variable
5111 (org-set-local 'outline-isearch-open-invisible-function
5112 (lambda (&rest ignore) (org-show-context 'isearch))))
5114 ;; If empty file that did not turn on org-mode automatically, make it to.
5115 (if (and org-insert-mode-line-in-empty-file
5116 (interactive-p)
5117 (= (point-min) (point-max)))
5118 (insert "# -*- mode: org -*-\n\n"))
5120 (unless org-inhibit-startup
5121 (when org-startup-align-all-tables
5122 (let ((bmp (buffer-modified-p)))
5123 (org-table-map-tables 'org-table-align)
5124 (set-buffer-modified-p bmp)))
5125 (org-cycle-hide-drawers 'all)
5126 (cond
5127 ((eq org-startup-folded t)
5128 (org-cycle '(4)))
5129 ((eq org-startup-folded 'content)
5130 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5131 (org-cycle '(4)) (org-cycle '(4)))))))
5133 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5135 (defsubst org-call-with-arg (command arg)
5136 "Call COMMAND interactively, but pretend prefix are was ARG."
5137 (let ((current-prefix-arg arg)) (call-interactively command)))
5139 (defsubst org-current-line (&optional pos)
5140 (save-excursion
5141 (and pos (goto-char pos))
5142 ;; works also in narrowed buffer, because we start at 1, not point-min
5143 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5145 (defun org-current-time ()
5146 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5147 (if (> (car org-time-stamp-rounding-minutes) 1)
5148 (let ((r (car org-time-stamp-rounding-minutes))
5149 (time (decode-time)))
5150 (apply 'encode-time
5151 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5152 (nthcdr 2 time))))
5153 (current-time)))
5155 (defun org-add-props (string plist &rest props)
5156 "Add text properties to entire string, from beginning to end.
5157 PLIST may be a list of properties, PROPS are individual properties and values
5158 that will be added to PLIST. Returns the string that was modified."
5159 (add-text-properties
5160 0 (length string) (if props (append plist props) plist) string)
5161 string)
5162 (put 'org-add-props 'lisp-indent-function 2)
5165 ;;;; Font-Lock stuff, including the activators
5167 (defvar org-mouse-map (make-sparse-keymap))
5168 (org-defkey org-mouse-map
5169 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5170 (org-defkey org-mouse-map
5171 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5172 (when org-mouse-1-follows-link
5173 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5174 (when org-tab-follows-link
5175 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5176 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5177 (when org-return-follows-link
5178 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5179 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5181 (require 'font-lock)
5183 (defconst org-non-link-chars "]\t\n\r<>")
5184 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
5185 "shell" "elisp"))
5186 (defvar org-link-re-with-space nil
5187 "Matches a link with spaces, optional angular brackets around it.")
5188 (defvar org-link-re-with-space2 nil
5189 "Matches a link with spaces, optional angular brackets around it.")
5190 (defvar org-angle-link-re nil
5191 "Matches link with angular brackets, spaces are allowed.")
5192 (defvar org-plain-link-re nil
5193 "Matches plain link, without spaces.")
5194 (defvar org-bracket-link-regexp nil
5195 "Matches a link in double brackets.")
5196 (defvar org-bracket-link-analytic-regexp nil
5197 "Regular expression used to analyze links.
5198 Here is what the match groups contain after a match:
5199 1: http:
5200 2: http
5201 3: path
5202 4: [desc]
5203 5: desc")
5204 (defvar org-any-link-re nil
5205 "Regular expression matching any link.")
5207 (defun org-make-link-regexps ()
5208 "Update the link regular expressions.
5209 This should be called after the variable `org-link-types' has changed."
5210 (setq org-link-re-with-space
5211 (concat
5212 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5213 "\\([^" org-non-link-chars " ]"
5214 "[^" org-non-link-chars "]*"
5215 "[^" org-non-link-chars " ]\\)>?")
5216 org-link-re-with-space2
5217 (concat
5218 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5219 "\\([^" org-non-link-chars " ]"
5220 "[^]\t\n\r]*"
5221 "[^" org-non-link-chars " ]\\)>?")
5222 org-angle-link-re
5223 (concat
5224 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5225 "\\([^" org-non-link-chars " ]"
5226 "[^" org-non-link-chars "]*"
5227 "\\)>")
5228 org-plain-link-re
5229 (concat
5230 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5231 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5232 org-bracket-link-regexp
5233 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5234 org-bracket-link-analytic-regexp
5235 (concat
5236 "\\[\\["
5237 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5238 "\\([^]]+\\)"
5239 "\\]"
5240 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5241 "\\]")
5242 org-any-link-re
5243 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5244 org-angle-link-re "\\)\\|\\("
5245 org-plain-link-re "\\)")))
5247 (org-make-link-regexps)
5249 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5250 "Regular expression for fast time stamp matching.")
5251 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5252 "Regular expression for fast time stamp matching.")
5253 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5254 "Regular expression matching time strings for analysis.
5255 This one does not require the space after the date, so it can be used
5256 on a string that terminates immediately after the date.")
5257 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5258 "Regular expression matching time strings for analysis.")
5259 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5260 "Regular expression matching time stamps, with groups.")
5261 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5262 "Regular expression matching time stamps (also [..]), with groups.")
5263 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5264 "Regular expression matching a time stamp range.")
5265 (defconst org-tr-regexp-both
5266 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5267 "Regular expression matching a time stamp range.")
5268 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5269 org-ts-regexp "\\)?")
5270 "Regular expression matching a time stamp or time stamp range.")
5271 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5272 org-ts-regexp-both "\\)?")
5273 "Regular expression matching a time stamp or time stamp range.
5274 The time stamps may be either active or inactive.")
5276 (defvar org-emph-face nil)
5278 (defun org-do-emphasis-faces (limit)
5279 "Run through the buffer and add overlays to links."
5280 (let (rtn)
5281 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5282 (if (not (= (char-after (match-beginning 3))
5283 (char-after (match-beginning 4))))
5284 (progn
5285 (setq rtn t)
5286 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5287 'face
5288 (nth 1 (assoc (match-string 3)
5289 org-emphasis-alist)))
5290 (add-text-properties (match-beginning 2) (match-end 2)
5291 '(font-lock-multiline t))
5292 (when org-hide-emphasis-markers
5293 (add-text-properties (match-end 4) (match-beginning 5)
5294 '(invisible org-link))
5295 (add-text-properties (match-beginning 3) (match-end 3)
5296 '(invisible org-link)))))
5297 (backward-char 1))
5298 rtn))
5300 (defun org-emphasize (&optional char)
5301 "Insert or change an emphasis, i.e. a font like bold or italic.
5302 If there is an active region, change that region to a new emphasis.
5303 If there is no region, just insert the marker characters and position
5304 the cursor between them.
5305 CHAR should be either the marker character, or the first character of the
5306 HTML tag associated with that emphasis. If CHAR is a space, the means
5307 to remove the emphasis of the selected region.
5308 If char is not given (for example in an interactive call) it
5309 will be prompted for."
5310 (interactive)
5311 (let ((eal org-emphasis-alist) e det
5312 (erc org-emphasis-regexp-components)
5313 (prompt "")
5314 (string "") beg end move tag c s)
5315 (if (org-region-active-p)
5316 (setq beg (region-beginning) end (region-end)
5317 string (buffer-substring beg end))
5318 (setq move t))
5320 (while (setq e (pop eal))
5321 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5322 c (aref tag 0))
5323 (push (cons c (string-to-char (car e))) det)
5324 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5325 (substring tag 1)))))
5326 (unless char
5327 (message "%s" (concat "Emphasis marker or tag:" prompt))
5328 (setq char (read-char-exclusive)))
5329 (setq char (or (cdr (assoc char det)) char))
5330 (if (equal char ?\ )
5331 (setq s "" move nil)
5332 (unless (assoc (char-to-string char) org-emphasis-alist)
5333 (error "No such emphasis marker: \"%c\"" char))
5334 (setq s (char-to-string char)))
5335 (while (and (> (length string) 1)
5336 (equal (substring string 0 1) (substring string -1))
5337 (assoc (substring string 0 1) org-emphasis-alist))
5338 (setq string (substring string 1 -1)))
5339 (setq string (concat s string s))
5340 (if beg (delete-region beg end))
5341 (unless (or (bolp)
5342 (string-match (concat "[" (nth 0 erc) "\n]")
5343 (char-to-string (char-before (point)))))
5344 (insert " "))
5345 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5346 (char-to-string (char-after (point))))
5347 (insert " ") (backward-char 1))
5348 (insert string)
5349 (and move (backward-char 1))))
5351 (defconst org-nonsticky-props
5352 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5355 (defun org-activate-plain-links (limit)
5356 "Run through the buffer and add overlays to links."
5357 (catch 'exit
5358 (let (f)
5359 (while (re-search-forward org-plain-link-re limit t)
5360 (setq f (get-text-property (match-beginning 0) 'face))
5361 (if (or (eq f 'org-tag)
5362 (and (listp f) (memq 'org-tag f)))
5364 (add-text-properties (match-beginning 0) (match-end 0)
5365 (list 'mouse-face 'highlight
5366 'rear-nonsticky org-nonsticky-props
5367 'keymap org-mouse-map
5369 (throw 'exit t))))))
5371 (defun org-activate-code (limit)
5372 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5373 (unless (get-text-property (match-beginning 1) 'face)
5374 (remove-text-properties (match-beginning 0) (match-end 0)
5375 '(display t invisible t intangible t))
5376 t)))
5378 (defun org-activate-angle-links (limit)
5379 "Run through the buffer and add overlays to links."
5380 (if (re-search-forward org-angle-link-re limit t)
5381 (progn
5382 (add-text-properties (match-beginning 0) (match-end 0)
5383 (list 'mouse-face 'highlight
5384 'rear-nonsticky org-nonsticky-props
5385 'keymap org-mouse-map
5387 t)))
5389 (defmacro org-maybe-intangible (props)
5390 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5391 In emacs 21, invisible text is not avoided by the command loop, so the
5392 intangible property is needed to make sure point skips this text.
5393 In Emacs 22, this is not necessary. The intangible text property has
5394 led to problems with flyspell. These problems are fixed in flyspell.el,
5395 but we still avoid setting the property in Emacs 22 and later.
5396 We use a macro so that the test can happen at compilation time."
5397 (if (< emacs-major-version 22)
5398 `(append '(intangible t) ,props)
5399 props))
5401 (defun org-activate-bracket-links (limit)
5402 "Run through the buffer and add overlays to bracketed links."
5403 (if (re-search-forward org-bracket-link-regexp limit t)
5404 (let* ((help (concat "LINK: "
5405 (org-match-string-no-properties 1)))
5406 ;; FIXME: above we should remove the escapes.
5407 ;; but that requires another match, protecting match data,
5408 ;; a lot of overhead for font-lock.
5409 (ip (org-maybe-intangible
5410 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5411 'keymap org-mouse-map 'mouse-face 'highlight
5412 'font-lock-multiline t 'help-echo help)))
5413 (vp (list 'rear-nonsticky org-nonsticky-props
5414 'keymap org-mouse-map 'mouse-face 'highlight
5415 ' font-lock-multiline t 'help-echo help)))
5416 ;; We need to remove the invisible property here. Table narrowing
5417 ;; may have made some of this invisible.
5418 (remove-text-properties (match-beginning 0) (match-end 0)
5419 '(invisible nil))
5420 (if (match-end 3)
5421 (progn
5422 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5423 (add-text-properties (match-beginning 3) (match-end 3) vp)
5424 (add-text-properties (match-end 3) (match-end 0) ip))
5425 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5426 (add-text-properties (match-beginning 1) (match-end 1) vp)
5427 (add-text-properties (match-end 1) (match-end 0) ip))
5428 t)))
5430 (defun org-activate-dates (limit)
5431 "Run through the buffer and add overlays to dates."
5432 (if (re-search-forward org-tsr-regexp-both limit t)
5433 (progn
5434 (add-text-properties (match-beginning 0) (match-end 0)
5435 (list 'mouse-face 'highlight
5436 'rear-nonsticky org-nonsticky-props
5437 'keymap org-mouse-map))
5438 (when org-display-custom-times
5439 (if (match-end 3)
5440 (org-display-custom-time (match-beginning 3) (match-end 3)))
5441 (org-display-custom-time (match-beginning 1) (match-end 1)))
5442 t)))
5444 (defvar org-target-link-regexp nil
5445 "Regular expression matching radio targets in plain text.")
5446 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5447 "Regular expression matching a link target.")
5448 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5449 "Regular expression matching a radio target.")
5450 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5451 "Regular expression matching any target.")
5453 (defun org-activate-target-links (limit)
5454 "Run through the buffer and add overlays to target matches."
5455 (when org-target-link-regexp
5456 (let ((case-fold-search t))
5457 (if (re-search-forward org-target-link-regexp limit t)
5458 (progn
5459 (add-text-properties (match-beginning 0) (match-end 0)
5460 (list 'mouse-face 'highlight
5461 'rear-nonsticky org-nonsticky-props
5462 'keymap org-mouse-map
5463 'help-echo "Radio target link"
5464 'org-linked-text t))
5465 t)))))
5467 (defun org-update-radio-target-regexp ()
5468 "Find all radio targets in this file and update the regular expression."
5469 (interactive)
5470 (when (memq 'radio org-activate-links)
5471 (setq org-target-link-regexp
5472 (org-make-target-link-regexp (org-all-targets 'radio)))
5473 (org-restart-font-lock)))
5475 (defun org-hide-wide-columns (limit)
5476 (let (s e)
5477 (setq s (text-property-any (point) (or limit (point-max))
5478 'org-cwidth t))
5479 (when s
5480 (setq e (next-single-property-change s 'org-cwidth))
5481 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5482 (goto-char e)
5483 t)))
5485 (defvar org-latex-and-specials-regexp nil
5486 "Regular expression for highlighting export special stuff.")
5487 (defvar org-match-substring-regexp)
5488 (defvar org-match-substring-with-braces-regexp)
5489 (defvar org-export-html-special-string-regexps)
5491 (defun org-compute-latex-and-specials-regexp ()
5492 "Compute regular expression for stuff treated specially by exporters."
5493 (if (not org-highlight-latex-fragments-and-specials)
5494 (org-set-local 'org-latex-and-specials-regexp nil)
5495 (let*
5496 ((matchers (plist-get org-format-latex-options :matchers))
5497 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5498 org-latex-regexps)))
5499 (options (org-combine-plists (org-default-export-plist)
5500 (org-infile-export-plist)))
5501 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5502 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5503 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5504 (org-export-html-expand (plist-get options :expand-quoted-html))
5505 (org-export-with-special-strings (plist-get options :special-strings))
5506 (re-sub
5507 (cond
5508 ((equal org-export-with-sub-superscripts '{})
5509 (list org-match-substring-with-braces-regexp))
5510 (org-export-with-sub-superscripts
5511 (list org-match-substring-regexp))
5512 (t nil)))
5513 (re-latex
5514 (if org-export-with-LaTeX-fragments
5515 (mapcar (lambda (x) (nth 1 x)) latexs)))
5516 (re-macros
5517 (if org-export-with-TeX-macros
5518 (list (concat "\\\\"
5519 (regexp-opt
5520 (append (mapcar 'car org-html-entities)
5521 (if (boundp 'org-latex-entities)
5522 org-latex-entities nil))
5523 'words))) ; FIXME
5525 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5526 (re-special (if org-export-with-special-strings
5527 (mapcar (lambda (x) (car x))
5528 org-export-html-special-string-regexps)))
5529 (re-rest
5530 (delq nil
5531 (list
5532 (if org-export-html-expand "@<[^>\n]+>")
5533 ))))
5534 (org-set-local
5535 'org-latex-and-specials-regexp
5536 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5537 re-rest) "\\|")))))
5539 (defface org-latex-and-export-specials
5540 (let ((font (cond ((assq :inherit custom-face-attributes)
5541 '(:inherit underline))
5542 (t '(:underline t)))))
5543 `((((class grayscale) (background light))
5544 (:foreground "DimGray" ,@font))
5545 (((class grayscale) (background dark))
5546 (:foreground "LightGray" ,@font))
5547 (((class color) (background light))
5548 (:foreground "SaddleBrown"))
5549 (((class color) (background dark))
5550 (:foreground "burlywood"))
5551 (t (,@font))))
5552 "Face used to highlight math latex and other special exporter stuff."
5553 :group 'org-faces)
5555 (defun org-do-latex-and-special-faces (limit)
5556 "Run through the buffer and add overlays to links."
5557 (when org-latex-and-specials-regexp
5558 (let (rtn d)
5559 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5560 limit t))
5561 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5562 'face))
5563 '(org-code org-verbatim underline)))
5564 (progn
5565 (setq rtn t
5566 d (cond ((member (char-after (1+ (match-beginning 0)))
5567 '(?_ ?^)) 1)
5568 (t 0)))
5569 (font-lock-prepend-text-property
5570 (+ d (match-beginning 0)) (match-end 0)
5571 'face 'org-latex-and-export-specials)
5572 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5573 '(font-lock-multiline t)))))
5574 rtn)))
5576 (defun org-restart-font-lock ()
5577 "Restart font-lock-mode, to force refontification."
5578 (when (and (boundp 'font-lock-mode) font-lock-mode)
5579 (font-lock-mode -1)
5580 (font-lock-mode 1)))
5582 (defun org-all-targets (&optional radio)
5583 "Return a list of all targets in this file.
5584 With optional argument RADIO, only find radio targets."
5585 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5586 rtn)
5587 (save-excursion
5588 (goto-char (point-min))
5589 (while (re-search-forward re nil t)
5590 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5591 rtn)))
5593 (defun org-make-target-link-regexp (targets)
5594 "Make regular expression matching all strings in TARGETS.
5595 The regular expression finds the targets also if there is a line break
5596 between words."
5597 (and targets
5598 (concat
5599 "\\<\\("
5600 (mapconcat
5601 (lambda (x)
5602 (while (string-match " +" x)
5603 (setq x (replace-match "\\s-+" t t x)))
5605 targets
5606 "\\|")
5607 "\\)\\>")))
5609 (defun org-activate-tags (limit)
5610 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5611 (progn
5612 (add-text-properties (match-beginning 1) (match-end 1)
5613 (list 'mouse-face 'highlight
5614 'rear-nonsticky org-nonsticky-props
5615 'keymap org-mouse-map))
5616 t)))
5618 (defun org-outline-level ()
5619 (save-excursion
5620 (looking-at outline-regexp)
5621 (if (match-beginning 1)
5622 (+ (org-get-string-indentation (match-string 1)) 1000)
5623 (1- (- (match-end 0) (match-beginning 0))))))
5625 (defvar org-font-lock-keywords nil)
5627 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5628 "Regular expression matching a property line.")
5630 (defun org-set-font-lock-defaults ()
5631 (let* ((em org-fontify-emphasized-text)
5632 (lk org-activate-links)
5633 (org-font-lock-extra-keywords
5634 (list
5635 ;; Headlines
5636 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5637 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5638 ;; Table lines
5639 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5640 (1 'org-table t))
5641 ;; Table internals
5642 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5643 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5644 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5645 ;; Drawers
5646 (list org-drawer-regexp '(0 'org-special-keyword t))
5647 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5648 ;; Properties
5649 (list org-property-re
5650 '(1 'org-special-keyword t)
5651 '(3 'org-property-value t))
5652 (if org-format-transports-properties-p
5653 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5654 ;; Links
5655 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5656 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5657 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5658 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5659 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5660 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5661 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5662 '(org-hide-wide-columns (0 nil append))
5663 ;; TODO lines
5664 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5665 '(1 (org-get-todo-face 1) t))
5666 ;; DONE
5667 (if org-fontify-done-headline
5668 (list (concat "^[*]+ +\\<\\("
5669 (mapconcat 'regexp-quote org-done-keywords "\\|")
5670 "\\)\\(.*\\)")
5671 '(2 'org-headline-done t))
5672 nil)
5673 ;; Priorities
5674 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5675 ;; Special keywords
5676 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5677 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5678 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5679 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5680 ;; Emphasis
5681 (if em
5682 (if (featurep 'xemacs)
5683 '(org-do-emphasis-faces (0 nil append))
5684 '(org-do-emphasis-faces)))
5685 ;; Checkboxes
5686 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5687 2 'bold prepend)
5688 (if org-provide-checkbox-statistics
5689 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5690 (0 (org-get-checkbox-statistics-face) t)))
5691 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5692 '(1 'org-archived prepend))
5693 ;; Specials
5694 '(org-do-latex-and-special-faces)
5695 ;; Code
5696 '(org-activate-code (1 'org-code t))
5697 ;; COMMENT
5698 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5699 "\\|" org-quote-string "\\)\\>")
5700 '(1 'org-special-keyword t))
5701 '("^#.*" (0 'font-lock-comment-face t))
5703 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5704 ;; Now set the full font-lock-keywords
5705 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5706 (org-set-local 'font-lock-defaults
5707 '(org-font-lock-keywords t nil nil backward-paragraph))
5708 (kill-local-variable 'font-lock-keywords) nil))
5710 (defvar org-m nil)
5711 (defvar org-l nil)
5712 (defvar org-f nil)
5713 (defun org-get-level-face (n)
5714 "Get the right face for match N in font-lock matching of healdines."
5715 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5716 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5717 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5718 (cond
5719 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5720 ((eq n 2) org-f)
5721 (t (if org-level-color-stars-only nil org-f))))
5723 (defun org-get-todo-face (kwd)
5724 "Get the right face for a TODO keyword KWD.
5725 If KWD is a number, get the corresponding match group."
5726 (if (numberp kwd) (setq kwd (match-string kwd)))
5727 (or (cdr (assoc kwd org-todo-keyword-faces))
5728 (and (member kwd org-done-keywords) 'org-done)
5729 'org-todo))
5731 (defun org-unfontify-region (beg end &optional maybe_loudly)
5732 "Remove fontification and activation overlays from links."
5733 (font-lock-default-unfontify-region beg end)
5734 (let* ((buffer-undo-list t)
5735 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5736 (inhibit-modification-hooks t)
5737 deactivate-mark buffer-file-name buffer-file-truename)
5738 (remove-text-properties beg end
5739 '(mouse-face t keymap t org-linked-text t
5740 invisible t intangible t))))
5742 ;;;; Visibility cycling, including org-goto and indirect buffer
5744 ;;; Cycling
5746 (defvar org-cycle-global-status nil)
5747 (make-variable-buffer-local 'org-cycle-global-status)
5748 (defvar org-cycle-subtree-status nil)
5749 (make-variable-buffer-local 'org-cycle-subtree-status)
5751 ;;;###autoload
5752 (defun org-cycle (&optional arg)
5753 "Visibility cycling for Org-mode.
5755 - When this function is called with a prefix argument, rotate the entire
5756 buffer through 3 states (global cycling)
5757 1. OVERVIEW: Show only top-level headlines.
5758 2. CONTENTS: Show all headlines of all levels, but no body text.
5759 3. SHOW ALL: Show everything.
5761 - When point is at the beginning of a headline, rotate the subtree started
5762 by this line through 3 different states (local cycling)
5763 1. FOLDED: Only the main headline is shown.
5764 2. CHILDREN: The main headline and the direct children are shown.
5765 From this state, you can move to one of the children
5766 and zoom in further.
5767 3. SUBTREE: Show the entire subtree, including body text.
5769 - When there is a numeric prefix, go up to a heading with level ARG, do
5770 a `show-subtree' and return to the previous cursor position. If ARG
5771 is negative, go up that many levels.
5773 - When point is not at the beginning of a headline, execute
5774 `indent-relative', like TAB normally does. See the option
5775 `org-cycle-emulate-tab' for details.
5777 - Special case: if point is at the beginning of the buffer and there is
5778 no headline in line 1, this function will act as if called with prefix arg.
5779 But only if also the variable `org-cycle-global-at-bob' is t."
5780 (interactive "P")
5781 (org-load-modules-maybe)
5782 (let* ((outline-regexp
5783 (if (and (org-mode-p) org-cycle-include-plain-lists)
5784 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5785 outline-regexp))
5786 (bob-special (and org-cycle-global-at-bob (bobp)
5787 (not (looking-at outline-regexp))))
5788 (org-cycle-hook
5789 (if bob-special
5790 (delq 'org-optimize-window-after-visibility-change
5791 (copy-sequence org-cycle-hook))
5792 org-cycle-hook))
5793 (pos (point)))
5795 (if (or bob-special (equal arg '(4)))
5796 ;; special case: use global cycling
5797 (setq arg t))
5799 (cond
5801 ((org-at-table-p 'any)
5802 ;; Enter the table or move to the next field in the table
5803 (or (org-table-recognize-table.el)
5804 (progn
5805 (if arg (org-table-edit-field t)
5806 (org-table-justify-field-maybe)
5807 (call-interactively 'org-table-next-field)))))
5809 ((eq arg t) ;; Global cycling
5811 (cond
5812 ((and (eq last-command this-command)
5813 (eq org-cycle-global-status 'overview))
5814 ;; We just created the overview - now do table of contents
5815 ;; This can be slow in very large buffers, so indicate action
5816 (message "CONTENTS...")
5817 (org-content)
5818 (message "CONTENTS...done")
5819 (setq org-cycle-global-status 'contents)
5820 (run-hook-with-args 'org-cycle-hook 'contents))
5822 ((and (eq last-command this-command)
5823 (eq org-cycle-global-status 'contents))
5824 ;; We just showed the table of contents - now show everything
5825 (show-all)
5826 (message "SHOW ALL")
5827 (setq org-cycle-global-status 'all)
5828 (run-hook-with-args 'org-cycle-hook 'all))
5831 ;; Default action: go to overview
5832 (org-overview)
5833 (message "OVERVIEW")
5834 (setq org-cycle-global-status 'overview)
5835 (run-hook-with-args 'org-cycle-hook 'overview))))
5837 ((and org-drawers org-drawer-regexp
5838 (save-excursion
5839 (beginning-of-line 1)
5840 (looking-at org-drawer-regexp)))
5841 ;; Toggle block visibility
5842 (org-flag-drawer
5843 (not (get-char-property (match-end 0) 'invisible))))
5845 ((integerp arg)
5846 ;; Show-subtree, ARG levels up from here.
5847 (save-excursion
5848 (org-back-to-heading)
5849 (outline-up-heading (if (< arg 0) (- arg)
5850 (- (funcall outline-level) arg)))
5851 (org-show-subtree)))
5853 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5854 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5855 ;; At a heading: rotate between three different views
5856 (org-back-to-heading)
5857 (let ((goal-column 0) eoh eol eos)
5858 ;; First, some boundaries
5859 (save-excursion
5860 (org-back-to-heading)
5861 (save-excursion
5862 (beginning-of-line 2)
5863 (while (and (not (eobp)) ;; this is like `next-line'
5864 (get-char-property (1- (point)) 'invisible))
5865 (beginning-of-line 2)) (setq eol (point)))
5866 (outline-end-of-heading) (setq eoh (point))
5867 (org-end-of-subtree t)
5868 (unless (eobp)
5869 (skip-chars-forward " \t\n")
5870 (beginning-of-line 1) ; in case this is an item
5872 (setq eos (1- (point))))
5873 ;; Find out what to do next and set `this-command'
5874 (cond
5875 ((= eos eoh)
5876 ;; Nothing is hidden behind this heading
5877 (message "EMPTY ENTRY")
5878 (setq org-cycle-subtree-status nil)
5879 (save-excursion
5880 (goto-char eos)
5881 (outline-next-heading)
5882 (if (org-invisible-p) (org-flag-heading nil))))
5883 ((or (>= eol eos)
5884 (not (string-match "\\S-" (buffer-substring eol eos))))
5885 ;; Entire subtree is hidden in one line: open it
5886 (org-show-entry)
5887 (show-children)
5888 (message "CHILDREN")
5889 (save-excursion
5890 (goto-char eos)
5891 (outline-next-heading)
5892 (if (org-invisible-p) (org-flag-heading nil)))
5893 (setq org-cycle-subtree-status 'children)
5894 (run-hook-with-args 'org-cycle-hook 'children))
5895 ((and (eq last-command this-command)
5896 (eq org-cycle-subtree-status 'children))
5897 ;; We just showed the children, now show everything.
5898 (org-show-subtree)
5899 (message "SUBTREE")
5900 (setq org-cycle-subtree-status 'subtree)
5901 (run-hook-with-args 'org-cycle-hook 'subtree))
5903 ;; Default action: hide the subtree.
5904 (hide-subtree)
5905 (message "FOLDED")
5906 (setq org-cycle-subtree-status 'folded)
5907 (run-hook-with-args 'org-cycle-hook 'folded)))))
5909 ;; TAB emulation
5910 (buffer-read-only (org-back-to-heading))
5912 ((org-try-cdlatex-tab))
5914 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5915 (or (not (bolp))
5916 (not (looking-at outline-regexp))))
5917 (call-interactively (global-key-binding "\t")))
5919 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5920 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5921 (or (and (eq org-cycle-emulate-tab 'white)
5922 (= (match-end 0) (point-at-eol)))
5923 (and (eq org-cycle-emulate-tab 'whitestart)
5924 (>= (match-end 0) pos))))
5926 (eq org-cycle-emulate-tab t))
5927 ; (if (and (looking-at "[ \n\r\t]")
5928 ; (string-match "^[ \t]*$" (buffer-substring
5929 ; (point-at-bol) (point))))
5930 ; (progn
5931 ; (beginning-of-line 1)
5932 ; (and (looking-at "[ \t]+") (replace-match ""))))
5933 (call-interactively (global-key-binding "\t")))
5935 (t (save-excursion
5936 (org-back-to-heading)
5937 (org-cycle))))))
5939 ;;;###autoload
5940 (defun org-global-cycle (&optional arg)
5941 "Cycle the global visibility. For details see `org-cycle'."
5942 (interactive "P")
5943 (let ((org-cycle-include-plain-lists
5944 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5945 (if (integerp arg)
5946 (progn
5947 (show-all)
5948 (hide-sublevels arg)
5949 (setq org-cycle-global-status 'contents))
5950 (org-cycle '(4)))))
5952 (defun org-overview ()
5953 "Switch to overview mode, shoing only top-level headlines.
5954 Really, this shows all headlines with level equal or greater than the level
5955 of the first headline in the buffer. This is important, because if the
5956 first headline is not level one, then (hide-sublevels 1) gives confusing
5957 results."
5958 (interactive)
5959 (let ((level (save-excursion
5960 (goto-char (point-min))
5961 (if (re-search-forward (concat "^" outline-regexp) nil t)
5962 (progn
5963 (goto-char (match-beginning 0))
5964 (funcall outline-level))))))
5965 (and level (hide-sublevels level))))
5967 (defun org-content (&optional arg)
5968 "Show all headlines in the buffer, like a table of contents.
5969 With numerical argument N, show content up to level N."
5970 (interactive "P")
5971 (save-excursion
5972 ;; Visit all headings and show their offspring
5973 (and (integerp arg) (org-overview))
5974 (goto-char (point-max))
5975 (catch 'exit
5976 (while (and (progn (condition-case nil
5977 (outline-previous-visible-heading 1)
5978 (error (goto-char (point-min))))
5980 (looking-at outline-regexp))
5981 (if (integerp arg)
5982 (show-children (1- arg))
5983 (show-branches))
5984 (if (bobp) (throw 'exit nil))))))
5987 (defun org-optimize-window-after-visibility-change (state)
5988 "Adjust the window after a change in outline visibility.
5989 This function is the default value of the hook `org-cycle-hook'."
5990 (when (get-buffer-window (current-buffer))
5991 (cond
5992 ; ((eq state 'overview) (org-first-headline-recenter 1))
5993 ; ((eq state 'overview) (org-beginning-of-line))
5994 ((eq state 'content) nil)
5995 ((eq state 'all) nil)
5996 ((eq state 'folded) nil)
5997 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5998 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6000 (defun org-compact-display-after-subtree-move ()
6001 (let (beg end)
6002 (save-excursion
6003 (if (org-up-heading-safe)
6004 (progn
6005 (hide-subtree)
6006 (show-entry)
6007 (show-children)
6008 (org-cycle-show-empty-lines 'children)
6009 (org-cycle-hide-drawers 'children))
6010 (org-overview)))))
6012 (defun org-cycle-show-empty-lines (state)
6013 "Show empty lines above all visible headlines.
6014 The region to be covered depends on STATE when called through
6015 `org-cycle-hook'. Lisp program can use t for STATE to get the
6016 entire buffer covered. Note that an empty line is only shown if there
6017 are at least `org-cycle-separator-lines' empty lines before the headeline."
6018 (when (> org-cycle-separator-lines 0)
6019 (save-excursion
6020 (let* ((n org-cycle-separator-lines)
6021 (re (cond
6022 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6023 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6024 (t (let ((ns (number-to-string (- n 2))))
6025 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6026 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6027 beg end)
6028 (cond
6029 ((memq state '(overview contents t))
6030 (setq beg (point-min) end (point-max)))
6031 ((memq state '(children folded))
6032 (setq beg (point) end (progn (org-end-of-subtree t t)
6033 (beginning-of-line 2)
6034 (point)))))
6035 (when beg
6036 (goto-char beg)
6037 (while (re-search-forward re end t)
6038 (if (not (get-char-property (match-end 1) 'invisible))
6039 (outline-flag-region
6040 (match-beginning 1) (match-end 1) nil)))))))
6041 ;; Never hide empty lines at the end of the file.
6042 (save-excursion
6043 (goto-char (point-max))
6044 (outline-previous-heading)
6045 (outline-end-of-heading)
6046 (if (and (looking-at "[ \t\n]+")
6047 (= (match-end 0) (point-max)))
6048 (outline-flag-region (point) (match-end 0) nil))))
6050 (defun org-subtree-end-visible-p ()
6051 "Is the end of the current subtree visible?"
6052 (pos-visible-in-window-p
6053 (save-excursion (org-end-of-subtree t) (point))))
6055 (defun org-first-headline-recenter (&optional N)
6056 "Move cursor to the first headline and recenter the headline.
6057 Optional argument N means, put the headline into the Nth line of the window."
6058 (goto-char (point-min))
6059 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6060 (beginning-of-line)
6061 (recenter (prefix-numeric-value N))))
6063 ;;; Org-goto
6065 (defvar org-goto-window-configuration nil)
6066 (defvar org-goto-marker nil)
6067 (defvar org-goto-map
6068 (let ((map (make-sparse-keymap)))
6069 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6070 (while (setq cmd (pop cmds))
6071 (substitute-key-definition cmd cmd map global-map)))
6072 (suppress-keymap map)
6073 (org-defkey map "\C-m" 'org-goto-ret)
6074 (org-defkey map [(return)] 'org-goto-ret)
6075 (org-defkey map [(left)] 'org-goto-left)
6076 (org-defkey map [(right)] 'org-goto-right)
6077 (org-defkey map [(control ?g)] 'org-goto-quit)
6078 (org-defkey map "\C-i" 'org-cycle)
6079 (org-defkey map [(tab)] 'org-cycle)
6080 (org-defkey map [(down)] 'outline-next-visible-heading)
6081 (org-defkey map [(up)] 'outline-previous-visible-heading)
6082 (if org-goto-auto-isearch
6083 (if (fboundp 'define-key-after)
6084 (define-key-after map [t] 'org-goto-local-auto-isearch)
6085 nil)
6086 (org-defkey map "q" 'org-goto-quit)
6087 (org-defkey map "n" 'outline-next-visible-heading)
6088 (org-defkey map "p" 'outline-previous-visible-heading)
6089 (org-defkey map "f" 'outline-forward-same-level)
6090 (org-defkey map "b" 'outline-backward-same-level)
6091 (org-defkey map "u" 'outline-up-heading))
6092 (org-defkey map "/" 'org-occur)
6093 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6094 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6095 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6096 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6097 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6098 map))
6100 (defconst org-goto-help
6101 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6102 RET=jump to location [Q]uit and return to previous location
6103 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6105 (defvar org-goto-start-pos) ; dynamically scoped parameter
6107 (defun org-goto (&optional alternative-interface)
6108 "Look up a different location in the current file, keeping current visibility.
6110 When you want look-up or go to a different location in a document, the
6111 fastest way is often to fold the entire buffer and then dive into the tree.
6112 This method has the disadvantage, that the previous location will be folded,
6113 which may not be what you want.
6115 This command works around this by showing a copy of the current buffer
6116 in an indirect buffer, in overview mode. You can dive into the tree in
6117 that copy, use org-occur and incremental search to find a location.
6118 When pressing RET or `Q', the command returns to the original buffer in
6119 which the visibility is still unchanged. After RET is will also jump to
6120 the location selected in the indirect buffer and expose the
6121 the headline hierarchy above."
6122 (interactive "P")
6123 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6124 (org-refile-use-outline-path t)
6125 (interface
6126 (if (not alternative-interface)
6127 org-goto-interface
6128 (if (eq org-goto-interface 'outline)
6129 'outline-path-completion
6130 'outline)))
6131 (org-goto-start-pos (point))
6132 (selected-point
6133 (if (eq interface 'outline)
6134 (car (org-get-location (current-buffer) org-goto-help))
6135 (nth 3 (org-refile-get-location "Goto: ")))))
6136 (if selected-point
6137 (progn
6138 (org-mark-ring-push org-goto-start-pos)
6139 (goto-char selected-point)
6140 (if (or (org-invisible-p) (org-invisible-p2))
6141 (org-show-context 'org-goto)))
6142 (message "Quit"))))
6144 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6145 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6146 (defvar org-goto-local-auto-isearch-map) ; defined below
6148 (defun org-get-location (buf help)
6149 "Let the user select a location in the Org-mode buffer BUF.
6150 This function uses a recursive edit. It returns the selected position
6151 or nil."
6152 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6153 (isearch-hide-immediately nil)
6154 (isearch-search-fun-function
6155 (lambda () 'org-goto-local-search-forward-headings))
6156 (org-goto-selected-point org-goto-exit-command))
6157 (save-excursion
6158 (save-window-excursion
6159 (delete-other-windows)
6160 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6161 (switch-to-buffer
6162 (condition-case nil
6163 (make-indirect-buffer (current-buffer) "*org-goto*")
6164 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6165 (with-output-to-temp-buffer "*Help*"
6166 (princ help))
6167 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6168 (setq buffer-read-only nil)
6169 (let ((org-startup-truncated t)
6170 (org-startup-folded nil)
6171 (org-startup-align-all-tables nil))
6172 (org-mode)
6173 (org-overview))
6174 (setq buffer-read-only t)
6175 (if (and (boundp 'org-goto-start-pos)
6176 (integer-or-marker-p org-goto-start-pos))
6177 (let ((org-show-hierarchy-above t)
6178 (org-show-siblings t)
6179 (org-show-following-heading t))
6180 (goto-char org-goto-start-pos)
6181 (and (org-invisible-p) (org-show-context)))
6182 (goto-char (point-min)))
6183 (org-beginning-of-line)
6184 (message "Select location and press RET")
6185 (use-local-map org-goto-map)
6186 (recursive-edit)
6188 (kill-buffer "*org-goto*")
6189 (cons org-goto-selected-point org-goto-exit-command)))
6191 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6192 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6193 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6194 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6196 (defun org-goto-local-search-forward-headings (string bound noerror)
6197 "Search and make sure that anu matches are in headlines."
6198 (catch 'return
6199 (while (search-forward string bound noerror)
6200 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6201 (and (member :headline context)
6202 (not (member :tags context))))
6203 (throw 'return (point))))))
6205 (defun org-goto-local-auto-isearch ()
6206 "Start isearch."
6207 (interactive)
6208 (goto-char (point-min))
6209 (let ((keys (this-command-keys)))
6210 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6211 (isearch-mode t)
6212 (isearch-process-search-char (string-to-char keys)))))
6214 (defun org-goto-ret (&optional arg)
6215 "Finish `org-goto' by going to the new location."
6216 (interactive "P")
6217 (setq org-goto-selected-point (point)
6218 org-goto-exit-command 'return)
6219 (throw 'exit nil))
6221 (defun org-goto-left ()
6222 "Finish `org-goto' by going to the new location."
6223 (interactive)
6224 (if (org-on-heading-p)
6225 (progn
6226 (beginning-of-line 1)
6227 (setq org-goto-selected-point (point)
6228 org-goto-exit-command 'left)
6229 (throw 'exit nil))
6230 (error "Not on a heading")))
6232 (defun org-goto-right ()
6233 "Finish `org-goto' by going to the new location."
6234 (interactive)
6235 (if (org-on-heading-p)
6236 (progn
6237 (setq org-goto-selected-point (point)
6238 org-goto-exit-command 'right)
6239 (throw 'exit nil))
6240 (error "Not on a heading")))
6242 (defun org-goto-quit ()
6243 "Finish `org-goto' without cursor motion."
6244 (interactive)
6245 (setq org-goto-selected-point nil)
6246 (setq org-goto-exit-command 'quit)
6247 (throw 'exit nil))
6249 ;;; Indirect buffer display of subtrees
6251 (defvar org-indirect-dedicated-frame nil
6252 "This is the frame being used for indirect tree display.")
6253 (defvar org-last-indirect-buffer nil)
6255 (defun org-tree-to-indirect-buffer (&optional arg)
6256 "Create indirect buffer and narrow it to current subtree.
6257 With numerical prefix ARG, go up to this level and then take that tree.
6258 If ARG is negative, go up that many levels.
6259 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6260 indirect buffer previously made with this command, to avoid proliferation of
6261 indirect buffers. However, when you call the command with a `C-u' prefix, or
6262 when `org-indirect-buffer-display' is `new-frame', the last buffer
6263 is kept so that you can work with several indirect buffers at the same time.
6264 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6265 requests that a new frame be made for the new buffer, so that the dedicated
6266 frame is not changed."
6267 (interactive "P")
6268 (let ((cbuf (current-buffer))
6269 (cwin (selected-window))
6270 (pos (point))
6271 beg end level heading ibuf)
6272 (save-excursion
6273 (org-back-to-heading t)
6274 (when (numberp arg)
6275 (setq level (org-outline-level))
6276 (if (< arg 0) (setq arg (+ level arg)))
6277 (while (> (setq level (org-outline-level)) arg)
6278 (outline-up-heading 1 t)))
6279 (setq beg (point)
6280 heading (org-get-heading))
6281 (org-end-of-subtree t) (setq end (point)))
6282 (if (and (buffer-live-p org-last-indirect-buffer)
6283 (not (eq org-indirect-buffer-display 'new-frame))
6284 (not arg))
6285 (kill-buffer org-last-indirect-buffer))
6286 (setq ibuf (org-get-indirect-buffer cbuf)
6287 org-last-indirect-buffer ibuf)
6288 (cond
6289 ((or (eq org-indirect-buffer-display 'new-frame)
6290 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6291 (select-frame (make-frame))
6292 (delete-other-windows)
6293 (switch-to-buffer ibuf)
6294 (org-set-frame-title heading))
6295 ((eq org-indirect-buffer-display 'dedicated-frame)
6296 (raise-frame
6297 (select-frame (or (and org-indirect-dedicated-frame
6298 (frame-live-p org-indirect-dedicated-frame)
6299 org-indirect-dedicated-frame)
6300 (setq org-indirect-dedicated-frame (make-frame)))))
6301 (delete-other-windows)
6302 (switch-to-buffer ibuf)
6303 (org-set-frame-title (concat "Indirect: " heading)))
6304 ((eq org-indirect-buffer-display 'current-window)
6305 (switch-to-buffer ibuf))
6306 ((eq org-indirect-buffer-display 'other-window)
6307 (pop-to-buffer ibuf))
6308 (t (error "Invalid value.")))
6309 (if (featurep 'xemacs)
6310 (save-excursion (org-mode) (turn-on-font-lock)))
6311 (narrow-to-region beg end)
6312 (show-all)
6313 (goto-char pos)
6314 (and (window-live-p cwin) (select-window cwin))))
6316 (defun org-get-indirect-buffer (&optional buffer)
6317 (setq buffer (or buffer (current-buffer)))
6318 (let ((n 1) (base (buffer-name buffer)) bname)
6319 (while (buffer-live-p
6320 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6321 (setq n (1+ n)))
6322 (condition-case nil
6323 (make-indirect-buffer buffer bname 'clone)
6324 (error (make-indirect-buffer buffer bname)))))
6326 (defun org-set-frame-title (title)
6327 "Set the title of the current frame to the string TITLE."
6328 ;; FIXME: how to name a single frame in XEmacs???
6329 (unless (featurep 'xemacs)
6330 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6332 ;;;; Structure editing
6334 ;;; Inserting headlines
6336 (defun org-insert-heading (&optional force-heading)
6337 "Insert a new heading or item with same depth at point.
6338 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6339 If point is at the beginning of a headline, insert a sibling before the
6340 current headline. If point is not at the beginning, do not split the line,
6341 but create the new hedline after the current line."
6342 (interactive "P")
6343 (if (= (buffer-size) 0)
6344 (insert "\n* ")
6345 (when (or force-heading (not (org-insert-item)))
6346 (let* ((head (save-excursion
6347 (condition-case nil
6348 (progn
6349 (org-back-to-heading)
6350 (match-string 0))
6351 (error "*"))))
6352 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6353 pos)
6354 (cond
6355 ((and (org-on-heading-p) (bolp)
6356 (or (bobp)
6357 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6358 ;; insert before the current line
6359 (open-line (if blank 2 1)))
6360 ((and (bolp)
6361 (or (bobp)
6362 (save-excursion
6363 (backward-char 1) (not (org-invisible-p)))))
6364 ;; insert right here
6365 nil)
6367 ; ;; in the middle of the line
6368 ; (org-show-entry)
6369 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6370 ; (if (and
6371 ; (org-on-heading-p)
6372 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6373 ; ;; protect the tags
6374 ;; (let ((tags (match-string 2)) pos)
6375 ; (delete-region (match-beginning 1) (match-end 1))
6376 ; (setq pos (point-at-bol))
6377 ; (newline (if blank 2 1))
6378 ; (save-excursion
6379 ; (goto-char pos)
6380 ; (end-of-line 1)
6381 ; (insert " " tags)
6382 ; (org-set-tags nil 'align)))
6383 ; (newline (if blank 2 1)))
6384 ; (newline (if blank 2 1))))
6387 ;; in the middle of the line
6388 (org-show-entry)
6389 (let ((split
6390 (org-get-alist-option org-M-RET-may-split-line 'headline))
6391 tags pos)
6392 (if (org-on-heading-p)
6393 (progn
6394 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6395 (setq tags (and (match-end 2) (match-string 2)))
6396 (and (match-end 1)
6397 (delete-region (match-beginning 1) (match-end 1)))
6398 (setq pos (point-at-bol))
6399 (or split (end-of-line 1))
6400 (delete-horizontal-space)
6401 (newline (if blank 2 1))
6402 (when tags
6403 (save-excursion
6404 (goto-char pos)
6405 (end-of-line 1)
6406 (insert " " tags)
6407 (org-set-tags nil 'align))))
6408 (or split (end-of-line 1))
6409 (newline (if blank 2 1))))))
6410 (insert head) (just-one-space)
6411 (setq pos (point))
6412 (end-of-line 1)
6413 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6414 (run-hooks 'org-insert-heading-hook)))))
6416 (defun org-insert-heading-after-current ()
6417 "Insert a new heading with same level as current, after current subtree."
6418 (interactive)
6419 (org-back-to-heading)
6420 (org-insert-heading)
6421 (org-move-subtree-down)
6422 (end-of-line 1))
6424 (defun org-insert-todo-heading (arg)
6425 "Insert a new heading with the same level and TODO state as current heading.
6426 If the heading has no TODO state, or if the state is DONE, use the first
6427 state (TODO by default). Also with prefix arg, force first state."
6428 (interactive "P")
6429 (when (not (org-insert-item 'checkbox))
6430 (org-insert-heading)
6431 (save-excursion
6432 (org-back-to-heading)
6433 (outline-previous-heading)
6434 (looking-at org-todo-line-regexp))
6435 (if (or arg
6436 (not (match-beginning 2))
6437 (member (match-string 2) org-done-keywords))
6438 (insert (car org-todo-keywords-1) " ")
6439 (insert (match-string 2) " "))))
6441 (defun org-insert-subheading (arg)
6442 "Insert a new subheading and demote it.
6443 Works for outline headings and for plain lists alike."
6444 (interactive "P")
6445 (org-insert-heading arg)
6446 (cond
6447 ((org-on-heading-p) (org-do-demote))
6448 ((org-at-item-p) (org-indent-item 1))))
6450 (defun org-insert-todo-subheading (arg)
6451 "Insert a new subheading with TODO keyword or checkbox and demote it.
6452 Works for outline headings and for plain lists alike."
6453 (interactive "P")
6454 (org-insert-todo-heading arg)
6455 (cond
6456 ((org-on-heading-p) (org-do-demote))
6457 ((org-at-item-p) (org-indent-item 1))))
6459 ;;; Promotion and Demotion
6461 (defun org-promote-subtree ()
6462 "Promote the entire subtree.
6463 See also `org-promote'."
6464 (interactive)
6465 (save-excursion
6466 (org-map-tree 'org-promote))
6467 (org-fix-position-after-promote))
6469 (defun org-demote-subtree ()
6470 "Demote the entire subtree. See `org-demote'.
6471 See also `org-promote'."
6472 (interactive)
6473 (save-excursion
6474 (org-map-tree 'org-demote))
6475 (org-fix-position-after-promote))
6478 (defun org-do-promote ()
6479 "Promote the current heading higher up the tree.
6480 If the region is active in `transient-mark-mode', promote all headings
6481 in the region."
6482 (interactive)
6483 (save-excursion
6484 (if (org-region-active-p)
6485 (org-map-region 'org-promote (region-beginning) (region-end))
6486 (org-promote)))
6487 (org-fix-position-after-promote))
6489 (defun org-do-demote ()
6490 "Demote the current heading lower down the tree.
6491 If the region is active in `transient-mark-mode', demote all headings
6492 in the region."
6493 (interactive)
6494 (save-excursion
6495 (if (org-region-active-p)
6496 (org-map-region 'org-demote (region-beginning) (region-end))
6497 (org-demote)))
6498 (org-fix-position-after-promote))
6500 (defun org-fix-position-after-promote ()
6501 "Make sure that after pro/demotion cursor position is right."
6502 (let ((pos (point)))
6503 (when (save-excursion
6504 (beginning-of-line 1)
6505 (looking-at org-todo-line-regexp)
6506 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6507 (cond ((eobp) (insert " "))
6508 ((eolp) (insert " "))
6509 ((equal (char-after) ?\ ) (forward-char 1))))))
6511 (defun org-reduced-level (l)
6512 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6514 (defun org-get-valid-level (level &optional change)
6515 "Rectify a level change under the influence of `org-odd-levels-only'
6516 LEVEL is a current level, CHANGE is by how much the level should be
6517 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6518 even level numbers will become the next higher odd number."
6519 (if org-odd-levels-only
6520 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6521 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6522 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6523 (max 1 (+ level change))))
6525 (if (featurep 'xemacs)
6526 (define-obsolete-function-alias 'org-get-legal-level
6527 'org-get-valid-level)
6528 (define-obsolete-function-alias 'org-get-legal-level
6529 'org-get-valid-level "23.1"))
6531 (defun org-promote ()
6532 "Promote the current heading higher up the tree.
6533 If the region is active in `transient-mark-mode', promote all headings
6534 in the region."
6535 (org-back-to-heading t)
6536 (let* ((level (save-match-data (funcall outline-level)))
6537 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6538 (diff (abs (- level (length up-head) -1))))
6539 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6540 (replace-match up-head nil t)
6541 ;; Fixup tag positioning
6542 (and org-auto-align-tags (org-set-tags nil t))
6543 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6545 (defun org-demote ()
6546 "Demote the current heading lower down the tree.
6547 If the region is active in `transient-mark-mode', demote all headings
6548 in the region."
6549 (org-back-to-heading t)
6550 (let* ((level (save-match-data (funcall outline-level)))
6551 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6552 (diff (abs (- level (length down-head) -1))))
6553 (replace-match down-head nil t)
6554 ;; Fixup tag positioning
6555 (and org-auto-align-tags (org-set-tags nil t))
6556 (if org-adapt-indentation (org-fixup-indentation diff))))
6558 (defun org-map-tree (fun)
6559 "Call FUN for every heading underneath the current one."
6560 (org-back-to-heading)
6561 (let ((level (funcall outline-level)))
6562 (save-excursion
6563 (funcall fun)
6564 (while (and (progn
6565 (outline-next-heading)
6566 (> (funcall outline-level) level))
6567 (not (eobp)))
6568 (funcall fun)))))
6570 (defun org-map-region (fun beg end)
6571 "Call FUN for every heading between BEG and END."
6572 (let ((org-ignore-region t))
6573 (save-excursion
6574 (setq end (copy-marker end))
6575 (goto-char beg)
6576 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6577 (< (point) end))
6578 (funcall fun))
6579 (while (and (progn
6580 (outline-next-heading)
6581 (< (point) end))
6582 (not (eobp)))
6583 (funcall fun)))))
6585 (defun org-fixup-indentation (diff)
6586 "Change the indentation in the current entry by DIFF
6587 However, if any line in the current entry has no indentation, or if it
6588 would end up with no indentation after the change, nothing at all is done."
6589 (save-excursion
6590 (let ((end (save-excursion (outline-next-heading)
6591 (point-marker)))
6592 (prohibit (if (> diff 0)
6593 "^\\S-"
6594 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6595 col)
6596 (unless (save-excursion (end-of-line 1)
6597 (re-search-forward prohibit end t))
6598 (while (and (< (point) end)
6599 (re-search-forward "^[ \t]+" end t))
6600 (goto-char (match-end 0))
6601 (setq col (current-column))
6602 (if (< diff 0) (replace-match ""))
6603 (indent-to (+ diff col))))
6604 (move-marker end nil))))
6606 (defun org-convert-to-odd-levels ()
6607 "Convert an org-mode file with all levels allowed to one with odd levels.
6608 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6609 level 5 etc."
6610 (interactive)
6611 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6612 (let ((org-odd-levels-only nil) n)
6613 (save-excursion
6614 (goto-char (point-min))
6615 (while (re-search-forward "^\\*\\*+ " nil t)
6616 (setq n (- (length (match-string 0)) 2))
6617 (while (>= (setq n (1- n)) 0)
6618 (org-demote))
6619 (end-of-line 1))))))
6622 (defun org-convert-to-oddeven-levels ()
6623 "Convert an org-mode file with only odd levels to one with odd and even levels.
6624 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6625 section with an even level, conversion would destroy the structure of the file. An error
6626 is signaled in this case."
6627 (interactive)
6628 (goto-char (point-min))
6629 ;; First check if there are no even levels
6630 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6631 (org-show-context t)
6632 (error "Not all levels are odd in this file. Conversion not possible."))
6633 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6634 (let ((org-odd-levels-only nil) n)
6635 (save-excursion
6636 (goto-char (point-min))
6637 (while (re-search-forward "^\\*\\*+ " nil t)
6638 (setq n (/ (1- (length (match-string 0))) 2))
6639 (while (>= (setq n (1- n)) 0)
6640 (org-promote))
6641 (end-of-line 1))))))
6643 (defun org-tr-level (n)
6644 "Make N odd if required."
6645 (if org-odd-levels-only (1+ (/ n 2)) n))
6647 ;;; Vertical tree motion, cutting and pasting of subtrees
6649 (defun org-move-subtree-up (&optional arg)
6650 "Move the current subtree up past ARG headlines of the same level."
6651 (interactive "p")
6652 (org-move-subtree-down (- (prefix-numeric-value arg))))
6654 (defun org-move-subtree-down (&optional arg)
6655 "Move the current subtree down past ARG headlines of the same level."
6656 (interactive "p")
6657 (setq arg (prefix-numeric-value arg))
6658 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6659 'outline-get-last-sibling))
6660 (ins-point (make-marker))
6661 (cnt (abs arg))
6662 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6663 ;; Select the tree
6664 (org-back-to-heading)
6665 (setq beg0 (point))
6666 (save-excursion
6667 (setq ne-beg (org-back-over-empty-lines))
6668 (setq beg (point)))
6669 (save-match-data
6670 (save-excursion (outline-end-of-heading)
6671 (setq folded (org-invisible-p)))
6672 (outline-end-of-subtree))
6673 (outline-next-heading)
6674 (setq ne-end (org-back-over-empty-lines))
6675 (setq end (point))
6676 (goto-char beg0)
6677 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6678 ;; include less whitespace
6679 (save-excursion
6680 (goto-char beg)
6681 (forward-line (- ne-beg ne-end))
6682 (setq beg (point))))
6683 ;; Find insertion point, with error handling
6684 (while (> cnt 0)
6685 (or (and (funcall movfunc) (looking-at outline-regexp))
6686 (progn (goto-char beg0)
6687 (error "Cannot move past superior level or buffer limit")))
6688 (setq cnt (1- cnt)))
6689 (if (> arg 0)
6690 ;; Moving forward - still need to move over subtree
6691 (progn (org-end-of-subtree t t)
6692 (save-excursion
6693 (org-back-over-empty-lines)
6694 (or (bolp) (newline)))))
6695 (setq ne-ins (org-back-over-empty-lines))
6696 (move-marker ins-point (point))
6697 (setq txt (buffer-substring beg end))
6698 (delete-region beg end)
6699 (outline-flag-region (1- beg) beg nil)
6700 (outline-flag-region (1- (point)) (point) nil)
6701 (insert txt)
6702 (or (bolp) (insert "\n"))
6703 (setq ins-end (point))
6704 (goto-char ins-point)
6705 (org-skip-whitespace)
6706 (when (and (< arg 0)
6707 (org-first-sibling-p)
6708 (> ne-ins ne-beg))
6709 ;; Move whitespace back to beginning
6710 (save-excursion
6711 (goto-char ins-end)
6712 (let ((kill-whole-line t))
6713 (kill-line (- ne-ins ne-beg)) (point)))
6714 (insert (make-string (- ne-ins ne-beg) ?\n)))
6715 (move-marker ins-point nil)
6716 (org-compact-display-after-subtree-move)
6717 (unless folded
6718 (org-show-entry)
6719 (show-children)
6720 (org-cycle-hide-drawers 'children))))
6722 (defvar org-subtree-clip ""
6723 "Clipboard for cut and paste of subtrees.
6724 This is actually only a copy of the kill, because we use the normal kill
6725 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6727 (defvar org-subtree-clip-folded nil
6728 "Was the last copied subtree folded?
6729 This is used to fold the tree back after pasting.")
6731 (defun org-cut-subtree (&optional n)
6732 "Cut the current subtree into the clipboard.
6733 With prefix arg N, cut this many sequential subtrees.
6734 This is a short-hand for marking the subtree and then cutting it."
6735 (interactive "p")
6736 (org-copy-subtree n 'cut))
6738 (defun org-copy-subtree (&optional n cut)
6739 "Cut the current subtree into the clipboard.
6740 With prefix arg N, cut this many sequential subtrees.
6741 This is a short-hand for marking the subtree and then copying it.
6742 If CUT is non-nil, actually cut the subtree."
6743 (interactive "p")
6744 (let (beg end folded (beg0 (point)))
6745 (if (interactive-p)
6746 (org-back-to-heading nil) ; take what looks like a subtree
6747 (org-back-to-heading t)) ; take what is really there
6748 (org-back-over-empty-lines)
6749 (setq beg (point))
6750 (skip-chars-forward " \t\r\n")
6751 (save-match-data
6752 (save-excursion (outline-end-of-heading)
6753 (setq folded (org-invisible-p)))
6754 (condition-case nil
6755 (outline-forward-same-level (1- n))
6756 (error nil))
6757 (org-end-of-subtree t t))
6758 (org-back-over-empty-lines)
6759 (setq end (point))
6760 (goto-char beg0)
6761 (when (> end beg)
6762 (setq org-subtree-clip-folded folded)
6763 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6764 (setq org-subtree-clip (current-kill 0))
6765 (message "%s: Subtree(s) with %d characters"
6766 (if cut "Cut" "Copied")
6767 (length org-subtree-clip)))))
6769 (defun org-paste-subtree (&optional level tree)
6770 "Paste the clipboard as a subtree, with modification of headline level.
6771 The entire subtree is promoted or demoted in order to match a new headline
6772 level. By default, the new level is derived from the visible headings
6773 before and after the insertion point, and taken to be the inferior headline
6774 level of the two. So if the previous visible heading is level 3 and the
6775 next is level 4 (or vice versa), level 4 will be used for insertion.
6776 This makes sure that the subtree remains an independent subtree and does
6777 not swallow low level entries.
6779 You can also force a different level, either by using a numeric prefix
6780 argument, or by inserting the heading marker by hand. For example, if the
6781 cursor is after \"*****\", then the tree will be shifted to level 5.
6783 If you want to insert the tree as is, just use \\[yank].
6785 If optional TREE is given, use this text instead of the kill ring."
6786 (interactive "P")
6787 (unless (org-kill-is-subtree-p tree)
6788 (error "%s"
6789 (substitute-command-keys
6790 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6791 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6792 (^re (concat "^\\(" outline-regexp "\\)"))
6793 (re (concat "\\(" outline-regexp "\\)"))
6794 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6796 (old-level (if (string-match ^re txt)
6797 (- (match-end 0) (match-beginning 0) 1)
6798 -1))
6799 (force-level (cond (level (prefix-numeric-value level))
6800 ((string-match
6801 ^re_ (buffer-substring (point-at-bol) (point)))
6802 (- (match-end 1) (match-beginning 1)))
6803 (t nil)))
6804 (previous-level (save-excursion
6805 (condition-case nil
6806 (progn
6807 (outline-previous-visible-heading 1)
6808 (if (looking-at re)
6809 (- (match-end 0) (match-beginning 0) 1)
6811 (error 1))))
6812 (next-level (save-excursion
6813 (condition-case nil
6814 (progn
6815 (or (looking-at outline-regexp)
6816 (outline-next-visible-heading 1))
6817 (if (looking-at re)
6818 (- (match-end 0) (match-beginning 0) 1)
6820 (error 1))))
6821 (new-level (or force-level (max previous-level next-level)))
6822 (shift (if (or (= old-level -1)
6823 (= new-level -1)
6824 (= old-level new-level))
6826 (- new-level old-level)))
6827 (delta (if (> shift 0) -1 1))
6828 (func (if (> shift 0) 'org-demote 'org-promote))
6829 (org-odd-levels-only nil)
6830 beg end)
6831 ;; Remove the forced level indicator
6832 (if force-level
6833 (delete-region (point-at-bol) (point)))
6834 ;; Paste
6835 (beginning-of-line 1)
6836 (org-back-over-empty-lines) ;; FIXME: correct fix????
6837 (setq beg (point))
6838 (insert-before-markers txt) ;; FIXME: correct fix????
6839 (unless (string-match "\n\\'" txt) (insert "\n"))
6840 (setq end (point))
6841 (goto-char beg)
6842 (skip-chars-forward " \t\n\r")
6843 (setq beg (point))
6844 ;; Shift if necessary
6845 (unless (= shift 0)
6846 (save-restriction
6847 (narrow-to-region beg end)
6848 (while (not (= shift 0))
6849 (org-map-region func (point-min) (point-max))
6850 (setq shift (+ delta shift)))
6851 (goto-char (point-min))))
6852 (when (interactive-p)
6853 (message "Clipboard pasted as level %d subtree" new-level))
6854 (if (and kill-ring
6855 (eq org-subtree-clip (current-kill 0))
6856 org-subtree-clip-folded)
6857 ;; The tree was folded before it was killed/copied
6858 (hide-subtree))))
6860 (defun org-kill-is-subtree-p (&optional txt)
6861 "Check if the current kill is an outline subtree, or a set of trees.
6862 Returns nil if kill does not start with a headline, or if the first
6863 headline level is not the largest headline level in the tree.
6864 So this will actually accept several entries of equal levels as well,
6865 which is OK for `org-paste-subtree'.
6866 If optional TXT is given, check this string instead of the current kill."
6867 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6868 (start-level (and kill
6869 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6870 org-outline-regexp "\\)")
6871 kill)
6872 (- (match-end 2) (match-beginning 2) 1)))
6873 (re (concat "^" org-outline-regexp))
6874 (start (1+ (match-beginning 2))))
6875 (if (not start-level)
6876 (progn
6877 nil) ;; does not even start with a heading
6878 (catch 'exit
6879 (while (setq start (string-match re kill (1+ start)))
6880 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6881 (throw 'exit nil)))
6882 t))))
6884 (defun org-narrow-to-subtree ()
6885 "Narrow buffer to the current subtree."
6886 (interactive)
6887 (save-excursion
6888 (save-match-data
6889 (narrow-to-region
6890 (progn (org-back-to-heading) (point))
6891 (progn (org-end-of-subtree t t) (point))))))
6894 ;;; Outline Sorting
6896 (defun org-sort (with-case)
6897 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6898 Optional argument WITH-CASE means sort case-sensitively."
6899 (interactive "P")
6900 (if (org-at-table-p)
6901 (org-call-with-arg 'org-table-sort-lines with-case)
6902 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6904 (defvar org-priority-regexp) ; defined later in the file
6906 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6907 "Sort entries on a certain level of an outline tree.
6908 If there is an active region, the entries in the region are sorted.
6909 Else, if the cursor is before the first entry, sort the top-level items.
6910 Else, the children of the entry at point are sorted.
6912 Sorting can be alphabetically, numerically, and by date/time as given by
6913 the first time stamp in the entry. The command prompts for the sorting
6914 type unless it has been given to the function through the SORTING-TYPE
6915 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6916 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6917 called with point at the beginning of the record. It must return either
6918 a string or a number that should serve as the sorting key for that record.
6920 Comparing entries ignores case by default. However, with an optional argument
6921 WITH-CASE, the sorting considers case as well."
6922 (interactive "P")
6923 (let ((case-func (if with-case 'identity 'downcase))
6924 start beg end stars re re2
6925 txt what tmp plain-list-p)
6926 ;; Find beginning and end of region to sort
6927 (cond
6928 ((org-region-active-p)
6929 ;; we will sort the region
6930 (setq end (region-end)
6931 what "region")
6932 (goto-char (region-beginning))
6933 (if (not (org-on-heading-p)) (outline-next-heading))
6934 (setq start (point)))
6935 ((org-at-item-p)
6936 ;; we will sort this plain list
6937 (org-beginning-of-item-list) (setq start (point))
6938 (org-end-of-item-list) (setq end (point))
6939 (goto-char start)
6940 (setq plain-list-p t
6941 what "plain list"))
6942 ((or (org-on-heading-p)
6943 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6944 ;; we will sort the children of the current headline
6945 (org-back-to-heading)
6946 (setq start (point)
6947 end (progn (org-end-of-subtree t t)
6948 (org-back-over-empty-lines)
6949 (point))
6950 what "children")
6951 (goto-char start)
6952 (show-subtree)
6953 (outline-next-heading))
6955 ;; we will sort the top-level entries in this file
6956 (goto-char (point-min))
6957 (or (org-on-heading-p) (outline-next-heading))
6958 (setq start (point) end (point-max) what "top-level")
6959 (goto-char start)
6960 (show-all)))
6962 (setq beg (point))
6963 (if (>= beg end) (error "Nothing to sort"))
6965 (unless plain-list-p
6966 (looking-at "\\(\\*+\\)")
6967 (setq stars (match-string 1)
6968 re (concat "^" (regexp-quote stars) " +")
6969 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6970 txt (buffer-substring beg end))
6971 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6972 (if (and (not (equal stars "*")) (string-match re2 txt))
6973 (error "Region to sort contains a level above the first entry")))
6975 (unless sorting-type
6976 (message
6977 (if plain-list-p
6978 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6979 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6980 what)
6981 (setq sorting-type (read-char-exclusive))
6983 (and (= (downcase sorting-type) ?f)
6984 (setq getkey-func
6985 (completing-read "Sort using function: "
6986 obarray 'fboundp t nil nil))
6987 (setq getkey-func (intern getkey-func)))
6989 (and (= (downcase sorting-type) ?r)
6990 (setq property
6991 (completing-read "Property: "
6992 (mapcar 'list (org-buffer-property-keys t))
6993 nil t))))
6995 (message "Sorting entries...")
6997 (save-restriction
6998 (narrow-to-region start end)
7000 (let ((dcst (downcase sorting-type))
7001 (now (current-time)))
7002 (sort-subr
7003 (/= dcst sorting-type)
7004 ;; This function moves to the beginning character of the "record" to
7005 ;; be sorted.
7006 (if plain-list-p
7007 (lambda nil
7008 (if (org-at-item-p) t (goto-char (point-max))))
7009 (lambda nil
7010 (if (re-search-forward re nil t)
7011 (goto-char (match-beginning 0))
7012 (goto-char (point-max)))))
7013 ;; This function moves to the last character of the "record" being
7014 ;; sorted.
7015 (if plain-list-p
7016 'org-end-of-item
7017 (lambda nil
7018 (save-match-data
7019 (condition-case nil
7020 (outline-forward-same-level 1)
7021 (error
7022 (goto-char (point-max)))))))
7024 ;; This function returns the value that gets sorted against.
7025 (if plain-list-p
7026 (lambda nil
7027 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7028 (cond
7029 ((= dcst ?n)
7030 (string-to-number (buffer-substring (match-end 0)
7031 (point-at-eol))))
7032 ((= dcst ?a)
7033 (buffer-substring (match-end 0) (point-at-eol)))
7034 ((= dcst ?t)
7035 (if (re-search-forward org-ts-regexp
7036 (point-at-eol) t)
7037 (org-time-string-to-time (match-string 0))
7038 now))
7039 ((= dcst ?f)
7040 (if getkey-func
7041 (progn
7042 (setq tmp (funcall getkey-func))
7043 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7044 tmp)
7045 (error "Invalid key function `%s'" getkey-func)))
7046 (t (error "Invalid sorting type `%c'" sorting-type)))))
7047 (lambda nil
7048 (cond
7049 ((= dcst ?n)
7050 (if (looking-at outline-regexp)
7051 (string-to-number (buffer-substring (match-end 0)
7052 (point-at-eol)))
7053 nil))
7054 ((= dcst ?a)
7055 (funcall case-func (buffer-substring (point-at-bol)
7056 (point-at-eol))))
7057 ((= dcst ?t)
7058 (if (re-search-forward org-ts-regexp
7059 (save-excursion
7060 (forward-line 2)
7061 (point)) t)
7062 (org-time-string-to-time (match-string 0))
7063 now))
7064 ((= dcst ?p)
7065 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7066 (string-to-char (match-string 2))
7067 org-default-priority))
7068 ((= dcst ?r)
7069 (or (org-entry-get nil property) ""))
7070 ((= dcst ?f)
7071 (if getkey-func
7072 (progn
7073 (setq tmp (funcall getkey-func))
7074 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7075 tmp)
7076 (error "Invalid key function `%s'" getkey-func)))
7077 (t (error "Invalid sorting type `%c'" sorting-type)))))
7079 (cond
7080 ((= dcst ?a) 'string<)
7081 ((= dcst ?t) 'time-less-p)
7082 (t nil)))))
7083 (message "Sorting entries...done")))
7085 (defun org-do-sort (table what &optional with-case sorting-type)
7086 "Sort TABLE of WHAT according to SORTING-TYPE.
7087 The user will be prompted for the SORTING-TYPE if the call to this
7088 function does not specify it. WHAT is only for the prompt, to indicate
7089 what is being sorted. The sorting key will be extracted from
7090 the car of the elements of the table.
7091 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7092 (unless sorting-type
7093 (message
7094 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7095 what)
7096 (setq sorting-type (read-char-exclusive)))
7097 (let ((dcst (downcase sorting-type))
7098 extractfun comparefun)
7099 ;; Define the appropriate functions
7100 (cond
7101 ((= dcst ?n)
7102 (setq extractfun 'string-to-number
7103 comparefun (if (= dcst sorting-type) '< '>)))
7104 ((= dcst ?a)
7105 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7106 (lambda(x) (downcase (org-sort-remove-invisible x))))
7107 comparefun (if (= dcst sorting-type)
7108 'string<
7109 (lambda (a b) (and (not (string< a b))
7110 (not (string= a b)))))))
7111 ((= dcst ?t)
7112 (setq extractfun
7113 (lambda (x)
7114 (if (string-match org-ts-regexp x)
7115 (time-to-seconds
7116 (org-time-string-to-time (match-string 0 x)))
7118 comparefun (if (= dcst sorting-type) '< '>)))
7119 (t (error "Invalid sorting type `%c'" sorting-type)))
7121 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7122 table)
7123 (lambda (a b) (funcall comparefun (car a) (car b))))))
7125 ;;;; Plain list items, including checkboxes
7127 ;;; Plain list items
7129 (defun org-at-item-p ()
7130 "Is point in a line starting a hand-formatted item?"
7131 (let ((llt org-plain-list-ordered-item-terminator))
7132 (save-excursion
7133 (goto-char (point-at-bol))
7134 (looking-at
7135 (cond
7136 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7137 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7138 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7139 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7141 (defun org-in-item-p ()
7142 "It the cursor inside a plain list item.
7143 Does not have to be the first line."
7144 (save-excursion
7145 (condition-case nil
7146 (progn
7147 (org-beginning-of-item)
7148 (org-at-item-p)
7150 (error nil))))
7152 (defun org-insert-item (&optional checkbox)
7153 "Insert a new item at the current level.
7154 Return t when things worked, nil when we are not in an item."
7155 (when (save-excursion
7156 (condition-case nil
7157 (progn
7158 (org-beginning-of-item)
7159 (org-at-item-p)
7160 (if (org-invisible-p) (error "Invisible item"))
7162 (error nil)))
7163 (let* ((bul (match-string 0))
7164 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7165 (match-end 0)))
7166 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7167 pos)
7168 (cond
7169 ((and (org-at-item-p) (<= (point) eow))
7170 ;; before the bullet
7171 (beginning-of-line 1)
7172 (open-line (if blank 2 1)))
7173 ((<= (point) eow)
7174 (beginning-of-line 1))
7176 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7177 (end-of-line 1)
7178 (delete-horizontal-space))
7179 (newline (if blank 2 1))))
7180 (insert bul (if checkbox "[ ]" ""))
7181 (just-one-space)
7182 (setq pos (point))
7183 (end-of-line 1)
7184 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7185 (org-maybe-renumber-ordered-list)
7186 (and checkbox (org-update-checkbox-count-maybe))
7189 ;;; Checkboxes
7191 (defun org-at-item-checkbox-p ()
7192 "Is point at a line starting a plain-list item with a checklet?"
7193 (and (org-at-item-p)
7194 (save-excursion
7195 (goto-char (match-end 0))
7196 (skip-chars-forward " \t")
7197 (looking-at "\\[[- X]\\]"))))
7199 (defun org-toggle-checkbox (&optional arg)
7200 "Toggle the checkbox in the current line."
7201 (interactive "P")
7202 (catch 'exit
7203 (let (beg end status (firstnew 'unknown))
7204 (cond
7205 ((org-region-active-p)
7206 (setq beg (region-beginning) end (region-end)))
7207 ((org-on-heading-p)
7208 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7209 ((org-at-item-checkbox-p)
7210 (let ((pos (point)))
7211 (replace-match
7212 (cond (arg "[-]")
7213 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7214 (t "[ ]"))
7215 t t)
7216 (goto-char pos))
7217 (throw 'exit t))
7218 (t (error "Not at a checkbox or heading, and no active region")))
7219 (save-excursion
7220 (goto-char beg)
7221 (while (< (point) end)
7222 (when (org-at-item-checkbox-p)
7223 (setq status (equal (match-string 0) "[X]"))
7224 (when (eq firstnew 'unknown)
7225 (setq firstnew (not status)))
7226 (replace-match
7227 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7228 (beginning-of-line 2)))))
7229 (org-update-checkbox-count-maybe))
7231 (defun org-update-checkbox-count-maybe ()
7232 "Update checkbox statistics unless turned off by user."
7233 (when org-provide-checkbox-statistics
7234 (org-update-checkbox-count)))
7236 (defun org-update-checkbox-count (&optional all)
7237 "Update the checkbox statistics in the current section.
7238 This will find all statistic cookies like [57%] and [6/12] and update them
7239 with the current numbers. With optional prefix argument ALL, do this for
7240 the whole buffer."
7241 (interactive "P")
7242 (save-excursion
7243 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7244 (beg (condition-case nil
7245 (progn (outline-back-to-heading) (point))
7246 (error (point-min))))
7247 (end (move-marker (make-marker)
7248 (progn (outline-next-heading) (point))))
7249 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7250 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7251 (re-find (concat re "\\|" re-box))
7252 beg-cookie end-cookie is-percent c-on c-off lim
7253 eline curr-ind next-ind continue-from startsearch
7254 (cstat 0)
7256 (when all
7257 (goto-char (point-min))
7258 (outline-next-heading)
7259 (setq beg (point) end (point-max)))
7260 (goto-char end)
7261 ;; find each statistic cookie
7262 (while (re-search-backward re-find beg t)
7263 (setq beg-cookie (match-beginning 1)
7264 end-cookie (match-end 1)
7265 cstat (+ cstat (if end-cookie 1 0))
7266 startsearch (point-at-eol)
7267 continue-from (point-at-bol)
7268 is-percent (match-beginning 2)
7269 lim (cond
7270 ((org-on-heading-p) (outline-next-heading) (point))
7271 ((org-at-item-p) (org-end-of-item) (point))
7272 (t nil))
7273 c-on 0
7274 c-off 0)
7275 (when lim
7276 ;; find first checkbox for this cookie and gather
7277 ;; statistics from all that are at this indentation level
7278 (goto-char startsearch)
7279 (if (re-search-forward re-box lim t)
7280 (progn
7281 (org-beginning-of-item)
7282 (setq curr-ind (org-get-indentation))
7283 (setq next-ind curr-ind)
7284 (while (= curr-ind next-ind)
7285 (save-excursion (end-of-line) (setq eline (point)))
7286 (if (re-search-forward re-box eline t)
7287 (if (member (match-string 2) '("[ ]" "[-]"))
7288 (setq c-off (1+ c-off))
7289 (setq c-on (1+ c-on))
7292 (org-end-of-item)
7293 (setq next-ind (org-get-indentation))
7295 (goto-char continue-from)
7296 ;; update cookie
7297 (when end-cookie
7298 (delete-region beg-cookie end-cookie)
7299 (goto-char beg-cookie)
7300 (insert
7301 (if is-percent
7302 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7303 (format "[%d/%d]" c-on (+ c-on c-off)))))
7304 ;; update items checkbox if it has one
7305 (when (org-at-item-p)
7306 (org-beginning-of-item)
7307 (when (and (> (+ c-on c-off) 0)
7308 (re-search-forward re-box (point-at-eol) t))
7309 (setq beg-cookie (match-beginning 2)
7310 end-cookie (match-end 2))
7311 (delete-region beg-cookie end-cookie)
7312 (goto-char beg-cookie)
7313 (cond ((= c-off 0) (insert "[X]"))
7314 ((= c-on 0) (insert "[ ]"))
7315 (t (insert "[-]")))
7317 (goto-char continue-from))
7318 (when (interactive-p)
7319 (message "Checkbox satistics updated %s (%d places)"
7320 (if all "in entire file" "in current outline entry") cstat)))))
7322 (defun org-get-checkbox-statistics-face ()
7323 "Select the face for checkbox statistics.
7324 The face will be `org-done' when all relevant boxes are checked. Otherwise
7325 it will be `org-todo'."
7326 (if (match-end 1)
7327 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7328 (if (and (> (match-end 2) (match-beginning 2))
7329 (equal (match-string 2) (match-string 3)))
7330 'org-done
7331 'org-todo)))
7333 (defun org-get-indentation (&optional line)
7334 "Get the indentation of the current line, interpreting tabs.
7335 When LINE is given, assume it represents a line and compute its indentation."
7336 (if line
7337 (if (string-match "^ *" (org-remove-tabs line))
7338 (match-end 0))
7339 (save-excursion
7340 (beginning-of-line 1)
7341 (skip-chars-forward " \t")
7342 (current-column))))
7344 (defun org-remove-tabs (s &optional width)
7345 "Replace tabulators in S with spaces.
7346 Assumes that s is a single line, starting in column 0."
7347 (setq width (or width tab-width))
7348 (while (string-match "\t" s)
7349 (setq s (replace-match
7350 (make-string
7351 (- (* width (/ (+ (match-beginning 0) width) width))
7352 (match-beginning 0)) ?\ )
7353 t t s)))
7356 (defun org-fix-indentation (line ind)
7357 "Fix indentation in LINE.
7358 IND is a cons cell with target and minimum indentation.
7359 If the current indenation in LINE is smaller than the minimum,
7360 leave it alone. If it is larger than ind, set it to the target."
7361 (let* ((l (org-remove-tabs line))
7362 (i (org-get-indentation l))
7363 (i1 (car ind)) (i2 (cdr ind)))
7364 (if (>= i i2) (setq l (substring line i2)))
7365 (if (> i1 0)
7366 (concat (make-string i1 ?\ ) l)
7367 l)))
7369 (defcustom org-empty-line-terminates-plain-lists nil
7370 "Non-nil means, an empty line ends all plain list levels.
7371 When nil, empty lines are part of the preceeding item."
7372 :group 'org-plain-lists
7373 :type 'boolean)
7375 (defun org-beginning-of-item ()
7376 "Go to the beginning of the current hand-formatted item.
7377 If the cursor is not in an item, throw an error."
7378 (interactive)
7379 (let ((pos (point))
7380 (limit (save-excursion
7381 (condition-case nil
7382 (progn
7383 (org-back-to-heading)
7384 (beginning-of-line 2) (point))
7385 (error (point-min)))))
7386 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7387 ind ind1)
7388 (if (org-at-item-p)
7389 (beginning-of-line 1)
7390 (beginning-of-line 1)
7391 (skip-chars-forward " \t")
7392 (setq ind (current-column))
7393 (if (catch 'exit
7394 (while t
7395 (beginning-of-line 0)
7396 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7398 (if (looking-at "[ \t]*$")
7399 (setq ind1 ind-empty)
7400 (skip-chars-forward " \t")
7401 (setq ind1 (current-column)))
7402 (if (< ind1 ind)
7403 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7405 (goto-char pos)
7406 (error "Not in an item")))))
7408 (defun org-end-of-item ()
7409 "Go to the end of the current hand-formatted item.
7410 If the cursor is not in an item, throw an error."
7411 (interactive)
7412 (let* ((pos (point))
7413 ind1
7414 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7415 (limit (save-excursion (outline-next-heading) (point)))
7416 (ind (save-excursion
7417 (org-beginning-of-item)
7418 (skip-chars-forward " \t")
7419 (current-column)))
7420 (end (catch 'exit
7421 (while t
7422 (beginning-of-line 2)
7423 (if (eobp) (throw 'exit (point)))
7424 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7425 (if (looking-at "[ \t]*$")
7426 (setq ind1 ind-empty)
7427 (skip-chars-forward " \t")
7428 (setq ind1 (current-column)))
7429 (if (<= ind1 ind)
7430 (throw 'exit (point-at-bol)))))))
7431 (if end
7432 (goto-char end)
7433 (goto-char pos)
7434 (error "Not in an item"))))
7436 (defun org-next-item ()
7437 "Move to the beginning of the next item in the current plain list.
7438 Error if not at a plain list, or if this is the last item in the list."
7439 (interactive)
7440 (let (ind ind1 (pos (point)))
7441 (org-beginning-of-item)
7442 (setq ind (org-get-indentation))
7443 (org-end-of-item)
7444 (setq ind1 (org-get-indentation))
7445 (unless (and (org-at-item-p) (= ind ind1))
7446 (goto-char pos)
7447 (error "On last item"))))
7449 (defun org-previous-item ()
7450 "Move to the beginning of the previous item in the current plain list.
7451 Error if not at a plain list, or if this is the first item in the list."
7452 (interactive)
7453 (let (beg ind ind1 (pos (point)))
7454 (org-beginning-of-item)
7455 (setq beg (point))
7456 (setq ind (org-get-indentation))
7457 (goto-char beg)
7458 (catch 'exit
7459 (while t
7460 (beginning-of-line 0)
7461 (if (looking-at "[ \t]*$")
7463 (if (<= (setq ind1 (org-get-indentation)) ind)
7464 (throw 'exit t)))))
7465 (condition-case nil
7466 (if (or (not (org-at-item-p))
7467 (< ind1 (1- ind)))
7468 (error "")
7469 (org-beginning-of-item))
7470 (error (goto-char pos)
7471 (error "On first item")))))
7473 (defun org-first-list-item-p ()
7474 "Is this heading the item in a plain list?"
7475 (unless (org-at-item-p)
7476 (error "Not at a plain list item"))
7477 (org-beginning-of-item)
7478 (= (point) (save-excursion (org-beginning-of-item-list))))
7480 (defun org-move-item-down ()
7481 "Move the plain list item at point down, i.e. swap with following item.
7482 Subitems (items with larger indentation) are considered part of the item,
7483 so this really moves item trees."
7484 (interactive)
7485 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7486 (org-beginning-of-item)
7487 (setq beg0 (point))
7488 (save-excursion
7489 (setq ne-beg (org-back-over-empty-lines))
7490 (setq beg (point)))
7491 (goto-char beg0)
7492 (setq ind (org-get-indentation))
7493 (org-end-of-item)
7494 (setq end0 (point))
7495 (setq ind1 (org-get-indentation))
7496 (setq ne-end (org-back-over-empty-lines))
7497 (setq end (point))
7498 (goto-char beg0)
7499 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7500 ;; include less whitespace
7501 (save-excursion
7502 (goto-char beg)
7503 (forward-line (- ne-beg ne-end))
7504 (setq beg (point))))
7505 (goto-char end0)
7506 (if (and (org-at-item-p) (= ind ind1))
7507 (progn
7508 (org-end-of-item)
7509 (org-back-over-empty-lines)
7510 (setq txt (buffer-substring beg end))
7511 (save-excursion
7512 (delete-region beg end))
7513 (setq pos (point))
7514 (insert txt)
7515 (goto-char pos) (org-skip-whitespace)
7516 (org-maybe-renumber-ordered-list))
7517 (goto-char pos)
7518 (error "Cannot move this item further down"))))
7520 (defun org-move-item-up (arg)
7521 "Move the plain list item at point up, i.e. swap with previous item.
7522 Subitems (items with larger indentation) are considered part of the item,
7523 so this really moves item trees."
7524 (interactive "p")
7525 (let (beg beg0 end ind ind1 (pos (point)) txt
7526 ne-beg ne-ins ins-end)
7527 (org-beginning-of-item)
7528 (setq beg0 (point))
7529 (setq ind (org-get-indentation))
7530 (save-excursion
7531 (setq ne-beg (org-back-over-empty-lines))
7532 (setq beg (point)))
7533 (goto-char beg0)
7534 (org-end-of-item)
7535 (setq end (point))
7536 (goto-char beg0)
7537 (catch 'exit
7538 (while t
7539 (beginning-of-line 0)
7540 (if (looking-at "[ \t]*$")
7541 (if org-empty-line-terminates-plain-lists
7542 (progn
7543 (goto-char pos)
7544 (error "Cannot move this item further up"))
7545 nil)
7546 (if (<= (setq ind1 (org-get-indentation)) ind)
7547 (throw 'exit t)))))
7548 (condition-case nil
7549 (org-beginning-of-item)
7550 (error (goto-char beg)
7551 (error "Cannot move this item further up")))
7552 (setq ind1 (org-get-indentation))
7553 (if (and (org-at-item-p) (= ind ind1))
7554 (progn
7555 (setq ne-ins (org-back-over-empty-lines))
7556 (setq txt (buffer-substring beg end))
7557 (save-excursion
7558 (delete-region beg end))
7559 (setq pos (point))
7560 (insert txt)
7561 (setq ins-end (point))
7562 (goto-char pos) (org-skip-whitespace)
7564 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7565 ;; Move whitespace back to beginning
7566 (save-excursion
7567 (goto-char ins-end)
7568 (let ((kill-whole-line t))
7569 (kill-line (- ne-ins ne-beg)) (point)))
7570 (insert (make-string (- ne-ins ne-beg) ?\n)))
7572 (org-maybe-renumber-ordered-list))
7573 (goto-char pos)
7574 (error "Cannot move this item further up"))))
7576 (defun org-maybe-renumber-ordered-list ()
7577 "Renumber the ordered list at point if setup allows it.
7578 This tests the user option `org-auto-renumber-ordered-lists' before
7579 doing the renumbering."
7580 (interactive)
7581 (when (and org-auto-renumber-ordered-lists
7582 (org-at-item-p))
7583 (if (match-beginning 3)
7584 (org-renumber-ordered-list 1)
7585 (org-fix-bullet-type))))
7587 (defun org-maybe-renumber-ordered-list-safe ()
7588 (condition-case nil
7589 (save-excursion
7590 (org-maybe-renumber-ordered-list))
7591 (error nil)))
7593 (defun org-cycle-list-bullet (&optional which)
7594 "Cycle through the different itemize/enumerate bullets.
7595 This cycle the entire list level through the sequence:
7597 `-' -> `+' -> `*' -> `1.' -> `1)'
7599 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7600 0 meand `-', 1 means `+' etc."
7601 (interactive "P")
7602 (org-preserve-lc
7603 (org-beginning-of-item-list)
7604 (org-at-item-p)
7605 (beginning-of-line 1)
7606 (let ((current (match-string 0))
7607 (prevp (eq which 'previous))
7608 new)
7609 (setq new (cond
7610 ((and (numberp which)
7611 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7612 ((string-match "-" current) (if prevp "1)" "+"))
7613 ((string-match "\\+" current)
7614 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7615 ((string-match "\\*" current) (if prevp "+" "1."))
7616 ((string-match "\\." current) (if prevp "*" "1)"))
7617 ((string-match ")" current) (if prevp "1." "-"))
7618 (t (error "This should not happen"))))
7619 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7620 (org-fix-bullet-type)
7621 (org-maybe-renumber-ordered-list))))
7623 (defun org-get-string-indentation (s)
7624 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7625 (let ((n -1) (i 0) (w tab-width) c)
7626 (catch 'exit
7627 (while (< (setq n (1+ n)) (length s))
7628 (setq c (aref s n))
7629 (cond ((= c ?\ ) (setq i (1+ i)))
7630 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7631 (t (throw 'exit t)))))
7634 (defun org-renumber-ordered-list (arg)
7635 "Renumber an ordered plain list.
7636 Cursor needs to be in the first line of an item, the line that starts
7637 with something like \"1.\" or \"2)\"."
7638 (interactive "p")
7639 (unless (and (org-at-item-p)
7640 (match-beginning 3))
7641 (error "This is not an ordered list"))
7642 (let ((line (org-current-line))
7643 (col (current-column))
7644 (ind (org-get-string-indentation
7645 (buffer-substring (point-at-bol) (match-beginning 3))))
7646 ;; (term (substring (match-string 3) -1))
7647 ind1 (n (1- arg))
7648 fmt)
7649 ;; find where this list begins
7650 (org-beginning-of-item-list)
7651 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7652 (setq fmt (concat "%d" (match-string 1)))
7653 (beginning-of-line 0)
7654 ;; walk forward and replace these numbers
7655 (catch 'exit
7656 (while t
7657 (catch 'next
7658 (beginning-of-line 2)
7659 (if (eobp) (throw 'exit nil))
7660 (if (looking-at "[ \t]*$") (throw 'next nil))
7661 (skip-chars-forward " \t") (setq ind1 (current-column))
7662 (if (> ind1 ind) (throw 'next t))
7663 (if (< ind1 ind) (throw 'exit t))
7664 (if (not (org-at-item-p)) (throw 'exit nil))
7665 (delete-region (match-beginning 2) (match-end 2))
7666 (goto-char (match-beginning 2))
7667 (insert (format fmt (setq n (1+ n)))))))
7668 (goto-line line)
7669 (move-to-column col)))
7671 (defun org-fix-bullet-type ()
7672 "Make sure all items in this list have the same bullet as the firsst item."
7673 (interactive)
7674 (unless (org-at-item-p) (error "This is not a list"))
7675 (let ((line (org-current-line))
7676 (col (current-column))
7677 (ind (current-indentation))
7678 ind1 bullet)
7679 ;; find where this list begins
7680 (org-beginning-of-item-list)
7681 (beginning-of-line 1)
7682 ;; find out what the bullet type is
7683 (looking-at "[ \t]*\\(\\S-+\\)")
7684 (setq bullet (match-string 1))
7685 ;; walk forward and replace these numbers
7686 (beginning-of-line 0)
7687 (catch 'exit
7688 (while t
7689 (catch 'next
7690 (beginning-of-line 2)
7691 (if (eobp) (throw 'exit nil))
7692 (if (looking-at "[ \t]*$") (throw 'next nil))
7693 (skip-chars-forward " \t") (setq ind1 (current-column))
7694 (if (> ind1 ind) (throw 'next t))
7695 (if (< ind1 ind) (throw 'exit t))
7696 (if (not (org-at-item-p)) (throw 'exit nil))
7697 (skip-chars-forward " \t")
7698 (looking-at "\\S-+")
7699 (replace-match bullet))))
7700 (goto-line line)
7701 (move-to-column col)
7702 (if (string-match "[0-9]" bullet)
7703 (org-renumber-ordered-list 1))))
7705 (defun org-beginning-of-item-list ()
7706 "Go to the beginning of the current item list.
7707 I.e. to the first item in this list."
7708 (interactive)
7709 (org-beginning-of-item)
7710 (let ((pos (point-at-bol))
7711 (ind (org-get-indentation))
7712 ind1)
7713 ;; find where this list begins
7714 (catch 'exit
7715 (while t
7716 (catch 'next
7717 (beginning-of-line 0)
7718 (if (looking-at "[ \t]*$")
7719 (throw (if (bobp) 'exit 'next) t))
7720 (skip-chars-forward " \t") (setq ind1 (current-column))
7721 (if (or (< ind1 ind)
7722 (and (= ind1 ind)
7723 (not (org-at-item-p)))
7724 (bobp))
7725 (throw 'exit t)
7726 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7727 (goto-char pos)))
7730 (defun org-end-of-item-list ()
7731 "Go to the end of the current item list.
7732 I.e. to the text after the last item."
7733 (interactive)
7734 (org-beginning-of-item)
7735 (let ((pos (point-at-bol))
7736 (ind (org-get-indentation))
7737 ind1)
7738 ;; find where this list begins
7739 (catch 'exit
7740 (while t
7741 (catch 'next
7742 (beginning-of-line 2)
7743 (if (looking-at "[ \t]*$")
7744 (throw (if (eobp) 'exit 'next) t))
7745 (skip-chars-forward " \t") (setq ind1 (current-column))
7746 (if (or (< ind1 ind)
7747 (and (= ind1 ind)
7748 (not (org-at-item-p)))
7749 (eobp))
7750 (progn
7751 (setq pos (point-at-bol))
7752 (throw 'exit t))))))
7753 (goto-char pos)))
7756 (defvar org-last-indent-begin-marker (make-marker))
7757 (defvar org-last-indent-end-marker (make-marker))
7759 (defun org-outdent-item (arg)
7760 "Outdent a local list item."
7761 (interactive "p")
7762 (org-indent-item (- arg)))
7764 (defun org-indent-item (arg)
7765 "Indent a local list item."
7766 (interactive "p")
7767 (unless (org-at-item-p)
7768 (error "Not on an item"))
7769 (save-excursion
7770 (let (beg end ind ind1 tmp delta ind-down ind-up)
7771 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7772 (setq beg org-last-indent-begin-marker
7773 end org-last-indent-end-marker)
7774 (org-beginning-of-item)
7775 (setq beg (move-marker org-last-indent-begin-marker (point)))
7776 (org-end-of-item)
7777 (setq end (move-marker org-last-indent-end-marker (point))))
7778 (goto-char beg)
7779 (setq tmp (org-item-indent-positions)
7780 ind (car tmp)
7781 ind-down (nth 2 tmp)
7782 ind-up (nth 1 tmp)
7783 delta (if (> arg 0)
7784 (if ind-down (- ind-down ind) 2)
7785 (if ind-up (- ind-up ind) -2)))
7786 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7787 (while (< (point) end)
7788 (beginning-of-line 1)
7789 (skip-chars-forward " \t") (setq ind1 (current-column))
7790 (delete-region (point-at-bol) (point))
7791 (or (eolp) (indent-to-column (+ ind1 delta)))
7792 (beginning-of-line 2))))
7793 (org-fix-bullet-type)
7794 (org-maybe-renumber-ordered-list-safe)
7795 (save-excursion
7796 (beginning-of-line 0)
7797 (condition-case nil (org-beginning-of-item) (error nil))
7798 (org-maybe-renumber-ordered-list-safe)))
7800 (defun org-item-indent-positions ()
7801 "Return indentation for plain list items.
7802 This returns a list with three values: The current indentation, the
7803 parent indentation and the indentation a child should habe.
7804 Assumes cursor in item line."
7805 (let* ((bolpos (point-at-bol))
7806 (ind (org-get-indentation))
7807 ind-down ind-up pos)
7808 (save-excursion
7809 (org-beginning-of-item-list)
7810 (skip-chars-backward "\n\r \t")
7811 (when (org-in-item-p)
7812 (org-beginning-of-item)
7813 (setq ind-up (org-get-indentation))))
7814 (setq pos (point))
7815 (save-excursion
7816 (cond
7817 ((and (condition-case nil (progn (org-previous-item) t)
7818 (error nil))
7819 (or (forward-char 1) t)
7820 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7821 (setq ind-down (org-get-indentation)))
7822 ((and (goto-char pos)
7823 (org-at-item-p))
7824 (goto-char (match-end 0))
7825 (skip-chars-forward " \t")
7826 (setq ind-down (current-column)))))
7827 (list ind ind-up ind-down)))
7829 ;;; The orgstruct minor mode
7831 ;; Define a minor mode which can be used in other modes in order to
7832 ;; integrate the org-mode structure editing commands.
7834 ;; This is really a hack, because the org-mode structure commands use
7835 ;; keys which normally belong to the major mode. Here is how it
7836 ;; works: The minor mode defines all the keys necessary to operate the
7837 ;; structure commands, but wraps the commands into a function which
7838 ;; tests if the cursor is currently at a headline or a plain list
7839 ;; item. If that is the case, the structure command is used,
7840 ;; temporarily setting many Org-mode variables like regular
7841 ;; expressions for filling etc. However, when any of those keys is
7842 ;; used at a different location, function uses `key-binding' to look
7843 ;; up if the key has an associated command in another currently active
7844 ;; keymap (minor modes, major mode, global), and executes that
7845 ;; command. There might be problems if any of the keys is otherwise
7846 ;; used as a prefix key.
7848 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7849 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7850 ;; addresses this by checking explicitly for both bindings.
7852 (defvar orgstruct-mode-map (make-sparse-keymap)
7853 "Keymap for the minor `orgstruct-mode'.")
7855 (defvar org-local-vars nil
7856 "List of local variables, for use by `orgstruct-mode'")
7858 ;;;###autoload
7859 (define-minor-mode orgstruct-mode
7860 "Toggle the minor more `orgstruct-mode'.
7861 This mode is for using Org-mode structure commands in other modes.
7862 The following key behave as if Org-mode was active, if the cursor
7863 is on a headline, or on a plain list item (both in the definition
7864 of Org-mode).
7866 M-up Move entry/item up
7867 M-down Move entry/item down
7868 M-left Promote
7869 M-right Demote
7870 M-S-up Move entry/item up
7871 M-S-down Move entry/item down
7872 M-S-left Promote subtree
7873 M-S-right Demote subtree
7874 M-q Fill paragraph and items like in Org-mode
7875 C-c ^ Sort entries
7876 C-c - Cycle list bullet
7877 TAB Cycle item visibility
7878 M-RET Insert new heading/item
7879 S-M-RET Insert new TODO heading / Chekbox item
7880 C-c C-c Set tags / toggle checkbox"
7881 nil " OrgStruct" nil
7882 (org-load-modules-maybe)
7883 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7885 ;;;###autoload
7886 (defun turn-on-orgstruct ()
7887 "Unconditionally turn on `orgstruct-mode'."
7888 (orgstruct-mode 1))
7890 ;;;###autoload
7891 (defun turn-on-orgstruct++ ()
7892 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7893 In addition to setting orgstruct-mode, this also exports all indentation and
7894 autofilling variables from org-mode into the buffer. Note that turning
7895 off orgstruct-mode will *not* remove these additional settings."
7896 (orgstruct-mode 1)
7897 (let (var val)
7898 (mapc
7899 (lambda (x)
7900 (when (string-match
7901 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7902 (symbol-name (car x)))
7903 (setq var (car x) val (nth 1 x))
7904 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7905 org-local-vars)))
7907 (defun orgstruct-error ()
7908 "Error when there is no default binding for a structure key."
7909 (interactive)
7910 (error "This key has no function outside structure elements"))
7912 (defun orgstruct-setup ()
7913 "Setup orgstruct keymaps."
7914 (let ((nfunc 0)
7915 (bindings
7916 (list
7917 '([(meta up)] org-metaup)
7918 '([(meta down)] org-metadown)
7919 '([(meta left)] org-metaleft)
7920 '([(meta right)] org-metaright)
7921 '([(meta shift up)] org-shiftmetaup)
7922 '([(meta shift down)] org-shiftmetadown)
7923 '([(meta shift left)] org-shiftmetaleft)
7924 '([(meta shift right)] org-shiftmetaright)
7925 '([(shift up)] org-shiftup)
7926 '([(shift down)] org-shiftdown)
7927 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7928 '("\M-q" fill-paragraph)
7929 '("\C-c^" org-sort)
7930 '("\C-c-" org-cycle-list-bullet)))
7931 elt key fun cmd)
7932 (while (setq elt (pop bindings))
7933 (setq nfunc (1+ nfunc))
7934 (setq key (org-key (car elt))
7935 fun (nth 1 elt)
7936 cmd (orgstruct-make-binding fun nfunc key))
7937 (org-defkey orgstruct-mode-map key cmd))
7939 ;; Special treatment needed for TAB and RET
7940 (org-defkey orgstruct-mode-map [(tab)]
7941 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7942 (org-defkey orgstruct-mode-map "\C-i"
7943 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7945 (org-defkey orgstruct-mode-map "\M-\C-m"
7946 (orgstruct-make-binding 'org-insert-heading 105
7947 "\M-\C-m" [(meta return)]))
7948 (org-defkey orgstruct-mode-map [(meta return)]
7949 (orgstruct-make-binding 'org-insert-heading 106
7950 [(meta return)] "\M-\C-m"))
7952 (org-defkey orgstruct-mode-map [(shift meta return)]
7953 (orgstruct-make-binding 'org-insert-todo-heading 107
7954 [(meta return)] "\M-\C-m"))
7956 (unless org-local-vars
7957 (setq org-local-vars (org-get-local-variables)))
7961 (defun orgstruct-make-binding (fun n &rest keys)
7962 "Create a function for binding in the structure minor mode.
7963 FUN is the command to call inside a table. N is used to create a unique
7964 command name. KEYS are keys that should be checked in for a command
7965 to execute outside of tables."
7966 (eval
7967 (list 'defun
7968 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7969 '(arg)
7970 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7971 "Outside of structure, run the binding of `"
7972 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7973 "'.")
7974 '(interactive "p")
7975 (list 'if
7976 '(org-context-p 'headline 'item)
7977 (list 'org-run-like-in-org-mode (list 'quote fun))
7978 (list 'let '(orgstruct-mode)
7979 (list 'call-interactively
7980 (append '(or)
7981 (mapcar (lambda (k)
7982 (list 'key-binding k))
7983 keys)
7984 '('orgstruct-error))))))))
7986 (defun org-context-p (&rest contexts)
7987 "Check if local context is and of CONTEXTS.
7988 Possible values in the list of contexts are `table', `headline', and `item'."
7989 (let ((pos (point)))
7990 (goto-char (point-at-bol))
7991 (prog1 (or (and (memq 'table contexts)
7992 (looking-at "[ \t]*|"))
7993 (and (memq 'headline contexts)
7994 (looking-at "\\*+"))
7995 (and (memq 'item contexts)
7996 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7997 (goto-char pos))))
7999 (defun org-get-local-variables ()
8000 "Return a list of all local variables in an org-mode buffer."
8001 (let (varlist)
8002 (with-current-buffer (get-buffer-create "*Org tmp*")
8003 (erase-buffer)
8004 (org-mode)
8005 (setq varlist (buffer-local-variables)))
8006 (kill-buffer "*Org tmp*")
8007 (delq nil
8008 (mapcar
8009 (lambda (x)
8010 (setq x
8011 (if (symbolp x)
8012 (list x)
8013 (list (car x) (list 'quote (cdr x)))))
8014 (if (string-match
8015 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8016 (symbol-name (car x)))
8017 x nil))
8018 varlist))))
8020 ;;;###autoload
8021 (defun org-run-like-in-org-mode (cmd)
8022 (org-load-modules-maybe)
8023 (unless org-local-vars
8024 (setq org-local-vars (org-get-local-variables)))
8025 (eval (list 'let org-local-vars
8026 (list 'call-interactively (list 'quote cmd)))))
8028 ;;;; Archiving
8030 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8032 (defun org-archive-subtree (&optional find-done)
8033 "Move the current subtree to the archive.
8034 The archive can be a certain top-level heading in the current file, or in
8035 a different file. The tree will be moved to that location, the subtree
8036 heading be marked DONE, and the current time will be added.
8038 When called with prefix argument FIND-DONE, find whole trees without any
8039 open TODO items and archive them (after getting confirmation from the user).
8040 If the cursor is not at a headline when this comand is called, try all level
8041 1 trees. If the cursor is on a headline, only try the direct children of
8042 this heading."
8043 (interactive "P")
8044 (if find-done
8045 (org-archive-all-done)
8046 ;; Save all relevant TODO keyword-relatex variables
8048 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8049 (tr-org-todo-keywords-1 org-todo-keywords-1)
8050 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8051 (tr-org-done-keywords org-done-keywords)
8052 (tr-org-todo-regexp org-todo-regexp)
8053 (tr-org-todo-line-regexp org-todo-line-regexp)
8054 (tr-org-odd-levels-only org-odd-levels-only)
8055 (this-buffer (current-buffer))
8056 (org-archive-location org-archive-location)
8057 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8058 ;; start of variables that will be used for saving context
8059 ;; The compiler complains about them - keep them anyway!
8060 (file (abbreviate-file-name (buffer-file-name)))
8061 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8062 (time (format-time-string
8063 (substring (cdr org-time-stamp-formats) 1 -1)
8064 (current-time)))
8065 afile heading buffer level newfile-p
8066 category todo priority
8067 ;; start of variables that will be used for savind context
8068 ltags itags prop)
8070 ;; Try to find a local archive location
8071 (save-excursion
8072 (save-restriction
8073 (widen)
8074 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8075 (if (and prop (string-match "\\S-" prop))
8076 (setq org-archive-location prop)
8077 (if (or (re-search-backward re nil t)
8078 (re-search-forward re nil t))
8079 (setq org-archive-location (match-string 1))))))
8081 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8082 (progn
8083 (setq afile (format (match-string 1 org-archive-location)
8084 (file-name-nondirectory buffer-file-name))
8085 heading (match-string 2 org-archive-location)))
8086 (error "Invalid `org-archive-location'"))
8087 (if (> (length afile) 0)
8088 (setq newfile-p (not (file-exists-p afile))
8089 buffer (find-file-noselect afile))
8090 (setq buffer (current-buffer)))
8091 (unless buffer
8092 (error "Cannot access file \"%s\"" afile))
8093 (if (and (> (length heading) 0)
8094 (string-match "^\\*+" heading))
8095 (setq level (match-end 0))
8096 (setq heading nil level 0))
8097 (save-excursion
8098 (org-back-to-heading t)
8099 ;; Get context information that will be lost by moving the tree
8100 (org-refresh-category-properties)
8101 (setq category (org-get-category)
8102 todo (and (looking-at org-todo-line-regexp)
8103 (match-string 2))
8104 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8105 ltags (org-get-tags)
8106 itags (org-delete-all ltags (org-get-tags-at)))
8107 (setq ltags (mapconcat 'identity ltags " ")
8108 itags (mapconcat 'identity itags " "))
8109 ;; We first only copy, in case something goes wrong
8110 ;; we need to protect this-command, to avoid kill-region sets it,
8111 ;; which would lead to duplication of subtrees
8112 (let (this-command) (org-copy-subtree))
8113 (set-buffer buffer)
8114 ;; Enforce org-mode for the archive buffer
8115 (if (not (org-mode-p))
8116 ;; Force the mode for future visits.
8117 (let ((org-insert-mode-line-in-empty-file t)
8118 (org-inhibit-startup t))
8119 (call-interactively 'org-mode)))
8120 (when newfile-p
8121 (goto-char (point-max))
8122 (insert (format "\nArchived entries from file %s\n\n"
8123 (buffer-file-name this-buffer))))
8124 ;; Force the TODO keywords of the original buffer
8125 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8126 (org-todo-keywords-1 tr-org-todo-keywords-1)
8127 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8128 (org-done-keywords tr-org-done-keywords)
8129 (org-todo-regexp tr-org-todo-regexp)
8130 (org-todo-line-regexp tr-org-todo-line-regexp)
8131 (org-odd-levels-only
8132 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8133 org-odd-levels-only
8134 tr-org-odd-levels-only)))
8135 (goto-char (point-min))
8136 (show-all)
8137 (if heading
8138 (progn
8139 (if (re-search-forward
8140 (concat "^" (regexp-quote heading)
8141 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8142 nil t)
8143 (goto-char (match-end 0))
8144 ;; Heading not found, just insert it at the end
8145 (goto-char (point-max))
8146 (or (bolp) (insert "\n"))
8147 (insert "\n" heading "\n")
8148 (end-of-line 0))
8149 ;; Make the subtree visible
8150 (show-subtree)
8151 (org-end-of-subtree t)
8152 (skip-chars-backward " \t\r\n")
8153 (and (looking-at "[ \t\r\n]*")
8154 (replace-match "\n\n")))
8155 ;; No specific heading, just go to end of file.
8156 (goto-char (point-max)) (insert "\n"))
8157 ;; Paste
8158 (org-paste-subtree (org-get-valid-level level 1))
8160 ;; Mark the entry as done
8161 (when (and org-archive-mark-done
8162 (looking-at org-todo-line-regexp)
8163 (or (not (match-end 2))
8164 (not (member (match-string 2) org-done-keywords))))
8165 (let (org-log-done org-todo-log-states)
8166 (org-todo
8167 (car (or (member org-archive-mark-done org-done-keywords)
8168 org-done-keywords)))))
8170 ;; Add the context info
8171 (when org-archive-save-context-info
8172 (let ((l org-archive-save-context-info) e n v)
8173 (while (setq e (pop l))
8174 (when (and (setq v (symbol-value e))
8175 (stringp v) (string-match "\\S-" v))
8176 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8177 (org-entry-put (point) n v)))))
8179 ;; Save and kill the buffer, if it is not the same buffer.
8180 (if (not (eq this-buffer buffer))
8181 (progn (save-buffer) (kill-buffer buffer)))))
8182 ;; Here we are back in the original buffer. Everything seems to have
8183 ;; worked. So now cut the tree and finish up.
8184 (let (this-command) (org-cut-subtree))
8185 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8186 (message "Subtree archived %s"
8187 (if (eq this-buffer buffer)
8188 (concat "under heading: " heading)
8189 (concat "in file: " (abbreviate-file-name afile)))))))
8191 (defun org-refresh-category-properties ()
8192 "Refresh category text properties in teh buffer."
8193 (let ((def-cat (cond
8194 ((null org-category)
8195 (if buffer-file-name
8196 (file-name-sans-extension
8197 (file-name-nondirectory buffer-file-name))
8198 "???"))
8199 ((symbolp org-category) (symbol-name org-category))
8200 (t org-category)))
8201 beg end cat pos optionp)
8202 (org-unmodified
8203 (save-excursion
8204 (save-restriction
8205 (widen)
8206 (goto-char (point-min))
8207 (put-text-property (point) (point-max) 'org-category def-cat)
8208 (while (re-search-forward
8209 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8210 (setq pos (match-end 0)
8211 optionp (equal (char-after (match-beginning 0)) ?#)
8212 cat (org-trim (match-string 2)))
8213 (if optionp
8214 (setq beg (point-at-bol) end (point-max))
8215 (org-back-to-heading t)
8216 (setq beg (point) end (org-end-of-subtree t t)))
8217 (put-text-property beg end 'org-category cat)
8218 (goto-char pos)))))))
8220 (defun org-archive-all-done (&optional tag)
8221 "Archive sublevels of the current tree without open TODO items.
8222 If the cursor is not on a headline, try all level 1 trees. If
8223 it is on a headline, try all direct children.
8224 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8225 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8226 (rea (concat ".*:" org-archive-tag ":"))
8227 (begm (make-marker))
8228 (endm (make-marker))
8229 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8230 "Move subtree to archive (no open TODO items)? "))
8231 beg end (cntarch 0))
8232 (if (org-on-heading-p)
8233 (progn
8234 (setq re1 (concat "^" (regexp-quote
8235 (make-string
8236 (1+ (- (match-end 0) (match-beginning 0) 1))
8237 ?*))
8238 " "))
8239 (move-marker begm (point))
8240 (move-marker endm (org-end-of-subtree t)))
8241 (setq re1 "^* ")
8242 (move-marker begm (point-min))
8243 (move-marker endm (point-max)))
8244 (save-excursion
8245 (goto-char begm)
8246 (while (re-search-forward re1 endm t)
8247 (setq beg (match-beginning 0)
8248 end (save-excursion (org-end-of-subtree t) (point)))
8249 (goto-char beg)
8250 (if (re-search-forward re end t)
8251 (goto-char end)
8252 (goto-char beg)
8253 (if (and (or (not tag) (not (looking-at rea)))
8254 (y-or-n-p question))
8255 (progn
8256 (if tag
8257 (org-toggle-tag org-archive-tag 'on)
8258 (org-archive-subtree))
8259 (setq cntarch (1+ cntarch)))
8260 (goto-char end)))))
8261 (message "%d trees archived" cntarch)))
8263 (defun org-cycle-hide-drawers (state)
8264 "Re-hide all drawers after a visibility state change."
8265 (when (and (org-mode-p)
8266 (not (memq state '(overview folded))))
8267 (save-excursion
8268 (let* ((globalp (memq state '(contents all)))
8269 (beg (if globalp (point-min) (point)))
8270 (end (if globalp (point-max) (org-end-of-subtree t))))
8271 (goto-char beg)
8272 (while (re-search-forward org-drawer-regexp end t)
8273 (org-flag-drawer t))))))
8275 (defun org-flag-drawer (flag)
8276 (save-excursion
8277 (beginning-of-line 1)
8278 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8279 (let ((b (match-end 0))
8280 (outline-regexp org-outline-regexp))
8281 (if (re-search-forward
8282 "^[ \t]*:END:"
8283 (save-excursion (outline-next-heading) (point)) t)
8284 (outline-flag-region b (point-at-eol) flag)
8285 (error ":END: line missing"))))))
8287 (defun org-cycle-hide-archived-subtrees (state)
8288 "Re-hide all archived subtrees after a visibility state change."
8289 (when (and (not org-cycle-open-archived-trees)
8290 (not (memq state '(overview folded))))
8291 (save-excursion
8292 (let* ((globalp (memq state '(contents all)))
8293 (beg (if globalp (point-min) (point)))
8294 (end (if globalp (point-max) (org-end-of-subtree t))))
8295 (org-hide-archived-subtrees beg end)
8296 (goto-char beg)
8297 (if (looking-at (concat ".*:" org-archive-tag ":"))
8298 (message "%s" (substitute-command-keys
8299 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8301 (defun org-force-cycle-archived ()
8302 "Cycle subtree even if it is archived."
8303 (interactive)
8304 (setq this-command 'org-cycle)
8305 (let ((org-cycle-open-archived-trees t))
8306 (call-interactively 'org-cycle)))
8308 (defun org-hide-archived-subtrees (beg end)
8309 "Re-hide all archived subtrees after a visibility state change."
8310 (save-excursion
8311 (let* ((re (concat ":" org-archive-tag ":")))
8312 (goto-char beg)
8313 (while (re-search-forward re end t)
8314 (and (org-on-heading-p) (hide-subtree))
8315 (org-end-of-subtree t)))))
8317 (defun org-toggle-tag (tag &optional onoff)
8318 "Toggle the tag TAG for the current line.
8319 If ONOFF is `on' or `off', don't toggle but set to this state."
8320 (unless (org-on-heading-p t) (error "Not on headling"))
8321 (let (res current)
8322 (save-excursion
8323 (beginning-of-line)
8324 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8325 (point-at-eol) t)
8326 (progn
8327 (setq current (match-string 1))
8328 (replace-match ""))
8329 (setq current ""))
8330 (setq current (nreverse (org-split-string current ":")))
8331 (cond
8332 ((eq onoff 'on)
8333 (setq res t)
8334 (or (member tag current) (push tag current)))
8335 ((eq onoff 'off)
8336 (or (not (member tag current)) (setq current (delete tag current))))
8337 (t (if (member tag current)
8338 (setq current (delete tag current))
8339 (setq res t)
8340 (push tag current))))
8341 (end-of-line 1)
8342 (if current
8343 (progn
8344 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8345 (org-set-tags nil t))
8346 (delete-horizontal-space))
8347 (run-hooks 'org-after-tags-change-hook))
8348 res))
8350 (defun org-toggle-archive-tag (&optional arg)
8351 "Toggle the archive tag for the current headline.
8352 With prefix ARG, check all children of current headline and offer tagging
8353 the children that do not contain any open TODO items."
8354 (interactive "P")
8355 (if arg
8356 (org-archive-all-done 'tag)
8357 (let (set)
8358 (save-excursion
8359 (org-back-to-heading t)
8360 (setq set (org-toggle-tag org-archive-tag))
8361 (when set (hide-subtree)))
8362 (and set (beginning-of-line 1))
8363 (message "Subtree %s" (if set "archived" "unarchived")))))
8366 ;;;; Tables
8368 ;;; The table editor
8370 ;; Watch out: Here we are talking about two different kind of tables.
8371 ;; Most of the code is for the tables created with the Org-mode table editor.
8372 ;; Sometimes, we talk about tables created and edited with the table.el
8373 ;; Emacs package. We call the former org-type tables, and the latter
8374 ;; table.el-type tables.
8376 (defun org-before-change-function (beg end)
8377 "Every change indicates that a table might need an update."
8378 (setq org-table-may-need-update t))
8380 (defconst org-table-line-regexp "^[ \t]*|"
8381 "Detects an org-type table line.")
8382 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8383 "Detects an org-type table line.")
8384 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8385 "Detects a table line marked for automatic recalculation.")
8386 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8387 "Detects a table line marked for automatic recalculation.")
8388 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8389 "Detects a table line marked for automatic recalculation.")
8390 (defconst org-table-hline-regexp "^[ \t]*|-"
8391 "Detects an org-type table hline.")
8392 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8393 "Detects a table-type table hline.")
8394 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8395 "Detects an org-type or table-type table.")
8396 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8397 "Searching from within a table (any type) this finds the first line
8398 outside the table.")
8399 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8400 "Searching from within a table (any type) this finds the first line
8401 outside the table.")
8403 (defvar org-table-last-highlighted-reference nil)
8404 (defvar org-table-formula-history nil)
8406 (defvar org-table-column-names nil
8407 "Alist with column names, derived from the `!' line.")
8408 (defvar org-table-column-name-regexp nil
8409 "Regular expression matching the current column names.")
8410 (defvar org-table-local-parameters nil
8411 "Alist with parameter names, derived from the `$' line.")
8412 (defvar org-table-named-field-locations nil
8413 "Alist with locations of named fields.")
8415 (defvar org-table-current-line-types nil
8416 "Table row types, non-nil only for the duration of a comand.")
8417 (defvar org-table-current-begin-line nil
8418 "Table begin line, non-nil only for the duration of a comand.")
8419 (defvar org-table-current-begin-pos nil
8420 "Table begin position, non-nil only for the duration of a comand.")
8421 (defvar org-table-dlines nil
8422 "Vector of data line line numbers in the current table.")
8423 (defvar org-table-hlines nil
8424 "Vector of hline line numbers in the current table.")
8426 (defconst org-table-range-regexp
8427 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8428 ;; 1 2 3 4 5
8429 "Regular expression for matching ranges in formulas.")
8431 (defconst org-table-range-regexp2
8432 (concat
8433 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8434 "\\.\\."
8435 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8436 "Match a range for reference display.")
8438 (defconst org-table-translate-regexp
8439 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8440 "Match a reference that needs translation, for reference display.")
8442 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8444 (defun org-table-create-with-table.el ()
8445 "Use the table.el package to insert a new table.
8446 If there is already a table at point, convert between Org-mode tables
8447 and table.el tables."
8448 (interactive)
8449 (require 'table)
8450 (cond
8451 ((org-at-table.el-p)
8452 (if (y-or-n-p "Convert table to Org-mode table? ")
8453 (org-table-convert)))
8454 ((org-at-table-p)
8455 (if (y-or-n-p "Convert table to table.el table? ")
8456 (org-table-convert)))
8457 (t (call-interactively 'table-insert))))
8459 (defun org-table-create-or-convert-from-region (arg)
8460 "Convert region to table, or create an empty table.
8461 If there is an active region, convert it to a table, using the function
8462 `org-table-convert-region'. See the documentation of that function
8463 to learn how the prefix argument is interpreted to determine the field
8464 separator.
8465 If there is no such region, create an empty table with `org-table-create'."
8466 (interactive "P")
8467 (if (org-region-active-p)
8468 (org-table-convert-region (region-beginning) (region-end) arg)
8469 (org-table-create arg)))
8471 (defun org-table-create (&optional size)
8472 "Query for a size and insert a table skeleton.
8473 SIZE is a string Columns x Rows like for example \"3x2\"."
8474 (interactive "P")
8475 (unless size
8476 (setq size (read-string
8477 (concat "Table size Columns x Rows [e.g. "
8478 org-table-default-size "]: ")
8479 "" nil org-table-default-size)))
8481 (let* ((pos (point))
8482 (indent (make-string (current-column) ?\ ))
8483 (split (org-split-string size " *x *"))
8484 (rows (string-to-number (nth 1 split)))
8485 (columns (string-to-number (car split)))
8486 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8487 "\n")))
8488 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8489 (point-at-bol) (point)))
8490 (beginning-of-line 1)
8491 (newline))
8492 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8493 (dotimes (i rows) (insert line))
8494 (goto-char pos)
8495 (if (> rows 1)
8496 ;; Insert a hline after the first row.
8497 (progn
8498 (end-of-line 1)
8499 (insert "\n|-")
8500 (goto-char pos)))
8501 (org-table-align)))
8503 (defun org-table-convert-region (beg0 end0 &optional separator)
8504 "Convert region to a table.
8505 The region goes from BEG0 to END0, but these borders will be moved
8506 slightly, to make sure a beginning of line in the first line is included.
8508 SEPARATOR specifies the field separator in the lines. It can have the
8509 following values:
8511 '(4) Use the comma as a field separator
8512 '(16) Use a TAB as field separator
8513 integer When a number, use that many spaces as field separator
8514 nil When nil, the command tries to be smart and figure out the
8515 separator in the following way:
8516 - when each line contains a TAB, assume TAB-separated material
8517 - when each line contains a comme, assume CSV material
8518 - else, assume one or more SPACE charcters as separator."
8519 (interactive "rP")
8520 (let* ((beg (min beg0 end0))
8521 (end (max beg0 end0))
8523 (goto-char beg)
8524 (beginning-of-line 1)
8525 (setq beg (move-marker (make-marker) (point)))
8526 (goto-char end)
8527 (if (bolp) (backward-char 1) (end-of-line 1))
8528 (setq end (move-marker (make-marker) (point)))
8529 ;; Get the right field separator
8530 (unless separator
8531 (goto-char beg)
8532 (setq separator
8533 (cond
8534 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8535 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8536 (t 1))))
8537 (setq re (cond
8538 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8539 ((equal separator '(16)) "^\\|\t")
8540 ((integerp separator)
8541 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8542 (t (error "This should not happen"))))
8543 (goto-char beg)
8544 (while (re-search-forward re end t)
8545 (replace-match "| " t t))
8546 (goto-char beg)
8547 (insert " ")
8548 (org-table-align)))
8550 (defun org-table-import (file arg)
8551 "Import FILE as a table.
8552 The file is assumed to be tab-separated. Such files can be produced by most
8553 spreadsheet and database applications. If no tabs (at least one per line)
8554 are found, lines will be split on whitespace into fields."
8555 (interactive "f\nP")
8556 (or (bolp) (newline))
8557 (let ((beg (point))
8558 (pm (point-max)))
8559 (insert-file-contents file)
8560 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8562 (defun org-table-export ()
8563 "Export table as a tab-separated file.
8564 Such a file can be imported into a spreadsheet program like Excel."
8565 (interactive)
8566 (let* ((beg (org-table-begin))
8567 (end (org-table-end))
8568 (table (buffer-substring beg end))
8569 (file (read-file-name "Export table to: "))
8570 buf)
8571 (unless (or (not (file-exists-p file))
8572 (y-or-n-p (format "Overwrite file %s? " file)))
8573 (error "Abort"))
8574 (with-current-buffer (find-file-noselect file)
8575 (setq buf (current-buffer))
8576 (erase-buffer)
8577 (fundamental-mode)
8578 (insert table)
8579 (goto-char (point-min))
8580 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8581 (replace-match "" t t)
8582 (end-of-line 1))
8583 (goto-char (point-min))
8584 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8585 (replace-match "" t t)
8586 (goto-char (min (1+ (point)) (point-max))))
8587 (goto-char (point-min))
8588 (while (re-search-forward "^-[-+]*$" nil t)
8589 (replace-match "")
8590 (if (looking-at "\n")
8591 (delete-char 1)))
8592 (goto-char (point-min))
8593 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8594 (replace-match "\t" t t))
8595 (save-buffer))
8596 (kill-buffer buf)))
8598 (defvar org-table-aligned-begin-marker (make-marker)
8599 "Marker at the beginning of the table last aligned.
8600 Used to check if cursor still is in that table, to minimize realignment.")
8601 (defvar org-table-aligned-end-marker (make-marker)
8602 "Marker at the end of the table last aligned.
8603 Used to check if cursor still is in that table, to minimize realignment.")
8604 (defvar org-table-last-alignment nil
8605 "List of flags for flushright alignment, from the last re-alignment.
8606 This is being used to correctly align a single field after TAB or RET.")
8607 (defvar org-table-last-column-widths nil
8608 "List of max width of fields in each column.
8609 This is being used to correctly align a single field after TAB or RET.")
8610 (defvar org-table-overlay-coordinates nil
8611 "Overlay coordinates after each align of a table.")
8612 (make-variable-buffer-local 'org-table-overlay-coordinates)
8614 (defvar org-last-recalc-line nil)
8615 (defconst org-narrow-column-arrow "=>"
8616 "Used as display property in narrowed table columns.")
8618 (defun org-table-align ()
8619 "Align the table at point by aligning all vertical bars."
8620 (interactive)
8621 (let* (
8622 ;; Limits of table
8623 (beg (org-table-begin))
8624 (end (org-table-end))
8625 ;; Current cursor position
8626 (linepos (org-current-line))
8627 (colpos (org-table-current-column))
8628 (winstart (window-start))
8629 (winstartline (org-current-line (min winstart (1- (point-max)))))
8630 lines (new "") lengths l typenums ty fields maxfields i
8631 column
8632 (indent "") cnt frac
8633 rfmt hfmt
8634 (spaces '(1 . 1))
8635 (sp1 (car spaces))
8636 (sp2 (cdr spaces))
8637 (rfmt1 (concat
8638 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8639 (hfmt1 (concat
8640 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8641 emptystrings links dates emph narrow fmax f1 len c e)
8642 (untabify beg end)
8643 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8644 ;; Check if we have links or dates
8645 (goto-char beg)
8646 (setq links (re-search-forward org-bracket-link-regexp end t))
8647 (goto-char beg)
8648 (setq emph (and org-hide-emphasis-markers
8649 (re-search-forward org-emph-re end t)))
8650 (goto-char beg)
8651 (setq dates (and org-display-custom-times
8652 (re-search-forward org-ts-regexp-both end t)))
8653 ;; Make sure the link properties are right
8654 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8655 ;; Make sure the date properties are right
8656 (when dates (goto-char beg) (while (org-activate-dates end)))
8657 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8659 ;; Check if we are narrowing any columns
8660 (goto-char beg)
8661 (setq narrow (and org-format-transports-properties-p
8662 (re-search-forward "<[0-9]+>" end t)))
8663 ;; Get the rows
8664 (setq lines (org-split-string
8665 (buffer-substring beg end) "\n"))
8666 ;; Store the indentation of the first line
8667 (if (string-match "^ *" (car lines))
8668 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8669 ;; Mark the hlines by setting the corresponding element to nil
8670 ;; At the same time, we remove trailing space.
8671 (setq lines (mapcar (lambda (l)
8672 (if (string-match "^ *|-" l)
8674 (if (string-match "[ \t]+$" l)
8675 (substring l 0 (match-beginning 0))
8676 l)))
8677 lines))
8678 ;; Get the data fields by splitting the lines.
8679 (setq fields (mapcar
8680 (lambda (l)
8681 (org-split-string l " *| *"))
8682 (delq nil (copy-sequence lines))))
8683 ;; How many fields in the longest line?
8684 (condition-case nil
8685 (setq maxfields (apply 'max (mapcar 'length fields)))
8686 (error
8687 (kill-region beg end)
8688 (org-table-create org-table-default-size)
8689 (error "Empty table - created default table")))
8690 ;; A list of empty strings to fill any short rows on output
8691 (setq emptystrings (make-list maxfields ""))
8692 ;; Check for special formatting.
8693 (setq i -1)
8694 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8695 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8696 ;; Check if there is an explicit width specified
8697 (when narrow
8698 (setq c column fmax nil)
8699 (while c
8700 (setq e (pop c))
8701 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8702 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8703 ;; Find fields that are wider than fmax, and shorten them
8704 (when fmax
8705 (loop for xx in column do
8706 (when (and (stringp xx)
8707 (> (org-string-width xx) fmax))
8708 (org-add-props xx nil
8709 'help-echo
8710 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8711 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8712 (unless (> f1 1)
8713 (error "Cannot narrow field starting with wide link \"%s\""
8714 (match-string 0 xx)))
8715 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8716 (add-text-properties (- f1 2) f1
8717 (list 'display org-narrow-column-arrow)
8718 xx)))))
8719 ;; Get the maximum width for each column
8720 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8721 ;; Get the fraction of numbers, to decide about alignment of the column
8722 (setq cnt 0 frac 0.0)
8723 (loop for x in column do
8724 (if (equal x "")
8726 (setq frac ( / (+ (* frac cnt)
8727 (if (string-match org-table-number-regexp x) 1 0))
8728 (setq cnt (1+ cnt))))))
8729 (push (>= frac org-table-number-fraction) typenums))
8730 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8732 ;; Store the alignment of this table, for later editing of single fields
8733 (setq org-table-last-alignment typenums
8734 org-table-last-column-widths lengths)
8736 ;; With invisible characters, `format' does not get the field width right
8737 ;; So we need to make these fields wide by hand.
8738 (when (or links emph)
8739 (loop for i from 0 upto (1- maxfields) do
8740 (setq len (nth i lengths))
8741 (loop for j from 0 upto (1- (length fields)) do
8742 (setq c (nthcdr i (car (nthcdr j fields))))
8743 (if (and (stringp (car c))
8744 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8745 ; (string-match org-bracket-link-regexp (car c))
8746 (< (org-string-width (car c)) len))
8747 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8749 ;; Compute the formats needed for output of the table
8750 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8751 (while (setq l (pop lengths))
8752 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8753 (setq rfmt (concat rfmt (format rfmt1 ty l))
8754 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8755 (setq rfmt (concat rfmt "\n")
8756 hfmt (concat (substring hfmt 0 -1) "|\n"))
8758 (setq new (mapconcat
8759 (lambda (l)
8760 (if l (apply 'format rfmt
8761 (append (pop fields) emptystrings))
8762 hfmt))
8763 lines ""))
8764 ;; Replace the old one
8765 (delete-region beg end)
8766 (move-marker end nil)
8767 (move-marker org-table-aligned-begin-marker (point))
8768 (insert new)
8769 (move-marker org-table-aligned-end-marker (point))
8770 (when (and orgtbl-mode (not (org-mode-p)))
8771 (goto-char org-table-aligned-begin-marker)
8772 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8773 ;; Try to move to the old location
8774 (goto-line winstartline)
8775 (setq winstart (point-at-bol))
8776 (goto-line linepos)
8777 (set-window-start (selected-window) winstart 'noforce)
8778 (org-table-goto-column colpos)
8779 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8780 (setq org-table-may-need-update nil)
8783 (defun org-string-width (s)
8784 "Compute width of string, ignoring invisible characters.
8785 This ignores character with invisibility property `org-link', and also
8786 characters with property `org-cwidth', because these will become invisible
8787 upon the next fontification round."
8788 (let (b l)
8789 (when (or (eq t buffer-invisibility-spec)
8790 (assq 'org-link buffer-invisibility-spec))
8791 (while (setq b (text-property-any 0 (length s)
8792 'invisible 'org-link s))
8793 (setq s (concat (substring s 0 b)
8794 (substring s (or (next-single-property-change
8795 b 'invisible s) (length s)))))))
8796 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8797 (setq s (concat (substring s 0 b)
8798 (substring s (or (next-single-property-change
8799 b 'org-cwidth s) (length s))))))
8800 (setq l (string-width s) b -1)
8801 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8802 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8805 (defun org-table-begin (&optional table-type)
8806 "Find the beginning of the table and return its position.
8807 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8808 (save-excursion
8809 (if (not (re-search-backward
8810 (if table-type org-table-any-border-regexp
8811 org-table-border-regexp)
8812 nil t))
8813 (progn (goto-char (point-min)) (point))
8814 (goto-char (match-beginning 0))
8815 (beginning-of-line 2)
8816 (point))))
8818 (defun org-table-end (&optional table-type)
8819 "Find the end of the table and return its position.
8820 With argument TABLE-TYPE, go to the end of a table.el-type table."
8821 (save-excursion
8822 (if (not (re-search-forward
8823 (if table-type org-table-any-border-regexp
8824 org-table-border-regexp)
8825 nil t))
8826 (goto-char (point-max))
8827 (goto-char (match-beginning 0)))
8828 (point-marker)))
8830 (defun org-table-justify-field-maybe (&optional new)
8831 "Justify the current field, text to left, number to right.
8832 Optional argument NEW may specify text to replace the current field content."
8833 (cond
8834 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8835 ((org-at-table-hline-p))
8836 ((and (not new)
8837 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8838 (current-buffer)))
8839 (< (point) org-table-aligned-begin-marker)
8840 (>= (point) org-table-aligned-end-marker)))
8841 ;; This is not the same table, force a full re-align
8842 (setq org-table-may-need-update t))
8843 (t ;; realign the current field, based on previous full realign
8844 (let* ((pos (point)) s
8845 (col (org-table-current-column))
8846 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8847 l f n o e)
8848 (when (> col 0)
8849 (skip-chars-backward "^|\n")
8850 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8851 (progn
8852 (setq s (match-string 1)
8853 o (match-string 0)
8854 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8855 e (not (= (match-beginning 2) (match-end 2))))
8856 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8857 l (if e "|" (setq org-table-may-need-update t) ""))
8858 n (format f s))
8859 (if new
8860 (if (<= (length new) l) ;; FIXME: length -> str-width?
8861 (setq n (format f new))
8862 (setq n (concat new "|") org-table-may-need-update t)))
8863 (or (equal n o)
8864 (let (org-table-may-need-update)
8865 (replace-match n t t))))
8866 (setq org-table-may-need-update t))
8867 (goto-char pos))))))
8869 (defun org-table-next-field ()
8870 "Go to the next field in the current table, creating new lines as needed.
8871 Before doing so, re-align the table if necessary."
8872 (interactive)
8873 (org-table-maybe-eval-formula)
8874 (org-table-maybe-recalculate-line)
8875 (if (and org-table-automatic-realign
8876 org-table-may-need-update)
8877 (org-table-align))
8878 (let ((end (org-table-end)))
8879 (if (org-at-table-hline-p)
8880 (end-of-line 1))
8881 (condition-case nil
8882 (progn
8883 (re-search-forward "|" end)
8884 (if (looking-at "[ \t]*$")
8885 (re-search-forward "|" end))
8886 (if (and (looking-at "-")
8887 org-table-tab-jumps-over-hlines
8888 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8889 (goto-char (match-beginning 1)))
8890 (if (looking-at "-")
8891 (progn
8892 (beginning-of-line 0)
8893 (org-table-insert-row 'below))
8894 (if (looking-at " ") (forward-char 1))))
8895 (error
8896 (org-table-insert-row 'below)))))
8898 (defun org-table-previous-field ()
8899 "Go to the previous field in the table.
8900 Before doing so, re-align the table if necessary."
8901 (interactive)
8902 (org-table-justify-field-maybe)
8903 (org-table-maybe-recalculate-line)
8904 (if (and org-table-automatic-realign
8905 org-table-may-need-update)
8906 (org-table-align))
8907 (if (org-at-table-hline-p)
8908 (end-of-line 1))
8909 (re-search-backward "|" (org-table-begin))
8910 (re-search-backward "|" (org-table-begin))
8911 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8912 (re-search-backward "|" (org-table-begin)))
8913 (if (looking-at "| ?")
8914 (goto-char (match-end 0))))
8916 (defun org-table-next-row ()
8917 "Go to the next row (same column) in the current table.
8918 Before doing so, re-align the table if necessary."
8919 (interactive)
8920 (org-table-maybe-eval-formula)
8921 (org-table-maybe-recalculate-line)
8922 (if (or (looking-at "[ \t]*$")
8923 (save-excursion (skip-chars-backward " \t") (bolp)))
8924 (newline)
8925 (if (and org-table-automatic-realign
8926 org-table-may-need-update)
8927 (org-table-align))
8928 (let ((col (org-table-current-column)))
8929 (beginning-of-line 2)
8930 (if (or (not (org-at-table-p))
8931 (org-at-table-hline-p))
8932 (progn
8933 (beginning-of-line 0)
8934 (org-table-insert-row 'below)))
8935 (org-table-goto-column col)
8936 (skip-chars-backward "^|\n\r")
8937 (if (looking-at " ") (forward-char 1)))))
8939 (defun org-table-copy-down (n)
8940 "Copy a field down in the current column.
8941 If the field at the cursor is empty, copy into it the content of the nearest
8942 non-empty field above. With argument N, use the Nth non-empty field.
8943 If the current field is not empty, it is copied down to the next row, and
8944 the cursor is moved with it. Therefore, repeating this command causes the
8945 column to be filled row-by-row.
8946 If the variable `org-table-copy-increment' is non-nil and the field is an
8947 integer or a timestamp, it will be incremented while copying. In the case of
8948 a timestamp, if the cursor is on the year, change the year. If it is on the
8949 month or the day, change that. Point will stay on the current date field
8950 in order to easily repeat the interval."
8951 (interactive "p")
8952 (let* ((colpos (org-table-current-column))
8953 (col (current-column))
8954 (field (org-table-get-field))
8955 (non-empty (string-match "[^ \t]" field))
8956 (beg (org-table-begin))
8957 txt)
8958 (org-table-check-inside-data-field)
8959 (if non-empty
8960 (progn
8961 (setq txt (org-trim field))
8962 (org-table-next-row)
8963 (org-table-blank-field))
8964 (save-excursion
8965 (setq txt
8966 (catch 'exit
8967 (while (progn (beginning-of-line 1)
8968 (re-search-backward org-table-dataline-regexp
8969 beg t))
8970 (org-table-goto-column colpos t)
8971 (if (and (looking-at
8972 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8973 (= (setq n (1- n)) 0))
8974 (throw 'exit (match-string 1))))))))
8975 (if txt
8976 (progn
8977 (if (and org-table-copy-increment
8978 (string-match "^[0-9]+$" txt))
8979 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8980 (insert txt)
8981 (move-to-column col)
8982 (if (and org-table-copy-increment (org-at-timestamp-p t))
8983 (org-timestamp-up 1)
8984 (org-table-maybe-recalculate-line))
8985 (org-table-align)
8986 (move-to-column col))
8987 (error "No non-empty field found"))))
8989 (defun org-table-check-inside-data-field ()
8990 "Is point inside a table data field?
8991 I.e. not on a hline or before the first or after the last column?
8992 This actually throws an error, so it aborts the current command."
8993 (if (or (not (org-at-table-p))
8994 (= (org-table-current-column) 0)
8995 (org-at-table-hline-p)
8996 (looking-at "[ \t]*$"))
8997 (error "Not in table data field")))
8999 (defvar org-table-clip nil
9000 "Clipboard for table regions.")
9002 (defun org-table-blank-field ()
9003 "Blank the current table field or active region."
9004 (interactive)
9005 (org-table-check-inside-data-field)
9006 (if (and (interactive-p) (org-region-active-p))
9007 (let (org-table-clip)
9008 (org-table-cut-region (region-beginning) (region-end)))
9009 (skip-chars-backward "^|")
9010 (backward-char 1)
9011 (if (looking-at "|[^|\n]+")
9012 (let* ((pos (match-beginning 0))
9013 (match (match-string 0))
9014 (len (org-string-width match)))
9015 (replace-match (concat "|" (make-string (1- len) ?\ )))
9016 (goto-char (+ 2 pos))
9017 (substring match 1)))))
9019 (defun org-table-get-field (&optional n replace)
9020 "Return the value of the field in column N of current row.
9021 N defaults to current field.
9022 If REPLACE is a string, replace field with this value. The return value
9023 is always the old value."
9024 (and n (org-table-goto-column n))
9025 (skip-chars-backward "^|\n")
9026 (backward-char 1)
9027 (if (looking-at "|[^|\r\n]*")
9028 (let* ((pos (match-beginning 0))
9029 (val (buffer-substring (1+ pos) (match-end 0))))
9030 (if replace
9031 (replace-match (concat "|" replace) t t))
9032 (goto-char (min (point-at-eol) (+ 2 pos)))
9033 val)
9034 (forward-char 1) ""))
9036 (defun org-table-field-info (arg)
9037 "Show info about the current field, and highlight any reference at point."
9038 (interactive "P")
9039 (org-table-get-specials)
9040 (save-excursion
9041 (let* ((pos (point))
9042 (col (org-table-current-column))
9043 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9044 (name (car (rassoc (list (org-current-line) col)
9045 org-table-named-field-locations)))
9046 (eql (org-table-get-stored-formulas))
9047 (dline (org-table-current-dline))
9048 (ref (format "@%d$%d" dline col))
9049 (ref1 (org-table-convert-refs-to-an ref))
9050 (fequation (or (assoc name eql) (assoc ref eql)))
9051 (cequation (assoc (int-to-string col) eql))
9052 (eqn (or fequation cequation)))
9053 (goto-char pos)
9054 (condition-case nil
9055 (org-table-show-reference 'local)
9056 (error nil))
9057 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9058 dline col
9059 (if cname (concat " or $" cname) "")
9060 dline col ref1
9061 (if name (concat " or $" name) "")
9062 ;; FIXME: formula info not correct if special table line
9063 (if eqn
9064 (concat ", formula: "
9065 (org-table-formula-to-user
9066 (concat
9067 (if (string-match "^[$@]"(car eqn)) "" "$")
9068 (car eqn) "=" (cdr eqn))))
9069 "")))))
9071 (defun org-table-current-column ()
9072 "Find out which column we are in.
9073 When called interactively, column is also displayed in echo area."
9074 (interactive)
9075 (if (interactive-p) (org-table-check-inside-data-field))
9076 (save-excursion
9077 (let ((cnt 0) (pos (point)))
9078 (beginning-of-line 1)
9079 (while (search-forward "|" pos t)
9080 (setq cnt (1+ cnt)))
9081 (if (interactive-p) (message "This is table column %d" cnt))
9082 cnt)))
9084 (defun org-table-current-dline ()
9085 "Find out what table data line we are in.
9086 Only datalins count for this."
9087 (interactive)
9088 (if (interactive-p) (org-table-check-inside-data-field))
9089 (save-excursion
9090 (let ((cnt 0) (pos (point)))
9091 (goto-char (org-table-begin))
9092 (while (<= (point) pos)
9093 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9094 (beginning-of-line 2))
9095 (if (interactive-p) (message "This is table line %d" cnt))
9096 cnt)))
9098 (defun org-table-goto-column (n &optional on-delim force)
9099 "Move the cursor to the Nth column in the current table line.
9100 With optional argument ON-DELIM, stop with point before the left delimiter
9101 of the field.
9102 If there are less than N fields, just go to after the last delimiter.
9103 However, when FORCE is non-nil, create new columns if necessary."
9104 (interactive "p")
9105 (let ((pos (point-at-eol)))
9106 (beginning-of-line 1)
9107 (when (> n 0)
9108 (while (and (> (setq n (1- n)) -1)
9109 (or (search-forward "|" pos t)
9110 (and force
9111 (progn (end-of-line 1)
9112 (skip-chars-backward "^|")
9113 (insert " | "))))))
9114 ; (backward-char 2) t)))))
9115 (when (and force (not (looking-at ".*|")))
9116 (save-excursion (end-of-line 1) (insert " | ")))
9117 (if on-delim
9118 (backward-char 1)
9119 (if (looking-at " ") (forward-char 1))))))
9121 (defun org-at-table-p (&optional table-type)
9122 "Return t if the cursor is inside an org-type table.
9123 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9124 (if org-enable-table-editor
9125 (save-excursion
9126 (beginning-of-line 1)
9127 (looking-at (if table-type org-table-any-line-regexp
9128 org-table-line-regexp)))
9129 nil))
9131 (defun org-at-table.el-p ()
9132 "Return t if and only if we are at a table.el table."
9133 (and (org-at-table-p 'any)
9134 (save-excursion
9135 (goto-char (org-table-begin 'any))
9136 (looking-at org-table1-hline-regexp))))
9138 (defun org-table-recognize-table.el ()
9139 "If there is a table.el table nearby, recognize it and move into it."
9140 (if org-table-tab-recognizes-table.el
9141 (if (org-at-table.el-p)
9142 (progn
9143 (beginning-of-line 1)
9144 (if (looking-at org-table-dataline-regexp)
9146 (if (looking-at org-table1-hline-regexp)
9147 (progn
9148 (beginning-of-line 2)
9149 (if (looking-at org-table-any-border-regexp)
9150 (beginning-of-line -1)))))
9151 (if (re-search-forward "|" (org-table-end t) t)
9152 (progn
9153 (require 'table)
9154 (if (table--at-cell-p (point))
9156 (message "recognizing table.el table...")
9157 (table-recognize-table)
9158 (message "recognizing table.el table...done")))
9159 (error "This should not happen..."))
9161 nil)
9162 nil))
9164 (defun org-at-table-hline-p ()
9165 "Return t if the cursor is inside a hline in a table."
9166 (if org-enable-table-editor
9167 (save-excursion
9168 (beginning-of-line 1)
9169 (looking-at org-table-hline-regexp))
9170 nil))
9172 (defun org-table-insert-column ()
9173 "Insert a new column into the table."
9174 (interactive)
9175 (if (not (org-at-table-p))
9176 (error "Not at a table"))
9177 (org-table-find-dataline)
9178 (let* ((col (max 1 (org-table-current-column)))
9179 (beg (org-table-begin))
9180 (end (org-table-end))
9181 ;; Current cursor position
9182 (linepos (org-current-line))
9183 (colpos col))
9184 (goto-char beg)
9185 (while (< (point) end)
9186 (if (org-at-table-hline-p)
9188 (org-table-goto-column col t)
9189 (insert "| "))
9190 (beginning-of-line 2))
9191 (move-marker end nil)
9192 (goto-line linepos)
9193 (org-table-goto-column colpos)
9194 (org-table-align)
9195 (org-table-fix-formulas "$" nil (1- col) 1)))
9197 (defun org-table-find-dataline ()
9198 "Find a dataline in the current table, which is needed for column commands."
9199 (if (and (org-at-table-p)
9200 (not (org-at-table-hline-p)))
9202 (let ((col (current-column))
9203 (end (org-table-end)))
9204 (move-to-column col)
9205 (while (and (< (point) end)
9206 (or (not (= (current-column) col))
9207 (org-at-table-hline-p)))
9208 (beginning-of-line 2)
9209 (move-to-column col))
9210 (if (and (org-at-table-p)
9211 (not (org-at-table-hline-p)))
9213 (error
9214 "Please position cursor in a data line for column operations")))))
9216 (defun org-table-delete-column ()
9217 "Delete a column from the table."
9218 (interactive)
9219 (if (not (org-at-table-p))
9220 (error "Not at a table"))
9221 (org-table-find-dataline)
9222 (org-table-check-inside-data-field)
9223 (let* ((col (org-table-current-column))
9224 (beg (org-table-begin))
9225 (end (org-table-end))
9226 ;; Current cursor position
9227 (linepos (org-current-line))
9228 (colpos col))
9229 (goto-char beg)
9230 (while (< (point) end)
9231 (if (org-at-table-hline-p)
9233 (org-table-goto-column col t)
9234 (and (looking-at "|[^|\n]+|")
9235 (replace-match "|")))
9236 (beginning-of-line 2))
9237 (move-marker end nil)
9238 (goto-line linepos)
9239 (org-table-goto-column colpos)
9240 (org-table-align)
9241 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9242 col -1 col)))
9244 (defun org-table-move-column-right ()
9245 "Move column to the right."
9246 (interactive)
9247 (org-table-move-column nil))
9248 (defun org-table-move-column-left ()
9249 "Move column to the left."
9250 (interactive)
9251 (org-table-move-column 'left))
9253 (defun org-table-move-column (&optional left)
9254 "Move the current column to the right. With arg LEFT, move to the left."
9255 (interactive "P")
9256 (if (not (org-at-table-p))
9257 (error "Not at a table"))
9258 (org-table-find-dataline)
9259 (org-table-check-inside-data-field)
9260 (let* ((col (org-table-current-column))
9261 (col1 (if left (1- col) col))
9262 (beg (org-table-begin))
9263 (end (org-table-end))
9264 ;; Current cursor position
9265 (linepos (org-current-line))
9266 (colpos (if left (1- col) (1+ col))))
9267 (if (and left (= col 1))
9268 (error "Cannot move column further left"))
9269 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9270 (error "Cannot move column further right"))
9271 (goto-char beg)
9272 (while (< (point) end)
9273 (if (org-at-table-hline-p)
9275 (org-table-goto-column col1 t)
9276 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9277 (replace-match "|\\2|\\1|")))
9278 (beginning-of-line 2))
9279 (move-marker end nil)
9280 (goto-line linepos)
9281 (org-table-goto-column colpos)
9282 (org-table-align)
9283 (org-table-fix-formulas
9284 "$" (list (cons (number-to-string col) (number-to-string colpos))
9285 (cons (number-to-string colpos) (number-to-string col))))))
9287 (defun org-table-move-row-down ()
9288 "Move table row down."
9289 (interactive)
9290 (org-table-move-row nil))
9291 (defun org-table-move-row-up ()
9292 "Move table row up."
9293 (interactive)
9294 (org-table-move-row 'up))
9296 (defun org-table-move-row (&optional up)
9297 "Move the current table line down. With arg UP, move it up."
9298 (interactive "P")
9299 (let* ((col (current-column))
9300 (pos (point))
9301 (hline1p (save-excursion (beginning-of-line 1)
9302 (looking-at org-table-hline-regexp)))
9303 (dline1 (org-table-current-dline))
9304 (dline2 (+ dline1 (if up -1 1)))
9305 (tonew (if up 0 2))
9306 txt hline2p)
9307 (beginning-of-line tonew)
9308 (unless (org-at-table-p)
9309 (goto-char pos)
9310 (error "Cannot move row further"))
9311 (setq hline2p (looking-at org-table-hline-regexp))
9312 (goto-char pos)
9313 (beginning-of-line 1)
9314 (setq pos (point))
9315 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9316 (delete-region (point) (1+ (point-at-eol)))
9317 (beginning-of-line tonew)
9318 (insert txt)
9319 (beginning-of-line 0)
9320 (move-to-column col)
9321 (unless (or hline1p hline2p)
9322 (org-table-fix-formulas
9323 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9324 (cons (number-to-string dline2) (number-to-string dline1)))))))
9326 (defun org-table-insert-row (&optional arg)
9327 "Insert a new row above the current line into the table.
9328 With prefix ARG, insert below the current line."
9329 (interactive "P")
9330 (if (not (org-at-table-p))
9331 (error "Not at a table"))
9332 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9333 (new (org-table-clean-line line)))
9334 ;; Fix the first field if necessary
9335 (if (string-match "^[ \t]*| *[#$] *|" line)
9336 (setq new (replace-match (match-string 0 line) t t new)))
9337 (beginning-of-line (if arg 2 1))
9338 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9339 (beginning-of-line 0)
9340 (re-search-forward "| ?" (point-at-eol) t)
9341 (and (or org-table-may-need-update org-table-overlay-coordinates)
9342 (org-table-align))
9343 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9345 (defun org-table-insert-hline (&optional above)
9346 "Insert a horizontal-line below the current line into the table.
9347 With prefix ABOVE, insert above the current line."
9348 (interactive "P")
9349 (if (not (org-at-table-p))
9350 (error "Not at a table"))
9351 (let ((line (org-table-clean-line
9352 (buffer-substring (point-at-bol) (point-at-eol))))
9353 (col (current-column)))
9354 (while (string-match "|\\( +\\)|" line)
9355 (setq line (replace-match
9356 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9357 ?-) "|") t t line)))
9358 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9359 (beginning-of-line (if above 1 2))
9360 (insert line "\n")
9361 (beginning-of-line (if above 1 -1))
9362 (move-to-column col)
9363 (and org-table-overlay-coordinates (org-table-align))))
9365 (defun org-table-hline-and-move (&optional same-column)
9366 "Insert a hline and move to the row below that line."
9367 (interactive "P")
9368 (let ((col (org-table-current-column)))
9369 (org-table-maybe-eval-formula)
9370 (org-table-maybe-recalculate-line)
9371 (org-table-insert-hline)
9372 (end-of-line 2)
9373 (if (looking-at "\n[ \t]*|-")
9374 (progn (insert "\n|") (org-table-align))
9375 (org-table-next-field))
9376 (if same-column (org-table-goto-column col))))
9378 (defun org-table-clean-line (s)
9379 "Convert a table line S into a string with only \"|\" and space.
9380 In particular, this does handle wide and invisible characters."
9381 (if (string-match "^[ \t]*|-" s)
9382 ;; It's a hline, just map the characters
9383 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9384 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9385 (setq s (replace-match
9386 (concat "|" (make-string (org-string-width (match-string 1 s))
9387 ?\ ) "|")
9388 t t s)))
9391 (defun org-table-kill-row ()
9392 "Delete the current row or horizontal line from the table."
9393 (interactive)
9394 (if (not (org-at-table-p))
9395 (error "Not at a table"))
9396 (let ((col (current-column))
9397 (dline (org-table-current-dline)))
9398 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9399 (if (not (org-at-table-p)) (beginning-of-line 0))
9400 (move-to-column col)
9401 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9402 dline -1 dline)))
9404 (defun org-table-sort-lines (with-case &optional sorting-type)
9405 "Sort table lines according to the column at point.
9407 The position of point indicates the column to be used for
9408 sorting, and the range of lines is the range between the nearest
9409 horizontal separator lines, or the entire table of no such lines
9410 exist. If point is before the first column, you will be prompted
9411 for the sorting column. If there is an active region, the mark
9412 specifies the first line and the sorting column, while point
9413 should be in the last line to be included into the sorting.
9415 The command then prompts for the sorting type which can be
9416 alphabetically, numerically, or by time (as given in a time stamp
9417 in the field). Sorting in reverse order is also possible.
9419 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9421 If SORTING-TYPE is specified when this function is called from a Lisp
9422 program, no prompting will take place. SORTING-TYPE must be a character,
9423 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9424 should be done in reverse order."
9425 (interactive "P")
9426 (let* ((thisline (org-current-line))
9427 (thiscol (org-table-current-column))
9428 beg end bcol ecol tend tbeg column lns pos)
9429 (when (equal thiscol 0)
9430 (if (interactive-p)
9431 (setq thiscol
9432 (string-to-number
9433 (read-string "Use column N for sorting: ")))
9434 (setq thiscol 1))
9435 (org-table-goto-column thiscol))
9436 (org-table-check-inside-data-field)
9437 (if (org-region-active-p)
9438 (progn
9439 (setq beg (region-beginning) end (region-end))
9440 (goto-char beg)
9441 (setq column (org-table-current-column)
9442 beg (point-at-bol))
9443 (goto-char end)
9444 (setq end (point-at-bol 2)))
9445 (setq column (org-table-current-column)
9446 pos (point)
9447 tbeg (org-table-begin)
9448 tend (org-table-end))
9449 (if (re-search-backward org-table-hline-regexp tbeg t)
9450 (setq beg (point-at-bol 2))
9451 (goto-char tbeg)
9452 (setq beg (point-at-bol 1)))
9453 (goto-char pos)
9454 (if (re-search-forward org-table-hline-regexp tend t)
9455 (setq end (point-at-bol 1))
9456 (goto-char tend)
9457 (setq end (point-at-bol))))
9458 (setq beg (move-marker (make-marker) beg)
9459 end (move-marker (make-marker) end))
9460 (untabify beg end)
9461 (goto-char beg)
9462 (org-table-goto-column column)
9463 (skip-chars-backward "^|")
9464 (setq bcol (current-column))
9465 (org-table-goto-column (1+ column))
9466 (skip-chars-backward "^|")
9467 (setq ecol (1- (current-column)))
9468 (org-table-goto-column column)
9469 (setq lns (mapcar (lambda(x) (cons
9470 (org-sort-remove-invisible
9471 (nth (1- column)
9472 (org-split-string x "[ \t]*|[ \t]*")))
9474 (org-split-string (buffer-substring beg end) "\n")))
9475 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9476 (delete-region beg end)
9477 (move-marker beg nil)
9478 (move-marker end nil)
9479 (insert (mapconcat 'cdr lns "\n") "\n")
9480 (goto-line thisline)
9481 (org-table-goto-column thiscol)
9482 (message "%d lines sorted, based on column %d" (length lns) column)))
9484 ;; FIXME: maybe we will not need this? Table sorting is broken....
9485 (defun org-sort-remove-invisible (s)
9486 (remove-text-properties 0 (length s) org-rm-props s)
9487 (while (string-match org-bracket-link-regexp s)
9488 (setq s (replace-match (if (match-end 2)
9489 (match-string 3 s)
9490 (match-string 1 s)) t t s)))
9493 (defun org-table-cut-region (beg end)
9494 "Copy region in table to the clipboard and blank all relevant fields."
9495 (interactive "r")
9496 (org-table-copy-region beg end 'cut))
9498 (defun org-table-copy-region (beg end &optional cut)
9499 "Copy rectangular region in table to clipboard.
9500 A special clipboard is used which can only be accessed
9501 with `org-table-paste-rectangle'."
9502 (interactive "rP")
9503 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9504 region cols
9505 (rpl (if cut " " nil)))
9506 (goto-char beg)
9507 (org-table-check-inside-data-field)
9508 (setq l01 (org-current-line)
9509 c01 (org-table-current-column))
9510 (goto-char end)
9511 (org-table-check-inside-data-field)
9512 (setq l02 (org-current-line)
9513 c02 (org-table-current-column))
9514 (setq l1 (min l01 l02) l2 (max l01 l02)
9515 c1 (min c01 c02) c2 (max c01 c02))
9516 (catch 'exit
9517 (while t
9518 (catch 'nextline
9519 (if (> l1 l2) (throw 'exit t))
9520 (goto-line l1)
9521 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9522 (setq cols nil ic1 c1 ic2 c2)
9523 (while (< ic1 (1+ ic2))
9524 (push (org-table-get-field ic1 rpl) cols)
9525 (setq ic1 (1+ ic1)))
9526 (push (nreverse cols) region)
9527 (setq l1 (1+ l1)))))
9528 (setq org-table-clip (nreverse region))
9529 (if cut (org-table-align))
9530 org-table-clip))
9532 (defun org-table-paste-rectangle ()
9533 "Paste a rectangular region into a table.
9534 The upper right corner ends up in the current field. All involved fields
9535 will be overwritten. If the rectangle does not fit into the present table,
9536 the table is enlarged as needed. The process ignores horizontal separator
9537 lines."
9538 (interactive)
9539 (unless (and org-table-clip (listp org-table-clip))
9540 (error "First cut/copy a region to paste!"))
9541 (org-table-check-inside-data-field)
9542 (let* ((clip org-table-clip)
9543 (line (org-current-line))
9544 (col (org-table-current-column))
9545 (org-enable-table-editor t)
9546 (org-table-automatic-realign nil)
9547 c cols field)
9548 (while (setq cols (pop clip))
9549 (while (org-at-table-hline-p) (beginning-of-line 2))
9550 (if (not (org-at-table-p))
9551 (progn (end-of-line 0) (org-table-next-field)))
9552 (setq c col)
9553 (while (setq field (pop cols))
9554 (org-table-goto-column c nil 'force)
9555 (org-table-get-field nil field)
9556 (setq c (1+ c)))
9557 (beginning-of-line 2))
9558 (goto-line line)
9559 (org-table-goto-column col)
9560 (org-table-align)))
9562 (defun org-table-convert ()
9563 "Convert from `org-mode' table to table.el and back.
9564 Obviously, this only works within limits. When an Org-mode table is
9565 converted to table.el, all horizontal separator lines get lost, because
9566 table.el uses these as cell boundaries and has no notion of horizontal lines.
9567 A table.el table can be converted to an Org-mode table only if it does not
9568 do row or column spanning. Multiline cells will become multiple cells.
9569 Beware, Org-mode does not test if the table can be successfully converted - it
9570 blindly applies a recipe that works for simple tables."
9571 (interactive)
9572 (require 'table)
9573 (if (org-at-table.el-p)
9574 ;; convert to Org-mode table
9575 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9576 (end (move-marker (make-marker) (org-table-end t))))
9577 (table-unrecognize-region beg end)
9578 (goto-char beg)
9579 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9580 (replace-match ""))
9581 (goto-char beg))
9582 (if (org-at-table-p)
9583 ;; convert to table.el table
9584 (let ((beg (move-marker (make-marker) (org-table-begin)))
9585 (end (move-marker (make-marker) (org-table-end))))
9586 ;; first, get rid of all horizontal lines
9587 (goto-char beg)
9588 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9589 (replace-match ""))
9590 ;; insert a hline before first
9591 (goto-char beg)
9592 (org-table-insert-hline 'above)
9593 (beginning-of-line -1)
9594 ;; insert a hline after each line
9595 (while (progn (beginning-of-line 3) (< (point) end))
9596 (org-table-insert-hline))
9597 (goto-char beg)
9598 (setq end (move-marker end (org-table-end)))
9599 ;; replace "+" at beginning and ending of hlines
9600 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9601 (replace-match "\\1+-"))
9602 (goto-char beg)
9603 (while (re-search-forward "-|[ \t]*$" end t)
9604 (replace-match "-+"))
9605 (goto-char beg)))))
9607 (defun org-table-wrap-region (arg)
9608 "Wrap several fields in a column like a paragraph.
9609 This is useful if you'd like to spread the contents of a field over several
9610 lines, in order to keep the table compact.
9612 If there is an active region, and both point and mark are in the same column,
9613 the text in the column is wrapped to minimum width for the given number of
9614 lines. Generally, this makes the table more compact. A prefix ARG may be
9615 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9616 formats the selected text to two lines. If the region was longer than two
9617 lines, the remaining lines remain empty. A negative prefix argument reduces
9618 the current number of lines by that amount. The wrapped text is pasted back
9619 into the table. If you formatted it to more lines than it was before, fields
9620 further down in the table get overwritten - so you might need to make space in
9621 the table first.
9623 If there is no region, the current field is split at the cursor position and
9624 the text fragment to the right of the cursor is prepended to the field one
9625 line down.
9627 If there is no region, but you specify a prefix ARG, the current field gets
9628 blank, and the content is appended to the field above."
9629 (interactive "P")
9630 (org-table-check-inside-data-field)
9631 (if (org-region-active-p)
9632 ;; There is a region: fill as a paragraph
9633 (let* ((beg (region-beginning))
9634 (cline (save-excursion (goto-char beg) (org-current-line)))
9635 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9636 nlines)
9637 (org-table-cut-region (region-beginning) (region-end))
9638 (if (> (length (car org-table-clip)) 1)
9639 (error "Region must be limited to single column"))
9640 (setq nlines (if arg
9641 (if (< arg 1)
9642 (+ (length org-table-clip) arg)
9643 arg)
9644 (length org-table-clip)))
9645 (setq org-table-clip
9646 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9647 nil nlines)))
9648 (goto-line cline)
9649 (org-table-goto-column ccol)
9650 (org-table-paste-rectangle))
9651 ;; No region, split the current field at point
9652 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9653 (skip-chars-forward "^\r\n|"))
9654 (if arg
9655 ;; combine with field above
9656 (let ((s (org-table-blank-field))
9657 (col (org-table-current-column)))
9658 (beginning-of-line 0)
9659 (while (org-at-table-hline-p) (beginning-of-line 0))
9660 (org-table-goto-column col)
9661 (skip-chars-forward "^|")
9662 (skip-chars-backward " ")
9663 (insert " " (org-trim s))
9664 (org-table-align))
9665 ;; split field
9666 (if (looking-at "\\([^|]+\\)+|")
9667 (let ((s (match-string 1)))
9668 (replace-match " |")
9669 (goto-char (match-beginning 0))
9670 (org-table-next-row)
9671 (insert (org-trim s) " ")
9672 (org-table-align))
9673 (org-table-next-row)))))
9675 (defvar org-field-marker nil)
9677 (defun org-table-edit-field (arg)
9678 "Edit table field in a different window.
9679 This is mainly useful for fields that contain hidden parts.
9680 When called with a \\[universal-argument] prefix, just make the full field visible so that
9681 it can be edited in place."
9682 (interactive "P")
9683 (if arg
9684 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9685 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9686 (remove-text-properties b e '(org-cwidth t invisible t
9687 display t intangible t))
9688 (if (and (boundp 'font-lock-mode) font-lock-mode)
9689 (font-lock-fontify-block)))
9690 (let ((pos (move-marker (make-marker) (point)))
9691 (field (org-table-get-field))
9692 (cw (current-window-configuration))
9694 (org-switch-to-buffer-other-window "*Org tmp*")
9695 (erase-buffer)
9696 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9697 (let ((org-inhibit-startup t)) (org-mode))
9698 (goto-char (setq p (point-max)))
9699 (insert (org-trim field))
9700 (remove-text-properties p (point-max)
9701 '(invisible t org-cwidth t display t
9702 intangible t))
9703 (goto-char p)
9704 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9705 (org-set-local 'org-window-configuration cw)
9706 (org-set-local 'org-field-marker pos)
9707 (message "Edit and finish with C-c C-c"))))
9709 (defun org-table-finish-edit-field ()
9710 "Finish editing a table data field.
9711 Remove all newline characters, insert the result into the table, realign
9712 the table and kill the editing buffer."
9713 (let ((pos org-field-marker)
9714 (cw org-window-configuration)
9715 (cb (current-buffer))
9716 text)
9717 (goto-char (point-min))
9718 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9719 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9720 (replace-match " "))
9721 (setq text (org-trim (buffer-string)))
9722 (set-window-configuration cw)
9723 (kill-buffer cb)
9724 (select-window (get-buffer-window (marker-buffer pos)))
9725 (goto-char pos)
9726 (move-marker pos nil)
9727 (org-table-check-inside-data-field)
9728 (org-table-get-field nil text)
9729 (org-table-align)
9730 (message "New field value inserted")))
9732 (defun org-trim (s)
9733 "Remove whitespace at beginning and end of string."
9734 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9735 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9738 (defun org-wrap (string &optional width lines)
9739 "Wrap string to either a number of lines, or a width in characters.
9740 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9741 that costs. If there is a word longer than WIDTH, the text is actually
9742 wrapped to the length of that word.
9743 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9744 many lines, whatever width that takes.
9745 The return value is a list of lines, without newlines at the end."
9746 (let* ((words (org-split-string string "[ \t\n]+"))
9747 (maxword (apply 'max (mapcar 'org-string-width words)))
9748 w ll)
9749 (cond (width
9750 (org-do-wrap words (max maxword width)))
9751 (lines
9752 (setq w maxword)
9753 (setq ll (org-do-wrap words maxword))
9754 (if (<= (length ll) lines)
9756 (setq ll words)
9757 (while (> (length ll) lines)
9758 (setq w (1+ w))
9759 (setq ll (org-do-wrap words w)))
9760 ll))
9761 (t (error "Cannot wrap this")))))
9764 (defun org-do-wrap (words width)
9765 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9766 (let (lines line)
9767 (while words
9768 (setq line (pop words))
9769 (while (and words (< (+ (length line) (length (car words))) width))
9770 (setq line (concat line " " (pop words))))
9771 (setq lines (push line lines)))
9772 (nreverse lines)))
9774 (defun org-split-string (string &optional separators)
9775 "Splits STRING into substrings at SEPARATORS.
9776 No empty strings are returned if there are matches at the beginning
9777 and end of string."
9778 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9779 (start 0)
9780 notfirst
9781 (list nil))
9782 (while (and (string-match rexp string
9783 (if (and notfirst
9784 (= start (match-beginning 0))
9785 (< start (length string)))
9786 (1+ start) start))
9787 (< (match-beginning 0) (length string)))
9788 (setq notfirst t)
9789 (or (eq (match-beginning 0) 0)
9790 (and (eq (match-beginning 0) (match-end 0))
9791 (eq (match-beginning 0) start))
9792 (setq list
9793 (cons (substring string start (match-beginning 0))
9794 list)))
9795 (setq start (match-end 0)))
9796 (or (eq start (length string))
9797 (setq list
9798 (cons (substring string start)
9799 list)))
9800 (nreverse list)))
9802 (defun org-table-map-tables (function)
9803 "Apply FUNCTION to the start of all tables in the buffer."
9804 (save-excursion
9805 (save-restriction
9806 (widen)
9807 (goto-char (point-min))
9808 (while (re-search-forward org-table-any-line-regexp nil t)
9809 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9810 (beginning-of-line 1)
9811 (if (looking-at org-table-line-regexp)
9812 (save-excursion (funcall function)))
9813 (re-search-forward org-table-any-border-regexp nil 1))))
9814 (message "Mapping tables: done"))
9816 (defvar org-timecnt) ; dynamically scoped parameter
9818 (defun org-table-sum (&optional beg end nlast)
9819 "Sum numbers in region of current table column.
9820 The result will be displayed in the echo area, and will be available
9821 as kill to be inserted with \\[yank].
9823 If there is an active region, it is interpreted as a rectangle and all
9824 numbers in that rectangle will be summed. If there is no active
9825 region and point is located in a table column, sum all numbers in that
9826 column.
9828 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9829 numbers are assumed to be times as well (in decimal hours) and the
9830 numbers are added as such.
9832 If NLAST is a number, only the NLAST fields will actually be summed."
9833 (interactive)
9834 (save-excursion
9835 (let (col (org-timecnt 0) diff h m s org-table-clip)
9836 (cond
9837 ((and beg end)) ; beg and end given explicitly
9838 ((org-region-active-p)
9839 (setq beg (region-beginning) end (region-end)))
9841 (setq col (org-table-current-column))
9842 (goto-char (org-table-begin))
9843 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9844 (error "No table data"))
9845 (org-table-goto-column col)
9846 (setq beg (point))
9847 (goto-char (org-table-end))
9848 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9849 (error "No table data"))
9850 (org-table-goto-column col)
9851 (setq end (point))))
9852 (let* ((items (apply 'append (org-table-copy-region beg end)))
9853 (items1 (cond ((not nlast) items)
9854 ((>= nlast (length items)) items)
9855 (t (setq items (reverse items))
9856 (setcdr (nthcdr (1- nlast) items) nil)
9857 (nreverse items))))
9858 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9859 items1)))
9860 (res (apply '+ numbers))
9861 (sres (if (= org-timecnt 0)
9862 (format "%g" res)
9863 (setq diff (* 3600 res)
9864 h (floor (/ diff 3600)) diff (mod diff 3600)
9865 m (floor (/ diff 60)) diff (mod diff 60)
9866 s diff)
9867 (format "%d:%02d:%02d" h m s))))
9868 (kill-new sres)
9869 (if (interactive-p)
9870 (message "%s"
9871 (substitute-command-keys
9872 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9873 (length numbers) sres))))
9874 sres))))
9876 (defun org-table-get-number-for-summing (s)
9877 (let (n)
9878 (if (string-match "^ *|? *" s)
9879 (setq s (replace-match "" nil nil s)))
9880 (if (string-match " *|? *$" s)
9881 (setq s (replace-match "" nil nil s)))
9882 (setq n (string-to-number s))
9883 (cond
9884 ((and (string-match "0" s)
9885 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9886 ((string-match "\\`[ \t]+\\'" s) nil)
9887 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9888 (let ((h (string-to-number (or (match-string 1 s) "0")))
9889 (m (string-to-number (or (match-string 2 s) "0")))
9890 (s (string-to-number (or (match-string 4 s) "0"))))
9891 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9892 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9893 ((equal n 0) nil)
9894 (t n))))
9896 (defun org-table-current-field-formula (&optional key noerror)
9897 "Return the formula active for the current field.
9898 Assumes that specials are in place.
9899 If KEY is given, return the key to this formula.
9900 Otherwise return the formula preceeded with \"=\" or \":=\"."
9901 (let* ((name (car (rassoc (list (org-current-line)
9902 (org-table-current-column))
9903 org-table-named-field-locations)))
9904 (col (org-table-current-column))
9905 (scol (int-to-string col))
9906 (ref (format "@%d$%d" (org-table-current-dline) col))
9907 (stored-list (org-table-get-stored-formulas noerror))
9908 (ass (or (assoc name stored-list)
9909 (assoc ref stored-list)
9910 (assoc scol stored-list))))
9911 (if key
9912 (car ass)
9913 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9914 (cdr ass))))))
9916 (defun org-table-get-formula (&optional equation named)
9917 "Read a formula from the minibuffer, offer stored formula as default.
9918 When NAMED is non-nil, look for a named equation."
9919 (let* ((stored-list (org-table-get-stored-formulas))
9920 (name (car (rassoc (list (org-current-line)
9921 (org-table-current-column))
9922 org-table-named-field-locations)))
9923 (ref (format "@%d$%d" (org-table-current-dline)
9924 (org-table-current-column)))
9925 (refass (assoc ref stored-list))
9926 (scol (if named
9927 (if name name ref)
9928 (int-to-string (org-table-current-column))))
9929 (dummy (and (or name refass) (not named)
9930 (not (y-or-n-p "Replace field formula with column formula? " ))
9931 (error "Abort")))
9932 (name (or name ref))
9933 (org-table-may-need-update nil)
9934 (stored (cdr (assoc scol stored-list)))
9935 (eq (cond
9936 ((and stored equation (string-match "^ *=? *$" equation))
9937 stored)
9938 ((stringp equation)
9939 equation)
9940 (t (org-table-formula-from-user
9941 (read-string
9942 (org-table-formula-to-user
9943 (format "%s formula %s%s="
9944 (if named "Field" "Column")
9945 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9946 scol))
9947 (if stored (org-table-formula-to-user stored) "")
9948 'org-table-formula-history
9949 )))))
9950 mustsave)
9951 (when (not (string-match "\\S-" eq))
9952 ;; remove formula
9953 (setq stored-list (delq (assoc scol stored-list) stored-list))
9954 (org-table-store-formulas stored-list)
9955 (error "Formula removed"))
9956 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9957 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9958 (if (and name (not named))
9959 ;; We set the column equation, delete the named one.
9960 (setq stored-list (delq (assoc name stored-list) stored-list)
9961 mustsave t))
9962 (if stored
9963 (setcdr (assoc scol stored-list) eq)
9964 (setq stored-list (cons (cons scol eq) stored-list)))
9965 (if (or mustsave (not (equal stored eq)))
9966 (org-table-store-formulas stored-list))
9967 eq))
9969 (defun org-table-store-formulas (alist)
9970 "Store the list of formulas below the current table."
9971 (setq alist (sort alist 'org-table-formula-less-p))
9972 (save-excursion
9973 (goto-char (org-table-end))
9974 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9975 (progn
9976 ;; don't overwrite TBLFM, we might use text properties to store stuff
9977 (goto-char (match-beginning 2))
9978 (delete-region (match-beginning 2) (match-end 0)))
9979 (insert "#+TBLFM:"))
9980 (insert " "
9981 (mapconcat (lambda (x)
9982 (concat
9983 (if (equal (string-to-char (car x)) ?@) "" "$")
9984 (car x) "=" (cdr x)))
9985 alist "::")
9986 "\n")))
9988 (defsubst org-table-formula-make-cmp-string (a)
9989 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9990 (concat
9991 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9992 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9993 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9995 (defun org-table-formula-less-p (a b)
9996 "Compare two formulas for sorting."
9997 (let ((as (org-table-formula-make-cmp-string (car a)))
9998 (bs (org-table-formula-make-cmp-string (car b))))
9999 (and as bs (string< as bs))))
10001 (defun org-table-get-stored-formulas (&optional noerror)
10002 "Return an alist with the stored formulas directly after current table."
10003 (interactive)
10004 (let (scol eq eq-alist strings string seen)
10005 (save-excursion
10006 (goto-char (org-table-end))
10007 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10008 (setq strings (org-split-string (match-string 2) " *:: *"))
10009 (while (setq string (pop strings))
10010 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10011 (setq scol (if (match-end 2)
10012 (match-string 2 string)
10013 (match-string 1 string))
10014 eq (match-string 3 string)
10015 eq-alist (cons (cons scol eq) eq-alist))
10016 (if (member scol seen)
10017 (if noerror
10018 (progn
10019 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10020 (ding)
10021 (sit-for 2))
10022 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10023 (push scol seen))))))
10024 (nreverse eq-alist)))
10026 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10027 "Modify the equations after the table structure has been edited.
10028 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10029 For all numbers larger than LIMIT, shift them by DELTA."
10030 (save-excursion
10031 (goto-char (org-table-end))
10032 (when (looking-at "#\\+TBLFM:")
10033 (let ((re (concat key "\\([0-9]+\\)"))
10034 (re2
10035 (when remove
10036 (if (equal key "$")
10037 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10038 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10039 s n a)
10040 (when remove
10041 (while (re-search-forward re2 (point-at-eol) t)
10042 (replace-match "")))
10043 (while (re-search-forward re (point-at-eol) t)
10044 (setq s (match-string 1) n (string-to-number s))
10045 (cond
10046 ((setq a (assoc s replace))
10047 (replace-match (concat key (cdr a)) t t))
10048 ((and limit (> n limit))
10049 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10051 (defun org-table-get-specials ()
10052 "Get the column names and local parameters for this table."
10053 (save-excursion
10054 (let ((beg (org-table-begin)) (end (org-table-end))
10055 names name fields fields1 field cnt
10056 c v l line col types dlines hlines)
10057 (setq org-table-column-names nil
10058 org-table-local-parameters nil
10059 org-table-named-field-locations nil
10060 org-table-current-begin-line nil
10061 org-table-current-begin-pos nil
10062 org-table-current-line-types nil)
10063 (goto-char beg)
10064 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10065 (setq names (org-split-string (match-string 1) " *| *")
10066 cnt 1)
10067 (while (setq name (pop names))
10068 (setq cnt (1+ cnt))
10069 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10070 (push (cons name (int-to-string cnt)) org-table-column-names))))
10071 (setq org-table-column-names (nreverse org-table-column-names))
10072 (setq org-table-column-name-regexp
10073 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10074 (goto-char beg)
10075 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10076 (setq fields (org-split-string (match-string 1) " *| *"))
10077 (while (setq field (pop fields))
10078 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10079 (push (cons (match-string 1 field) (match-string 2 field))
10080 org-table-local-parameters))))
10081 (goto-char beg)
10082 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10083 (setq c (match-string 1)
10084 fields (org-split-string (match-string 2) " *| *"))
10085 (save-excursion
10086 (beginning-of-line (if (equal c "_") 2 0))
10087 (setq line (org-current-line) col 1)
10088 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10089 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10090 (while (and fields1 (setq field (pop fields)))
10091 (setq v (pop fields1) col (1+ col))
10092 (when (and (stringp field) (stringp v)
10093 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10094 (push (cons field v) org-table-local-parameters)
10095 (push (list field line col) org-table-named-field-locations))))
10096 ;; Analyse the line types
10097 (goto-char beg)
10098 (setq org-table-current-begin-line (org-current-line)
10099 org-table-current-begin-pos (point)
10100 l org-table-current-begin-line)
10101 (while (looking-at "[ \t]*|\\(-\\)?")
10102 (push (if (match-end 1) 'hline 'dline) types)
10103 (if (match-end 1) (push l hlines) (push l dlines))
10104 (beginning-of-line 2)
10105 (setq l (1+ l)))
10106 (setq org-table-current-line-types (apply 'vector (nreverse types))
10107 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10108 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10110 (defun org-table-maybe-eval-formula ()
10111 "Check if the current field starts with \"=\" or \":=\".
10112 If yes, store the formula and apply it."
10113 ;; We already know we are in a table. Get field will only return a formula
10114 ;; when appropriate. It might return a separator line, but no problem.
10115 (when org-table-formula-evaluate-inline
10116 (let* ((field (org-trim (or (org-table-get-field) "")))
10117 named eq)
10118 (when (string-match "^:?=\\(.*\\)" field)
10119 (setq named (equal (string-to-char field) ?:)
10120 eq (match-string 1 field))
10121 (if (or (fboundp 'calc-eval)
10122 (equal (substring eq 0 (min 2 (length eq))) "'("))
10123 (org-table-eval-formula (if named '(4) nil)
10124 (org-table-formula-from-user eq))
10125 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10127 (defvar org-recalc-commands nil
10128 "List of commands triggering the recalculation of a line.
10129 Will be filled automatically during use.")
10131 (defvar org-recalc-marks
10132 '((" " . "Unmarked: no special line, no automatic recalculation")
10133 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10134 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10135 ("!" . "Column name definition line. Reference in formula as $name.")
10136 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10137 ("_" . "Names for values in row below this one.")
10138 ("^" . "Names for values in row above this one.")))
10140 (defun org-table-rotate-recalc-marks (&optional newchar)
10141 "Rotate the recalculation mark in the first column.
10142 If in any row, the first field is not consistent with a mark,
10143 insert a new column for the markers.
10144 When there is an active region, change all the lines in the region,
10145 after prompting for the marking character.
10146 After each change, a message will be displayed indicating the meaning
10147 of the new mark."
10148 (interactive)
10149 (unless (org-at-table-p) (error "Not at a table"))
10150 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10151 (beg (org-table-begin))
10152 (end (org-table-end))
10153 (l (org-current-line))
10154 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10155 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10156 (have-col
10157 (save-excursion
10158 (goto-char beg)
10159 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10160 (col (org-table-current-column))
10161 (forcenew (car (assoc newchar org-recalc-marks)))
10162 epos new)
10163 (when l1
10164 (message "Change region to what mark? Type # * ! $ or SPC: ")
10165 (setq newchar (char-to-string (read-char-exclusive))
10166 forcenew (car (assoc newchar org-recalc-marks))))
10167 (if (and newchar (not forcenew))
10168 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10169 newchar))
10170 (if l1 (goto-line l1))
10171 (save-excursion
10172 (beginning-of-line 1)
10173 (unless (looking-at org-table-dataline-regexp)
10174 (error "Not at a table data line")))
10175 (unless have-col
10176 (org-table-goto-column 1)
10177 (org-table-insert-column)
10178 (org-table-goto-column (1+ col)))
10179 (setq epos (point-at-eol))
10180 (save-excursion
10181 (beginning-of-line 1)
10182 (org-table-get-field
10183 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10184 (concat " "
10185 (setq new (or forcenew
10186 (cadr (member (match-string 1) marks))))
10187 " ")
10188 " # ")))
10189 (if (and l1 l2)
10190 (progn
10191 (goto-line l1)
10192 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10193 (and (looking-at org-table-dataline-regexp)
10194 (org-table-get-field 1 (concat " " new " "))))
10195 (goto-line l1)))
10196 (if (not (= epos (point-at-eol))) (org-table-align))
10197 (goto-line l)
10198 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10200 (defun org-table-maybe-recalculate-line ()
10201 "Recompute the current line if marked for it, and if we haven't just done it."
10202 (interactive)
10203 (and org-table-allow-automatic-line-recalculation
10204 (not (and (memq last-command org-recalc-commands)
10205 (equal org-last-recalc-line (org-current-line))))
10206 (save-excursion (beginning-of-line 1)
10207 (looking-at org-table-auto-recalculate-regexp))
10208 (org-table-recalculate) t))
10210 (defvar org-table-formula-debug nil
10211 "Non-nil means, debug table formulas.
10212 When nil, simply write \"#ERROR\" in corrupted fields.")
10213 (make-variable-buffer-local 'org-table-formula-debug)
10215 (defvar modes)
10216 (defsubst org-set-calc-mode (var &optional value)
10217 (if (stringp var)
10218 (setq var (assoc var '(("D" calc-angle-mode deg)
10219 ("R" calc-angle-mode rad)
10220 ("F" calc-prefer-frac t)
10221 ("S" calc-symbolic-mode t)))
10222 value (nth 2 var) var (nth 1 var)))
10223 (if (memq var modes)
10224 (setcar (cdr (memq var modes)) value)
10225 (cons var (cons value modes)))
10226 modes)
10228 (defun org-table-eval-formula (&optional arg equation
10229 suppress-align suppress-const
10230 suppress-store suppress-analysis)
10231 "Replace the table field value at the cursor by the result of a calculation.
10233 This function makes use of Dave Gillespie's Calc package, in my view the
10234 most exciting program ever written for GNU Emacs. So you need to have Calc
10235 installed in order to use this function.
10237 In a table, this command replaces the value in the current field with the
10238 result of a formula. It also installs the formula as the \"current\" column
10239 formula, by storing it in a special line below the table. When called
10240 with a `C-u' prefix, the current field must ba a named field, and the
10241 formula is installed as valid in only this specific field.
10243 When called with two `C-u' prefixes, insert the active equation
10244 for the field back into the current field, so that it can be
10245 edited there. This is useful in order to use \\[org-table-show-reference]
10246 to check the referenced fields.
10248 When called, the command first prompts for a formula, which is read in
10249 the minibuffer. Previously entered formulas are available through the
10250 history list, and the last used formula is offered as a default.
10251 These stored formulas are adapted correctly when moving, inserting, or
10252 deleting columns with the corresponding commands.
10254 The formula can be any algebraic expression understood by the Calc package.
10255 For details, see the Org-mode manual.
10257 This function can also be called from Lisp programs and offers
10258 additional arguments: EQUATION can be the formula to apply. If this
10259 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10260 used to speed-up recursive calls by by-passing unnecessary aligns.
10261 SUPPRESS-CONST suppresses the interpretation of constants in the
10262 formula, assuming that this has been done already outside the function.
10263 SUPPRESS-STORE means the formula should not be stored, either because
10264 it is already stored, or because it is a modified equation that should
10265 not overwrite the stored one."
10266 (interactive "P")
10267 (org-table-check-inside-data-field)
10268 (or suppress-analysis (org-table-get-specials))
10269 (if (equal arg '(16))
10270 (let ((eq (org-table-current-field-formula)))
10271 (or eq (error "No equation active for current field"))
10272 (org-table-get-field nil eq)
10273 (org-table-align)
10274 (setq org-table-may-need-update t))
10275 (let* (fields
10276 (ndown (if (integerp arg) arg 1))
10277 (org-table-automatic-realign nil)
10278 (case-fold-search nil)
10279 (down (> ndown 1))
10280 (formula (if (and equation suppress-store)
10281 equation
10282 (org-table-get-formula equation (equal arg '(4)))))
10283 (n0 (org-table-current-column))
10284 (modes (copy-sequence org-calc-default-modes))
10285 (numbers nil) ; was a variable, now fixed default
10286 (keep-empty nil)
10287 n form form0 bw fmt x ev orig c lispp literal)
10288 ;; Parse the format string. Since we have a lot of modes, this is
10289 ;; a lot of work. However, I think calc still uses most of the time.
10290 (if (string-match ";" formula)
10291 (let ((tmp (org-split-string formula ";")))
10292 (setq formula (car tmp)
10293 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10294 (nth 1 tmp)))
10295 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10296 (setq c (string-to-char (match-string 1 fmt))
10297 n (string-to-number (match-string 2 fmt)))
10298 (if (= c ?p)
10299 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10300 (setq modes (org-set-calc-mode
10301 'calc-float-format
10302 (list (cdr (assoc c '((?n . float) (?f . fix)
10303 (?s . sci) (?e . eng))))
10304 n))))
10305 (setq fmt (replace-match "" t t fmt)))
10306 (if (string-match "[NT]" fmt)
10307 (setq numbers (equal (match-string 0 fmt) "N")
10308 fmt (replace-match "" t t fmt)))
10309 (if (string-match "L" fmt)
10310 (setq literal t
10311 fmt (replace-match "" t t fmt)))
10312 (if (string-match "E" fmt)
10313 (setq keep-empty t
10314 fmt (replace-match "" t t fmt)))
10315 (while (string-match "[DRFS]" fmt)
10316 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10317 (setq fmt (replace-match "" t t fmt)))
10318 (unless (string-match "\\S-" fmt)
10319 (setq fmt nil))))
10320 (if (and (not suppress-const) org-table-formula-use-constants)
10321 (setq formula (org-table-formula-substitute-names formula)))
10322 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10323 (while (> ndown 0)
10324 (setq fields (org-split-string
10325 (org-no-properties
10326 (buffer-substring (point-at-bol) (point-at-eol)))
10327 " *| *"))
10328 (if (eq numbers t)
10329 (setq fields (mapcar
10330 (lambda (x) (number-to-string (string-to-number x)))
10331 fields)))
10332 (setq ndown (1- ndown))
10333 (setq form (copy-sequence formula)
10334 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10335 (if (and lispp literal) (setq lispp 'literal))
10336 ;; Check for old vertical references
10337 (setq form (org-rewrite-old-row-references form))
10338 ;; Insert complex ranges
10339 (while (string-match org-table-range-regexp form)
10340 (setq form
10341 (replace-match
10342 (save-match-data
10343 (org-table-make-reference
10344 (org-table-get-range (match-string 0 form) nil n0)
10345 keep-empty numbers lispp))
10346 t t form)))
10347 ;; Insert simple ranges
10348 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10349 (setq form
10350 (replace-match
10351 (save-match-data
10352 (org-table-make-reference
10353 (org-sublist
10354 fields (string-to-number (match-string 1 form))
10355 (string-to-number (match-string 2 form)))
10356 keep-empty numbers lispp))
10357 t t form)))
10358 (setq form0 form)
10359 ;; Insert the references to fields in same row
10360 (while (string-match "\\$\\([0-9]+\\)" form)
10361 (setq n (string-to-number (match-string 1 form))
10362 x (nth (1- (if (= n 0) n0 n)) fields))
10363 (unless x (error "Invalid field specifier \"%s\""
10364 (match-string 0 form)))
10365 (setq form (replace-match
10366 (save-match-data
10367 (org-table-make-reference x nil numbers lispp))
10368 t t form)))
10370 (if lispp
10371 (setq ev (condition-case nil
10372 (eval (eval (read form)))
10373 (error "#ERROR"))
10374 ev (if (numberp ev) (number-to-string ev) ev))
10375 (or (fboundp 'calc-eval)
10376 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10377 (setq ev (calc-eval (cons form modes)
10378 (if numbers 'num))))
10380 (when org-table-formula-debug
10381 (with-output-to-temp-buffer "*Substitution History*"
10382 (princ (format "Substitution history of formula
10383 Orig: %s
10384 $xyz-> %s
10385 @r$c-> %s
10386 $1-> %s\n" orig formula form0 form))
10387 (if (listp ev)
10388 (princ (format " %s^\nError: %s"
10389 (make-string (car ev) ?\-) (nth 1 ev)))
10390 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10391 ev (or fmt "NONE")
10392 (if fmt (format fmt (string-to-number ev)) ev)))))
10393 (setq bw (get-buffer-window "*Substitution History*"))
10394 (shrink-window-if-larger-than-buffer bw)
10395 (unless (and (interactive-p) (not ndown))
10396 (unless (let (inhibit-redisplay)
10397 (y-or-n-p "Debugging Formula. Continue to next? "))
10398 (org-table-align)
10399 (error "Abort"))
10400 (delete-window bw)
10401 (message "")))
10402 (if (listp ev) (setq fmt nil ev "#ERROR"))
10403 (org-table-justify-field-maybe
10404 (if fmt (format fmt (string-to-number ev)) ev))
10405 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10406 (call-interactively 'org-return)
10407 (setq ndown 0)))
10408 (and down (org-table-maybe-recalculate-line))
10409 (or suppress-align (and org-table-may-need-update
10410 (org-table-align))))))
10412 (defun org-table-put-field-property (prop value)
10413 (save-excursion
10414 (put-text-property (progn (skip-chars-backward "^|") (point))
10415 (progn (skip-chars-forward "^|") (point))
10416 prop value)))
10418 (defun org-table-get-range (desc &optional tbeg col highlight)
10419 "Get a calc vector from a column, accorting to descriptor DESC.
10420 Optional arguments TBEG and COL can give the beginning of the table and
10421 the current column, to avoid unnecessary parsing.
10422 HIGHLIGHT means, just highlight the range."
10423 (if (not (equal (string-to-char desc) ?@))
10424 (setq desc (concat "@" desc)))
10425 (save-excursion
10426 (or tbeg (setq tbeg (org-table-begin)))
10427 (or col (setq col (org-table-current-column)))
10428 (let ((thisline (org-current-line))
10429 beg end c1 c2 r1 r2 rangep tmp)
10430 (unless (string-match org-table-range-regexp desc)
10431 (error "Invalid table range specifier `%s'" desc))
10432 (setq rangep (match-end 3)
10433 r1 (and (match-end 1) (match-string 1 desc))
10434 r2 (and (match-end 4) (match-string 4 desc))
10435 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10436 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10438 (and c1 (setq c1 (+ (string-to-number c1)
10439 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10440 (and c2 (setq c2 (+ (string-to-number c2)
10441 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10442 (if (equal r1 "") (setq r1 nil))
10443 (if (equal r2 "") (setq r2 nil))
10444 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10445 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10446 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10447 (if (not r1) (setq r1 thisline))
10448 (if (not r2) (setq r2 thisline))
10449 (if (not c1) (setq c1 col))
10450 (if (not c2) (setq c2 col))
10451 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10452 ;; just one field
10453 (progn
10454 (goto-line r1)
10455 (while (not (looking-at org-table-dataline-regexp))
10456 (beginning-of-line 2))
10457 (prog1 (org-trim (org-table-get-field c1))
10458 (if highlight (org-table-highlight-rectangle (point) (point)))))
10459 ;; A range, return a vector
10460 ;; First sort the numbers to get a regular ractangle
10461 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10462 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10463 (goto-line r1)
10464 (while (not (looking-at org-table-dataline-regexp))
10465 (beginning-of-line 2))
10466 (org-table-goto-column c1)
10467 (setq beg (point))
10468 (goto-line r2)
10469 (while (not (looking-at org-table-dataline-regexp))
10470 (beginning-of-line 0))
10471 (org-table-goto-column c2)
10472 (setq end (point))
10473 (if highlight
10474 (org-table-highlight-rectangle
10475 beg (progn (skip-chars-forward "^|\n") (point))))
10476 ;; return string representation of calc vector
10477 (mapcar 'org-trim
10478 (apply 'append (org-table-copy-region beg end)))))))
10480 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10481 "Analyze descriptor DESC and retrieve the corresponding line number.
10482 The cursor is currently in line CLINE, the table begins in line BLINE,
10483 and TABLE is a vector with line types."
10484 (if (string-match "^[0-9]+$" desc)
10485 (aref org-table-dlines (string-to-number desc))
10486 (setq cline (or cline (org-current-line))
10487 bline (or bline org-table-current-begin-line)
10488 table (or table org-table-current-line-types))
10489 (if (or
10490 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10491 ;; 1 2 3 4 5 6
10492 (and (not (match-end 3)) (not (match-end 6)))
10493 (and (match-end 3) (match-end 6) (not (match-end 5))))
10494 (error "invalid row descriptor `%s'" desc))
10495 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10496 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10497 (odir (and (match-end 5) (match-string 5 desc)))
10498 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10499 (i (- cline bline))
10500 (rel (and (match-end 6)
10501 (or (and (match-end 1) (not (match-end 3)))
10502 (match-end 5)))))
10503 (if (and hn (not hdir))
10504 (progn
10505 (setq i 0 hdir "+")
10506 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10507 (if (and (not hn) on (not odir))
10508 (error "should never happen");;(aref org-table-dlines on)
10509 (if (and hn (> hn 0))
10510 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10511 (if on
10512 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10513 (+ bline i)))))
10515 (defun org-find-row-type (table i type backwards relative n)
10516 (let ((l (length table)))
10517 (while (> n 0)
10518 (while (and (setq i (+ i (if backwards -1 1)))
10519 (>= i 0) (< i l)
10520 (not (eq (aref table i) type))
10521 (if (and relative (eq (aref table i) 'hline))
10522 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10523 t)))
10524 (setq n (1- n)))
10525 (if (or (< i 0) (>= i l))
10526 (error "Row descriptior leads outside table")
10527 i)))
10529 (defun org-rewrite-old-row-references (s)
10530 (if (string-match "&[-+0-9I]" s)
10531 (error "Formula contains old &row reference, please rewrite using @-syntax")
10534 (defun org-table-make-reference (elements keep-empty numbers lispp)
10535 "Convert list ELEMENTS to something appropriate to insert into formula.
10536 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10537 NUMBERS indicates that everything should be converted to numbers.
10538 LISPP means to return something appropriate for a Lisp list."
10539 (if (stringp elements) ; just a single val
10540 (if lispp
10541 (if (eq lispp 'literal)
10542 elements
10543 (prin1-to-string (if numbers (string-to-number elements) elements)))
10544 (if (equal elements "") (setq elements "0"))
10545 (if numbers (number-to-string (string-to-number elements)) elements))
10546 (unless keep-empty
10547 (setq elements
10548 (delq nil
10549 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10550 elements))))
10551 (setq elements (or elements '("0")))
10552 (if lispp
10553 (mapconcat
10554 (lambda (x)
10555 (if (eq lispp 'literal)
10557 (prin1-to-string (if numbers (string-to-number x) x))))
10558 elements " ")
10559 (concat "[" (mapconcat
10560 (lambda (x)
10561 (if numbers (number-to-string (string-to-number x)) x))
10562 elements
10563 ",") "]"))))
10565 (defun org-table-recalculate (&optional all noalign)
10566 "Recalculate the current table line by applying all stored formulas.
10567 With prefix arg ALL, do this for all lines in the table."
10568 (interactive "P")
10569 (or (memq this-command org-recalc-commands)
10570 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10571 (unless (org-at-table-p) (error "Not at a table"))
10572 (if (equal all '(16))
10573 (org-table-iterate)
10574 (org-table-get-specials)
10575 (let* ((eqlist (sort (org-table-get-stored-formulas)
10576 (lambda (a b) (string< (car a) (car b)))))
10577 (inhibit-redisplay (not debug-on-error))
10578 (line-re org-table-dataline-regexp)
10579 (thisline (org-current-line))
10580 (thiscol (org-table-current-column))
10581 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10582 ;; Insert constants in all formulas
10583 (setq eqlist
10584 (mapcar (lambda (x)
10585 (setcdr x (org-table-formula-substitute-names (cdr x)))
10587 eqlist))
10588 ;; Split the equation list
10589 (while (setq eq (pop eqlist))
10590 (if (<= (string-to-char (car eq)) ?9)
10591 (push eq eqlnum)
10592 (push eq eqlname)))
10593 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10594 (if all
10595 (progn
10596 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10597 (goto-char (setq beg (org-table-begin)))
10598 (if (re-search-forward org-table-calculate-mark-regexp end t)
10599 ;; This is a table with marked lines, compute selected lines
10600 (setq line-re org-table-recalculate-regexp)
10601 ;; Move forward to the first non-header line
10602 (if (and (re-search-forward org-table-dataline-regexp end t)
10603 (re-search-forward org-table-hline-regexp end t)
10604 (re-search-forward org-table-dataline-regexp end t))
10605 (setq beg (match-beginning 0))
10606 nil))) ;; just leave beg where it is
10607 (setq beg (point-at-bol)
10608 end (move-marker (make-marker) (1+ (point-at-eol)))))
10609 (goto-char beg)
10610 (and all (message "Re-applying formulas to full table..."))
10612 ;; First find the named fields, and mark them untouchanble
10613 (remove-text-properties beg end '(org-untouchable t))
10614 (while (setq eq (pop eqlname))
10615 (setq name (car eq)
10616 a (assoc name org-table-named-field-locations))
10617 (and (not a)
10618 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10619 (setq a (list name
10620 (aref org-table-dlines
10621 (string-to-number (match-string 1 name)))
10622 (string-to-number (match-string 2 name)))))
10623 (when (and a (or all (equal (nth 1 a) thisline)))
10624 (message "Re-applying formula to field: %s" name)
10625 (goto-line (nth 1 a))
10626 (org-table-goto-column (nth 2 a))
10627 (push (append a (list (cdr eq))) eqlname1)
10628 (org-table-put-field-property :org-untouchable t)))
10630 ;; Now evauluate the column formulas, but skip fields covered by
10631 ;; field formulas
10632 (goto-char beg)
10633 (while (re-search-forward line-re end t)
10634 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10635 ;; Unprotected line, recalculate
10636 (and all (message "Re-applying formulas to full table...(line %d)"
10637 (setq cnt (1+ cnt))))
10638 (setq org-last-recalc-line (org-current-line))
10639 (setq eql eqlnum)
10640 (while (setq entry (pop eql))
10641 (goto-line org-last-recalc-line)
10642 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10643 (unless (get-text-property (point) :org-untouchable)
10644 (org-table-eval-formula nil (cdr entry)
10645 'noalign 'nocst 'nostore 'noanalysis)))))
10647 ;; Now evaluate the field formulas
10648 (while (setq eq (pop eqlname1))
10649 (message "Re-applying formula to field: %s" (car eq))
10650 (goto-line (nth 1 eq))
10651 (org-table-goto-column (nth 2 eq))
10652 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10653 'nostore 'noanalysis))
10655 (goto-line thisline)
10656 (org-table-goto-column thiscol)
10657 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10658 (or noalign (and org-table-may-need-update (org-table-align))
10659 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10661 ;; back to initial position
10662 (message "Re-applying formulas...done")
10663 (goto-line thisline)
10664 (org-table-goto-column thiscol)
10665 (or noalign (and org-table-may-need-update (org-table-align))
10666 (and all (message "Re-applying formulas...done"))))))
10668 (defun org-table-iterate (&optional arg)
10669 "Recalculate the table until it does not change anymore."
10670 (interactive "P")
10671 (let ((imax (if arg (prefix-numeric-value arg) 10))
10672 (i 0)
10673 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10674 thistbl)
10675 (catch 'exit
10676 (while (< i imax)
10677 (setq i (1+ i))
10678 (org-table-recalculate 'all)
10679 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10680 (if (not (string= lasttbl thistbl))
10681 (setq lasttbl thistbl)
10682 (if (> i 1)
10683 (message "Convergence after %d iterations" i)
10684 (message "Table was already stable"))
10685 (throw 'exit t)))
10686 (error "No convergence after %d iterations" i))))
10688 (defun org-table-formula-substitute-names (f)
10689 "Replace $const with values in string F."
10690 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10691 ;; First, check for column names
10692 (while (setq start (string-match org-table-column-name-regexp f start))
10693 (setq start (1+ start))
10694 (setq a (assoc (match-string 1 f) org-table-column-names))
10695 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10696 ;; Parameters and constants
10697 (setq start 0)
10698 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10699 (setq start (1+ start))
10700 (if (setq a (save-match-data
10701 (org-table-get-constant (match-string 1 f))))
10702 (setq f (replace-match
10703 (concat (if pp "(") a (if pp ")")) t t f))))
10704 (if org-table-formula-debug
10705 (put-text-property 0 (length f) :orig-formula f1 f))
10708 (defun org-table-get-constant (const)
10709 "Find the value for a parameter or constant in a formula.
10710 Parameters get priority."
10711 (or (cdr (assoc const org-table-local-parameters))
10712 (cdr (assoc const org-table-formula-constants-local))
10713 (cdr (assoc const org-table-formula-constants))
10714 (and (fboundp 'constants-get) (constants-get const))
10715 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10716 (org-entry-get nil (substring const 5) 'inherit))
10717 "#UNDEFINED_NAME"))
10719 (defvar org-table-fedit-map
10720 (let ((map (make-sparse-keymap)))
10721 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10722 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10723 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10724 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10725 (org-defkey map "\C-c?" 'org-table-show-reference)
10726 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10727 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10728 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10729 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10730 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10731 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10732 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10733 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10734 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10735 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10736 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10737 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10738 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10739 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10740 map))
10742 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10743 '("Edit-Formulas"
10744 ["Finish and Install" org-table-fedit-finish t]
10745 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10746 ["Abort" org-table-fedit-abort t]
10747 "--"
10748 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10749 ["Complete Lisp Symbol" lisp-complete-symbol t]
10750 "--"
10751 "Shift Reference at Point"
10752 ["Up" org-table-fedit-ref-up t]
10753 ["Down" org-table-fedit-ref-down t]
10754 ["Left" org-table-fedit-ref-left t]
10755 ["Right" org-table-fedit-ref-right t]
10757 "Change Test Row for Column Formulas"
10758 ["Up" org-table-fedit-line-up t]
10759 ["Down" org-table-fedit-line-down t]
10760 "--"
10761 ["Scroll Table Window" org-table-fedit-scroll t]
10762 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10763 ["Show Table Grid" org-table-fedit-toggle-coordinates
10764 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10765 org-table-overlay-coordinates)]
10766 "--"
10767 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10768 :style toggle :selected org-table-buffer-is-an]))
10770 (defvar org-pos)
10772 (defun org-table-edit-formulas ()
10773 "Edit the formulas of the current table in a separate buffer."
10774 (interactive)
10775 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10776 (beginning-of-line 0))
10777 (unless (org-at-table-p) (error "Not at a table"))
10778 (org-table-get-specials)
10779 (let ((key (org-table-current-field-formula 'key 'noerror))
10780 (eql (sort (org-table-get-stored-formulas 'noerror)
10781 'org-table-formula-less-p))
10782 (pos (move-marker (make-marker) (point)))
10783 (startline 1)
10784 (wc (current-window-configuration))
10785 (titles '((column . "# Column Formulas\n")
10786 (field . "# Field Formulas\n")
10787 (named . "# Named Field Formulas\n")))
10788 entry s type title)
10789 (org-switch-to-buffer-other-window "*Edit Formulas*")
10790 (erase-buffer)
10791 ;; Keep global-font-lock-mode from turning on font-lock-mode
10792 (let ((font-lock-global-modes '(not fundamental-mode)))
10793 (fundamental-mode))
10794 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10795 (org-set-local 'org-pos pos)
10796 (org-set-local 'org-window-configuration wc)
10797 (use-local-map org-table-fedit-map)
10798 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10799 (easy-menu-add org-table-fedit-menu)
10800 (setq startline (org-current-line))
10801 (while (setq entry (pop eql))
10802 (setq type (cond
10803 ((equal (string-to-char (car entry)) ?@) 'field)
10804 ((string-match "^[0-9]" (car entry)) 'column)
10805 (t 'named)))
10806 (when (setq title (assq type titles))
10807 (or (bobp) (insert "\n"))
10808 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10809 (setq titles (delq title titles)))
10810 (if (equal key (car entry)) (setq startline (org-current-line)))
10811 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10812 (car entry) " = " (cdr entry) "\n"))
10813 (remove-text-properties 0 (length s) '(face nil) s)
10814 (insert s))
10815 (if (eq org-table-use-standard-references t)
10816 (org-table-fedit-toggle-ref-type))
10817 (goto-line startline)
10818 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10820 (defun org-table-fedit-post-command ()
10821 (when (not (memq this-command '(lisp-complete-symbol)))
10822 (let ((win (selected-window)))
10823 (save-excursion
10824 (condition-case nil
10825 (org-table-show-reference)
10826 (error nil))
10827 (select-window win)))))
10829 (defun org-table-formula-to-user (s)
10830 "Convert a formula from internal to user representation."
10831 (if (eq org-table-use-standard-references t)
10832 (org-table-convert-refs-to-an s)
10835 (defun org-table-formula-from-user (s)
10836 "Convert a formula from user to internal representation."
10837 (if org-table-use-standard-references
10838 (org-table-convert-refs-to-rc s)
10841 (defun org-table-convert-refs-to-rc (s)
10842 "Convert spreadsheet references from AB7 to @7$28.
10843 Works for single references, but also for entire formulas and even the
10844 full TBLFM line."
10845 (let ((start 0))
10846 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10847 (cond
10848 ((match-end 3)
10849 ;; format match, just advance
10850 (setq start (match-end 0)))
10851 ((and (> (match-beginning 0) 0)
10852 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10853 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10854 ;; 3.e5 or something like this.
10855 (setq start (match-end 0)))
10857 (setq start (match-beginning 0)
10858 s (replace-match
10859 (if (equal (match-string 2 s) "&")
10860 (format "$%d" (org-letters-to-number (match-string 1 s)))
10861 (format "@%d$%d"
10862 (string-to-number (match-string 2 s))
10863 (org-letters-to-number (match-string 1 s))))
10864 t t s)))))
10867 (defun org-table-convert-refs-to-an (s)
10868 "Convert spreadsheet references from to @7$28 to AB7.
10869 Works for single references, but also for entire formulas and even the
10870 full TBLFM line."
10871 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10872 (setq s (replace-match
10873 (format "%s%d"
10874 (org-number-to-letters
10875 (string-to-number (match-string 2 s)))
10876 (string-to-number (match-string 1 s)))
10877 t t s)))
10878 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10879 (setq s (replace-match (concat "\\1"
10880 (org-number-to-letters
10881 (string-to-number (match-string 2 s))) "&")
10882 t nil s)))
10885 (defun org-letters-to-number (s)
10886 "Convert a base 26 number represented by letters into an integer.
10887 For example: AB -> 28."
10888 (let ((n 0))
10889 (setq s (upcase s))
10890 (while (> (length s) 0)
10891 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10892 s (substring s 1)))
10895 (defun org-number-to-letters (n)
10896 "Convert an integer into a base 26 number represented by letters.
10897 For example: 28 -> AB."
10898 (let ((s ""))
10899 (while (> n 0)
10900 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10901 n (/ (1- n) 26)))
10904 (defun org-table-fedit-convert-buffer (function)
10905 "Convert all references in this buffer, using FUNTION."
10906 (let ((line (org-current-line)))
10907 (goto-char (point-min))
10908 (while (not (eobp))
10909 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10910 (delete-region (point) (point-at-eol))
10911 (or (eobp) (forward-char 1)))
10912 (goto-line line)))
10914 (defun org-table-fedit-toggle-ref-type ()
10915 "Convert all references in the buffer from B3 to @3$2 and back."
10916 (interactive)
10917 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10918 (org-table-fedit-convert-buffer
10919 (if org-table-buffer-is-an
10920 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10921 (message "Reference type switched to %s"
10922 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10924 (defun org-table-fedit-ref-up ()
10925 "Shift the reference at point one row/hline up."
10926 (interactive)
10927 (org-table-fedit-shift-reference 'up))
10928 (defun org-table-fedit-ref-down ()
10929 "Shift the reference at point one row/hline down."
10930 (interactive)
10931 (org-table-fedit-shift-reference 'down))
10932 (defun org-table-fedit-ref-left ()
10933 "Shift the reference at point one field to the left."
10934 (interactive)
10935 (org-table-fedit-shift-reference 'left))
10936 (defun org-table-fedit-ref-right ()
10937 "Shift the reference at point one field to the right."
10938 (interactive)
10939 (org-table-fedit-shift-reference 'right))
10941 (defun org-table-fedit-shift-reference (dir)
10942 (cond
10943 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10944 (if (memq dir '(left right))
10945 (org-rematch-and-replace 1 (eq dir 'left))
10946 (error "Cannot shift reference in this direction")))
10947 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10948 ;; A B3-like reference
10949 (if (memq dir '(up down))
10950 (org-rematch-and-replace 2 (eq dir 'up))
10951 (org-rematch-and-replace 1 (eq dir 'left))))
10952 ((org-at-regexp-p
10953 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10954 ;; An internal reference
10955 (if (memq dir '(up down))
10956 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10957 (org-rematch-and-replace 5 (eq dir 'left))))))
10959 (defun org-rematch-and-replace (n &optional decr hline)
10960 "Re-match the group N, and replace it with the shifted refrence."
10961 (or (match-end n) (error "Cannot shift reference in this direction"))
10962 (goto-char (match-beginning n))
10963 (and (looking-at (regexp-quote (match-string n)))
10964 (replace-match (org-shift-refpart (match-string 0) decr hline)
10965 t t)))
10967 (defun org-shift-refpart (ref &optional decr hline)
10968 "Shift a refrence part REF.
10969 If DECR is set, decrease the references row/column, else increase.
10970 If HLINE is set, this may be a hline reference, it certainly is not
10971 a translation reference."
10972 (save-match-data
10973 (let* ((sign (string-match "^[-+]" ref)) n)
10975 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10976 (cond
10977 ((and hline (string-match "^I+" ref))
10978 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10979 (setq n (+ n (if decr -1 1)))
10980 (if (= n 0) (setq n (+ n (if decr -1 1))))
10981 (if sign
10982 (setq sign (if (< n 0) "-" "+") n (abs n))
10983 (setq n (max 1 n)))
10984 (concat sign (make-string n ?I)))
10986 ((string-match "^[0-9]+" ref)
10987 (setq n (string-to-number (concat sign ref)))
10988 (setq n (+ n (if decr -1 1)))
10989 (if sign
10990 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10991 (number-to-string (max 1 n))))
10993 ((string-match "^[a-zA-Z]+" ref)
10994 (org-number-to-letters
10995 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10997 (t (error "Cannot shift reference"))))))
10999 (defun org-table-fedit-toggle-coordinates ()
11000 "Toggle the display of coordinates in the refrenced table."
11001 (interactive)
11002 (let ((pos (marker-position org-pos)))
11003 (with-current-buffer (marker-buffer org-pos)
11004 (save-excursion
11005 (goto-char pos)
11006 (org-table-toggle-coordinate-overlays)))))
11008 (defun org-table-fedit-finish (&optional arg)
11009 "Parse the buffer for formula definitions and install them.
11010 With prefix ARG, apply the new formulas to the table."
11011 (interactive "P")
11012 (org-table-remove-rectangle-highlight)
11013 (if org-table-use-standard-references
11014 (progn
11015 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11016 (setq org-table-buffer-is-an nil)))
11017 (let ((pos org-pos) eql var form)
11018 (goto-char (point-min))
11019 (while (re-search-forward
11020 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11021 nil t)
11022 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11023 form (match-string 3))
11024 (setq form (org-trim form))
11025 (when (not (equal form ""))
11026 (while (string-match "[ \t]*\n[ \t]*" form)
11027 (setq form (replace-match " " t t form)))
11028 (when (assoc var eql)
11029 (error "Double formulas for %s" var))
11030 (push (cons var form) eql)))
11031 (setq org-pos nil)
11032 (set-window-configuration org-window-configuration)
11033 (select-window (get-buffer-window (marker-buffer pos)))
11034 (goto-char pos)
11035 (unless (org-at-table-p)
11036 (error "Lost table position - cannot install formulae"))
11037 (org-table-store-formulas eql)
11038 (move-marker pos nil)
11039 (kill-buffer "*Edit Formulas*")
11040 (if arg
11041 (org-table-recalculate 'all)
11042 (message "New formulas installed - press C-u C-c C-c to apply."))))
11044 (defun org-table-fedit-abort ()
11045 "Abort editing formulas, without installing the changes."
11046 (interactive)
11047 (org-table-remove-rectangle-highlight)
11048 (let ((pos org-pos))
11049 (set-window-configuration org-window-configuration)
11050 (select-window (get-buffer-window (marker-buffer pos)))
11051 (goto-char pos)
11052 (move-marker pos nil)
11053 (message "Formula editing aborted without installing changes")))
11055 (defun org-table-fedit-lisp-indent ()
11056 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11057 (interactive)
11058 (let ((pos (point)) beg end ind)
11059 (beginning-of-line 1)
11060 (cond
11061 ((looking-at "[ \t]")
11062 (goto-char pos)
11063 (call-interactively 'lisp-indent-line))
11064 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11065 ((not (fboundp 'pp-buffer))
11066 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11067 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11068 (goto-char (- (match-end 0) 2))
11069 (setq beg (point))
11070 (setq ind (make-string (current-column) ?\ ))
11071 (condition-case nil (forward-sexp 1)
11072 (error
11073 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11074 (setq end (point))
11075 (save-restriction
11076 (narrow-to-region beg end)
11077 (if (eq last-command this-command)
11078 (progn
11079 (goto-char (point-min))
11080 (setq this-command nil)
11081 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11082 (replace-match " ")))
11083 (pp-buffer)
11084 (untabify (point-min) (point-max))
11085 (goto-char (1+ (point-min)))
11086 (while (re-search-forward "^." nil t)
11087 (beginning-of-line 1)
11088 (insert ind))
11089 (goto-char (point-max))
11090 (backward-delete-char 1)))
11091 (goto-char beg))
11092 (t nil))))
11094 (defvar org-show-positions nil)
11096 (defun org-table-show-reference (&optional local)
11097 "Show the location/value of the $ expression at point."
11098 (interactive)
11099 (org-table-remove-rectangle-highlight)
11100 (catch 'exit
11101 (let ((pos (if local (point) org-pos))
11102 (face2 'highlight)
11103 (org-inhibit-highlight-removal t)
11104 (win (selected-window))
11105 (org-show-positions nil)
11106 var name e what match dest)
11107 (if local (org-table-get-specials))
11108 (setq what (cond
11109 ((or (org-at-regexp-p org-table-range-regexp2)
11110 (org-at-regexp-p org-table-translate-regexp)
11111 (org-at-regexp-p org-table-range-regexp))
11112 (setq match
11113 (save-match-data
11114 (org-table-convert-refs-to-rc (match-string 0))))
11115 'range)
11116 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11117 ((org-at-regexp-p "\\$[0-9]+") 'column)
11118 ((not local) nil)
11119 (t (error "No reference at point")))
11120 match (and what (or match (match-string 0))))
11121 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11122 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11123 'secondary-selection))
11124 (org-add-hook 'before-change-functions
11125 'org-table-remove-rectangle-highlight)
11126 (if (eq what 'name) (setq var (substring match 1)))
11127 (when (eq what 'range)
11128 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11129 (setq match (org-table-formula-substitute-names match)))
11130 (unless local
11131 (save-excursion
11132 (end-of-line 1)
11133 (re-search-backward "^\\S-" nil t)
11134 (beginning-of-line 1)
11135 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11136 (setq dest
11137 (save-match-data
11138 (org-table-convert-refs-to-rc (match-string 1))))
11139 (org-table-add-rectangle-overlay
11140 (match-beginning 1) (match-end 1) face2))))
11141 (if (and (markerp pos) (marker-buffer pos))
11142 (if (get-buffer-window (marker-buffer pos))
11143 (select-window (get-buffer-window (marker-buffer pos)))
11144 (org-switch-to-buffer-other-window (get-buffer-window
11145 (marker-buffer pos)))))
11146 (goto-char pos)
11147 (org-table-force-dataline)
11148 (when dest
11149 (setq name (substring dest 1))
11150 (cond
11151 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11152 (setq e (assoc name org-table-named-field-locations))
11153 (goto-line (nth 1 e))
11154 (org-table-goto-column (nth 2 e)))
11155 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11156 (let ((l (string-to-number (match-string 1 dest)))
11157 (c (string-to-number (match-string 2 dest))))
11158 (goto-line (aref org-table-dlines l))
11159 (org-table-goto-column c)))
11160 (t (org-table-goto-column (string-to-number name))))
11161 (move-marker pos (point))
11162 (org-table-highlight-rectangle nil nil face2))
11163 (cond
11164 ((equal dest match))
11165 ((not match))
11166 ((eq what 'range)
11167 (condition-case nil
11168 (save-excursion
11169 (org-table-get-range match nil nil 'highlight))
11170 (error nil)))
11171 ((setq e (assoc var org-table-named-field-locations))
11172 (goto-line (nth 1 e))
11173 (org-table-goto-column (nth 2 e))
11174 (org-table-highlight-rectangle (point) (point))
11175 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11176 ((setq e (assoc var org-table-column-names))
11177 (org-table-goto-column (string-to-number (cdr e)))
11178 (org-table-highlight-rectangle (point) (point))
11179 (goto-char (org-table-begin))
11180 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11181 (org-table-end) t)
11182 (progn
11183 (goto-char (match-beginning 1))
11184 (org-table-highlight-rectangle)
11185 (message "Named column (column %s)" (cdr e)))
11186 (error "Column name not found")))
11187 ((eq what 'column)
11188 ;; column number
11189 (org-table-goto-column (string-to-number (substring match 1)))
11190 (org-table-highlight-rectangle (point) (point))
11191 (message "Column %s" (substring match 1)))
11192 ((setq e (assoc var org-table-local-parameters))
11193 (goto-char (org-table-begin))
11194 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11195 (progn
11196 (goto-char (match-beginning 1))
11197 (org-table-highlight-rectangle)
11198 (message "Local parameter."))
11199 (error "Parameter not found")))
11201 (cond
11202 ((not var) (error "No reference at point"))
11203 ((setq e (assoc var org-table-formula-constants-local))
11204 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11205 var (cdr e)))
11206 ((setq e (assoc var org-table-formula-constants))
11207 (message "Constant: $%s=%s in `org-table-formula-constants'."
11208 var (cdr e)))
11209 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11210 (message "Constant: $%s=%s, from `constants.el'%s."
11211 var e (format " (%s units)" constants-unit-system)))
11212 (t (error "Undefined name $%s" var)))))
11213 (goto-char pos)
11214 (when (and org-show-positions
11215 (not (memq this-command '(org-table-fedit-scroll
11216 org-table-fedit-scroll-down))))
11217 (push pos org-show-positions)
11218 (push org-table-current-begin-pos org-show-positions)
11219 (let ((min (apply 'min org-show-positions))
11220 (max (apply 'max org-show-positions)))
11221 (goto-char min) (recenter 0)
11222 (goto-char max)
11223 (or (pos-visible-in-window-p max) (recenter -1))))
11224 (select-window win))))
11226 (defun org-table-force-dataline ()
11227 "Make sure the cursor is in a dataline in a table."
11228 (unless (save-excursion
11229 (beginning-of-line 1)
11230 (looking-at org-table-dataline-regexp))
11231 (let* ((re org-table-dataline-regexp)
11232 (p1 (save-excursion (re-search-forward re nil 'move)))
11233 (p2 (save-excursion (re-search-backward re nil 'move))))
11234 (cond ((and p1 p2)
11235 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11236 p1 p2)))
11237 ((or p1 p2) (goto-char (or p1 p2)))
11238 (t (error "No table dataline around here"))))))
11240 (defun org-table-fedit-line-up ()
11241 "Move cursor one line up in the window showing the table."
11242 (interactive)
11243 (org-table-fedit-move 'previous-line))
11245 (defun org-table-fedit-line-down ()
11246 "Move cursor one line down in the window showing the table."
11247 (interactive)
11248 (org-table-fedit-move 'next-line))
11250 (defun org-table-fedit-move (command)
11251 "Move the cursor in the window shoinw the table.
11252 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11253 (let ((org-table-allow-automatic-line-recalculation nil)
11254 (pos org-pos) (win (selected-window)) p)
11255 (select-window (get-buffer-window (marker-buffer org-pos)))
11256 (setq p (point))
11257 (call-interactively command)
11258 (while (and (org-at-table-p)
11259 (org-at-table-hline-p))
11260 (call-interactively command))
11261 (or (org-at-table-p) (goto-char p))
11262 (move-marker pos (point))
11263 (select-window win)))
11265 (defun org-table-fedit-scroll (N)
11266 (interactive "p")
11267 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11268 (scroll-other-window N)))
11270 (defun org-table-fedit-scroll-down (N)
11271 (interactive "p")
11272 (org-table-fedit-scroll (- N)))
11274 (defvar org-table-rectangle-overlays nil)
11276 (defun org-table-add-rectangle-overlay (beg end &optional face)
11277 "Add a new overlay."
11278 (let ((ov (org-make-overlay beg end)))
11279 (org-overlay-put ov 'face (or face 'secondary-selection))
11280 (push ov org-table-rectangle-overlays)))
11282 (defun org-table-highlight-rectangle (&optional beg end face)
11283 "Highlight rectangular region in a table."
11284 (setq beg (or beg (point)) end (or end (point)))
11285 (let ((b (min beg end))
11286 (e (max beg end))
11287 l1 c1 l2 c2 tmp)
11288 (and (boundp 'org-show-positions)
11289 (setq org-show-positions (cons b (cons e org-show-positions))))
11290 (goto-char (min beg end))
11291 (setq l1 (org-current-line)
11292 c1 (org-table-current-column))
11293 (goto-char (max beg end))
11294 (setq l2 (org-current-line)
11295 c2 (org-table-current-column))
11296 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11297 (goto-line l1)
11298 (beginning-of-line 1)
11299 (loop for line from l1 to l2 do
11300 (when (looking-at org-table-dataline-regexp)
11301 (org-table-goto-column c1)
11302 (skip-chars-backward "^|\n") (setq beg (point))
11303 (org-table-goto-column c2)
11304 (skip-chars-forward "^|\n") (setq end (point))
11305 (org-table-add-rectangle-overlay beg end face))
11306 (beginning-of-line 2))
11307 (goto-char b))
11308 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11310 (defun org-table-remove-rectangle-highlight (&rest ignore)
11311 "Remove the rectangle overlays."
11312 (unless org-inhibit-highlight-removal
11313 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11314 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11315 (setq org-table-rectangle-overlays nil)))
11317 (defvar org-table-coordinate-overlays nil
11318 "Collects the cooordinate grid overlays, so that they can be removed.")
11319 (make-variable-buffer-local 'org-table-coordinate-overlays)
11321 (defun org-table-overlay-coordinates ()
11322 "Add overlays to the table at point, to show row/column coordinates."
11323 (interactive)
11324 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11325 (setq org-table-coordinate-overlays nil)
11326 (save-excursion
11327 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11328 (goto-char (org-table-begin))
11329 (while (org-at-table-p)
11330 (setq eol (point-at-eol))
11331 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11332 (push ov org-table-coordinate-overlays)
11333 (setq hline (looking-at org-table-hline-regexp))
11334 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11335 (format "%4d" (setq id (1+ id)))))
11336 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11337 (when hline
11338 (setq ic 0)
11339 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11340 (setq beg (1+ (match-beginning 0))
11341 ic (1+ ic)
11342 s1 (concat "$" (int-to-string ic))
11343 s2 (org-number-to-letters ic)
11344 str (if (eq org-table-use-standard-references t) s2 s1))
11345 (setq ov (org-make-overlay beg (+ beg (length str))))
11346 (push ov org-table-coordinate-overlays)
11347 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11348 (beginning-of-line 2)))))
11350 (defun org-table-toggle-coordinate-overlays ()
11351 "Toggle the display of Row/Column numbers in tables."
11352 (interactive)
11353 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11354 (message "Row/Column number display turned %s"
11355 (if org-table-overlay-coordinates "on" "off"))
11356 (if (and (org-at-table-p) org-table-overlay-coordinates)
11357 (org-table-align))
11358 (unless org-table-overlay-coordinates
11359 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11360 (setq org-table-coordinate-overlays nil)))
11362 (defun org-table-toggle-formula-debugger ()
11363 "Toggle the formula debugger in tables."
11364 (interactive)
11365 (setq org-table-formula-debug (not org-table-formula-debug))
11366 (message "Formula debugging has been turned %s"
11367 (if org-table-formula-debug "on" "off")))
11369 ;;; The orgtbl minor mode
11371 ;; Define a minor mode which can be used in other modes in order to
11372 ;; integrate the org-mode table editor.
11374 ;; This is really a hack, because the org-mode table editor uses several
11375 ;; keys which normally belong to the major mode, for example the TAB and
11376 ;; RET keys. Here is how it works: The minor mode defines all the keys
11377 ;; necessary to operate the table editor, but wraps the commands into a
11378 ;; function which tests if the cursor is currently inside a table. If that
11379 ;; is the case, the table editor command is executed. However, when any of
11380 ;; those keys is used outside a table, the function uses `key-binding' to
11381 ;; look up if the key has an associated command in another currently active
11382 ;; keymap (minor modes, major mode, global), and executes that command.
11383 ;; There might be problems if any of the keys used by the table editor is
11384 ;; otherwise used as a prefix key.
11386 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11387 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11388 ;; addresses this by checking explicitly for both bindings.
11390 ;; The optimized version (see variable `orgtbl-optimized') takes over
11391 ;; all keys which are bound to `self-insert-command' in the *global map*.
11392 ;; Some modes bind other commands to simple characters, for example
11393 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11394 ;; active, this binding is ignored inside tables and replaced with a
11395 ;; modified self-insert.
11397 (defvar orgtbl-mode nil
11398 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11399 table editor in arbitrary modes.")
11400 (make-variable-buffer-local 'orgtbl-mode)
11402 (defvar orgtbl-mode-map (make-keymap)
11403 "Keymap for `orgtbl-mode'.")
11405 ;;;###autoload
11406 (defun turn-on-orgtbl ()
11407 "Unconditionally turn on `orgtbl-mode'."
11408 (orgtbl-mode 1))
11410 (defvar org-old-auto-fill-inhibit-regexp nil
11411 "Local variable used by `orgtbl-mode'")
11413 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11414 "Matches a line belonging to an orgtbl.")
11416 (defconst orgtbl-extra-font-lock-keywords
11417 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11418 0 (quote 'org-table) 'prepend))
11419 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11421 ;;;###autoload
11422 (defun orgtbl-mode (&optional arg)
11423 "The `org-mode' table editor as a minor mode for use in other modes."
11424 (interactive)
11425 (org-load-modules-maybe)
11426 (if (org-mode-p)
11427 ;; Exit without error, in case some hook functions calls this
11428 ;; by accident in org-mode.
11429 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11430 (setq orgtbl-mode
11431 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11432 (if orgtbl-mode
11433 (progn
11434 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11435 ;; Make sure we are first in minor-mode-map-alist
11436 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11437 (and c (setq minor-mode-map-alist
11438 (cons c (delq c minor-mode-map-alist)))))
11439 (org-set-local (quote org-table-may-need-update) t)
11440 (org-add-hook 'before-change-functions 'org-before-change-function
11441 nil 'local)
11442 (org-set-local 'org-old-auto-fill-inhibit-regexp
11443 auto-fill-inhibit-regexp)
11444 (org-set-local 'auto-fill-inhibit-regexp
11445 (if auto-fill-inhibit-regexp
11446 (concat orgtbl-line-start-regexp "\\|"
11447 auto-fill-inhibit-regexp)
11448 orgtbl-line-start-regexp))
11449 (org-add-to-invisibility-spec '(org-cwidth))
11450 (when (fboundp 'font-lock-add-keywords)
11451 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11452 (org-restart-font-lock))
11453 (easy-menu-add orgtbl-mode-menu)
11454 (run-hooks 'orgtbl-mode-hook))
11455 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11456 (org-cleanup-narrow-column-properties)
11457 (org-remove-from-invisibility-spec '(org-cwidth))
11458 (remove-hook 'before-change-functions 'org-before-change-function t)
11459 (when (fboundp 'font-lock-remove-keywords)
11460 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11461 (org-restart-font-lock))
11462 (easy-menu-remove orgtbl-mode-menu)
11463 (force-mode-line-update 'all))))
11465 (defun org-cleanup-narrow-column-properties ()
11466 "Remove all properties related to narrow-column invisibility."
11467 (let ((s 1))
11468 (while (setq s (text-property-any s (point-max)
11469 'display org-narrow-column-arrow))
11470 (remove-text-properties s (1+ s) '(display t)))
11471 (setq s 1)
11472 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11473 (remove-text-properties s (1+ s) '(org-cwidth t)))
11474 (setq s 1)
11475 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11476 (remove-text-properties s (1+ s) '(invisible t)))))
11478 ;; Install it as a minor mode.
11479 (put 'orgtbl-mode :included t)
11480 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11481 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11483 (defun orgtbl-make-binding (fun n &rest keys)
11484 "Create a function for binding in the table minor mode.
11485 FUN is the command to call inside a table. N is used to create a unique
11486 command name. KEYS are keys that should be checked in for a command
11487 to execute outside of tables."
11488 (eval
11489 (list 'defun
11490 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11491 '(arg)
11492 (concat "In tables, run `" (symbol-name fun) "'.\n"
11493 "Outside of tables, run the binding of `"
11494 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11495 "'.")
11496 '(interactive "p")
11497 (list 'if
11498 '(org-at-table-p)
11499 (list 'call-interactively (list 'quote fun))
11500 (list 'let '(orgtbl-mode)
11501 (list 'call-interactively
11502 (append '(or)
11503 (mapcar (lambda (k)
11504 (list 'key-binding k))
11505 keys)
11506 '('orgtbl-error))))))))
11508 (defun orgtbl-error ()
11509 "Error when there is no default binding for a table key."
11510 (interactive)
11511 (error "This key has no function outside tables"))
11513 (defun orgtbl-setup ()
11514 "Setup orgtbl keymaps."
11515 (let ((nfunc 0)
11516 (bindings
11517 (list
11518 '([(meta shift left)] org-table-delete-column)
11519 '([(meta left)] org-table-move-column-left)
11520 '([(meta right)] org-table-move-column-right)
11521 '([(meta shift right)] org-table-insert-column)
11522 '([(meta shift up)] org-table-kill-row)
11523 '([(meta shift down)] org-table-insert-row)
11524 '([(meta up)] org-table-move-row-up)
11525 '([(meta down)] org-table-move-row-down)
11526 '("\C-c\C-w" org-table-cut-region)
11527 '("\C-c\M-w" org-table-copy-region)
11528 '("\C-c\C-y" org-table-paste-rectangle)
11529 '("\C-c-" org-table-insert-hline)
11530 '("\C-c}" org-table-toggle-coordinate-overlays)
11531 '("\C-c{" org-table-toggle-formula-debugger)
11532 '("\C-m" org-table-next-row)
11533 '([(shift return)] org-table-copy-down)
11534 '("\C-c\C-q" org-table-wrap-region)
11535 '("\C-c?" org-table-field-info)
11536 '("\C-c " org-table-blank-field)
11537 '("\C-c+" org-table-sum)
11538 '("\C-c=" org-table-eval-formula)
11539 '("\C-c'" org-table-edit-formulas)
11540 '("\C-c`" org-table-edit-field)
11541 '("\C-c*" org-table-recalculate)
11542 '("\C-c|" org-table-create-or-convert-from-region)
11543 '("\C-c^" org-table-sort-lines)
11544 '([(control ?#)] org-table-rotate-recalc-marks)))
11545 elt key fun cmd)
11546 (while (setq elt (pop bindings))
11547 (setq nfunc (1+ nfunc))
11548 (setq key (org-key (car elt))
11549 fun (nth 1 elt)
11550 cmd (orgtbl-make-binding fun nfunc key))
11551 (org-defkey orgtbl-mode-map key cmd))
11553 ;; Special treatment needed for TAB and RET
11554 (org-defkey orgtbl-mode-map [(return)]
11555 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11556 (org-defkey orgtbl-mode-map "\C-m"
11557 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11559 (org-defkey orgtbl-mode-map [(tab)]
11560 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11561 (org-defkey orgtbl-mode-map "\C-i"
11562 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11564 (org-defkey orgtbl-mode-map [(shift tab)]
11565 (orgtbl-make-binding 'org-table-previous-field 104
11566 [(shift tab)] [(tab)] "\C-i"))
11568 (org-defkey orgtbl-mode-map "\M-\C-m"
11569 (orgtbl-make-binding 'org-table-wrap-region 105
11570 "\M-\C-m" [(meta return)]))
11571 (org-defkey orgtbl-mode-map [(meta return)]
11572 (orgtbl-make-binding 'org-table-wrap-region 106
11573 [(meta return)] "\M-\C-m"))
11575 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11576 (when orgtbl-optimized
11577 ;; If the user wants maximum table support, we need to hijack
11578 ;; some standard editing functions
11579 (org-remap orgtbl-mode-map
11580 'self-insert-command 'orgtbl-self-insert-command
11581 'delete-char 'org-delete-char
11582 'delete-backward-char 'org-delete-backward-char)
11583 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11584 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11585 '("OrgTbl"
11586 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11587 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11588 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11589 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11590 "--"
11591 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11592 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11593 ["Copy Field from Above"
11594 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11595 "--"
11596 ("Column"
11597 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11598 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11599 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11600 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11601 ("Row"
11602 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11603 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11604 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11605 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11606 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11607 "--"
11608 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11609 ("Rectangle"
11610 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11611 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11612 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11613 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11614 "--"
11615 ("Radio tables"
11616 ["Insert table template" orgtbl-insert-radio-table
11617 (assq major-mode orgtbl-radio-table-templates)]
11618 ["Comment/uncomment table" orgtbl-toggle-comment t])
11619 "--"
11620 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11621 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11622 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11623 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11624 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11625 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11626 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11627 ["Sum Column/Rectangle" org-table-sum
11628 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11629 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11630 ["Debug Formulas"
11631 org-table-toggle-formula-debugger :active (org-at-table-p)
11632 :keys "C-c {"
11633 :style toggle :selected org-table-formula-debug]
11634 ["Show Col/Row Numbers"
11635 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11636 :keys "C-c }"
11637 :style toggle :selected org-table-overlay-coordinates]
11641 (defun orgtbl-ctrl-c-ctrl-c (arg)
11642 "If the cursor is inside a table, realign the table.
11643 It it is a table to be sent away to a receiver, do it.
11644 With prefix arg, also recompute table."
11645 (interactive "P")
11646 (let ((pos (point)) action)
11647 (save-excursion
11648 (beginning-of-line 1)
11649 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11650 ((looking-at "[ \t]*|") pos)
11651 ((looking-at "#\\+TBLFM:") 'recalc))))
11652 (cond
11653 ((integerp action)
11654 (goto-char action)
11655 (org-table-maybe-eval-formula)
11656 (if arg
11657 (call-interactively 'org-table-recalculate)
11658 (org-table-maybe-recalculate-line))
11659 (call-interactively 'org-table-align)
11660 (orgtbl-send-table 'maybe))
11661 ((eq action 'recalc)
11662 (save-excursion
11663 (beginning-of-line 1)
11664 (skip-chars-backward " \r\n\t")
11665 (if (org-at-table-p)
11666 (org-call-with-arg 'org-table-recalculate t))))
11667 (t (let (orgtbl-mode)
11668 (call-interactively (key-binding "\C-c\C-c")))))))
11670 (defun orgtbl-tab (arg)
11671 "Justification and field motion for `orgtbl-mode'."
11672 (interactive "P")
11673 (if arg (org-table-edit-field t)
11674 (org-table-justify-field-maybe)
11675 (org-table-next-field)))
11677 (defun orgtbl-ret ()
11678 "Justification and field motion for `orgtbl-mode'."
11679 (interactive)
11680 (org-table-justify-field-maybe)
11681 (org-table-next-row))
11683 (defun orgtbl-self-insert-command (N)
11684 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11685 If the cursor is in a table looking at whitespace, the whitespace is
11686 overwritten, and the table is not marked as requiring realignment."
11687 (interactive "p")
11688 (if (and (org-at-table-p)
11690 (and org-table-auto-blank-field
11691 (member last-command
11692 '(orgtbl-hijacker-command-100
11693 orgtbl-hijacker-command-101
11694 orgtbl-hijacker-command-102
11695 orgtbl-hijacker-command-103
11696 orgtbl-hijacker-command-104
11697 orgtbl-hijacker-command-105))
11698 (org-table-blank-field))
11700 (eq N 1)
11701 (looking-at "[^|\n]* +|"))
11702 (let (org-table-may-need-update)
11703 (goto-char (1- (match-end 0)))
11704 (delete-backward-char 1)
11705 (goto-char (match-beginning 0))
11706 (self-insert-command N))
11707 (setq org-table-may-need-update t)
11708 (let (orgtbl-mode)
11709 (call-interactively (key-binding (vector last-input-event))))))
11711 (defun org-force-self-insert (N)
11712 "Needed to enforce self-insert under remapping."
11713 (interactive "p")
11714 (self-insert-command N))
11716 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11717 "Regula expression matching exponentials as produced by calc.")
11719 (defvar org-table-clean-did-remove-column nil)
11721 (defun orgtbl-export (table target)
11722 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11723 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11724 org-table-last-alignment org-table-last-column-widths
11725 maxcol column)
11726 (if (not (fboundp func))
11727 (error "Cannot export orgtbl table to %s" target))
11728 (setq lines (org-table-clean-before-export lines))
11729 (setq table
11730 (mapcar
11731 (lambda (x)
11732 (if (string-match org-table-hline-regexp x)
11733 'hline
11734 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11735 lines))
11736 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11737 table)))
11738 (loop for i from (1- maxcol) downto 0 do
11739 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11740 (setq column (delq nil column))
11741 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11742 (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))
11743 (funcall func table nil)))
11745 (defun orgtbl-send-table (&optional maybe)
11746 "Send a tranformed version of this table to the receiver position.
11747 With argument MAYBE, fail quietly if no transformation is defined for
11748 this table."
11749 (interactive)
11750 (catch 'exit
11751 (unless (org-at-table-p) (error "Not at a table"))
11752 ;; when non-interactive, we assume align has just happened.
11753 (when (interactive-p) (org-table-align))
11754 (save-excursion
11755 (goto-char (org-table-begin))
11756 (beginning-of-line 0)
11757 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11758 (if maybe
11759 (throw 'exit nil)
11760 (error "Don't know how to transform this table."))))
11761 (let* ((name (match-string 1))
11763 (transform (intern (match-string 2)))
11764 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11765 (skip (plist-get params :skip))
11766 (skipcols (plist-get params :skipcols))
11767 (txt (buffer-substring-no-properties
11768 (org-table-begin) (org-table-end)))
11769 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11770 (lines (org-table-clean-before-export lines))
11771 (i0 (if org-table-clean-did-remove-column 2 1))
11772 (table (mapcar
11773 (lambda (x)
11774 (if (string-match org-table-hline-regexp x)
11775 'hline
11776 (org-remove-by-index
11777 (org-split-string (org-trim x) "\\s-*|\\s-*")
11778 skipcols i0)))
11779 lines))
11780 (fun (if (= i0 2) 'cdr 'identity))
11781 (org-table-last-alignment
11782 (org-remove-by-index (funcall fun org-table-last-alignment)
11783 skipcols i0))
11784 (org-table-last-column-widths
11785 (org-remove-by-index (funcall fun org-table-last-column-widths)
11786 skipcols i0)))
11788 (unless (fboundp transform)
11789 (error "No such transformation function %s" transform))
11790 (setq txt (funcall transform table params))
11791 ;; Find the insertion place
11792 (save-excursion
11793 (goto-char (point-min))
11794 (unless (re-search-forward
11795 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11796 (error "Don't know where to insert translated table"))
11797 (goto-char (match-beginning 0))
11798 (beginning-of-line 2)
11799 (setq beg (point))
11800 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11801 (error "Cannot find end of insertion region"))
11802 (beginning-of-line 1)
11803 (delete-region beg (point))
11804 (goto-char beg)
11805 (insert txt "\n"))
11806 (message "Table converted and installed at receiver location"))))
11808 (defun org-remove-by-index (list indices &optional i0)
11809 "Remove the elements in LIST with indices in INDICES.
11810 First element has index 0, or I0 if given."
11811 (if (not indices)
11812 list
11813 (if (integerp indices) (setq indices (list indices)))
11814 (setq i0 (1- (or i0 0)))
11815 (delq :rm (mapcar (lambda (x)
11816 (setq i0 (1+ i0))
11817 (if (memq i0 indices) :rm x))
11818 list))))
11820 (defun orgtbl-toggle-comment ()
11821 "Comment or uncomment the orgtbl at point."
11822 (interactive)
11823 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11824 (re2 (concat "^" orgtbl-line-start-regexp))
11825 (commented (save-excursion (beginning-of-line 1)
11826 (cond ((looking-at re1) t)
11827 ((looking-at re2) nil)
11828 (t (error "Not at an org table")))))
11829 (re (if commented re1 re2))
11830 beg end)
11831 (save-excursion
11832 (beginning-of-line 1)
11833 (while (looking-at re) (beginning-of-line 0))
11834 (beginning-of-line 2)
11835 (setq beg (point))
11836 (while (looking-at re) (beginning-of-line 2))
11837 (setq end (point)))
11838 (comment-region beg end (if commented '(4) nil))))
11840 (defun orgtbl-insert-radio-table ()
11841 "Insert a radio table template appropriate for this major mode."
11842 (interactive)
11843 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11844 (txt (nth 1 e))
11845 name pos)
11846 (unless e (error "No radio table setup defined for %s" major-mode))
11847 (setq name (read-string "Table name: "))
11848 (while (string-match "%n" txt)
11849 (setq txt (replace-match name t t txt)))
11850 (or (bolp) (insert "\n"))
11851 (setq pos (point))
11852 (insert txt)
11853 (goto-char pos)))
11855 (defun org-get-param (params header i sym &optional hsym)
11856 "Get parameter value for symbol SYM.
11857 If this is a header line, actually get the value for the symbol with an
11858 additional \"h\" inserted after the colon.
11859 If the value is a protperty list, get the element for the current column.
11860 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11861 (let ((val (plist-get params sym)))
11862 (and hsym header (setq val (or (plist-get params hsym) val)))
11863 (if (consp val) (plist-get val i) val)))
11865 (defun orgtbl-to-generic (table params)
11866 "Convert the orgtbl-mode TABLE to some other format.
11867 This generic routine can be used for many standard cases.
11868 TABLE is a list, each entry either the symbol `hline' for a horizontal
11869 separator line, or a list of fields for that line.
11870 PARAMS is a property list of parameters that can influence the conversion.
11871 For the generic converter, some parameters are obligatory: You need to
11872 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11873 :splice, you must have :tstart and :tend.
11875 Valid parameters are
11877 :tstart String to start the table. Ignored when :splice is t.
11878 :tend String to end the table. Ignored when :splice is t.
11880 :splice When set to t, return only table body lines, don't wrap
11881 them into :tstart and :tend. Default is nil.
11883 :hline String to be inserted on horizontal separation lines.
11884 May be nil to ignore hlines.
11886 :lstart String to start a new table line.
11887 :lend String to end a table line
11888 :sep Separator between two fields
11889 :lfmt Format for entire line, with enough %s to capture all fields.
11890 If this is present, :lstart, :lend, and :sep are ignored.
11891 :fmt A format to be used to wrap the field, should contain
11892 %s for the original field value. For example, to wrap
11893 everything in dollars, you could use :fmt \"$%s$\".
11894 This may also be a property list with column numbers and
11895 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11897 :hlstart :hlend :hlsep :hlfmt :hfmt
11898 Same as above, specific for the header lines in the table.
11899 All lines before the first hline are treated as header.
11900 If any of these is not present, the data line value is used.
11902 :efmt Use this format to print numbers with exponentials.
11903 The format should have %s twice for inserting mantissa
11904 and exponent, for example \"%s\\\\times10^{%s}\". This
11905 may also be a property list with column numbers and
11906 formats. :fmt will still be applied after :efmt.
11908 In addition to this, the parameters :skip and :skipcols are always handled
11909 directly by `orgtbl-send-table'. See manual."
11910 (interactive)
11911 (let* ((p params)
11912 (splicep (plist-get p :splice))
11913 (hline (plist-get p :hline))
11914 rtn line i fm efm lfmt h)
11916 ;; Do we have a header?
11917 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11918 (setq h t))
11920 ;; Put header
11921 (unless splicep
11922 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11924 ;; Now loop over all lines
11925 (while (setq line (pop table))
11926 (if (eq line 'hline)
11927 ;; A horizontal separator line
11928 (progn (if hline (push hline rtn))
11929 (setq h nil)) ; no longer in header
11930 ;; A normal line. Convert the fields, push line onto the result list
11931 (setq i 0)
11932 (setq line
11933 (mapcar
11934 (lambda (f)
11935 (setq i (1+ i)
11936 fm (org-get-param p h i :fmt :hfmt)
11937 efm (org-get-param p h i :efmt))
11938 (if (and efm (string-match orgtbl-exp-regexp f))
11939 (setq f (format
11940 efm (match-string 1 f) (match-string 2 f))))
11941 (if fm (setq f (format fm f)))
11943 line))
11944 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11945 (push (apply 'format lfmt line) rtn)
11946 (push (concat
11947 (org-get-param p h i :lstart :hlstart)
11948 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11949 (org-get-param p h i :lend :hlend))
11950 rtn))))
11952 (unless splicep
11953 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11955 (mapconcat 'identity (nreverse rtn) "\n")))
11957 (defun orgtbl-to-latex (table params)
11958 "Convert the orgtbl-mode TABLE to LaTeX.
11959 TABLE is a list, each entry either the symbol `hline' for a horizontal
11960 separator line, or a list of fields for that line.
11961 PARAMS is a property list of parameters that can influence the conversion.
11962 Supports all parameters from `orgtbl-to-generic'. Most important for
11963 LaTeX are:
11965 :splice When set to t, return only table body lines, don't wrap
11966 them into a tabular environment. Default is nil.
11968 :fmt A format to be used to wrap the field, should contain %s for the
11969 original field value. For example, to wrap everything in dollars,
11970 use :fmt \"$%s$\". This may also be a property list with column
11971 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11973 :efmt Format for transforming numbers with exponentials. The format
11974 should have %s twice for inserting mantissa and exponent, for
11975 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11976 This may also be a property list with column numbers and formats.
11978 The general parameters :skip and :skipcols have already been applied when
11979 this function is called."
11980 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11981 org-table-last-alignment ""))
11982 (params2
11983 (list
11984 :tstart (concat "\\begin{tabular}{" alignment "}")
11985 :tend "\\end{tabular}"
11986 :lstart "" :lend " \\\\" :sep " & "
11987 :efmt "%s\\,(%s)" :hline "\\hline")))
11988 (orgtbl-to-generic table (org-combine-plists params2 params))))
11990 (defun orgtbl-to-html (table params)
11991 "Convert the orgtbl-mode TABLE to LaTeX.
11992 TABLE is a list, each entry either the symbol `hline' for a horizontal
11993 separator line, or a list of fields for that line.
11994 PARAMS is a property list of parameters that can influence the conversion.
11995 Currently this function recognizes the following parameters:
11997 :splice When set to t, return only table body lines, don't wrap
11998 them into a <table> environment. Default is nil.
12000 The general parameters :skip and :skipcols have already been applied when
12001 this function is called. The function does *not* use `orgtbl-to-generic',
12002 so you cannot specify parameters for it."
12003 (let* ((splicep (plist-get params :splice))
12004 html)
12005 ;; Just call the formatter we already have
12006 ;; We need to make text lines for it, so put the fields back together.
12007 (setq html (org-format-org-table-html
12008 (mapcar
12009 (lambda (x)
12010 (if (eq x 'hline)
12011 "|----+----|"
12012 (concat "| " (mapconcat 'identity x " | ") " |")))
12013 table)
12014 splicep))
12015 (if (string-match "\n+\\'" html)
12016 (setq html (replace-match "" t t html)))
12017 html))
12019 (defun orgtbl-to-texinfo (table params)
12020 "Convert the orgtbl-mode TABLE to TeXInfo.
12021 TABLE is a list, each entry either the symbol `hline' for a horizontal
12022 separator line, or a list of fields for that line.
12023 PARAMS is a property list of parameters that can influence the conversion.
12024 Supports all parameters from `orgtbl-to-generic'. Most important for
12025 TeXInfo are:
12027 :splice nil/t When set to t, return only table body lines, don't wrap
12028 them into a multitable environment. Default is nil.
12030 :fmt fmt A format to be used to wrap the field, should contain
12031 %s for the original field value. For example, to wrap
12032 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12033 This may also be a property list with column numbers and
12034 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12036 :cf \"f1 f2..\" The column fractions for the table. By default these
12037 are computed automatically from the width of the columns
12038 under org-mode.
12040 The general parameters :skip and :skipcols have already been applied when
12041 this function is called."
12042 (let* ((total (float (apply '+ org-table-last-column-widths)))
12043 (colfrac (or (plist-get params :cf)
12044 (mapconcat
12045 (lambda (x) (format "%.3f" (/ (float x) total)))
12046 org-table-last-column-widths " ")))
12047 (params2
12048 (list
12049 :tstart (concat "@multitable @columnfractions " colfrac)
12050 :tend "@end multitable"
12051 :lstart "@item " :lend "" :sep " @tab "
12052 :hlstart "@headitem ")))
12053 (orgtbl-to-generic table (org-combine-plists params2 params))))
12055 ;;;; Link Stuff
12057 ;;; Link abbreviations
12059 (defun org-link-expand-abbrev (link)
12060 "Apply replacements as defined in `org-link-abbrev-alist."
12061 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12062 (let* ((key (match-string 1 link))
12063 (as (or (assoc key org-link-abbrev-alist-local)
12064 (assoc key org-link-abbrev-alist)))
12065 (tag (and (match-end 2) (match-string 3 link)))
12066 rpl)
12067 (if (not as)
12068 link
12069 (setq rpl (cdr as))
12070 (cond
12071 ((symbolp rpl) (funcall rpl tag))
12072 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12073 (t (concat rpl tag)))))
12074 link))
12076 ;;; Storing and inserting links
12078 (defvar org-insert-link-history nil
12079 "Minibuffer history for links inserted with `org-insert-link'.")
12081 (defvar org-stored-links nil
12082 "Contains the links stored with `org-store-link'.")
12084 (defvar org-store-link-plist nil
12085 "Plist with info about the most recently link created with `org-store-link'.")
12087 (defvar org-link-protocols nil
12088 "Link protocols added to Org-mode using `org-add-link-type'.")
12090 (defvar org-store-link-functions nil
12091 "List of functions that are called to create and store a link.
12092 Each function will be called in turn until one returns a non-nil
12093 value. Each function should check if it is responsible for creating
12094 this link (for example by looking at the major mode).
12095 If not, it must exit and return nil.
12096 If yes, it should return a non-nil value after a calling
12097 `org-store-link-props' with a list of properties and values.
12098 Special properties are:
12100 :type The link prefix. like \"http\". This must be given.
12101 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12102 This is obligatory as well.
12103 :description Optional default description for the second pair
12104 of brackets in an Org-mode link. The user can still change
12105 this when inserting this link into an Org-mode buffer.
12107 In addition to these, any additional properties can be specified
12108 and then used in remember templates.")
12110 (defun org-add-link-type (type &optional follow export)
12111 "Add TYPE to the list of `org-link-types'.
12112 Re-compute all regular expressions depending on `org-link-types'
12114 FOLLOW and EXPORT are two functions.
12116 FOLLOW should take the link path as the single argument and do whatever
12117 is necessary to follow the link, for example find a file or display
12118 a mail message.
12120 EXPORT should format the link path for export to one of the export formats.
12121 It should be a function accepting three arguments:
12123 path the path of the link, the text after the prefix (like \"http:\")
12124 desc the description of the link, if any, nil if there was no descripton
12125 format the export format, a symbol like `html' or `latex'.
12127 The function may use the FORMAT information to return different values
12128 depending on the format. The return value will be put literally into
12129 the exported file.
12130 Org-mode has a built-in default for exporting links. If you are happy with
12131 this default, there is no need to define an export function for the link
12132 type. For a simple example of an export function, see `org-bbdb.el'."
12133 (add-to-list 'org-link-types type t)
12134 (org-make-link-regexps)
12135 (if (assoc type org-link-protocols)
12136 (setcdr (assoc type org-link-protocols) (list follow export))
12137 (push (list type follow export) org-link-protocols)))
12140 (defun org-add-agenda-custom-command (entry)
12141 "Replace or add a command in `org-agenda-custom-commands'.
12142 This is mostly for hacking and trying a new command - once the command
12143 works you probably want to add it to `org-agenda-custom-commands' for good."
12144 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12145 (if ass
12146 (setcdr ass (cdr entry))
12147 (push entry org-agenda-custom-commands))))
12149 ;;;###autoload
12150 (defun org-store-link (arg)
12151 "\\<org-mode-map>Store an org-link to the current location.
12152 This link is added to `org-stored-links' and can later be inserted
12153 into an org-buffer with \\[org-insert-link].
12155 For some link types, a prefix arg is interpreted:
12156 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12157 For file links, arg negates `org-context-in-file-links'."
12158 (interactive "P")
12159 (org-load-modules-maybe)
12160 (setq org-store-link-plist nil) ; reset
12161 (let (link cpltxt desc description search txt)
12162 (cond
12164 ((run-hook-with-args-until-success 'org-store-link-functions)
12165 (setq link (plist-get org-store-link-plist :link)
12166 desc (or (plist-get org-store-link-plist :description) link)))
12168 ((eq major-mode 'calendar-mode)
12169 (let ((cd (calendar-cursor-to-date)))
12170 (setq link
12171 (format-time-string
12172 (car org-time-stamp-formats)
12173 (apply 'encode-time
12174 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12175 nil nil nil))))
12176 (org-store-link-props :type "calendar" :date cd)))
12178 ((eq major-mode 'w3-mode)
12179 (setq cpltxt (url-view-url t)
12180 link (org-make-link cpltxt))
12181 (org-store-link-props :type "w3" :url (url-view-url t)))
12183 ((eq major-mode 'w3m-mode)
12184 (setq cpltxt (or w3m-current-title w3m-current-url)
12185 link (org-make-link w3m-current-url))
12186 (org-store-link-props :type "w3m" :url (url-view-url t)))
12188 ((setq search (run-hook-with-args-until-success
12189 'org-create-file-search-functions))
12190 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12191 "::" search))
12192 (setq cpltxt (or description link)))
12194 ((eq major-mode 'image-mode)
12195 (setq cpltxt (concat "file:"
12196 (abbreviate-file-name buffer-file-name))
12197 link (org-make-link cpltxt))
12198 (org-store-link-props :type "image" :file buffer-file-name))
12200 ((eq major-mode 'dired-mode)
12201 ;; link to the file in the current line
12202 (setq cpltxt (concat "file:"
12203 (abbreviate-file-name
12204 (expand-file-name
12205 (dired-get-filename nil t))))
12206 link (org-make-link cpltxt)))
12208 ((and buffer-file-name (org-mode-p))
12209 ;; Just link to current headline
12210 (setq cpltxt (concat "file:"
12211 (abbreviate-file-name buffer-file-name)))
12212 ;; Add a context search string
12213 (when (org-xor org-context-in-file-links arg)
12214 ;; Check if we are on a target
12215 (if (org-in-regexp "<<\\(.*?\\)>>")
12216 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12217 (setq txt (cond
12218 ((org-on-heading-p) nil)
12219 ((org-region-active-p)
12220 (buffer-substring (region-beginning) (region-end)))
12221 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12222 (when (or (null txt) (string-match "\\S-" txt))
12223 (setq cpltxt
12224 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12225 desc "NONE"))))
12226 (if (string-match "::\\'" cpltxt)
12227 (setq cpltxt (substring cpltxt 0 -2)))
12228 (setq link (org-make-link cpltxt)))
12230 ((buffer-file-name (buffer-base-buffer))
12231 ;; Just link to this file here.
12232 (setq cpltxt (concat "file:"
12233 (abbreviate-file-name
12234 (buffer-file-name (buffer-base-buffer)))))
12235 ;; Add a context string
12236 (when (org-xor org-context-in-file-links arg)
12237 (setq txt (if (org-region-active-p)
12238 (buffer-substring (region-beginning) (region-end))
12239 (buffer-substring (point-at-bol) (point-at-eol))))
12240 ;; Only use search option if there is some text.
12241 (when (string-match "\\S-" txt)
12242 (setq cpltxt
12243 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12244 desc "NONE")))
12245 (setq link (org-make-link cpltxt)))
12247 ((interactive-p)
12248 (error "Cannot link to a buffer which is not visiting a file"))
12250 (t (setq link nil)))
12252 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12253 (setq link (or link cpltxt)
12254 desc (or desc cpltxt))
12255 (if (equal desc "NONE") (setq desc nil))
12257 (if (and (interactive-p) link)
12258 (progn
12259 (setq org-stored-links
12260 (cons (list link desc) org-stored-links))
12261 (message "Stored: %s" (or desc link)))
12262 (and link (org-make-link-string link desc)))))
12264 (defun org-store-link-props (&rest plist)
12265 "Store link properties, extract names and addresses."
12266 (let (x adr)
12267 (when (setq x (plist-get plist :from))
12268 (setq adr (mail-extract-address-components x))
12269 (plist-put plist :fromname (car adr))
12270 (plist-put plist :fromaddress (nth 1 adr)))
12271 (when (setq x (plist-get plist :to))
12272 (setq adr (mail-extract-address-components x))
12273 (plist-put plist :toname (car adr))
12274 (plist-put plist :toaddress (nth 1 adr))))
12275 (let ((from (plist-get plist :from))
12276 (to (plist-get plist :to)))
12277 (when (and from to org-from-is-user-regexp)
12278 (plist-put plist :fromto
12279 (if (string-match org-from-is-user-regexp from)
12280 (concat "to %t")
12281 (concat "from %f")))))
12282 (setq org-store-link-plist plist))
12284 (defun org-add-link-props (&rest plist)
12285 "Add these properties to the link property list."
12286 (let (key value)
12287 (while plist
12288 (setq key (pop plist) value (pop plist))
12289 (setq org-store-link-plist
12290 (plist-put org-store-link-plist key value)))))
12292 (defun org-email-link-description (&optional fmt)
12293 "Return the description part of an email link.
12294 This takes information from `org-store-link-plist' and formats it
12295 according to FMT (default from `org-email-link-description-format')."
12296 (setq fmt (or fmt org-email-link-description-format))
12297 (let* ((p org-store-link-plist)
12298 (to (plist-get p :toaddress))
12299 (from (plist-get p :fromaddress))
12300 (table
12301 (list
12302 (cons "%c" (plist-get p :fromto))
12303 (cons "%F" (plist-get p :from))
12304 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12305 (cons "%T" (plist-get p :to))
12306 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12307 (cons "%s" (plist-get p :subject))
12308 (cons "%m" (plist-get p :message-id)))))
12309 (when (string-match "%c" fmt)
12310 ;; Check if the user wrote this message
12311 (if (and org-from-is-user-regexp from to
12312 (save-match-data (string-match org-from-is-user-regexp from)))
12313 (setq fmt (replace-match "to %t" t t fmt))
12314 (setq fmt (replace-match "from %f" t t fmt))))
12315 (org-replace-escapes fmt table)))
12317 (defun org-make-org-heading-search-string (&optional string heading)
12318 "Make search string for STRING or current headline."
12319 (interactive)
12320 (let ((s (or string (org-get-heading))))
12321 (unless (and string (not heading))
12322 ;; We are using a headline, clean up garbage in there.
12323 (if (string-match org-todo-regexp s)
12324 (setq s (replace-match "" t t s)))
12325 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12326 (setq s (replace-match "" t t s)))
12327 (setq s (org-trim s))
12328 (if (string-match (concat "^\\(" org-quote-string "\\|"
12329 org-comment-string "\\)") s)
12330 (setq s (replace-match "" t t s)))
12331 (while (string-match org-ts-regexp s)
12332 (setq s (replace-match "" t t s))))
12333 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12334 (setq s (replace-match " " t t s)))
12335 (or string (setq s (concat "*" s))) ; Add * for headlines
12336 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12338 (defun org-make-link (&rest strings)
12339 "Concatenate STRINGS."
12340 (apply 'concat strings))
12342 (defun org-make-link-string (link &optional description)
12343 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12344 (unless (string-match "\\S-" link)
12345 (error "Empty link"))
12346 (when (stringp description)
12347 ;; Remove brackets from the description, they are fatal.
12348 (while (string-match "\\[" description)
12349 (setq description (replace-match "{" t t description)))
12350 (while (string-match "\\]" description)
12351 (setq description (replace-match "}" t t description))))
12352 (when (equal (org-link-escape link) description)
12353 ;; No description needed, it is identical
12354 (setq description nil))
12355 (when (and (not description)
12356 (not (equal link (org-link-escape link))))
12357 (setq description link))
12358 (concat "[[" (org-link-escape link) "]"
12359 (if description (concat "[" description "]") "")
12360 "]"))
12362 (defconst org-link-escape-chars
12363 '((?\ . "%20")
12364 (?\[ . "%5B")
12365 (?\] . "%5D")
12366 (?\340 . "%E0") ; `a
12367 (?\342 . "%E2") ; ^a
12368 (?\347 . "%E7") ; ,c
12369 (?\350 . "%E8") ; `e
12370 (?\351 . "%E9") ; 'e
12371 (?\352 . "%EA") ; ^e
12372 (?\356 . "%EE") ; ^i
12373 (?\364 . "%F4") ; ^o
12374 (?\371 . "%F9") ; `u
12375 (?\373 . "%FB") ; ^u
12376 (?\; . "%3B")
12377 (?? . "%3F")
12378 (?= . "%3D")
12379 (?+ . "%2B")
12381 "Association list of escapes for some characters problematic in links.
12382 This is the list that is used for internal purposes.")
12384 (defconst org-link-escape-chars-browser
12385 '((?\ . "%20")) ; 32 for the SPC char
12386 "Association list of escapes for some characters problematic in links.
12387 This is the list that is used before handing over to the browser.")
12389 (defun org-link-escape (text &optional table)
12390 "Escape charaters in TEXT that are problematic for links."
12391 (setq table (or table org-link-escape-chars))
12392 (when text
12393 (let ((re (mapconcat (lambda (x) (regexp-quote
12394 (char-to-string (car x))))
12395 table "\\|")))
12396 (while (string-match re text)
12397 (setq text
12398 (replace-match
12399 (cdr (assoc (string-to-char (match-string 0 text))
12400 table))
12401 t t text)))
12402 text)))
12404 (defun org-link-unescape (text &optional table)
12405 "Reverse the action of `org-link-escape'."
12406 (setq table (or table org-link-escape-chars))
12407 (when text
12408 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12409 table "\\|")))
12410 (while (string-match re text)
12411 (setq text
12412 (replace-match
12413 (char-to-string (car (rassoc (match-string 0 text) table)))
12414 t t text)))
12415 text)))
12417 (defun org-xor (a b)
12418 "Exclusive or."
12419 (if a (not b) b))
12421 (defun org-get-header (header)
12422 "Find a header field in the current buffer."
12423 (save-excursion
12424 (goto-char (point-min))
12425 (let ((case-fold-search t) s)
12426 (cond
12427 ((eq header 'from)
12428 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12429 (setq s (match-string 1)))
12430 (while (string-match "\"" s)
12431 (setq s (replace-match "" t t s)))
12432 (if (string-match "[<(].*" s)
12433 (setq s (replace-match "" t t s))))
12434 ((eq header 'message-id)
12435 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12436 (setq s (match-string 1))))
12437 ((eq header 'subject)
12438 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12439 (setq s (match-string 1)))))
12440 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12441 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12442 s)))
12445 (defun org-fixup-message-id-for-http (s)
12446 "Replace special characters in a message id, so it can be used in an http query."
12447 (while (string-match "<" s)
12448 (setq s (replace-match "%3C" t t s)))
12449 (while (string-match ">" s)
12450 (setq s (replace-match "%3E" t t s)))
12451 (while (string-match "@" s)
12452 (setq s (replace-match "%40" t t s)))
12455 ;;;###autoload
12456 (defun org-insert-link-global ()
12457 "Insert a link like Org-mode does.
12458 This command can be called in any mode to insert a link in Org-mode syntax."
12459 (interactive)
12460 (org-load-modules-maybe)
12461 (org-run-like-in-org-mode 'org-insert-link))
12463 (defun org-insert-link (&optional complete-file)
12464 "Insert a link. At the prompt, enter the link.
12466 Completion can be used to select a link previously stored with
12467 `org-store-link'. When the empty string is entered (i.e. if you just
12468 press RET at the prompt), the link defaults to the most recently
12469 stored link. As SPC triggers completion in the minibuffer, you need to
12470 use M-SPC or C-q SPC to force the insertion of a space character.
12472 You will also be prompted for a description, and if one is given, it will
12473 be displayed in the buffer instead of the link.
12475 If there is already a link at point, this command will allow you to edit link
12476 and description parts.
12478 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12479 selected using completion. The path to the file will be relative to
12480 the current directory if the file is in the current directory or a
12481 subdirectory. Otherwise, the link will be the absolute path as
12482 completed in the minibuffer (i.e. normally ~/path/to/file).
12484 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12485 is in the current directory or below.
12486 With three \\[universal-argument] prefixes, negate the meaning of
12487 `org-keep-stored-link-after-insertion'."
12488 (interactive "P")
12489 (let* ((wcf (current-window-configuration))
12490 (region (if (org-region-active-p)
12491 (buffer-substring (region-beginning) (region-end))))
12492 (remove (and region (list (region-beginning) (region-end))))
12493 (desc region)
12494 tmphist ; byte-compile incorrectly complains about this
12495 link entry file)
12496 (cond
12497 ((org-in-regexp org-bracket-link-regexp 1)
12498 ;; We do have a link at point, and we are going to edit it.
12499 (setq remove (list (match-beginning 0) (match-end 0)))
12500 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12501 (setq link (read-string "Link: "
12502 (org-link-unescape
12503 (org-match-string-no-properties 1)))))
12504 ((or (org-in-regexp org-angle-link-re)
12505 (org-in-regexp org-plain-link-re))
12506 ;; Convert to bracket link
12507 (setq remove (list (match-beginning 0) (match-end 0))
12508 link (read-string "Link: "
12509 (org-remove-angle-brackets (match-string 0)))))
12510 ((equal complete-file '(4))
12511 ;; Completing read for file names.
12512 (setq file (read-file-name "File: "))
12513 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12514 (pwd1 (file-name-as-directory (abbreviate-file-name
12515 (expand-file-name ".")))))
12516 (cond
12517 ((equal complete-file '(16))
12518 (setq link (org-make-link
12519 "file:"
12520 (abbreviate-file-name (expand-file-name file)))))
12521 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12522 (setq link (org-make-link "file:" (match-string 1 file))))
12523 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12524 (expand-file-name file))
12525 (setq link (org-make-link
12526 "file:" (match-string 1 (expand-file-name file)))))
12527 (t (setq link (org-make-link "file:" file))))))
12529 ;; Read link, with completion for stored links.
12530 (with-output-to-temp-buffer "*Org Links*"
12531 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12532 (when org-stored-links
12533 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12534 (princ (mapconcat
12535 (lambda (x)
12536 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12537 (reverse org-stored-links) "\n"))))
12538 (let ((cw (selected-window)))
12539 (select-window (get-buffer-window "*Org Links*"))
12540 (shrink-window-if-larger-than-buffer)
12541 (setq truncate-lines t)
12542 (select-window cw))
12543 ;; Fake a link history, containing the stored links.
12544 (setq tmphist (append (mapcar 'car org-stored-links)
12545 org-insert-link-history))
12546 (unwind-protect
12547 (setq link (org-completing-read
12548 "Link: "
12549 (append
12550 (mapcar (lambda (x) (list (concat (car x) ":")))
12551 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12552 (mapcar (lambda (x) (list (concat x ":")))
12553 org-link-types))
12554 nil nil nil
12555 'tmphist
12556 (or (car (car org-stored-links)))))
12557 (set-window-configuration wcf)
12558 (kill-buffer "*Org Links*"))
12559 (setq entry (assoc link org-stored-links))
12560 (or entry (push link org-insert-link-history))
12561 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12562 (not org-keep-stored-link-after-insertion))
12563 (setq org-stored-links (delq (assoc link org-stored-links)
12564 org-stored-links)))
12565 (setq desc (or desc (nth 1 entry)))))
12567 (if (string-match org-plain-link-re link)
12568 ;; URL-like link, normalize the use of angular brackets.
12569 (setq link (org-make-link (org-remove-angle-brackets link))))
12571 ;; Check if we are linking to the current file with a search option
12572 ;; If yes, simplify the link by using only the search option.
12573 (when (and buffer-file-name
12574 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12575 (let* ((path (match-string 1 link))
12576 (case-fold-search nil)
12577 (search (match-string 2 link)))
12578 (save-match-data
12579 (if (equal (file-truename buffer-file-name) (file-truename path))
12580 ;; We are linking to this same file, with a search option
12581 (setq link search)))))
12583 ;; Check if we can/should use a relative path. If yes, simplify the link
12584 (when (string-match "\\<file:\\(.*\\)" link)
12585 (let* ((path (match-string 1 link))
12586 (origpath path)
12587 (case-fold-search nil))
12588 (cond
12589 ((eq org-link-file-path-type 'absolute)
12590 (setq path (abbreviate-file-name (expand-file-name path))))
12591 ((eq org-link-file-path-type 'noabbrev)
12592 (setq path (expand-file-name path)))
12593 ((eq org-link-file-path-type 'relative)
12594 (setq path (file-relative-name path)))
12596 (save-match-data
12597 (if (string-match (concat "^" (regexp-quote
12598 (file-name-as-directory
12599 (expand-file-name "."))))
12600 (expand-file-name path))
12601 ;; We are linking a file with relative path name.
12602 (setq path (substring (expand-file-name path)
12603 (match-end 0)))))))
12604 (setq link (concat "file:" path))
12605 (if (equal desc origpath)
12606 (setq desc path))))
12608 (setq desc (read-string "Description: " desc))
12609 (unless (string-match "\\S-" desc) (setq desc nil))
12610 (if remove (apply 'delete-region remove))
12611 (insert (org-make-link-string link desc))))
12613 (defun org-completing-read (&rest args)
12614 (let ((minibuffer-local-completion-map
12615 (copy-keymap minibuffer-local-completion-map)))
12616 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12617 (apply 'completing-read args)))
12619 ;;; Opening/following a link
12620 (defvar org-link-search-failed nil)
12622 (defun org-next-link ()
12623 "Move forward to the next link.
12624 If the link is in hidden text, expose it."
12625 (interactive)
12626 (when (and org-link-search-failed (eq this-command last-command))
12627 (goto-char (point-min))
12628 (message "Link search wrapped back to beginning of buffer"))
12629 (setq org-link-search-failed nil)
12630 (let* ((pos (point))
12631 (ct (org-context))
12632 (a (assoc :link ct)))
12633 (if a (goto-char (nth 2 a)))
12634 (if (re-search-forward org-any-link-re nil t)
12635 (progn
12636 (goto-char (match-beginning 0))
12637 (if (org-invisible-p) (org-show-context)))
12638 (goto-char pos)
12639 (setq org-link-search-failed t)
12640 (error "No further link found"))))
12642 (defun org-previous-link ()
12643 "Move backward to the previous link.
12644 If the link is in hidden text, expose it."
12645 (interactive)
12646 (when (and org-link-search-failed (eq this-command last-command))
12647 (goto-char (point-max))
12648 (message "Link search wrapped back to end of buffer"))
12649 (setq org-link-search-failed nil)
12650 (let* ((pos (point))
12651 (ct (org-context))
12652 (a (assoc :link ct)))
12653 (if a (goto-char (nth 1 a)))
12654 (if (re-search-backward org-any-link-re nil t)
12655 (progn
12656 (goto-char (match-beginning 0))
12657 (if (org-invisible-p) (org-show-context)))
12658 (goto-char pos)
12659 (setq org-link-search-failed t)
12660 (error "No further link found"))))
12662 (defun org-find-file-at-mouse (ev)
12663 "Open file link or URL at mouse."
12664 (interactive "e")
12665 (mouse-set-point ev)
12666 (org-open-at-point 'in-emacs))
12668 (defun org-open-at-mouse (ev)
12669 "Open file link or URL at mouse."
12670 (interactive "e")
12671 (mouse-set-point ev)
12672 (org-open-at-point))
12674 (defvar org-window-config-before-follow-link nil
12675 "The window configuration before following a link.
12676 This is saved in case the need arises to restore it.")
12678 (defvar org-open-link-marker (make-marker)
12679 "Marker pointing to the location where `org-open-at-point; was called.")
12681 ;;;###autoload
12682 (defun org-open-at-point-global ()
12683 "Follow a link like Org-mode does.
12684 This command can be called in any mode to follow a link that has
12685 Org-mode syntax."
12686 (interactive)
12687 (org-run-like-in-org-mode 'org-open-at-point))
12689 (defun org-open-at-point (&optional in-emacs)
12690 "Open link at or after point.
12691 If there is no link at point, this function will search forward up to
12692 the end of the current subtree.
12693 Normally, files will be opened by an appropriate application. If the
12694 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12695 (interactive "P")
12696 (org-load-modules-maybe)
12697 (move-marker org-open-link-marker (point))
12698 (setq org-window-config-before-follow-link (current-window-configuration))
12699 (org-remove-occur-highlights nil nil t)
12700 (if (org-at-timestamp-p t)
12701 (org-follow-timestamp-link)
12702 (let (type path link line search (pos (point)))
12703 (catch 'match
12704 (save-excursion
12705 (skip-chars-forward "^]\n\r")
12706 (when (org-in-regexp org-bracket-link-regexp)
12707 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12708 (while (string-match " *\n *" link)
12709 (setq link (replace-match " " t t link)))
12710 (setq link (org-link-expand-abbrev link))
12711 (if (string-match org-link-re-with-space2 link)
12712 (setq type (match-string 1 link) path (match-string 2 link))
12713 (setq type "thisfile" path link))
12714 (throw 'match t)))
12716 (when (get-text-property (point) 'org-linked-text)
12717 (setq type "thisfile"
12718 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12719 (1+ (point)) (point))
12720 path (buffer-substring
12721 (previous-single-property-change pos 'org-linked-text)
12722 (next-single-property-change pos 'org-linked-text)))
12723 (throw 'match t))
12725 (save-excursion
12726 (when (or (org-in-regexp org-angle-link-re)
12727 (org-in-regexp org-plain-link-re))
12728 (setq type (match-string 1) path (match-string 2))
12729 (throw 'match t)))
12730 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12731 (setq type "tree-match"
12732 path (match-string 1))
12733 (throw 'match t))
12734 (save-excursion
12735 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12736 (setq type "tags"
12737 path (match-string 1))
12738 (while (string-match ":" path)
12739 (setq path (replace-match "+" t t path)))
12740 (throw 'match t))))
12741 (unless path
12742 (error "No link found"))
12743 ;; Remove any trailing spaces in path
12744 (if (string-match " +\\'" path)
12745 (setq path (replace-match "" t t path)))
12747 (cond
12749 ((assoc type org-link-protocols)
12750 (funcall (nth 1 (assoc type org-link-protocols)) path))
12752 ((equal type "mailto")
12753 (let ((cmd (car org-link-mailto-program))
12754 (args (cdr org-link-mailto-program)) args1
12755 (address path) (subject "") a)
12756 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12757 (setq address (match-string 1 path)
12758 subject (org-link-escape (match-string 2 path))))
12759 (while args
12760 (cond
12761 ((not (stringp (car args))) (push (pop args) args1))
12762 (t (setq a (pop args))
12763 (if (string-match "%a" a)
12764 (setq a (replace-match address t t a)))
12765 (if (string-match "%s" a)
12766 (setq a (replace-match subject t t a)))
12767 (push a args1))))
12768 (apply cmd (nreverse args1))))
12770 ((member type '("http" "https" "ftp" "news"))
12771 (browse-url (concat type ":" (org-link-escape
12772 path org-link-escape-chars-browser))))
12774 ((member type '("message"))
12775 (browse-url (concat type ":" path)))
12777 ((string= type "tags")
12778 (org-tags-view in-emacs path))
12779 ((string= type "thisfile")
12780 (if in-emacs
12781 (switch-to-buffer-other-window
12782 (org-get-buffer-for-internal-link (current-buffer)))
12783 (org-mark-ring-push))
12784 (let ((cmd `(org-link-search
12785 ,path
12786 ,(cond ((equal in-emacs '(4)) 'occur)
12787 ((equal in-emacs '(16)) 'org-occur)
12788 (t nil))
12789 ,pos)))
12790 (condition-case nil (eval cmd)
12791 (error (progn (widen) (eval cmd))))))
12793 ((string= type "tree-match")
12794 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12796 ((string= type "file")
12797 (if (string-match "::\\([0-9]+\\)\\'" path)
12798 (setq line (string-to-number (match-string 1 path))
12799 path (substring path 0 (match-beginning 0)))
12800 (if (string-match "::\\(.+\\)\\'" path)
12801 (setq search (match-string 1 path)
12802 path (substring path 0 (match-beginning 0)))))
12803 (if (string-match "[*?{]" (file-name-nondirectory path))
12804 (dired path)
12805 (org-open-file path in-emacs line search)))
12807 ((string= type "news")
12808 (require 'org-gnus)
12809 (org-gnus-follow-link path))
12811 ((string= type "shell")
12812 (let ((cmd path))
12813 (if (or (not org-confirm-shell-link-function)
12814 (funcall org-confirm-shell-link-function
12815 (format "Execute \"%s\" in shell? "
12816 (org-add-props cmd nil
12817 'face 'org-warning))))
12818 (progn
12819 (message "Executing %s" cmd)
12820 (shell-command cmd))
12821 (error "Abort"))))
12823 ((string= type "elisp")
12824 (let ((cmd path))
12825 (if (or (not org-confirm-elisp-link-function)
12826 (funcall org-confirm-elisp-link-function
12827 (format "Execute \"%s\" as elisp? "
12828 (org-add-props cmd nil
12829 'face 'org-warning))))
12830 (message "%s => %s" cmd (eval (read cmd)))
12831 (error "Abort"))))
12834 (browse-url-at-point)))))
12835 (move-marker org-open-link-marker nil)
12836 (run-hook-with-args 'org-follow-link-hook))
12838 ;;; File search
12840 (defvar org-create-file-search-functions nil
12841 "List of functions to construct the right search string for a file link.
12842 These functions are called in turn with point at the location to
12843 which the link should point.
12845 A function in the hook should first test if it would like to
12846 handle this file type, for example by checking the major-mode or
12847 the file extension. If it decides not to handle this file, it
12848 should just return nil to give other functions a chance. If it
12849 does handle the file, it must return the search string to be used
12850 when following the link. The search string will be part of the
12851 file link, given after a double colon, and `org-open-at-point'
12852 will automatically search for it. If special measures must be
12853 taken to make the search successful, another function should be
12854 added to the companion hook `org-execute-file-search-functions',
12855 which see.
12857 A function in this hook may also use `setq' to set the variable
12858 `description' to provide a suggestion for the descriptive text to
12859 be used for this link when it gets inserted into an Org-mode
12860 buffer with \\[org-insert-link].")
12862 (defvar org-execute-file-search-functions nil
12863 "List of functions to execute a file search triggered by a link.
12865 Functions added to this hook must accept a single argument, the
12866 search string that was part of the file link, the part after the
12867 double colon. The function must first check if it would like to
12868 handle this search, for example by checking the major-mode or the
12869 file extension. If it decides not to handle this search, it
12870 should just return nil to give other functions a chance. If it
12871 does handle the search, it must return a non-nil value to keep
12872 other functions from trying.
12874 Each function can access the current prefix argument through the
12875 variable `current-prefix-argument'. Note that a single prefix is
12876 used to force opening a link in Emacs, so it may be good to only
12877 use a numeric or double prefix to guide the search function.
12879 In case this is needed, a function in this hook can also restore
12880 the window configuration before `org-open-at-point' was called using:
12882 (set-window-configuration org-window-config-before-follow-link)")
12884 (defun org-link-search (s &optional type avoid-pos)
12885 "Search for a link search option.
12886 If S is surrounded by forward slashes, it is interpreted as a
12887 regular expression. In org-mode files, this will create an `org-occur'
12888 sparse tree. In ordinary files, `occur' will be used to list matches.
12889 If the current buffer is in `dired-mode', grep will be used to search
12890 in all files. If AVOID-POS is given, ignore matches near that position."
12891 (let ((case-fold-search t)
12892 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12893 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12894 (append '(("") (" ") ("\t") ("\n"))
12895 org-emphasis-alist)
12896 "\\|") "\\)"))
12897 (pos (point))
12898 (pre "") (post "")
12899 words re0 re1 re2 re3 re4 re5 re2a reall)
12900 (cond
12901 ;; First check if there are any special
12902 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12903 ;; Now try the builtin stuff
12904 ((save-excursion
12905 (goto-char (point-min))
12906 (and
12907 (re-search-forward
12908 (concat "<<" (regexp-quote s0) ">>") nil t)
12909 (setq pos (match-beginning 0))))
12910 ;; There is an exact target for this
12911 (goto-char pos))
12912 ((string-match "^/\\(.*\\)/$" s)
12913 ;; A regular expression
12914 (cond
12915 ((org-mode-p)
12916 (org-occur (match-string 1 s)))
12917 ;;((eq major-mode 'dired-mode)
12918 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12919 (t (org-do-occur (match-string 1 s)))))
12921 ;; A normal search strings
12922 (when (equal (string-to-char s) ?*)
12923 ;; Anchor on headlines, post may include tags.
12924 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12925 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12926 s (substring s 1)))
12927 (remove-text-properties
12928 0 (length s)
12929 '(face nil mouse-face nil keymap nil fontified nil) s)
12930 ;; Make a series of regular expressions to find a match
12931 (setq words (org-split-string s "[ \n\r\t]+")
12932 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12933 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12934 "\\)" markers)
12935 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12936 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12937 re1 (concat pre re2 post)
12938 re3 (concat pre re4 post)
12939 re5 (concat pre ".*" re4)
12940 re2 (concat pre re2)
12941 re2a (concat pre re2a)
12942 re4 (concat pre re4)
12943 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12944 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12945 re5 "\\)"
12947 (cond
12948 ((eq type 'org-occur) (org-occur reall))
12949 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12950 (t (goto-char (point-min))
12951 (if (or (org-search-not-self 1 re0 nil t)
12952 (org-search-not-self 1 re1 nil t)
12953 (org-search-not-self 1 re2 nil t)
12954 (org-search-not-self 1 re2a nil t)
12955 (org-search-not-self 1 re3 nil t)
12956 (org-search-not-self 1 re4 nil t)
12957 (org-search-not-self 1 re5 nil t)
12959 (goto-char (match-beginning 1))
12960 (goto-char pos)
12961 (error "No match")))))
12963 ;; Normal string-search
12964 (goto-char (point-min))
12965 (if (search-forward s nil t)
12966 (goto-char (match-beginning 0))
12967 (error "No match"))))
12968 (and (org-mode-p) (org-show-context 'link-search))))
12970 (defun org-search-not-self (group &rest args)
12971 "Execute `re-search-forward', but only accept matches that do not
12972 enclose the position of `org-open-link-marker'."
12973 (let ((m org-open-link-marker))
12974 (catch 'exit
12975 (while (apply 're-search-forward args)
12976 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12977 (goto-char (match-end group))
12978 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12979 (> (match-beginning 0) (marker-position m))
12980 (< (match-end 0) (marker-position m)))
12981 (save-match-data
12982 (or (not (org-in-regexp
12983 org-bracket-link-analytic-regexp 1))
12984 (not (match-end 4)) ; no description
12985 (and (<= (match-beginning 4) (point))
12986 (>= (match-end 4) (point))))))
12987 (throw 'exit (point))))))))
12989 (defun org-get-buffer-for-internal-link (buffer)
12990 "Return a buffer to be used for displaying the link target of internal links."
12991 (cond
12992 ((not org-display-internal-link-with-indirect-buffer)
12993 buffer)
12994 ((string-match "(Clone)$" (buffer-name buffer))
12995 (message "Buffer is already a clone, not making another one")
12996 ;; we also do not modify visibility in this case
12997 buffer)
12998 (t ; make a new indirect buffer for displaying the link
12999 (let* ((bn (buffer-name buffer))
13000 (ibn (concat bn "(Clone)"))
13001 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13002 (with-current-buffer ib (org-overview))
13003 ib))))
13005 (defun org-do-occur (regexp &optional cleanup)
13006 "Call the Emacs command `occur'.
13007 If CLEANUP is non-nil, remove the printout of the regular expression
13008 in the *Occur* buffer. This is useful if the regex is long and not useful
13009 to read."
13010 (occur regexp)
13011 (when cleanup
13012 (let ((cwin (selected-window)) win beg end)
13013 (when (setq win (get-buffer-window "*Occur*"))
13014 (select-window win))
13015 (goto-char (point-min))
13016 (when (re-search-forward "match[a-z]+" nil t)
13017 (setq beg (match-end 0))
13018 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13019 (setq end (1- (match-beginning 0)))))
13020 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13021 (goto-char (point-min))
13022 (select-window cwin))))
13024 ;;; The mark ring for links jumps
13026 (defvar org-mark-ring nil
13027 "Mark ring for positions before jumps in Org-mode.")
13028 (defvar org-mark-ring-last-goto nil
13029 "Last position in the mark ring used to go back.")
13030 ;; Fill and close the ring
13031 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13032 (loop for i from 1 to org-mark-ring-length do
13033 (push (make-marker) org-mark-ring))
13034 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13035 org-mark-ring)
13037 (defun org-mark-ring-push (&optional pos buffer)
13038 "Put the current position or POS into the mark ring and rotate it."
13039 (interactive)
13040 (setq pos (or pos (point)))
13041 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13042 (move-marker (car org-mark-ring)
13043 (or pos (point))
13044 (or buffer (current-buffer)))
13045 (message "%s"
13046 (substitute-command-keys
13047 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13049 (defun org-mark-ring-goto (&optional n)
13050 "Jump to the previous position in the mark ring.
13051 With prefix arg N, jump back that many stored positions. When
13052 called several times in succession, walk through the entire ring.
13053 Org-mode commands jumping to a different position in the current file,
13054 or to another Org-mode file, automatically push the old position
13055 onto the ring."
13056 (interactive "p")
13057 (let (p m)
13058 (if (eq last-command this-command)
13059 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13060 (setq p org-mark-ring))
13061 (setq org-mark-ring-last-goto p)
13062 (setq m (car p))
13063 (switch-to-buffer (marker-buffer m))
13064 (goto-char m)
13065 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13067 (defun org-remove-angle-brackets (s)
13068 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13069 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13071 (defun org-add-angle-brackets (s)
13072 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13073 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13076 ;;; Following specific links
13078 (defun org-follow-timestamp-link ()
13079 (cond
13080 ((org-at-date-range-p t)
13081 (let ((org-agenda-start-on-weekday)
13082 (t1 (match-string 1))
13083 (t2 (match-string 2)))
13084 (setq t1 (time-to-days (org-time-string-to-time t1))
13085 t2 (time-to-days (org-time-string-to-time t2)))
13086 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13087 ((org-at-timestamp-p t)
13088 (org-agenda-list nil (time-to-days (org-time-string-to-time
13089 (substring (match-string 1) 0 10)))
13091 (t (error "This should not happen"))))
13094 ;;; BibTeX links
13096 ;; Use the custom search meachnism to construct and use search strings for
13097 ;; file links to BibTeX database entries.
13099 (defun org-create-file-search-in-bibtex ()
13100 "Create the search string and description for a BibTeX database entry."
13101 (when (eq major-mode 'bibtex-mode)
13102 ;; yes, we want to construct this search string.
13103 ;; Make a good description for this entry, using names, year and the title
13104 ;; Put it into the `description' variable which is dynamically scoped.
13105 (let ((bibtex-autokey-names 1)
13106 (bibtex-autokey-names-stretch 1)
13107 (bibtex-autokey-name-case-convert-function 'identity)
13108 (bibtex-autokey-name-separator " & ")
13109 (bibtex-autokey-additional-names " et al.")
13110 (bibtex-autokey-year-length 4)
13111 (bibtex-autokey-name-year-separator " ")
13112 (bibtex-autokey-titlewords 3)
13113 (bibtex-autokey-titleword-separator " ")
13114 (bibtex-autokey-titleword-case-convert-function 'identity)
13115 (bibtex-autokey-titleword-length 'infty)
13116 (bibtex-autokey-year-title-separator ": "))
13117 (setq description (bibtex-generate-autokey)))
13118 ;; Now parse the entry, get the key and return it.
13119 (save-excursion
13120 (bibtex-beginning-of-entry)
13121 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13123 (defun org-execute-file-search-in-bibtex (s)
13124 "Find the link search string S as a key for a database entry."
13125 (when (eq major-mode 'bibtex-mode)
13126 ;; Yes, we want to do the search in this file.
13127 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13128 (goto-char (point-min))
13129 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13130 (regexp-quote s) "[ \t\n]*,") nil t)
13131 (goto-char (match-beginning 0)))
13132 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13133 ;; Use double prefix to indicate that any web link should be browsed
13134 (let ((b (current-buffer)) (p (point)))
13135 ;; Restore the window configuration because we just use the web link
13136 (set-window-configuration org-window-config-before-follow-link)
13137 (save-excursion (set-buffer b) (goto-char p)
13138 (bibtex-url)))
13139 (recenter 0)) ; Move entry start to beginning of window
13140 ;; return t to indicate that the search is done.
13143 ;; Finally add the functions to the right hooks.
13144 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13145 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13147 ;; end of Bibtex link setup
13149 ;;; Following file links
13151 (defun org-open-file (path &optional in-emacs line search)
13152 "Open the file at PATH.
13153 First, this expands any special file name abbreviations. Then the
13154 configuration variable `org-file-apps' is checked if it contains an
13155 entry for this file type, and if yes, the corresponding command is launched.
13156 If no application is found, Emacs simply visits the file.
13157 With optional argument IN-EMACS, Emacs will visit the file.
13158 Optional LINE specifies a line to go to, optional SEARCH a string to
13159 search for. If LINE or SEARCH is given, the file will always be
13160 opened in Emacs.
13161 If the file does not exist, an error is thrown."
13162 (setq in-emacs (or in-emacs line search))
13163 (let* ((file (if (equal path "")
13164 buffer-file-name
13165 (substitute-in-file-name (expand-file-name path))))
13166 (apps (append org-file-apps (org-default-apps)))
13167 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13168 (dirp (if remp nil (file-directory-p file)))
13169 (dfile (downcase file))
13170 (old-buffer (current-buffer))
13171 (old-pos (point))
13172 (old-mode major-mode)
13173 ext cmd)
13174 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13175 (setq ext (match-string 1 dfile))
13176 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13177 (setq ext (match-string 1 dfile))))
13178 (if in-emacs
13179 (setq cmd 'emacs)
13180 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13181 (and dirp (cdr (assoc 'directory apps)))
13182 (cdr (assoc ext apps))
13183 (cdr (assoc t apps)))))
13184 (when (eq cmd 'mailcap)
13185 (require 'mailcap)
13186 (mailcap-parse-mailcaps)
13187 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13188 (command (mailcap-mime-info mime-type)))
13189 (if (stringp command)
13190 (setq cmd command)
13191 (setq cmd 'emacs))))
13192 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13193 (not (file-exists-p file))
13194 (not org-open-non-existing-files))
13195 (error "No such file: %s" file))
13196 (cond
13197 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13198 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13199 (while (string-match "['\"]%s['\"]" cmd)
13200 (setq cmd (replace-match "%s" t t cmd)))
13201 (while (string-match "%s" cmd)
13202 (setq cmd (replace-match
13203 (save-match-data (shell-quote-argument file))
13204 t t cmd)))
13205 (save-window-excursion
13206 (start-process-shell-command cmd nil cmd)))
13207 ((or (stringp cmd)
13208 (eq cmd 'emacs))
13209 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13210 (widen)
13211 (if line (goto-line line)
13212 (if search (org-link-search search))))
13213 ((consp cmd)
13214 (eval cmd))
13215 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13216 (and (org-mode-p) (eq old-mode 'org-mode)
13217 (or (not (equal old-buffer (current-buffer)))
13218 (not (equal old-pos (point))))
13219 (org-mark-ring-push old-pos old-buffer))))
13221 (defun org-default-apps ()
13222 "Return the default applications for this operating system."
13223 (cond
13224 ((eq system-type 'darwin)
13225 org-file-apps-defaults-macosx)
13226 ((eq system-type 'windows-nt)
13227 org-file-apps-defaults-windowsnt)
13228 (t org-file-apps-defaults-gnu)))
13230 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13231 (defun org-file-remote-p (file)
13232 "Test whether FILE specifies a location on a remote system.
13233 Return non-nil if the location is indeed remote.
13235 For example, the filename \"/user@host:/foo\" specifies a location
13236 on the system \"/user@host:\"."
13237 (cond ((fboundp 'file-remote-p)
13238 (file-remote-p file))
13239 ((fboundp 'tramp-handle-file-remote-p)
13240 (tramp-handle-file-remote-p file))
13241 ((and (boundp 'ange-ftp-name-format)
13242 (string-match (car ange-ftp-name-format) file))
13244 (t nil)))
13247 ;;;; Hooks for remember.el, and refiling
13249 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13250 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13252 ;;;###autoload
13253 (defun org-remember-insinuate ()
13254 "Setup remember.el for use wiht Org-mode."
13255 (require 'remember)
13256 (setq remember-annotation-functions '(org-remember-annotation))
13257 (setq remember-handler-functions '(org-remember-handler))
13258 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13260 ;;;###autoload
13261 (defun org-remember-annotation ()
13262 "Return a link to the current location as an annotation for remember.el.
13263 If you are using Org-mode files as target for data storage with
13264 remember.el, then the annotations should include a link compatible with the
13265 conventions in Org-mode. This function returns such a link."
13266 (org-store-link nil))
13268 (defconst org-remember-help
13269 "Select a destination location for the note.
13270 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13271 RET on headline -> Store as sublevel entry to current headline
13272 RET at beg-of-buf -> Append to file as level 2 headline
13273 <left>/<right> -> before/after current headline, same headings level")
13275 (defvar org-remember-previous-location nil)
13276 (defvar org-force-remember-template-char) ;; dynamically scoped
13278 ;; Save the major mode of the buffer we called remember from
13279 (defvar org-select-template-temp-major-mode nil)
13281 ;; Temporary store the buffer where remember was called from
13282 (defvar org-select-template-original-buffer nil)
13284 (defun org-select-remember-template (&optional use-char)
13285 (when org-remember-templates
13286 (let* ((pre-selected-templates
13287 (mapcar
13288 (lambda (tpl)
13289 (let ((ctxt (nth 5 tpl))
13290 (mode org-select-template-temp-major-mode)
13291 (buf org-select-template-original-buffer))
13292 (and (or (not ctxt) (eq ctxt t)
13293 (and (listp ctxt) (memq mode ctxt))
13294 (and (functionp ctxt)
13295 (with-current-buffer buf
13296 ;; Protect the user-defined function from error
13297 (condition-case nil (funcall ctxt) (error nil)))))
13298 tpl)))
13299 org-remember-templates))
13300 ;; If no template at this point, add the default templates:
13301 (pre-selected-templates1
13302 (if (not (delq nil pre-selected-templates))
13303 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13304 org-remember-templates)
13305 pre-selected-templates))
13306 ;; Then unconditionnally add template for any contexts
13307 (pre-selected-templates2
13308 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13309 org-remember-templates)
13310 (delq nil pre-selected-templates1)))
13311 (templates (mapcar (lambda (x)
13312 (if (stringp (car x))
13313 (append (list (nth 1 x) (car x)) (cddr x))
13314 (append (list (car x) "") (cdr x))))
13315 (delq nil pre-selected-templates2)))
13316 (char (or use-char
13317 (cond
13318 ((= (length templates) 1)
13319 (caar templates))
13320 ((and (boundp 'org-force-remember-template-char)
13321 org-force-remember-template-char)
13322 (if (stringp org-force-remember-template-char)
13323 (string-to-char org-force-remember-template-char)
13324 org-force-remember-template-char))
13326 (message "Select template: %s"
13327 (mapconcat
13328 (lambda (x)
13329 (cond
13330 ((not (string-match "\\S-" (nth 1 x)))
13331 (format "[%c]" (car x)))
13332 ((equal (downcase (car x))
13333 (downcase (aref (nth 1 x) 0)))
13334 (format "[%c]%s" (car x)
13335 (substring (nth 1 x) 1)))
13336 (t (format "[%c]%s" (car x) (nth 1 x)))))
13337 templates " "))
13338 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13339 (when (equal char0 ?\C-g)
13340 (jump-to-register remember-register)
13341 (kill-buffer remember-buffer))
13342 char0))))))
13343 (cddr (assoc char templates)))))
13345 (defvar x-last-selected-text)
13346 (defvar x-last-selected-text-primary)
13348 ;;;###autoload
13349 (defun org-remember-apply-template (&optional use-char skip-interactive)
13350 "Initialize *remember* buffer with template, invoke `org-mode'.
13351 This function should be placed into `remember-mode-hook' and in fact requires
13352 to be run from that hook to function properly."
13353 (if org-remember-templates
13354 (let* ((entry (org-select-remember-template use-char))
13355 (tpl (car entry))
13356 (plist-p (if org-store-link-plist t nil))
13357 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13358 (string-match "\\S-" (nth 1 entry)))
13359 (nth 1 entry)
13360 org-default-notes-file))
13361 (headline (nth 2 entry))
13362 (v-c (or (and (eq window-system 'x)
13363 (fboundp 'x-cut-buffer-or-selection-value)
13364 (x-cut-buffer-or-selection-value))
13365 (org-bound-and-true-p x-last-selected-text)
13366 (org-bound-and-true-p x-last-selected-text-primary)
13367 (and (> (length kill-ring) 0) (current-kill 0))))
13368 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13369 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13370 (v-u (concat "[" (substring v-t 1 -1) "]"))
13371 (v-U (concat "[" (substring v-T 1 -1) "]"))
13372 ;; `initial' and `annotation' are bound in `remember'
13373 (v-i (if (boundp 'initial) initial))
13374 (v-a (if (and (boundp 'annotation) annotation)
13375 (if (equal annotation "[[]]") "" annotation)
13376 ""))
13377 (v-A (if (and v-a
13378 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13379 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13380 v-a))
13381 (v-n user-full-name)
13382 (org-startup-folded nil)
13383 org-time-was-given org-end-time-was-given x
13384 prompt completions char time pos default histvar)
13385 (setq org-store-link-plist
13386 (append (list :annotation v-a :initial v-i)
13387 org-store-link-plist))
13388 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13389 (erase-buffer)
13390 (insert (substitute-command-keys
13391 (format
13392 "## Filing location: Select interactively, default, or last used:
13393 ## %s to select file and header location interactively.
13394 ## %s \"%s\" -> \"* %s\"
13395 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13396 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13397 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13398 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13399 (abbreviate-file-name (or file org-default-notes-file))
13400 (or headline "")
13401 (or (car org-remember-previous-location) "???")
13402 (or (cdr org-remember-previous-location) "???"))))
13403 (insert tpl) (goto-char (point-min))
13404 ;; Simple %-escapes
13405 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13406 (when (and initial (equal (match-string 0) "%i"))
13407 (save-match-data
13408 (let* ((lead (buffer-substring
13409 (point-at-bol) (match-beginning 0))))
13410 (setq v-i (mapconcat 'identity
13411 (org-split-string initial "\n")
13412 (concat "\n" lead))))))
13413 (replace-match
13414 (or (eval (intern (concat "v-" (match-string 1)))) "")
13415 t t))
13417 ;; %[] Insert contents of a file.
13418 (goto-char (point-min))
13419 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13420 (let ((start (match-beginning 0))
13421 (end (match-end 0))
13422 (filename (expand-file-name (match-string 1))))
13423 (goto-char start)
13424 (delete-region start end)
13425 (condition-case error
13426 (insert-file-contents filename)
13427 (error (insert (format "%%![Couldn't insert %s: %s]"
13428 filename error))))))
13429 ;; %() embedded elisp
13430 (goto-char (point-min))
13431 (while (re-search-forward "%\\((.+)\\)" nil t)
13432 (goto-char (match-beginning 0))
13433 (let ((template-start (point)))
13434 (forward-char 1)
13435 (let ((result
13436 (condition-case error
13437 (eval (read (current-buffer)))
13438 (error (format "%%![Error: %s]" error)))))
13439 (delete-region template-start (point))
13440 (insert result))))
13442 ;; From the property list
13443 (when plist-p
13444 (goto-char (point-min))
13445 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13446 (and (setq x (or (plist-get org-store-link-plist
13447 (intern (match-string 1))) ""))
13448 (replace-match x t t))))
13450 ;; Turn on org-mode in the remember buffer, set local variables
13451 (org-mode)
13452 (org-set-local 'org-finish-function 'org-remember-finalize)
13453 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13454 (org-set-local 'org-default-notes-file file))
13455 (if (and headline (stringp headline) (string-match "\\S-" headline))
13456 (org-set-local 'org-remember-default-headline headline))
13457 ;; Interactive template entries
13458 (goto-char (point-min))
13459 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13460 (setq char (if (match-end 3) (match-string 3))
13461 prompt (if (match-end 2) (match-string 2)))
13462 (goto-char (match-beginning 0))
13463 (replace-match "")
13464 (setq completions nil default nil)
13465 (when prompt
13466 (setq completions (org-split-string prompt "|")
13467 prompt (pop completions)
13468 default (car completions)
13469 histvar (intern (concat
13470 "org-remember-template-prompt-history::"
13471 (or prompt "")))
13472 completions (mapcar 'list completions)))
13473 (cond
13474 ((member char '("G" "g"))
13475 (let* ((org-last-tags-completion-table
13476 (org-global-tags-completion-table
13477 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13478 (org-add-colon-after-tag-completion t)
13479 (ins (completing-read
13480 (if prompt (concat prompt ": ") "Tags: ")
13481 'org-tags-completion-function nil nil nil
13482 'org-tags-history)))
13483 (setq ins (mapconcat 'identity
13484 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13485 ":"))
13486 (when (string-match "\\S-" ins)
13487 (or (equal (char-before) ?:) (insert ":"))
13488 (insert ins)
13489 (or (equal (char-after) ?:) (insert ":")))))
13490 (char
13491 (setq org-time-was-given (equal (upcase char) char))
13492 (setq time (org-read-date (equal (upcase char) "U") t nil
13493 prompt))
13494 (org-insert-time-stamp time org-time-was-given
13495 (member char '("u" "U"))
13496 nil nil (list org-end-time-was-given)))
13498 (insert (org-completing-read
13499 (concat (if prompt prompt "Enter string")
13500 (if default (concat " [" default "]"))
13501 ": ")
13502 completions nil nil nil histvar default)))))
13503 (goto-char (point-min))
13504 (if (re-search-forward "%\\?" nil t)
13505 (replace-match "")
13506 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13507 (org-mode)
13508 (org-set-local 'org-finish-function 'org-remember-finalize))
13509 (when (save-excursion
13510 (goto-char (point-min))
13511 (re-search-forward "%!" nil t))
13512 (replace-match "")
13513 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13515 (defun org-remember-finish-immediately ()
13516 "File remember note immediately.
13517 This should be run in `post-command-hook' and will remove itself
13518 from that hook."
13519 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13520 (when org-finish-function
13521 (funcall org-finish-function)))
13523 (defvar org-clock-marker) ; Defined below
13524 (defun org-remember-finalize ()
13525 "Finalize the remember process."
13526 (unless (fboundp 'remember-finalize)
13527 (defalias 'remember-finalize 'remember-buffer))
13528 (when (and org-clock-marker
13529 (equal (marker-buffer org-clock-marker) (current-buffer)))
13530 ;; FIXME: test this, this is w/o notetaking!
13531 (let (org-log-note-clock-out) (org-clock-out)))
13532 (when buffer-file-name
13533 (save-buffer)
13534 (setq buffer-file-name nil))
13535 (remember-finalize))
13537 ;;;###autoload
13538 (defun org-remember (&optional goto org-force-remember-template-char)
13539 "Call `remember'. If this is already a remember buffer, re-apply template.
13540 If there is an active region, make sure remember uses it as initial content
13541 of the remember buffer.
13543 When called interactively with a `C-u' prefix argument GOTO, don't remember
13544 anything, just go to the file/headline where the selected template usually
13545 stores its notes. With a double prefix arg `C-u C-u', go to the last
13546 note stored by remember.
13548 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13549 associated with a template in `org-remember-templates'."
13550 (interactive "P")
13551 (cond
13552 ((equal goto '(4)) (org-go-to-remember-target))
13553 ((equal goto '(16)) (org-remember-goto-last-stored))
13555 ;; set temporary variables that will be needed in
13556 ;; `org-select-remember-template'
13557 (setq org-select-template-temp-major-mode major-mode)
13558 (setq org-select-template-original-buffer (current-buffer))
13559 (if (memq org-finish-function '(remember-buffer remember-finalize))
13560 (progn
13561 (when (< (length org-remember-templates) 2)
13562 (error "No other template available"))
13563 (erase-buffer)
13564 (let ((annotation (plist-get org-store-link-plist :annotation))
13565 (initial (plist-get org-store-link-plist :initial)))
13566 (org-remember-apply-template))
13567 (message "Press C-c C-c to remember data"))
13568 (if (org-region-active-p)
13569 (remember (buffer-substring (point) (mark)))
13570 (call-interactively 'remember))))))
13572 (defun org-remember-goto-last-stored ()
13573 "Go to the location where the last remember note was stored."
13574 (interactive)
13575 (bookmark-jump "org-remember-last-stored")
13576 (message "This is the last note stored by remember"))
13578 (defun org-go-to-remember-target (&optional template-key)
13579 "Go to the target location of a remember template.
13580 The user is queried for the template."
13581 (interactive)
13582 (let* (org-select-template-temp-major-mode
13583 (entry (org-select-remember-template template-key))
13584 (file (nth 1 entry))
13585 (heading (nth 2 entry))
13586 visiting)
13587 (unless (and file (stringp file) (string-match "\\S-" file))
13588 (setq file org-default-notes-file))
13589 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13590 (setq heading org-remember-default-headline))
13591 (setq visiting (org-find-base-buffer-visiting file))
13592 (if (not visiting) (find-file-noselect file))
13593 (switch-to-buffer (or visiting (get-file-buffer file)))
13594 (widen)
13595 (goto-char (point-min))
13596 (if (re-search-forward
13597 (concat "^\\*+[ \t]+" (regexp-quote heading)
13598 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13599 nil t)
13600 (goto-char (match-beginning 0))
13601 (error "Target headline not found: %s" heading))))
13603 (defvar org-note-abort nil) ; dynamically scoped
13605 ;;;###autoload
13606 (defun org-remember-handler ()
13607 "Store stuff from remember.el into an org file.
13608 First prompts for an org file. If the user just presses return, the value
13609 of `org-default-notes-file' is used.
13610 Then the command offers the headings tree of the selected file in order to
13611 file the text at a specific location.
13612 You can either immediately press RET to get the note appended to the
13613 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13614 find a better place. Then press RET or <left> or <right> in insert the note.
13616 Key Cursor position Note gets inserted
13617 -----------------------------------------------------------------------------
13618 RET buffer-start as level 1 heading at end of file
13619 RET on headline as sublevel of the heading at cursor
13620 RET no heading at cursor position, level taken from context.
13621 Or use prefix arg to specify level manually.
13622 <left> on headline as same level, before current heading
13623 <right> on headline as same level, after current heading
13625 So the fastest way to store the note is to press RET RET to append it to
13626 the default file. This way your current train of thought is not
13627 interrupted, in accordance with the principles of remember.el.
13628 You can also get the fast execution without prompting by using
13629 C-u C-c C-c to exit the remember buffer. See also the variable
13630 `org-remember-store-without-prompt'.
13632 Before being stored away, the function ensures that the text has a
13633 headline, i.e. a first line that starts with a \"*\". If not, a headline
13634 is constructed from the current date and some additional data.
13636 If the variable `org-adapt-indentation' is non-nil, the entire text is
13637 also indented so that it starts in the same column as the headline
13638 \(i.e. after the stars).
13640 See also the variable `org-reverse-note-order'."
13641 (goto-char (point-min))
13642 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13643 (replace-match ""))
13644 (goto-char (point-max))
13645 (beginning-of-line 1)
13646 (while (looking-at "[ \t]*$\\|##.*")
13647 (delete-region (1- (point)) (point-max))
13648 (beginning-of-line 1))
13649 (catch 'quit
13650 (if org-note-abort (throw 'quit nil))
13651 (let* ((txt (buffer-substring (point-min) (point-max)))
13652 (fastp (org-xor (equal current-prefix-arg '(4))
13653 org-remember-store-without-prompt))
13654 (file (cond
13655 (fastp org-default-notes-file)
13656 ((and (eq org-remember-interactive-interface 'refile)
13657 org-refile-targets)
13658 org-default-notes-file)
13659 ((not (and (equal current-prefix-arg '(16))
13660 org-remember-previous-location))
13661 (org-get-org-file))))
13662 (heading org-remember-default-headline)
13663 (visiting (and file (org-find-base-buffer-visiting file)))
13664 (org-startup-folded nil)
13665 (org-startup-align-all-tables nil)
13666 (org-goto-start-pos 1)
13667 spos exitcmd level indent reversed)
13668 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13669 (setq file (car org-remember-previous-location)
13670 heading (cdr org-remember-previous-location)
13671 fastp t))
13672 (setq current-prefix-arg nil)
13673 (if (string-match "[ \t\n]+\\'" txt)
13674 (setq txt (replace-match "" t t txt)))
13675 ;; Modify text so that it becomes a nice subtree which can be inserted
13676 ;; into an org tree.
13677 (let* ((lines (split-string txt "\n"))
13678 first)
13679 (setq first (car lines) lines (cdr lines))
13680 (if (string-match "^\\*+ " first)
13681 ;; Is already a headline
13682 (setq indent nil)
13683 ;; We need to add a headline: Use time and first buffer line
13684 (setq lines (cons first lines)
13685 first (concat "* " (current-time-string)
13686 " (" (remember-buffer-desc) ")")
13687 indent " "))
13688 (if (and org-adapt-indentation indent)
13689 (setq lines (mapcar
13690 (lambda (x)
13691 (if (string-match "\\S-" x)
13692 (concat indent x) x))
13693 lines)))
13694 (setq txt (concat first "\n"
13695 (mapconcat 'identity lines "\n"))))
13696 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13697 (setq txt (replace-match "\n\n" t t txt))
13698 (if (string-match "[ \t\n]*\\'" txt)
13699 (setq txt (replace-match "\n" t t txt))))
13700 ;; Put the modified text back into the remember buffer, for refile.
13701 (erase-buffer)
13702 (insert txt)
13703 (goto-char (point-min))
13704 (when (and (eq org-remember-interactive-interface 'refile)
13705 (not fastp))
13706 (org-refile nil (or visiting (find-file-noselect file)))
13707 (throw 'quit t))
13708 ;; Find the file
13709 (if (not visiting) (find-file-noselect file))
13710 (with-current-buffer (or visiting (get-file-buffer file))
13711 (unless (org-mode-p)
13712 (error "Target files for remember notes must be in Org-mode"))
13713 (save-excursion
13714 (save-restriction
13715 (widen)
13716 (and (goto-char (point-min))
13717 (not (re-search-forward "^\\* " nil t))
13718 (insert "\n* " (or heading "Notes") "\n"))
13719 (setq reversed (org-notes-order-reversed-p))
13721 ;; Find the default location
13722 (when (and heading (stringp heading) (string-match "\\S-" heading))
13723 (goto-char (point-min))
13724 (if (re-search-forward
13725 (concat "^\\*+[ \t]+" (regexp-quote heading)
13726 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13727 nil t)
13728 (setq org-goto-start-pos (match-beginning 0))
13729 (when fastp
13730 (goto-char (point-max))
13731 (unless (bolp) (newline))
13732 (insert "* " heading "\n")
13733 (setq org-goto-start-pos (point-at-bol 0)))))
13735 ;; Ask the User for a location, using the appropriate interface
13736 (cond
13737 (fastp (setq spos org-goto-start-pos
13738 exitcmd 'return))
13739 ((eq org-remember-interactive-interface 'outline)
13740 (setq spos (org-get-location (current-buffer)
13741 org-remember-help)
13742 exitcmd (cdr spos)
13743 spos (car spos)))
13744 ((eq org-remember-interactive-interface 'outline-path-completion)
13745 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13746 (org-refile-use-outline-path t))
13747 (setq spos (org-refile-get-location "Heading: ")
13748 exitcmd 'return
13749 spos (nth 3 spos))))
13750 (t (error "this should not hapen")))
13751 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13752 ; not handle this note
13753 (goto-char spos)
13754 (cond ((org-on-heading-p t)
13755 (org-back-to-heading t)
13756 (setq level (funcall outline-level))
13757 (cond
13758 ((eq exitcmd 'return)
13759 ;; sublevel of current
13760 (setq org-remember-previous-location
13761 (cons (abbreviate-file-name file)
13762 (org-get-heading 'notags)))
13763 (if reversed
13764 (outline-next-heading)
13765 (org-end-of-subtree t)
13766 (if (not (bolp))
13767 (if (looking-at "[ \t]*\n")
13768 (beginning-of-line 2)
13769 (end-of-line 1)
13770 (insert "\n"))))
13771 (bookmark-set "org-remember-last-stored")
13772 (org-paste-subtree (org-get-valid-level level 1) txt))
13773 ((eq exitcmd 'left)
13774 ;; before current
13775 (bookmark-set "org-remember-last-stored")
13776 (org-paste-subtree level txt))
13777 ((eq exitcmd 'right)
13778 ;; after current
13779 (org-end-of-subtree t)
13780 (bookmark-set "org-remember-last-stored")
13781 (org-paste-subtree level txt))
13782 (t (error "This should not happen"))))
13784 ((and (bobp) (not reversed))
13785 ;; Put it at the end, one level below level 1
13786 (save-restriction
13787 (widen)
13788 (goto-char (point-max))
13789 (if (not (bolp)) (newline))
13790 (bookmark-set "org-remember-last-stored")
13791 (org-paste-subtree (org-get-valid-level 1 1) txt)))
13793 ((and (bobp) reversed)
13794 ;; Put it at the start, as level 1
13795 (save-restriction
13796 (widen)
13797 (goto-char (point-min))
13798 (re-search-forward "^\\*+ " nil t)
13799 (beginning-of-line 1)
13800 (bookmark-set "org-remember-last-stored")
13801 (org-paste-subtree 1 txt)))
13803 ;; Put it right there, with automatic level determined by
13804 ;; org-paste-subtree or from prefix arg
13805 (bookmark-set "org-remember-last-stored")
13806 (org-paste-subtree
13807 (if (numberp current-prefix-arg) current-prefix-arg)
13808 txt)))
13809 (when remember-save-after-remembering
13810 (save-buffer)
13811 (if (not visiting) (kill-buffer (current-buffer)))))))))
13813 t) ;; return t to indicate that we took care of this note.
13815 (defun org-get-org-file ()
13816 "Read a filename, with default directory `org-directory'."
13817 (let ((default (or org-default-notes-file remember-data-file)))
13818 (read-file-name (format "File name [%s]: " default)
13819 (file-name-as-directory org-directory)
13820 default)))
13822 (defun org-notes-order-reversed-p ()
13823 "Check if the current file should receive notes in reversed order."
13824 (cond
13825 ((not org-reverse-note-order) nil)
13826 ((eq t org-reverse-note-order) t)
13827 ((not (listp org-reverse-note-order)) nil)
13828 (t (catch 'exit
13829 (let ((all org-reverse-note-order)
13830 entry)
13831 (while (setq entry (pop all))
13832 (if (string-match (car entry) buffer-file-name)
13833 (throw 'exit (cdr entry))))
13834 nil)))))
13836 ;;; Refiling
13838 (defvar org-refile-target-table nil
13839 "The list of refile targets, created by `org-refile'.")
13841 (defvar org-agenda-new-buffers nil
13842 "Buffers created to visit agenda files.")
13844 (defun org-get-refile-targets (&optional default-buffer)
13845 "Produce a table with refile targets."
13846 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
13847 targets txt re files f desc descre)
13848 (with-current-buffer (or default-buffer (current-buffer))
13849 (while (setq entry (pop entries))
13850 (setq files (car entry) desc (cdr entry))
13851 (cond
13852 ((null files) (setq files (list (current-buffer))))
13853 ((eq files 'org-agenda-files)
13854 (setq files (org-agenda-files 'unrestricted)))
13855 ((and (symbolp files) (fboundp files))
13856 (setq files (funcall files)))
13857 ((and (symbolp files) (boundp files))
13858 (setq files (symbol-value files))))
13859 (if (stringp files) (setq files (list files)))
13860 (cond
13861 ((eq (car desc) :tag)
13862 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
13863 ((eq (car desc) :todo)
13864 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
13865 ((eq (car desc) :regexp)
13866 (setq descre (cdr desc)))
13867 ((eq (car desc) :level)
13868 (setq descre (concat "^\\*\\{" (number-to-string
13869 (if org-odd-levels-only
13870 (1- (* 2 (cdr desc)))
13871 (cdr desc)))
13872 "\\}[ \t]")))
13873 ((eq (car desc) :maxlevel)
13874 (setq descre (concat "^\\*\\{1," (number-to-string
13875 (if org-odd-levels-only
13876 (1- (* 2 (cdr desc)))
13877 (cdr desc)))
13878 "\\}[ \t]")))
13879 (t (error "Bad refiling target description %s" desc)))
13880 (while (setq f (pop files))
13881 (save-excursion
13882 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
13883 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
13884 (save-excursion
13885 (save-restriction
13886 (widen)
13887 (goto-char (point-min))
13888 (while (re-search-forward descre nil t)
13889 (goto-char (point-at-bol))
13890 (when (looking-at org-complex-heading-regexp)
13891 (setq txt (match-string 4)
13892 re (concat "^" (regexp-quote
13893 (buffer-substring (match-beginning 1)
13894 (match-end 4)))))
13895 (if (match-end 5) (setq re (concat re "[ \t]+"
13896 (regexp-quote
13897 (match-string 5)))))
13898 (setq re (concat re "[ \t]*$"))
13899 (when org-refile-use-outline-path
13900 (setq txt (mapconcat 'identity
13901 (append
13902 (if (eq org-refile-use-outline-path 'file)
13903 (list (file-name-nondirectory
13904 (buffer-file-name (buffer-base-buffer))))
13905 (if (eq org-refile-use-outline-path 'full-file-path)
13906 (list (buffer-file-name (buffer-base-buffer)))))
13907 (org-get-outline-path)
13908 (list txt))
13909 "/")))
13910 (push (list txt f re (point)) targets))
13911 (goto-char (point-at-eol))))))))
13912 (nreverse targets))))
13914 (defun org-get-outline-path ()
13915 "Return the outline path to the current entry, as a list."
13916 (let (rtn)
13917 (save-excursion
13918 (while (org-up-heading-safe)
13919 (when (looking-at org-complex-heading-regexp)
13920 (push (org-match-string-no-properties 4) rtn)))
13921 rtn)))
13923 (defvar org-refile-history nil
13924 "History for refiling operations.")
13926 (defun org-refile (&optional goto default-buffer)
13927 "Move the entry at point to another heading.
13928 The list of target headings is compiled using the information in
13929 `org-refile-targets', which see. This list is created upon first use, and
13930 you can update it by calling this command with a double prefix (`C-u C-u').
13931 FIXME: Can we find a better way of updating?
13933 At the target location, the entry is filed as a subitem of the target heading.
13934 Depending on `org-reverse-note-order', the new subitem will either be the
13935 first of the last subitem.
13937 With prefix arg GOTO, the command will only visit the target location,
13938 not actually move anything.
13939 With a double prefix `C-c C-c', go to the location where the last refiling
13940 operation has put the subtree.
13942 With a double prefix argument, the command can be used to jump to any
13943 heading in the current buffer."
13944 (interactive "P")
13945 (let* ((cbuf (current-buffer))
13946 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13947 pos it nbuf file re level reversed)
13948 (if (equal goto '(16))
13949 (org-refile-goto-last-stored)
13950 (when (setq it (org-refile-get-location
13951 (if goto "Goto: " "Refile to: ") default-buffer))
13952 (setq file (nth 1 it)
13953 re (nth 2 it)
13954 pos (nth 3 it))
13955 (setq nbuf (or (find-buffer-visiting file)
13956 (find-file-noselect file)))
13957 (if goto
13958 (progn
13959 (switch-to-buffer nbuf)
13960 (goto-char pos)
13961 (org-show-context 'org-goto))
13962 (org-copy-special)
13963 (save-excursion
13964 (set-buffer (setq nbuf (or (find-buffer-visiting file)
13965 (find-file-noselect file))))
13966 (setq reversed (org-notes-order-reversed-p))
13967 (save-excursion
13968 (save-restriction
13969 (widen)
13970 (goto-char pos)
13971 (looking-at outline-regexp)
13972 (setq level (org-get-valid-level (funcall outline-level) 1))
13973 (goto-char
13974 (if reversed
13975 (outline-next-heading)
13976 (or (save-excursion (outline-get-next-sibling))
13977 (org-end-of-subtree t t)
13978 (point-max))))
13979 (bookmark-set "org-refile-last-stored")
13980 (org-paste-subtree level))))
13981 (org-cut-special)
13982 (message "Entry refiled to \"%s\"" (car it)))))))
13984 (defun org-refile-goto-last-stored ()
13985 "Go to the location where the last refile was stored."
13986 (interactive)
13987 (bookmark-jump "org-refile-last-stored")
13988 (message "This is the location of the last refile"))
13990 (defun org-refile-get-location (&optional prompt default-buffer)
13991 "Prompt the user for a refile location, using PROMPT."
13992 (let ((org-refile-targets org-refile-targets)
13993 (org-refile-use-outline-path org-refile-use-outline-path))
13994 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
13995 (unless org-refile-target-table
13996 (error "No refile targets"))
13997 (let* ((cbuf (current-buffer))
13998 (filename (buffer-file-name (buffer-base-buffer cbuf)))
13999 (fname (and filename (file-truename filename)))
14000 (tbl (mapcar
14001 (lambda (x)
14002 (if (not (equal fname (file-truename (nth 1 x))))
14003 (cons (concat (car x) " (" (file-name-nondirectory
14004 (nth 1 x)) ")")
14005 (cdr x))
14007 org-refile-target-table))
14008 (completion-ignore-case t))
14009 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14010 tbl)))
14012 ;;;; Dynamic blocks
14014 (defun org-find-dblock (name)
14015 "Find the first dynamic block with name NAME in the buffer.
14016 If not found, stay at current position and return nil."
14017 (let (pos)
14018 (save-excursion
14019 (goto-char (point-min))
14020 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14021 nil t)
14022 (match-beginning 0))))
14023 (if pos (goto-char pos))
14024 pos))
14026 (defconst org-dblock-start-re
14027 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14028 "Matches the startline of a dynamic block, with parameters.")
14030 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14031 "Matches the end of a dyhamic block.")
14033 (defun org-create-dblock (plist)
14034 "Create a dynamic block section, with parameters taken from PLIST.
14035 PLIST must containe a :name entry which is used as name of the block."
14036 (unless (bolp) (newline))
14037 (let ((name (plist-get plist :name)))
14038 (insert "#+BEGIN: " name)
14039 (while plist
14040 (if (eq (car plist) :name)
14041 (setq plist (cddr plist))
14042 (insert " " (prin1-to-string (pop plist)))))
14043 (insert "\n\n#+END:\n")
14044 (beginning-of-line -2)))
14046 (defun org-prepare-dblock ()
14047 "Prepare dynamic block for refresh.
14048 This empties the block, puts the cursor at the insert position and returns
14049 the property list including an extra property :name with the block name."
14050 (unless (looking-at org-dblock-start-re)
14051 (error "Not at a dynamic block"))
14052 (let* ((begdel (1+ (match-end 0)))
14053 (name (org-no-properties (match-string 1)))
14054 (params (append (list :name name)
14055 (read (concat "(" (match-string 3) ")")))))
14056 (unless (re-search-forward org-dblock-end-re nil t)
14057 (error "Dynamic block not terminated"))
14058 (setq params
14059 (append params
14060 (list :content (buffer-substring
14061 begdel (match-beginning 0)))))
14062 (delete-region begdel (match-beginning 0))
14063 (goto-char begdel)
14064 (open-line 1)
14065 params))
14067 (defun org-map-dblocks (&optional command)
14068 "Apply COMMAND to all dynamic blocks in the current buffer.
14069 If COMMAND is not given, use `org-update-dblock'."
14070 (let ((cmd (or command 'org-update-dblock))
14071 pos)
14072 (save-excursion
14073 (goto-char (point-min))
14074 (while (re-search-forward org-dblock-start-re nil t)
14075 (goto-char (setq pos (match-beginning 0)))
14076 (condition-case nil
14077 (funcall cmd)
14078 (error (message "Error during update of dynamic block")))
14079 (goto-char pos)
14080 (unless (re-search-forward org-dblock-end-re nil t)
14081 (error "Dynamic block not terminated"))))))
14083 (defun org-dblock-update (&optional arg)
14084 "User command for updating dynamic blocks.
14085 Update the dynamic block at point. With prefix ARG, update all dynamic
14086 blocks in the buffer."
14087 (interactive "P")
14088 (if arg
14089 (org-update-all-dblocks)
14090 (or (looking-at org-dblock-start-re)
14091 (org-beginning-of-dblock))
14092 (org-update-dblock)))
14094 (defun org-update-dblock ()
14095 "Update the dynamic block at point
14096 This means to empty the block, parse for parameters and then call
14097 the correct writing function."
14098 (save-window-excursion
14099 (let* ((pos (point))
14100 (line (org-current-line))
14101 (params (org-prepare-dblock))
14102 (name (plist-get params :name))
14103 (cmd (intern (concat "org-dblock-write:" name))))
14104 (message "Updating dynamic block `%s' at line %d..." name line)
14105 (funcall cmd params)
14106 (message "Updating dynamic block `%s' at line %d...done" name line)
14107 (goto-char pos))))
14109 (defun org-beginning-of-dblock ()
14110 "Find the beginning of the dynamic block at point.
14111 Error if there is no scuh block at point."
14112 (let ((pos (point))
14113 beg)
14114 (end-of-line 1)
14115 (if (and (re-search-backward org-dblock-start-re nil t)
14116 (setq beg (match-beginning 0))
14117 (re-search-forward org-dblock-end-re nil t)
14118 (> (match-end 0) pos))
14119 (goto-char beg)
14120 (goto-char pos)
14121 (error "Not in a dynamic block"))))
14123 (defun org-update-all-dblocks ()
14124 "Update all dynamic blocks in the buffer.
14125 This function can be used in a hook."
14126 (when (org-mode-p)
14127 (org-map-dblocks 'org-update-dblock)))
14130 ;;;; Completion
14132 (defconst org-additional-option-like-keywords
14133 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14134 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14135 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14137 (defun org-complete (&optional arg)
14138 "Perform completion on word at point.
14139 At the beginning of a headline, this completes TODO keywords as given in
14140 `org-todo-keywords'.
14141 If the current word is preceded by a backslash, completes the TeX symbols
14142 that are supported for HTML support.
14143 If the current word is preceded by \"#+\", completes special words for
14144 setting file options.
14145 In the line after \"#+STARTUP:, complete valid keywords.\"
14146 At all other locations, this simply calls the value of
14147 `org-completion-fallback-command'."
14148 (interactive "P")
14149 (org-without-partial-completion
14150 (catch 'exit
14151 (let* ((end (point))
14152 (beg1 (save-excursion
14153 (skip-chars-backward (org-re "[:alnum:]_@"))
14154 (point)))
14155 (beg (save-excursion
14156 (skip-chars-backward "a-zA-Z0-9_:$")
14157 (point)))
14158 (confirm (lambda (x) (stringp (car x))))
14159 (searchhead (equal (char-before beg) ?*))
14160 (tag (and (equal (char-before beg1) ?:)
14161 (equal (char-after (point-at-bol)) ?*)))
14162 (prop (and (equal (char-before beg1) ?:)
14163 (not (equal (char-after (point-at-bol)) ?*))))
14164 (texp (equal (char-before beg) ?\\))
14165 (link (equal (char-before beg) ?\[))
14166 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14167 beg)
14168 "#+"))
14169 (startup (string-match "^#\\+STARTUP:.*"
14170 (buffer-substring (point-at-bol) (point))))
14171 (completion-ignore-case opt)
14172 (type nil)
14173 (tbl nil)
14174 (table (cond
14175 (opt
14176 (setq type :opt)
14177 (append
14178 (mapcar
14179 (lambda (x)
14180 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14181 (cons (match-string 2 x) (match-string 1 x)))
14182 (org-split-string (org-get-current-options) "\n"))
14183 (mapcar 'list org-additional-option-like-keywords)))
14184 (startup
14185 (setq type :startup)
14186 org-startup-options)
14187 (link (append org-link-abbrev-alist-local
14188 org-link-abbrev-alist))
14189 (texp
14190 (setq type :tex)
14191 org-html-entities)
14192 ((string-match "\\`\\*+[ \t]+\\'"
14193 (buffer-substring (point-at-bol) beg))
14194 (setq type :todo)
14195 (mapcar 'list org-todo-keywords-1))
14196 (searchhead
14197 (setq type :searchhead)
14198 (save-excursion
14199 (goto-char (point-min))
14200 (while (re-search-forward org-todo-line-regexp nil t)
14201 (push (list
14202 (org-make-org-heading-search-string
14203 (match-string 3) t))
14204 tbl)))
14205 tbl)
14206 (tag (setq type :tag beg beg1)
14207 (or org-tag-alist (org-get-buffer-tags)))
14208 (prop (setq type :prop beg beg1)
14209 (mapcar 'list (org-buffer-property-keys nil t t)))
14210 (t (progn
14211 (call-interactively org-completion-fallback-command)
14212 (throw 'exit nil)))))
14213 (pattern (buffer-substring-no-properties beg end))
14214 (completion (try-completion pattern table confirm)))
14215 (cond ((eq completion t)
14216 (if (not (assoc (upcase pattern) table))
14217 (message "Already complete")
14218 (if (equal type :opt)
14219 (insert (substring (cdr (assoc (upcase pattern) table))
14220 (length pattern)))
14221 (if (memq type '(:tag :prop)) (insert ":")))))
14222 ((null completion)
14223 (message "Can't find completion for \"%s\"" pattern)
14224 (ding))
14225 ((not (string= pattern completion))
14226 (delete-region beg end)
14227 (if (string-match " +$" completion)
14228 (setq completion (replace-match "" t t completion)))
14229 (insert completion)
14230 (if (get-buffer-window "*Completions*")
14231 (delete-window (get-buffer-window "*Completions*")))
14232 (if (assoc completion table)
14233 (if (eq type :todo) (insert " ")
14234 (if (memq type '(:tag :prop)) (insert ":"))))
14235 (if (and (equal type :opt) (assoc completion table))
14236 (message "%s" (substitute-command-keys
14237 "Press \\[org-complete] again to insert example settings"))))
14239 (message "Making completion list...")
14240 (let ((list (sort (all-completions pattern table confirm)
14241 'string<)))
14242 (with-output-to-temp-buffer "*Completions*"
14243 (condition-case nil
14244 ;; Protection needed for XEmacs and emacs 21
14245 (display-completion-list list pattern)
14246 (error (display-completion-list list)))))
14247 (message "Making completion list...%s" "done")))))))
14249 ;;;; TODO, DEADLINE, Comments
14251 (defun org-toggle-comment ()
14252 "Change the COMMENT state of an entry."
14253 (interactive)
14254 (save-excursion
14255 (org-back-to-heading)
14256 (let (case-fold-search)
14257 (if (looking-at (concat outline-regexp
14258 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14259 (replace-match "" t t nil 1)
14260 (if (looking-at outline-regexp)
14261 (progn
14262 (goto-char (match-end 0))
14263 (insert org-comment-string " ")))))))
14265 (defvar org-last-todo-state-is-todo nil
14266 "This is non-nil when the last TODO state change led to a TODO state.
14267 If the last change removed the TODO tag or switched to DONE, then
14268 this is nil.")
14270 (defvar org-setting-tags nil) ; dynamically skiped
14272 ;; FIXME: better place
14273 (defun org-property-or-variable-value (var &optional inherit)
14274 "Check if there is a property fixing the value of VAR.
14275 If yes, return this value. If not, return the current value of the variable."
14276 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14277 (if (and prop (stringp prop) (string-match "\\S-" prop))
14278 (read prop)
14279 (symbol-value var))))
14281 (defun org-parse-local-options (string var)
14282 "Parse STRING for startup setting relevant for variable VAR."
14283 (let ((rtn (symbol-value var))
14284 e opts)
14285 (save-match-data
14286 (if (or (not string) (not (string-match "\\S-" string)))
14288 (setq opts (delq nil (mapcar (lambda (x)
14289 (setq e (assoc x org-startup-options))
14290 (if (eq (nth 1 e) var) e nil))
14291 (org-split-string string "[ \t]+"))))
14292 (if (not opts)
14294 (setq rtn nil)
14295 (while (setq e (pop opts))
14296 (if (not (nth 3 e))
14297 (setq rtn (nth 2 e))
14298 (if (not (listp rtn)) (setq rtn nil))
14299 (push (nth 2 e) rtn)))
14300 rtn)))))
14302 (defvar org-blocker-hook nil
14303 "Hook for functions that are allowed to block a state change.
14305 Each function gets as its single argument a property list, see
14306 `org-trigger-hook' for more information about this list.
14308 If any of the functions in this hook returns nil, the state change
14309 is blocked.")
14311 (defvar org-trigger-hook nil
14312 "Hook for functions that are triggered by a state change.
14314 Each function gets as its single argument a property list with at least
14315 the following elements:
14317 (:type type-of-change :position pos-at-entry-start
14318 :from old-state :to new-state)
14320 Depending on the type, more properties may be present.
14322 This mechanism is currently implemented for:
14324 TODO state changes
14325 ------------------
14326 :type todo-state-change
14327 :from previous state (keyword as a string), or nil
14328 :to new state (keyword as a string), or nil")
14331 (defun org-todo (&optional arg)
14332 "Change the TODO state of an item.
14333 The state of an item is given by a keyword at the start of the heading,
14334 like
14335 *** TODO Write paper
14336 *** DONE Call mom
14338 The different keywords are specified in the variable `org-todo-keywords'.
14339 By default the available states are \"TODO\" and \"DONE\".
14340 So for this example: when the item starts with TODO, it is changed to DONE.
14341 When it starts with DONE, the DONE is removed. And when neither TODO nor
14342 DONE are present, add TODO at the beginning of the heading.
14344 With C-u prefix arg, use completion to determine the new state.
14345 With numeric prefix arg, switch to that state.
14347 For calling through lisp, arg is also interpreted in the following way:
14348 'none -> empty state
14349 \"\"(empty string) -> switch to empty state
14350 'done -> switch to DONE
14351 'nextset -> switch to the next set of keywords
14352 'previousset -> switch to the previous set of keywords
14353 \"WAITING\" -> switch to the specified keyword, but only if it
14354 really is a member of `org-todo-keywords'."
14355 (interactive "P")
14356 (save-excursion
14357 (catch 'exit
14358 (org-back-to-heading)
14359 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14360 (or (looking-at (concat " +" org-todo-regexp " *"))
14361 (looking-at " *"))
14362 (let* ((match-data (match-data))
14363 (startpos (point-at-bol))
14364 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14365 (org-log-done org-log-done)
14366 (org-log-repeat org-log-repeat)
14367 (org-todo-log-states org-todo-log-states)
14368 (this (match-string 1))
14369 (hl-pos (match-beginning 0))
14370 (head (org-get-todo-sequence-head this))
14371 (ass (assoc head org-todo-kwd-alist))
14372 (interpret (nth 1 ass))
14373 (done-word (nth 3 ass))
14374 (final-done-word (nth 4 ass))
14375 (last-state (or this ""))
14376 (completion-ignore-case t)
14377 (member (member this org-todo-keywords-1))
14378 (tail (cdr member))
14379 (state (cond
14380 ((and org-todo-key-trigger
14381 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14382 (and (not arg) org-use-fast-todo-selection
14383 (not (eq org-use-fast-todo-selection 'prefix)))))
14384 ;; Use fast selection
14385 (org-fast-todo-selection))
14386 ((and (equal arg '(4))
14387 (or (not org-use-fast-todo-selection)
14388 (not org-todo-key-trigger)))
14389 ;; Read a state with completion
14390 (completing-read "State: " (mapcar (lambda(x) (list x))
14391 org-todo-keywords-1)
14392 nil t))
14393 ((eq arg 'right)
14394 (if this
14395 (if tail (car tail) nil)
14396 (car org-todo-keywords-1)))
14397 ((eq arg 'left)
14398 (if (equal member org-todo-keywords-1)
14400 (if this
14401 (nth (- (length org-todo-keywords-1) (length tail) 2)
14402 org-todo-keywords-1)
14403 (org-last org-todo-keywords-1))))
14404 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14405 (setq arg nil))) ; hack to fall back to cycling
14406 (arg
14407 ;; user or caller requests a specific state
14408 (cond
14409 ((equal arg "") nil)
14410 ((eq arg 'none) nil)
14411 ((eq arg 'done) (or done-word (car org-done-keywords)))
14412 ((eq arg 'nextset)
14413 (or (car (cdr (member head org-todo-heads)))
14414 (car org-todo-heads)))
14415 ((eq arg 'previousset)
14416 (let ((org-todo-heads (reverse org-todo-heads)))
14417 (or (car (cdr (member head org-todo-heads)))
14418 (car org-todo-heads))))
14419 ((car (member arg org-todo-keywords-1)))
14420 ((nth (1- (prefix-numeric-value arg))
14421 org-todo-keywords-1))))
14422 ((null member) (or head (car org-todo-keywords-1)))
14423 ((equal this final-done-word) nil) ;; -> make empty
14424 ((null tail) nil) ;; -> first entry
14425 ((eq interpret 'sequence)
14426 (car tail))
14427 ((memq interpret '(type priority))
14428 (if (eq this-command last-command)
14429 (car tail)
14430 (if (> (length tail) 0)
14431 (or done-word (car org-done-keywords))
14432 nil)))
14433 (t nil)))
14434 (next (if state (concat " " state " ") " "))
14435 (change-plist (list :type 'todo-state-change :from this :to state
14436 :position startpos))
14437 dolog now-done-p)
14438 (when org-blocker-hook
14439 (unless (save-excursion
14440 (save-match-data
14441 (run-hook-with-args-until-failure
14442 'org-blocker-hook change-plist)))
14443 (if (interactive-p)
14444 (error "TODO state change from %s to %s blocked" this state)
14445 ;; fail silently
14446 (message "TODO state change from %s to %s blocked" this state)
14447 (throw 'exit nil))))
14448 (store-match-data match-data)
14449 (replace-match next t t)
14450 (unless (pos-visible-in-window-p hl-pos)
14451 (message "TODO state changed to %s" (org-trim next)))
14452 (unless head
14453 (setq head (org-get-todo-sequence-head state)
14454 ass (assoc head org-todo-kwd-alist)
14455 interpret (nth 1 ass)
14456 done-word (nth 3 ass)
14457 final-done-word (nth 4 ass)))
14458 (when (memq arg '(nextset previousset))
14459 (message "Keyword-Set %d/%d: %s"
14460 (- (length org-todo-sets) -1
14461 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14462 (length org-todo-sets)
14463 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14464 (setq org-last-todo-state-is-todo
14465 (not (member state org-done-keywords)))
14466 (setq now-done-p (and (member state org-done-keywords)
14467 (not (member this org-done-keywords))))
14468 (and logging (org-local-logging logging))
14469 (when (and (or org-todo-log-states org-log-done)
14470 (not (memq arg '(nextset previousset))))
14471 ;; we need to look at recording a time and note
14472 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14473 (nth 2 (assoc this org-todo-log-states))))
14474 (when (and state
14475 (member state org-not-done-keywords)
14476 (not (member this org-not-done-keywords)))
14477 ;; This is now a todo state and was not one before
14478 ;; If there was a CLOSED time stamp, get rid of it.
14479 (org-add-planning-info nil nil 'closed))
14480 (when (and now-done-p org-log-done)
14481 ;; It is now done, and it was not done before
14482 (org-add-planning-info 'closed (org-current-time))
14483 (if (and (not dolog) (eq 'note org-log-done))
14484 (org-add-log-maybe 'done state 'findpos 'note)))
14485 (when (and state dolog)
14486 ;; This is a non-nil state, and we need to log it
14487 (org-add-log-maybe 'state state 'findpos dolog)))
14488 ;; Fixup tag positioning
14489 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14490 (run-hooks 'org-after-todo-state-change-hook)
14491 (if (and arg (not (member state org-done-keywords)))
14492 (setq head (org-get-todo-sequence-head state)))
14493 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14494 ;; Do we need to trigger a repeat?
14495 (when now-done-p (org-auto-repeat-maybe state))
14496 ;; Fixup cursor location if close to the keyword
14497 (if (and (outline-on-heading-p)
14498 (not (bolp))
14499 (save-excursion (beginning-of-line 1)
14500 (looking-at org-todo-line-regexp))
14501 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14502 (progn
14503 (goto-char (or (match-end 2) (match-end 1)))
14504 (just-one-space)))
14505 (when org-trigger-hook
14506 (save-excursion
14507 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14509 (defun org-local-logging (value)
14510 "Get logging settings from a property VALUE."
14511 (let* (words w a)
14512 ;; directly set the variables, they are already local.
14513 (setq org-log-done nil
14514 org-log-repeat nil
14515 org-todo-log-states nil)
14516 (setq words (org-split-string value))
14517 (while (setq w (pop words))
14518 (cond
14519 ((setq a (assoc w org-startup-options))
14520 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14521 (set (nth 1 a) (nth 2 a))))
14522 ((setq a (org-extract-log-state-settings w))
14523 (and (member (car a) org-todo-keywords-1)
14524 (push a org-todo-log-states)))))))
14526 (defun org-get-todo-sequence-head (kwd)
14527 "Return the head of the TODO sequence to which KWD belongs.
14528 If KWD is not set, check if there is a text property remembering the
14529 right sequence."
14530 (let (p)
14531 (cond
14532 ((not kwd)
14533 (or (get-text-property (point-at-bol) 'org-todo-head)
14534 (progn
14535 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14536 nil (point-at-eol)))
14537 (get-text-property p 'org-todo-head))))
14538 ((not (member kwd org-todo-keywords-1))
14539 (car org-todo-keywords-1))
14540 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14542 (defun org-fast-todo-selection ()
14543 "Fast TODO keyword selection with single keys.
14544 Returns the new TODO keyword, or nil if no state change should occur."
14545 (let* ((fulltable org-todo-key-alist)
14546 (done-keywords org-done-keywords) ;; needed for the faces.
14547 (maxlen (apply 'max (mapcar
14548 (lambda (x)
14549 (if (stringp (car x)) (string-width (car x)) 0))
14550 fulltable)))
14551 (expert nil)
14552 (fwidth (+ maxlen 3 1 3))
14553 (ncol (/ (- (window-width) 4) fwidth))
14554 tg cnt e c tbl
14555 groups ingroup)
14556 (save-window-excursion
14557 (if expert
14558 (set-buffer (get-buffer-create " *Org todo*"))
14559 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14560 (erase-buffer)
14561 (org-set-local 'org-done-keywords done-keywords)
14562 (setq tbl fulltable cnt 0)
14563 (while (setq e (pop tbl))
14564 (cond
14565 ((equal e '(:startgroup))
14566 (push '() groups) (setq ingroup t)
14567 (when (not (= cnt 0))
14568 (setq cnt 0)
14569 (insert "\n"))
14570 (insert "{ "))
14571 ((equal e '(:endgroup))
14572 (setq ingroup nil cnt 0)
14573 (insert "}\n"))
14575 (setq tg (car e) c (cdr e))
14576 (if ingroup (push tg (car groups)))
14577 (setq tg (org-add-props tg nil 'face
14578 (org-get-todo-face tg)))
14579 (if (and (= cnt 0) (not ingroup)) (insert " "))
14580 (insert "[" c "] " tg (make-string
14581 (- fwidth 4 (length tg)) ?\ ))
14582 (when (= (setq cnt (1+ cnt)) ncol)
14583 (insert "\n")
14584 (if ingroup (insert " "))
14585 (setq cnt 0)))))
14586 (insert "\n")
14587 (goto-char (point-min))
14588 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14589 (fit-window-to-buffer))
14590 (message "[a-z..]:Set [SPC]:clear")
14591 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14592 (cond
14593 ((or (= c ?\C-g)
14594 (and (= c ?q) (not (rassoc c fulltable))))
14595 (setq quit-flag t))
14596 ((= c ?\ ) nil)
14597 ((setq e (rassoc c fulltable) tg (car e))
14599 (t (setq quit-flag t))))))
14601 (defun org-get-repeat ()
14602 "Check if tere is a deadline/schedule with repeater in this entry."
14603 (save-match-data
14604 (save-excursion
14605 (org-back-to-heading t)
14606 (if (re-search-forward
14607 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14608 (match-string 1)))))
14610 (defvar org-last-changed-timestamp)
14611 (defvar org-log-post-message)
14612 (defvar org-log-note-purpose)
14613 (defun org-auto-repeat-maybe (done-word)
14614 "Check if the current headline contains a repeated deadline/schedule.
14615 If yes, set TODO state back to what it was and change the base date
14616 of repeating deadline/scheduled time stamps to new date.
14617 This function is run automatically after each state change to a DONE state."
14618 ;; last-state is dynamically scoped into this function
14619 (let* ((repeat (org-get-repeat))
14620 (aa (assoc last-state org-todo-kwd-alist))
14621 (interpret (nth 1 aa))
14622 (head (nth 2 aa))
14623 (whata '(("d" . day) ("m" . month) ("y" . year)))
14624 (msg "Entry repeats: ")
14625 (org-log-done nil)
14626 (org-todo-log-states nil)
14627 (nshiftmax 10) (nshift 0)
14628 re type n what ts mb0 time)
14629 (when repeat
14630 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14631 (org-todo (if (eq interpret 'type) last-state head))
14632 (when (and org-log-repeat
14633 (or (not (memq 'org-add-log-note
14634 (default-value 'post-command-hook)))
14635 (eq org-log-note-purpose 'done)))
14636 ;; Make sure a note is taken;
14637 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14638 'findpos org-log-repeat))
14639 (org-back-to-heading t)
14640 (org-add-planning-info nil nil 'closed)
14641 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14642 org-deadline-time-regexp "\\)\\|\\("
14643 org-ts-regexp "\\)"))
14644 (while (re-search-forward
14645 re (save-excursion (outline-next-heading) (point)) t)
14646 (setq type (if (match-end 1) org-scheduled-string
14647 (if (match-end 3) org-deadline-string "Plain:"))
14648 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
14649 mb0 (match-beginning 0))
14650 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
14651 (setq n (string-to-number (match-string 2 ts))
14652 what (match-string 3 ts))
14653 (if (equal what "w") (setq n (* n 7) what "d"))
14654 ;; Preparation, see if we need to modify the start date for the change
14655 (when (match-end 1)
14656 (setq time (save-match-data (org-time-string-to-time ts)))
14657 (cond
14658 ((equal (match-string 1 ts) ".")
14659 ;; Shift starting date to today
14660 (org-timestamp-change
14661 (- (time-to-days (current-time)) (time-to-days time))
14662 'day))
14663 ((equal (match-string 1 ts) "+")
14664 (while (< (time-to-days time) (time-to-days (current-time)))
14665 (when (= (incf nshift) nshiftmax)
14666 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
14667 (error "Abort")))
14668 (org-timestamp-change n (cdr (assoc what whata)))
14669 (sit-for .0001) ;; so we can watch the date shifting
14670 (org-at-timestamp-p t)
14671 (setq ts (match-string 1))
14672 (setq time (save-match-data (org-time-string-to-time ts))))
14673 (org-timestamp-change (- n) (cdr (assoc what whata)))
14674 ;; rematch, so that we have everything in place for the real shift
14675 (org-at-timestamp-p t)
14676 (setq ts (match-string 1))
14677 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
14678 (org-timestamp-change n (cdr (assoc what whata)))
14679 (setq msg (concat msg type org-last-changed-timestamp " "))))
14680 (setq org-log-post-message msg)
14681 (message "%s" msg))))
14683 (defun org-show-todo-tree (arg)
14684 "Make a compact tree which shows all headlines marked with TODO.
14685 The tree will show the lines where the regexp matches, and all higher
14686 headlines above the match.
14687 With a \\[universal-argument] prefix, also show the DONE entries.
14688 With a numeric prefix N, construct a sparse tree for the Nth element
14689 of `org-todo-keywords-1'."
14690 (interactive "P")
14691 (let ((case-fold-search nil)
14692 (kwd-re
14693 (cond ((null arg) org-not-done-regexp)
14694 ((equal arg '(4))
14695 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14696 (mapcar 'list org-todo-keywords-1))))
14697 (concat "\\("
14698 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14699 "\\)\\>")))
14700 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14701 (regexp-quote (nth (1- (prefix-numeric-value arg))
14702 org-todo-keywords-1)))
14703 (t (error "Invalid prefix argument: %s" arg)))))
14704 (message "%d TODO entries found"
14705 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14707 (defun org-deadline (&optional remove)
14708 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14709 With argument REMOVE, remove any deadline from the item."
14710 (interactive "P")
14711 (if remove
14712 (progn
14713 (org-remove-timestamp-with-keyword org-deadline-string)
14714 (message "Item no longer has a deadline."))
14715 (org-add-planning-info 'deadline nil 'closed)))
14717 (defun org-schedule (&optional remove)
14718 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14719 With argument REMOVE, remove any scheduling date from the item."
14720 (interactive "P")
14721 (if remove
14722 (progn
14723 (org-remove-timestamp-with-keyword org-scheduled-string)
14724 (message "Item is no longer scheduled."))
14725 (org-add-planning-info 'scheduled nil 'closed)))
14727 (defun org-remove-timestamp-with-keyword (keyword)
14728 "Remove all time stamps with KEYWORD in the current entry."
14729 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14730 beg)
14731 (save-excursion
14732 (org-back-to-heading t)
14733 (setq beg (point))
14734 (org-end-of-subtree t t)
14735 (while (re-search-backward re beg t)
14736 (replace-match "")
14737 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14738 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14740 (defun org-add-planning-info (what &optional time &rest remove)
14741 "Insert new timestamp with keyword in the line directly after the headline.
14742 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14743 If non is given, the user is prompted for a date.
14744 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14745 be removed."
14746 (interactive)
14747 (let (org-time-was-given org-end-time-was-given ts
14748 end default-time default-input)
14750 (when (and (not time) (memq what '(scheduled deadline)))
14751 ;; Try to get a default date/time from existing timestamp
14752 (save-excursion
14753 (org-back-to-heading t)
14754 (setq end (save-excursion (outline-next-heading) (point)))
14755 (when (re-search-forward (if (eq what 'scheduled)
14756 org-scheduled-time-regexp
14757 org-deadline-time-regexp)
14758 end t)
14759 (setq ts (match-string 1)
14760 default-time
14761 (apply 'encode-time (org-parse-time-string ts))
14762 default-input (and ts (org-get-compact-tod ts))))))
14763 (when what
14764 ;; If necessary, get the time from the user
14765 (setq time (or time (org-read-date nil 'to-time nil nil
14766 default-time default-input))))
14768 (when (and org-insert-labeled-timestamps-at-point
14769 (member what '(scheduled deadline)))
14770 (insert
14771 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14772 (org-insert-time-stamp time org-time-was-given
14773 nil nil nil (list org-end-time-was-given))
14774 (setq what nil))
14775 (save-excursion
14776 (save-restriction
14777 (let (col list elt ts buffer-invisibility-spec)
14778 (org-back-to-heading t)
14779 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14780 (goto-char (match-end 1))
14781 (setq col (current-column))
14782 (goto-char (match-end 0))
14783 (if (eobp) (insert "\n") (forward-char 1))
14784 (if (and (not (looking-at outline-regexp))
14785 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14786 "[^\r\n]*"))
14787 (not (equal (match-string 1) org-clock-string)))
14788 (narrow-to-region (match-beginning 0) (match-end 0))
14789 (insert-before-markers "\n")
14790 (backward-char 1)
14791 (narrow-to-region (point) (point))
14792 (indent-to-column col))
14793 ;; Check if we have to remove something.
14794 (setq list (cons what remove))
14795 (while list
14796 (setq elt (pop list))
14797 (goto-char (point-min))
14798 (when (or (and (eq elt 'scheduled)
14799 (re-search-forward org-scheduled-time-regexp nil t))
14800 (and (eq elt 'deadline)
14801 (re-search-forward org-deadline-time-regexp nil t))
14802 (and (eq elt 'closed)
14803 (re-search-forward org-closed-time-regexp nil t)))
14804 (replace-match "")
14805 (if (looking-at "--+<[^>]+>") (replace-match ""))
14806 (if (looking-at " +") (replace-match ""))))
14807 (goto-char (point-max))
14808 (when what
14809 (insert
14810 (if (not (equal (char-before) ?\ )) " " "")
14811 (cond ((eq what 'scheduled) org-scheduled-string)
14812 ((eq what 'deadline) org-deadline-string)
14813 ((eq what 'closed) org-closed-string))
14814 " ")
14815 (setq ts (org-insert-time-stamp
14816 time
14817 (or org-time-was-given
14818 (and (eq what 'closed) org-log-done-with-time))
14819 (eq what 'closed)
14820 nil nil (list org-end-time-was-given)))
14821 (end-of-line 1))
14822 (goto-char (point-min))
14823 (widen)
14824 (if (looking-at "[ \t]+\r?\n")
14825 (replace-match ""))
14826 ts)))))
14828 (defvar org-log-note-marker (make-marker))
14829 (defvar org-log-note-purpose nil)
14830 (defvar org-log-note-state nil)
14831 (defvar org-log-note-how nil)
14832 (defvar org-log-note-window-configuration nil)
14833 (defvar org-log-note-return-to (make-marker))
14834 (defvar org-log-post-message nil
14835 "Message to be displayed after a log note has been stored.
14836 The auto-repeater uses this.")
14838 (defun org-add-log-maybe (&optional purpose state findpos how)
14839 "Set up the post command hook to take a note.
14840 If this is about to TODO state change, the new state is expected in STATE.
14841 When FINDPOS is non-nil, find the correct position for the note in
14842 the current entry. If not, assume that it can be inserted at point."
14843 (save-excursion
14844 (when findpos
14845 (org-back-to-heading t)
14846 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14847 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14848 "[^\r\n]*\\)?"))
14849 (goto-char (match-end 0))
14850 (unless org-log-states-order-reversed
14851 (and (= (char-after) ?\n) (forward-char 1))
14852 (org-skip-over-state-notes)
14853 (skip-chars-backward " \t\n\r")))
14854 (move-marker org-log-note-marker (point))
14855 (setq org-log-note-purpose purpose
14856 org-log-note-state state
14857 org-log-note-how how)
14858 (add-hook 'post-command-hook 'org-add-log-note 'append)))
14860 (defun org-skip-over-state-notes ()
14861 "Skip past the list of State notes in an entry."
14862 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14863 (while (looking-at "[ \t]*- State")
14864 (condition-case nil
14865 (org-next-item)
14866 (error (org-end-of-item)))))
14868 (defun org-add-log-note (&optional purpose)
14869 "Pop up a window for taking a note, and add this note later at point."
14870 (remove-hook 'post-command-hook 'org-add-log-note)
14871 (setq org-log-note-window-configuration (current-window-configuration))
14872 (delete-other-windows)
14873 (move-marker org-log-note-return-to (point))
14874 (switch-to-buffer (marker-buffer org-log-note-marker))
14875 (goto-char org-log-note-marker)
14876 (org-switch-to-buffer-other-window "*Org Note*")
14877 (erase-buffer)
14878 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
14879 (org-store-log-note)
14880 (let ((org-inhibit-startup t)) (org-mode))
14881 (insert (format "# Insert note for %s.
14882 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14883 (cond
14884 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14885 ((eq org-log-note-purpose 'done) "closed todo item")
14886 ((eq org-log-note-purpose 'state)
14887 (format "state change to \"%s\"" org-log-note-state))
14888 (t (error "This should not happen")))))
14889 (org-set-local 'org-finish-function 'org-store-log-note)))
14891 (defun org-store-log-note ()
14892 "Finish taking a log note, and insert it to where it belongs."
14893 (let ((txt (buffer-string))
14894 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14895 lines ind)
14896 (kill-buffer (current-buffer))
14897 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14898 (setq txt (replace-match "" t t txt)))
14899 (if (string-match "\\s-+\\'" txt)
14900 (setq txt (replace-match "" t t txt)))
14901 (setq lines (org-split-string txt "\n"))
14902 (when (and note (string-match "\\S-" note))
14903 (setq note
14904 (org-replace-escapes
14905 note
14906 (list (cons "%u" (user-login-name))
14907 (cons "%U" user-full-name)
14908 (cons "%t" (format-time-string
14909 (org-time-stamp-format 'long 'inactive)
14910 (current-time)))
14911 (cons "%s" (if org-log-note-state
14912 (concat "\"" org-log-note-state "\"")
14913 "")))))
14914 (if lines (setq note (concat note " \\\\")))
14915 (push note lines))
14916 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14917 (when lines
14918 (save-excursion
14919 (set-buffer (marker-buffer org-log-note-marker))
14920 (save-excursion
14921 (goto-char org-log-note-marker)
14922 (move-marker org-log-note-marker nil)
14923 (end-of-line 1)
14924 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14925 (indent-relative nil)
14926 (insert "- " (pop lines))
14927 (org-indent-line-function)
14928 (beginning-of-line 1)
14929 (looking-at "[ \t]*")
14930 (setq ind (concat (match-string 0) " "))
14931 (end-of-line 1)
14932 (while lines (insert "\n" ind (pop lines)))))))
14933 (set-window-configuration org-log-note-window-configuration)
14934 (with-current-buffer (marker-buffer org-log-note-return-to)
14935 (goto-char org-log-note-return-to))
14936 (move-marker org-log-note-return-to nil)
14937 (and org-log-post-message (message "%s" org-log-post-message)))
14939 ;; FIXME: what else would be useful?
14940 ;; - priority
14941 ;; - date
14943 (defun org-sparse-tree (&optional arg)
14944 "Create a sparse tree, prompt for the details.
14945 This command can create sparse trees. You first need to select the type
14946 of match used to create the tree:
14948 t Show entries with a specific TODO keyword.
14949 T Show entries selected by a tags match.
14950 p Enter a property name and its value (both with completion on existing
14951 names/values) and show entries with that property.
14952 r Show entries matching a regular expression
14953 d Show deadlines due within `org-deadline-warning-days'."
14954 (interactive "P")
14955 (let (ans kwd value)
14956 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
14957 (setq ans (read-char-exclusive))
14958 (cond
14959 ((equal ans ?d)
14960 (call-interactively 'org-check-deadlines))
14961 ((equal ans ?b)
14962 (call-interactively 'org-check-before-date))
14963 ((equal ans ?t)
14964 (org-show-todo-tree '(4)))
14965 ((equal ans ?T)
14966 (call-interactively 'org-tags-sparse-tree))
14967 ((member ans '(?p ?P))
14968 (setq kwd (completing-read "Property: "
14969 (mapcar 'list (org-buffer-property-keys))))
14970 (setq value (completing-read "Value: "
14971 (mapcar 'list (org-property-values kwd))))
14972 (unless (string-match "\\`{.*}\\'" value)
14973 (setq value (concat "\"" value "\"")))
14974 (org-tags-sparse-tree arg (concat kwd "=" value)))
14975 ((member ans '(?r ?R ?/))
14976 (call-interactively 'org-occur))
14977 (t (error "No such sparse tree command \"%c\"" ans)))))
14979 (defvar org-occur-highlights nil
14980 "List of overlays used for occur matches.")
14981 (make-variable-buffer-local 'org-occur-highlights)
14982 (defvar org-occur-parameters nil
14983 "Parameters of the active org-occur calls.
14984 This is a list, each call to org-occur pushes as cons cell,
14985 containing the regular expression and the callback, onto the list.
14986 The list can contain several entries if `org-occur' has been called
14987 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14988 will only contain one set of parameters. When the highlights are
14989 removed (for example with `C-c C-c', or with the next edit (depending
14990 on `org-remove-highlights-with-change'), this variable is emptied
14991 as well.")
14992 (make-variable-buffer-local 'org-occur-parameters)
14994 (defun org-occur (regexp &optional keep-previous callback)
14995 "Make a compact tree which shows all matches of REGEXP.
14996 The tree will show the lines where the regexp matches, and all higher
14997 headlines above the match. It will also show the heading after the match,
14998 to make sure editing the matching entry is easy.
14999 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15000 call to `org-occur' will be kept, to allow stacking of calls to this
15001 command.
15002 If CALLBACK is non-nil, it is a function which is called to confirm
15003 that the match should indeed be shown."
15004 (interactive "sRegexp: \nP")
15005 (unless keep-previous
15006 (org-remove-occur-highlights nil nil t))
15007 (push (cons regexp callback) org-occur-parameters)
15008 (let ((cnt 0))
15009 (save-excursion
15010 (goto-char (point-min))
15011 (if (or (not keep-previous) ; do not want to keep
15012 (not org-occur-highlights)) ; no previous matches
15013 ;; hide everything
15014 (org-overview))
15015 (while (re-search-forward regexp nil t)
15016 (when (or (not callback)
15017 (save-match-data (funcall callback)))
15018 (setq cnt (1+ cnt))
15019 (when org-highlight-sparse-tree-matches
15020 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15021 (org-show-context 'occur-tree))))
15022 (when org-remove-highlights-with-change
15023 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15024 nil 'local))
15025 (unless org-sparse-tree-open-archived-trees
15026 (org-hide-archived-subtrees (point-min) (point-max)))
15027 (run-hooks 'org-occur-hook)
15028 (if (interactive-p)
15029 (message "%d match(es) for regexp %s" cnt regexp))
15030 cnt))
15032 (defun org-show-context (&optional key)
15033 "Make sure point and context and visible.
15034 How much context is shown depends upon the variables
15035 `org-show-hierarchy-above', `org-show-following-heading'. and
15036 `org-show-siblings'."
15037 (let ((heading-p (org-on-heading-p t))
15038 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15039 (following-p (org-get-alist-option org-show-following-heading key))
15040 (entry-p (org-get-alist-option org-show-entry-below key))
15041 (siblings-p (org-get-alist-option org-show-siblings key)))
15042 (catch 'exit
15043 ;; Show heading or entry text
15044 (if (and heading-p (not entry-p))
15045 (org-flag-heading nil) ; only show the heading
15046 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15047 (org-show-hidden-entry))) ; show entire entry
15048 (when following-p
15049 ;; Show next sibling, or heading below text
15050 (save-excursion
15051 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15052 (org-flag-heading nil))))
15053 (when siblings-p (org-show-siblings))
15054 (when hierarchy-p
15055 ;; show all higher headings, possibly with siblings
15056 (save-excursion
15057 (while (and (condition-case nil
15058 (progn (org-up-heading-all 1) t)
15059 (error nil))
15060 (not (bobp)))
15061 (org-flag-heading nil)
15062 (when siblings-p (org-show-siblings))))))))
15064 (defun org-reveal (&optional siblings)
15065 "Show current entry, hierarchy above it, and the following headline.
15066 This can be used to show a consistent set of context around locations
15067 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15068 not t for the search context.
15070 With optional argument SIBLINGS, on each level of the hierarchy all
15071 siblings are shown. This repairs the tree structure to what it would
15072 look like when opened with hierarchical calls to `org-cycle'."
15073 (interactive "P")
15074 (let ((org-show-hierarchy-above t)
15075 (org-show-following-heading t)
15076 (org-show-siblings (if siblings t org-show-siblings)))
15077 (org-show-context nil)))
15079 (defun org-highlight-new-match (beg end)
15080 "Highlight from BEG to END and mark the highlight is an occur headline."
15081 (let ((ov (org-make-overlay beg end)))
15082 (org-overlay-put ov 'face 'secondary-selection)
15083 (push ov org-occur-highlights)))
15085 (defun org-remove-occur-highlights (&optional beg end noremove)
15086 "Remove the occur highlights from the buffer.
15087 BEG and END are ignored. If NOREMOVE is nil, remove this function
15088 from the `before-change-functions' in the current buffer."
15089 (interactive)
15090 (unless org-inhibit-highlight-removal
15091 (mapc 'org-delete-overlay org-occur-highlights)
15092 (setq org-occur-highlights nil)
15093 (setq org-occur-parameters nil)
15094 (unless noremove
15095 (remove-hook 'before-change-functions
15096 'org-remove-occur-highlights 'local))))
15098 ;;;; Priorities
15100 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15101 "Regular expression matching the priority indicator.")
15103 (defvar org-remove-priority-next-time nil)
15105 (defun org-priority-up ()
15106 "Increase the priority of the current item."
15107 (interactive)
15108 (org-priority 'up))
15110 (defun org-priority-down ()
15111 "Decrease the priority of the current item."
15112 (interactive)
15113 (org-priority 'down))
15115 (defun org-priority (&optional action)
15116 "Change the priority of an item by ARG.
15117 ACTION can be `set', `up', `down', or a character."
15118 (interactive)
15119 (setq action (or action 'set))
15120 (let (current new news have remove)
15121 (save-excursion
15122 (org-back-to-heading)
15123 (if (looking-at org-priority-regexp)
15124 (setq current (string-to-char (match-string 2))
15125 have t)
15126 (setq current org-default-priority))
15127 (cond
15128 ((or (eq action 'set) (integerp action))
15129 (if (integerp action)
15130 (setq new action)
15131 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15132 (setq new (read-char-exclusive)))
15133 (if (and (= (upcase org-highest-priority) org-highest-priority)
15134 (= (upcase org-lowest-priority) org-lowest-priority))
15135 (setq new (upcase new)))
15136 (cond ((equal new ?\ ) (setq remove t))
15137 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15138 (error "Priority must be between `%c' and `%c'"
15139 org-highest-priority org-lowest-priority))))
15140 ((eq action 'up)
15141 (if (and (not have) (eq last-command this-command))
15142 (setq new org-lowest-priority)
15143 (setq new (if (and org-priority-start-cycle-with-default (not have))
15144 org-default-priority (1- current)))))
15145 ((eq action 'down)
15146 (if (and (not have) (eq last-command this-command))
15147 (setq new org-highest-priority)
15148 (setq new (if (and org-priority-start-cycle-with-default (not have))
15149 org-default-priority (1+ current)))))
15150 (t (error "Invalid action")))
15151 (if (or (< (upcase new) org-highest-priority)
15152 (> (upcase new) org-lowest-priority))
15153 (setq remove t))
15154 (setq news (format "%c" new))
15155 (if have
15156 (if remove
15157 (replace-match "" t t nil 1)
15158 (replace-match news t t nil 2))
15159 (if remove
15160 (error "No priority cookie found in line")
15161 (looking-at org-todo-line-regexp)
15162 (if (match-end 2)
15163 (progn
15164 (goto-char (match-end 2))
15165 (insert " [#" news "]"))
15166 (goto-char (match-beginning 3))
15167 (insert "[#" news "] ")))))
15168 (org-preserve-lc (org-set-tags nil 'align))
15169 (if remove
15170 (message "Priority removed")
15171 (message "Priority of current item set to %s" news))))
15174 (defun org-get-priority (s)
15175 "Find priority cookie and return priority."
15176 (save-match-data
15177 (if (not (string-match org-priority-regexp s))
15178 (* 1000 (- org-lowest-priority org-default-priority))
15179 (* 1000 (- org-lowest-priority
15180 (string-to-char (match-string 2 s)))))))
15182 ;;;; Tags
15184 (defun org-scan-tags (action matcher &optional todo-only)
15185 "Scan headline tags with inheritance and produce output ACTION.
15186 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15187 evaluated, testing if a given set of tags qualifies a headline for
15188 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15189 are included in the output."
15190 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15191 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15192 (org-re
15193 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15194 (props (list 'face nil
15195 'done-face 'org-done
15196 'undone-face nil
15197 'mouse-face 'highlight
15198 'org-not-done-regexp org-not-done-regexp
15199 'org-todo-regexp org-todo-regexp
15200 'keymap org-agenda-keymap
15201 'help-echo
15202 (format "mouse-2 or RET jump to org file %s"
15203 (abbreviate-file-name
15204 (or (buffer-file-name (buffer-base-buffer))
15205 (buffer-name (buffer-base-buffer)))))))
15206 (case-fold-search nil)
15207 lspos
15208 tags tags-list tags-alist (llast 0) rtn level category i txt
15209 todo marker entry priority)
15210 (save-excursion
15211 (goto-char (point-min))
15212 (when (eq action 'sparse-tree)
15213 (org-overview)
15214 (org-remove-occur-highlights))
15215 (while (re-search-forward re nil t)
15216 (catch :skip
15217 (setq todo (if (match-end 1) (match-string 2))
15218 tags (if (match-end 4) (match-string 4)))
15219 (goto-char (setq lspos (1+ (match-beginning 0))))
15220 (setq level (org-reduced-level (funcall outline-level))
15221 category (org-get-category))
15222 (setq i llast llast level)
15223 ;; remove tag lists from same and sublevels
15224 (while (>= i level)
15225 (when (setq entry (assoc i tags-alist))
15226 (setq tags-alist (delete entry tags-alist)))
15227 (setq i (1- i)))
15228 ;; add the nex tags
15229 (when tags
15230 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15231 tags-alist
15232 (cons (cons level tags) tags-alist)))
15233 ;; compile tags for current headline
15234 (setq tags-list
15235 (if org-use-tag-inheritance
15236 (apply 'append (mapcar 'cdr tags-alist))
15237 tags))
15238 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15239 (eval matcher)
15240 (or (not org-agenda-skip-archived-trees)
15241 (not (member org-archive-tag tags-list))))
15242 (and (eq action 'agenda) (org-agenda-skip))
15243 ;; list this headline
15245 (if (eq action 'sparse-tree)
15246 (progn
15247 (and org-highlight-sparse-tree-matches
15248 (org-get-heading) (match-end 0)
15249 (org-highlight-new-match
15250 (match-beginning 0) (match-beginning 1)))
15251 (org-show-context 'tags-tree))
15252 (setq txt (org-format-agenda-item
15254 (concat
15255 (if org-tags-match-list-sublevels
15256 (make-string (1- level) ?.) "")
15257 (org-get-heading))
15258 category tags-list)
15259 priority (org-get-priority txt))
15260 (goto-char lspos)
15261 (setq marker (org-agenda-new-marker))
15262 (org-add-props txt props
15263 'org-marker marker 'org-hd-marker marker 'org-category category
15264 'priority priority 'type "tagsmatch")
15265 (push txt rtn))
15266 ;; if we are to skip sublevels, jump to end of subtree
15267 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15268 (when (and (eq action 'sparse-tree)
15269 (not org-sparse-tree-open-archived-trees))
15270 (org-hide-archived-subtrees (point-min) (point-max)))
15271 (nreverse rtn)))
15273 (defvar todo-only) ;; dynamically scoped
15275 (defun org-tags-sparse-tree (&optional todo-only match)
15276 "Create a sparse tree according to tags string MATCH.
15277 MATCH can contain positive and negative selection of tags, like
15278 \"+WORK+URGENT-WITHBOSS\".
15279 If optional argument TODO_ONLY is non-nil, only select lines that are
15280 also TODO lines."
15281 (interactive "P")
15282 (org-prepare-agenda-buffers (list (current-buffer)))
15283 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15285 (defvar org-cached-props nil)
15286 (defun org-cached-entry-get (pom property)
15287 (if (or (eq t org-use-property-inheritance)
15288 (member property org-use-property-inheritance))
15289 ;; Caching is not possible, check it directly
15290 (org-entry-get pom property 'inherit)
15291 ;; Get all properties, so that we can do complicated checks easily
15292 (cdr (assoc property (or org-cached-props
15293 (setq org-cached-props
15294 (org-entry-properties pom)))))))
15296 (defun org-global-tags-completion-table (&optional files)
15297 "Return the list of all tags in all agenda buffer/files."
15298 (save-excursion
15299 (org-uniquify
15300 (delq nil
15301 (apply 'append
15302 (mapcar
15303 (lambda (file)
15304 (set-buffer (find-file-noselect file))
15305 (append (org-get-buffer-tags)
15306 (mapcar (lambda (x) (if (stringp (car-safe x))
15307 (list (car-safe x)) nil))
15308 org-tag-alist)))
15309 (if (and files (car files))
15310 files
15311 (org-agenda-files))))))))
15313 (defun org-make-tags-matcher (match)
15314 "Create the TAGS//TODO matcher form for the selection string MATCH."
15315 ;; todo-only is scoped dynamically into this function, and the function
15316 ;; may change it it the matcher asksk for it.
15317 (unless match
15318 ;; Get a new match request, with completion
15319 (let ((org-last-tags-completion-table
15320 (org-global-tags-completion-table)))
15321 (setq match (completing-read
15322 "Match: " 'org-tags-completion-function nil nil nil
15323 'org-tags-history))))
15325 ;; Parse the string and create a lisp form
15326 (let ((match0 match)
15327 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15328 minus tag mm
15329 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15330 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15331 (if (string-match "/+" match)
15332 ;; match contains also a todo-matching request
15333 (progn
15334 (setq tagsmatch (substring match 0 (match-beginning 0))
15335 todomatch (substring match (match-end 0)))
15336 (if (string-match "^!" todomatch)
15337 (setq todo-only t todomatch (substring todomatch 1)))
15338 (if (string-match "^\\s-*$" todomatch)
15339 (setq todomatch nil)))
15340 ;; only matching tags
15341 (setq tagsmatch match todomatch nil))
15343 ;; Make the tags matcher
15344 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15345 (setq tagsmatcher t)
15346 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15347 (while (setq term (pop orterms))
15348 (while (and (equal (substring term -1) "\\") orterms)
15349 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15350 (while (string-match re term)
15351 (setq minus (and (match-end 1)
15352 (equal (match-string 1 term) "-"))
15353 tag (match-string 2 term)
15354 re-p (equal (string-to-char tag) ?{)
15355 level-p (match-end 3)
15356 prop-p (match-end 4)
15357 mm (cond
15358 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15359 (level-p `(= level ,(string-to-number
15360 (match-string 3 term))))
15361 (prop-p
15362 (setq pn (match-string 4 term)
15363 pv (match-string 5 term)
15364 cat-p (equal pn "CATEGORY")
15365 re-p (equal (string-to-char pv) ?{)
15366 pv (substring pv 1 -1))
15367 (if (equal pn "CATEGORY")
15368 (setq gv '(get-text-property (point) 'org-category))
15369 (setq gv `(org-cached-entry-get nil ,pn)))
15370 (if re-p
15371 `(string-match ,pv (or ,gv ""))
15372 `(equal ,pv (or ,gv ""))))
15373 (t `(member ,(downcase tag) tags-list)))
15374 mm (if minus (list 'not mm) mm)
15375 term (substring term (match-end 0)))
15376 (push mm tagsmatcher))
15377 (push (if (> (length tagsmatcher) 1)
15378 (cons 'and tagsmatcher)
15379 (car tagsmatcher))
15380 orlist)
15381 (setq tagsmatcher nil))
15382 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15383 (setq tagsmatcher
15384 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15386 ;; Make the todo matcher
15387 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15388 (setq todomatcher t)
15389 (setq orterms (org-split-string todomatch "|") orlist nil)
15390 (while (setq term (pop orterms))
15391 (while (string-match re term)
15392 (setq minus (and (match-end 1)
15393 (equal (match-string 1 term) "-"))
15394 kwd (match-string 2 term)
15395 re-p (equal (string-to-char kwd) ?{)
15396 term (substring term (match-end 0))
15397 mm (if re-p
15398 `(string-match ,(substring kwd 1 -1) todo)
15399 (list 'equal 'todo kwd))
15400 mm (if minus (list 'not mm) mm))
15401 (push mm todomatcher))
15402 (push (if (> (length todomatcher) 1)
15403 (cons 'and todomatcher)
15404 (car todomatcher))
15405 orlist)
15406 (setq todomatcher nil))
15407 (setq todomatcher (if (> (length orlist) 1)
15408 (cons 'or orlist) (car orlist))))
15410 ;; Return the string and lisp forms of the matcher
15411 (setq matcher (if todomatcher
15412 (list 'and tagsmatcher todomatcher)
15413 tagsmatcher))
15414 (cons match0 matcher)))
15416 (defun org-match-any-p (re list)
15417 "Does re match any element of list?"
15418 (setq list (mapcar (lambda (x) (string-match re x)) list))
15419 (delq nil list))
15421 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15422 (defvar org-tags-overlay (org-make-overlay 1 1))
15423 (org-detach-overlay org-tags-overlay)
15425 (defun org-align-tags-here (to-col)
15426 ;; Assumes that this is a headline
15427 (let ((pos (point)) (col (current-column)) tags)
15428 (beginning-of-line 1)
15429 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15430 (< pos (match-beginning 2)))
15431 (progn
15432 (setq tags (match-string 2))
15433 (goto-char (match-beginning 1))
15434 (insert " ")
15435 (delete-region (point) (1+ (match-end 0)))
15436 (backward-char 1)
15437 (move-to-column
15438 (max (1+ (current-column))
15439 (1+ col)
15440 (if (> to-col 0)
15441 to-col
15442 (- (abs to-col) (length tags))))
15444 (insert tags)
15445 (move-to-column (min (current-column) col) t))
15446 (goto-char pos))))
15448 (defun org-set-tags (&optional arg just-align)
15449 "Set the tags for the current headline.
15450 With prefix ARG, realign all tags in headings in the current buffer."
15451 (interactive "P")
15452 (let* ((re (concat "^" outline-regexp))
15453 (current (org-get-tags-string))
15454 (col (current-column))
15455 (org-setting-tags t)
15456 table current-tags inherited-tags ; computed below when needed
15457 tags p0 c0 c1 rpl)
15458 (if arg
15459 (save-excursion
15460 (goto-char (point-min))
15461 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15462 (while (re-search-forward re nil t)
15463 (org-set-tags nil t)
15464 (end-of-line 1)))
15465 (message "All tags realigned to column %d" org-tags-column))
15466 (if just-align
15467 (setq tags current)
15468 ;; Get a new set of tags from the user
15469 (save-excursion
15470 (setq table (or org-tag-alist (org-get-buffer-tags))
15471 org-last-tags-completion-table table
15472 current-tags (org-split-string current ":")
15473 inherited-tags (nreverse
15474 (nthcdr (length current-tags)
15475 (nreverse (org-get-tags-at))))
15476 tags
15477 (if (or (eq t org-use-fast-tag-selection)
15478 (and org-use-fast-tag-selection
15479 (delq nil (mapcar 'cdr table))))
15480 (org-fast-tag-selection
15481 current-tags inherited-tags table
15482 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15483 (let ((org-add-colon-after-tag-completion t))
15484 (org-trim
15485 (org-without-partial-completion
15486 (completing-read "Tags: " 'org-tags-completion-function
15487 nil nil current 'org-tags-history)))))))
15488 (while (string-match "[-+&]+" tags)
15489 ;; No boolean logic, just a list
15490 (setq tags (replace-match ":" t t tags))))
15492 (if (string-match "\\`[\t ]*\\'" tags)
15493 (setq tags "")
15494 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15495 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15497 ;; Insert new tags at the correct column
15498 (beginning-of-line 1)
15499 (cond
15500 ((and (equal current "") (equal tags "")))
15501 ((re-search-forward
15502 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15503 (point-at-eol) t)
15504 (if (equal tags "")
15505 (setq rpl "")
15506 (goto-char (match-beginning 0))
15507 (setq c0 (current-column) p0 (point)
15508 c1 (max (1+ c0) (if (> org-tags-column 0)
15509 org-tags-column
15510 (- (- org-tags-column) (length tags))))
15511 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15512 (replace-match rpl t t)
15513 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15514 tags)
15515 (t (error "Tags alignment failed")))
15516 (move-to-column col)
15517 (unless just-align
15518 (run-hooks 'org-after-tags-change-hook)))))
15520 (defun org-change-tag-in-region (beg end tag off)
15521 "Add or remove TAG for each entry in the region.
15522 This works in the agenda, and also in an org-mode buffer."
15523 (interactive
15524 (list (region-beginning) (region-end)
15525 (let ((org-last-tags-completion-table
15526 (if (org-mode-p)
15527 (org-get-buffer-tags)
15528 (org-global-tags-completion-table))))
15529 (completing-read
15530 "Tag: " 'org-tags-completion-function nil nil nil
15531 'org-tags-history))
15532 (progn
15533 (message "[s]et or [r]emove? ")
15534 (equal (read-char-exclusive) ?r))))
15535 (if (fboundp 'deactivate-mark) (deactivate-mark))
15536 (let ((agendap (equal major-mode 'org-agenda-mode))
15537 l1 l2 m buf pos newhead (cnt 0))
15538 (goto-char end)
15539 (setq l2 (1- (org-current-line)))
15540 (goto-char beg)
15541 (setq l1 (org-current-line))
15542 (loop for l from l1 to l2 do
15543 (goto-line l)
15544 (setq m (get-text-property (point) 'org-hd-marker))
15545 (when (or (and (org-mode-p) (org-on-heading-p))
15546 (and agendap m))
15547 (setq buf (if agendap (marker-buffer m) (current-buffer))
15548 pos (if agendap m (point)))
15549 (with-current-buffer buf
15550 (save-excursion
15551 (save-restriction
15552 (goto-char pos)
15553 (setq cnt (1+ cnt))
15554 (org-toggle-tag tag (if off 'off 'on))
15555 (setq newhead (org-get-heading)))))
15556 (and agendap (org-agenda-change-all-lines newhead m))))
15557 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15559 (defun org-tags-completion-function (string predicate &optional flag)
15560 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15561 (confirm (lambda (x) (stringp (car x)))))
15562 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15563 (setq s1 (match-string 1 string)
15564 s2 (match-string 2 string))
15565 (setq s1 "" s2 string))
15566 (cond
15567 ((eq flag nil)
15568 ;; try completion
15569 (setq rtn (try-completion s2 ctable confirm))
15570 (if (stringp rtn)
15571 (setq rtn
15572 (concat s1 s2 (substring rtn (length s2))
15573 (if (and org-add-colon-after-tag-completion
15574 (assoc rtn ctable))
15575 ":" ""))))
15576 rtn)
15577 ((eq flag t)
15578 ;; all-completions
15579 (all-completions s2 ctable confirm)
15581 ((eq flag 'lambda)
15582 ;; exact match?
15583 (assoc s2 ctable)))
15586 (defun org-fast-tag-insert (kwd tags face &optional end)
15587 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15588 (insert (format "%-12s" (concat kwd ":"))
15589 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15590 (or end "")))
15592 (defun org-fast-tag-show-exit (flag)
15593 (save-excursion
15594 (goto-line 3)
15595 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15596 (replace-match ""))
15597 (when flag
15598 (end-of-line 1)
15599 (move-to-column (- (window-width) 19) t)
15600 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15602 (defun org-set-current-tags-overlay (current prefix)
15603 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15604 (if (featurep 'xemacs)
15605 (org-overlay-display org-tags-overlay (concat prefix s)
15606 'secondary-selection)
15607 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15608 (org-overlay-display org-tags-overlay (concat prefix s)))))
15610 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15611 "Fast tag selection with single keys.
15612 CURRENT is the current list of tags in the headline, INHERITED is the
15613 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15614 possibly with grouping information. TODO-TABLE is a similar table with
15615 TODO keywords, should these have keys assigned to them.
15616 If the keys are nil, a-z are automatically assigned.
15617 Returns the new tags string, or nil to not change the current settings."
15618 (let* ((fulltable (append table todo-table))
15619 (maxlen (apply 'max (mapcar
15620 (lambda (x)
15621 (if (stringp (car x)) (string-width (car x)) 0))
15622 fulltable)))
15623 (buf (current-buffer))
15624 (expert (eq org-fast-tag-selection-single-key 'expert))
15625 (buffer-tags nil)
15626 (fwidth (+ maxlen 3 1 3))
15627 (ncol (/ (- (window-width) 4) fwidth))
15628 (i-face 'org-done)
15629 (c-face 'org-todo)
15630 tg cnt e c char c1 c2 ntable tbl rtn
15631 ov-start ov-end ov-prefix
15632 (exit-after-next org-fast-tag-selection-single-key)
15633 (done-keywords org-done-keywords)
15634 groups ingroup)
15635 (save-excursion
15636 (beginning-of-line 1)
15637 (if (looking-at
15638 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15639 (setq ov-start (match-beginning 1)
15640 ov-end (match-end 1)
15641 ov-prefix "")
15642 (setq ov-start (1- (point-at-eol))
15643 ov-end (1+ ov-start))
15644 (skip-chars-forward "^\n\r")
15645 (setq ov-prefix
15646 (concat
15647 (buffer-substring (1- (point)) (point))
15648 (if (> (current-column) org-tags-column)
15650 (make-string (- org-tags-column (current-column)) ?\ ))))))
15651 (org-move-overlay org-tags-overlay ov-start ov-end)
15652 (save-window-excursion
15653 (if expert
15654 (set-buffer (get-buffer-create " *Org tags*"))
15655 (delete-other-windows)
15656 (split-window-vertically)
15657 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15658 (erase-buffer)
15659 (org-set-local 'org-done-keywords done-keywords)
15660 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15661 (org-fast-tag-insert "Current" current c-face "\n\n")
15662 (org-fast-tag-show-exit exit-after-next)
15663 (org-set-current-tags-overlay current ov-prefix)
15664 (setq tbl fulltable char ?a cnt 0)
15665 (while (setq e (pop tbl))
15666 (cond
15667 ((equal e '(:startgroup))
15668 (push '() groups) (setq ingroup t)
15669 (when (not (= cnt 0))
15670 (setq cnt 0)
15671 (insert "\n"))
15672 (insert "{ "))
15673 ((equal e '(:endgroup))
15674 (setq ingroup nil cnt 0)
15675 (insert "}\n"))
15677 (setq tg (car e) c2 nil)
15678 (if (cdr e)
15679 (setq c (cdr e))
15680 ;; automatically assign a character.
15681 (setq c1 (string-to-char
15682 (downcase (substring
15683 tg (if (= (string-to-char tg) ?@) 1 0)))))
15684 (if (or (rassoc c1 ntable) (rassoc c1 table))
15685 (while (or (rassoc char ntable) (rassoc char table))
15686 (setq char (1+ char)))
15687 (setq c2 c1))
15688 (setq c (or c2 char)))
15689 (if ingroup (push tg (car groups)))
15690 (setq tg (org-add-props tg nil 'face
15691 (cond
15692 ((not (assoc tg table))
15693 (org-get-todo-face tg))
15694 ((member tg current) c-face)
15695 ((member tg inherited) i-face)
15696 (t nil))))
15697 (if (and (= cnt 0) (not ingroup)) (insert " "))
15698 (insert "[" c "] " tg (make-string
15699 (- fwidth 4 (length tg)) ?\ ))
15700 (push (cons tg c) ntable)
15701 (when (= (setq cnt (1+ cnt)) ncol)
15702 (insert "\n")
15703 (if ingroup (insert " "))
15704 (setq cnt 0)))))
15705 (setq ntable (nreverse ntable))
15706 (insert "\n")
15707 (goto-char (point-min))
15708 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15709 (fit-window-to-buffer))
15710 (setq rtn
15711 (catch 'exit
15712 (while t
15713 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15714 (if groups " [!] no groups" " [!]groups")
15715 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15716 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15717 (cond
15718 ((= c ?\r) (throw 'exit t))
15719 ((= c ?!)
15720 (setq groups (not groups))
15721 (goto-char (point-min))
15722 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15723 ((= c ?\C-c)
15724 (if (not expert)
15725 (org-fast-tag-show-exit
15726 (setq exit-after-next (not exit-after-next)))
15727 (setq expert nil)
15728 (delete-other-windows)
15729 (split-window-vertically)
15730 (org-switch-to-buffer-other-window " *Org tags*")
15731 (and (fboundp 'fit-window-to-buffer)
15732 (fit-window-to-buffer))))
15733 ((or (= c ?\C-g)
15734 (and (= c ?q) (not (rassoc c ntable))))
15735 (org-detach-overlay org-tags-overlay)
15736 (setq quit-flag t))
15737 ((= c ?\ )
15738 (setq current nil)
15739 (if exit-after-next (setq exit-after-next 'now)))
15740 ((= c ?\t)
15741 (condition-case nil
15742 (setq tg (completing-read
15743 "Tag: "
15744 (or buffer-tags
15745 (with-current-buffer buf
15746 (org-get-buffer-tags)))))
15747 (quit (setq tg "")))
15748 (when (string-match "\\S-" tg)
15749 (add-to-list 'buffer-tags (list tg))
15750 (if (member tg current)
15751 (setq current (delete tg current))
15752 (push tg current)))
15753 (if exit-after-next (setq exit-after-next 'now)))
15754 ((setq e (rassoc c todo-table) tg (car e))
15755 (with-current-buffer buf
15756 (save-excursion (org-todo tg)))
15757 (if exit-after-next (setq exit-after-next 'now)))
15758 ((setq e (rassoc c ntable) tg (car e))
15759 (if (member tg current)
15760 (setq current (delete tg current))
15761 (loop for g in groups do
15762 (if (member tg g)
15763 (mapc (lambda (x)
15764 (setq current (delete x current)))
15765 g)))
15766 (push tg current))
15767 (if exit-after-next (setq exit-after-next 'now))))
15769 ;; Create a sorted list
15770 (setq current
15771 (sort current
15772 (lambda (a b)
15773 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15774 (if (eq exit-after-next 'now) (throw 'exit t))
15775 (goto-char (point-min))
15776 (beginning-of-line 2)
15777 (delete-region (point) (point-at-eol))
15778 (org-fast-tag-insert "Current" current c-face)
15779 (org-set-current-tags-overlay current ov-prefix)
15780 (while (re-search-forward
15781 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15782 (setq tg (match-string 1))
15783 (add-text-properties
15784 (match-beginning 1) (match-end 1)
15785 (list 'face
15786 (cond
15787 ((member tg current) c-face)
15788 ((member tg inherited) i-face)
15789 (t (get-text-property (match-beginning 1) 'face))))))
15790 (goto-char (point-min)))))
15791 (org-detach-overlay org-tags-overlay)
15792 (if rtn
15793 (mapconcat 'identity current ":")
15794 nil))))
15796 (defun org-get-tags-string ()
15797 "Get the TAGS string in the current headline."
15798 (unless (org-on-heading-p t)
15799 (error "Not on a heading"))
15800 (save-excursion
15801 (beginning-of-line 1)
15802 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15803 (org-match-string-no-properties 1)
15804 "")))
15806 (defun org-get-tags ()
15807 "Get the list of tags specified in the current headline."
15808 (org-split-string (org-get-tags-string) ":"))
15810 (defun org-get-buffer-tags ()
15811 "Get a table of all tags used in the buffer, for completion."
15812 (let (tags)
15813 (save-excursion
15814 (goto-char (point-min))
15815 (while (re-search-forward
15816 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15817 (when (equal (char-after (point-at-bol 0)) ?*)
15818 (mapc (lambda (x) (add-to-list 'tags x))
15819 (org-split-string (org-match-string-no-properties 1) ":")))))
15820 (mapcar 'list tags)))
15823 ;;;; Properties
15825 ;;; Setting and retrieving properties
15827 (defconst org-special-properties
15828 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15829 "TIMESTAMP" "TIMESTAMP_IA")
15830 "The special properties valid in Org-mode.
15832 These are properties that are not defined in the property drawer,
15833 but in some other way.")
15835 (defconst org-default-properties
15836 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15837 "LOCATION" "LOGGING" "COLUMNS")
15838 "Some properties that are used by Org-mode for various purposes.
15839 Being in this list makes sure that they are offered for completion.")
15841 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15842 "Regular expression matching the first line of a property drawer.")
15844 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15845 "Regular expression matching the first line of a property drawer.")
15847 (defun org-property-action ()
15848 "Do an action on properties."
15849 (interactive)
15850 (let (c)
15851 (org-at-property-p)
15852 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15853 (setq c (read-char-exclusive))
15854 (cond
15855 ((equal c ?s)
15856 (call-interactively 'org-set-property))
15857 ((equal c ?d)
15858 (call-interactively 'org-delete-property))
15859 ((equal c ?D)
15860 (call-interactively 'org-delete-property-globally))
15861 ((equal c ?c)
15862 (call-interactively 'org-compute-property-at-point))
15863 (t (error "No such property action %c" c)))))
15865 (defun org-at-property-p ()
15866 "Is the cursor in a property line?"
15867 ;; FIXME: Does not check if we are actually in the drawer.
15868 ;; FIXME: also returns true on any drawers.....
15869 ;; This is used by C-c C-c for property action.
15870 (save-excursion
15871 (beginning-of-line 1)
15872 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15874 (defmacro org-with-point-at (pom &rest body)
15875 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15876 (declare (indent 1) (debug t))
15877 `(save-excursion
15878 (if (markerp pom) (set-buffer (marker-buffer pom)))
15879 (save-excursion
15880 (goto-char (or pom (point)))
15881 ,@body)))
15883 (defun org-get-property-block (&optional beg end force)
15884 "Return the (beg . end) range of the body of the property drawer.
15885 BEG and END can be beginning and end of subtree, if not given
15886 they will be found.
15887 If the drawer does not exist and FORCE is non-nil, create the drawer."
15888 (catch 'exit
15889 (save-excursion
15890 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15891 (end (or end (progn (outline-next-heading) (point)))))
15892 (goto-char beg)
15893 (if (re-search-forward org-property-start-re end t)
15894 (setq beg (1+ (match-end 0)))
15895 (if force
15896 (save-excursion
15897 (org-insert-property-drawer)
15898 (setq end (progn (outline-next-heading) (point))))
15899 (throw 'exit nil))
15900 (goto-char beg)
15901 (if (re-search-forward org-property-start-re end t)
15902 (setq beg (1+ (match-end 0)))))
15903 (if (re-search-forward org-property-end-re end t)
15904 (setq end (match-beginning 0))
15905 (or force (throw 'exit nil))
15906 (goto-char beg)
15907 (setq end beg)
15908 (org-indent-line-function)
15909 (insert ":END:\n"))
15910 (cons beg end)))))
15912 (defun org-entry-properties (&optional pom which)
15913 "Get all properties of the entry at point-or-marker POM.
15914 This includes the TODO keyword, the tags, time strings for deadline,
15915 scheduled, and clocking, and any additional properties defined in the
15916 entry. The return value is an alist, keys may occur multiple times
15917 if the property key was used several times.
15918 POM may also be nil, in which case the current entry is used.
15919 If WHICH is nil or `all', get all properties. If WHICH is
15920 `special' or `standard', only get that subclass."
15921 (setq which (or which 'all))
15922 (org-with-point-at pom
15923 (let ((clockstr (substring org-clock-string 0 -1))
15924 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15925 beg end range props sum-props key value string clocksum)
15926 (save-excursion
15927 (when (condition-case nil (org-back-to-heading t) (error nil))
15928 (setq beg (point))
15929 (setq sum-props (get-text-property (point) 'org-summaries))
15930 (setq clocksum (get-text-property (point) :org-clock-minutes))
15931 (outline-next-heading)
15932 (setq end (point))
15933 (when (memq which '(all special))
15934 ;; Get the special properties, like TODO and tags
15935 (goto-char beg)
15936 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15937 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15938 (when (looking-at org-priority-regexp)
15939 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15940 (when (and (setq value (org-get-tags-string))
15941 (string-match "\\S-" value))
15942 (push (cons "TAGS" value) props))
15943 (when (setq value (org-get-tags-at))
15944 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15945 props))
15946 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15947 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15948 string (if (equal key clockstr)
15949 (org-no-properties
15950 (org-trim
15951 (buffer-substring
15952 (match-beginning 3) (goto-char (point-at-eol)))))
15953 (substring (org-match-string-no-properties 3) 1 -1)))
15954 (unless key
15955 (if (= (char-after (match-beginning 3)) ?\[)
15956 (setq key "TIMESTAMP_IA")
15957 (setq key "TIMESTAMP")))
15958 (when (or (equal key clockstr) (not (assoc key props)))
15959 (push (cons key string) props)))
15963 (when (memq which '(all standard))
15964 ;; Get the standard properties, like :PORP: ...
15965 (setq range (org-get-property-block beg end))
15966 (when range
15967 (goto-char (car range))
15968 (while (re-search-forward
15969 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15970 (cdr range) t)
15971 (setq key (org-match-string-no-properties 1)
15972 value (org-trim (or (org-match-string-no-properties 2) "")))
15973 (unless (member key excluded)
15974 (push (cons key (or value "")) props)))))
15975 (if clocksum
15976 (push (cons "CLOCKSUM"
15977 (org-column-number-to-string (/ (float clocksum) 60.)
15978 'add_times))
15979 props))
15980 (append sum-props (nreverse props)))))))
15982 (defun org-entry-get (pom property &optional inherit)
15983 "Get value of PROPERTY for entry at point-or-marker POM.
15984 If INHERIT is non-nil and the entry does not have the property,
15985 then also check higher levels of the hierarchy.
15986 If the property is present but empty, the return value is the empty string.
15987 If the property is not present at all, nil is returned."
15988 (org-with-point-at pom
15989 (if inherit
15990 (org-entry-get-with-inheritance property)
15991 (if (member property org-special-properties)
15992 ;; We need a special property. Use brute force, get all properties.
15993 (cdr (assoc property (org-entry-properties nil 'special)))
15994 (let ((range (org-get-property-block)))
15995 (if (and range
15996 (goto-char (car range))
15997 (re-search-forward
15998 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15999 (cdr range) t))
16000 ;; Found the property, return it.
16001 (if (match-end 1)
16002 (org-match-string-no-properties 1)
16003 "")))))))
16005 (defun org-entry-delete (pom property)
16006 "Delete the property PROPERTY from entry at point-or-marker POM."
16007 (org-with-point-at pom
16008 (if (member property org-special-properties)
16009 nil ; cannot delete these properties.
16010 (let ((range (org-get-property-block)))
16011 (if (and range
16012 (goto-char (car range))
16013 (re-search-forward
16014 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16015 (cdr range) t))
16016 (progn
16017 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16019 nil)))))
16021 ;; Multi-values properties are properties that contain multiple values
16022 ;; These values are assumed to be single words, separated by whitespace.
16023 (defun org-entry-add-to-multivalued-property (pom property value)
16024 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16025 (let* ((old (org-entry-get pom property))
16026 (values (and old (org-split-string old "[ \t]"))))
16027 (unless (member value values)
16028 (setq values (cons value values))
16029 (org-entry-put pom property
16030 (mapconcat 'identity values " ")))))
16032 (defun org-entry-remove-from-multivalued-property (pom property value)
16033 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16034 (let* ((old (org-entry-get pom property))
16035 (values (and old (org-split-string old "[ \t]"))))
16036 (when (member value values)
16037 (setq values (delete value values))
16038 (org-entry-put pom property
16039 (mapconcat 'identity values " ")))))
16041 (defun org-entry-member-in-multivalued-property (pom property value)
16042 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16043 (let* ((old (org-entry-get pom property))
16044 (values (and old (org-split-string old "[ \t]"))))
16045 (member value values)))
16047 (defvar org-entry-property-inherited-from (make-marker))
16049 (defun org-entry-get-with-inheritance (property)
16050 "Get entry property, and search higher levels if not present."
16051 (let (tmp)
16052 (save-excursion
16053 (save-restriction
16054 (widen)
16055 (catch 'ex
16056 (while t
16057 (when (setq tmp (org-entry-get nil property))
16058 (org-back-to-heading t)
16059 (move-marker org-entry-property-inherited-from (point))
16060 (throw 'ex tmp))
16061 (or (org-up-heading-safe) (throw 'ex nil)))))
16062 (or tmp (cdr (assoc property org-local-properties))
16063 (cdr (assoc property org-global-properties))))))
16065 (defun org-entry-put (pom property value)
16066 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16067 (org-with-point-at pom
16068 (org-back-to-heading t)
16069 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16070 range)
16071 (cond
16072 ((equal property "TODO")
16073 (when (and (stringp value) (string-match "\\S-" value)
16074 (not (member value org-todo-keywords-1)))
16075 (error "\"%s\" is not a valid TODO state" value))
16076 (if (or (not value)
16077 (not (string-match "\\S-" value)))
16078 (setq value 'none))
16079 (org-todo value)
16080 (org-set-tags nil 'align))
16081 ((equal property "PRIORITY")
16082 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16083 (string-to-char value) ?\ ))
16084 (org-set-tags nil 'align))
16085 ((equal property "SCHEDULED")
16086 (if (re-search-forward org-scheduled-time-regexp end t)
16087 (cond
16088 ((eq value 'earlier) (org-timestamp-change -1 'day))
16089 ((eq value 'later) (org-timestamp-change 1 'day))
16090 (t (call-interactively 'org-schedule)))
16091 (call-interactively 'org-schedule)))
16092 ((equal property "DEADLINE")
16093 (if (re-search-forward org-deadline-time-regexp end t)
16094 (cond
16095 ((eq value 'earlier) (org-timestamp-change -1 'day))
16096 ((eq value 'later) (org-timestamp-change 1 'day))
16097 (t (call-interactively 'org-deadline)))
16098 (call-interactively 'org-deadline)))
16099 ((member property org-special-properties)
16100 (error "The %s property can not yet be set with `org-entry-put'"
16101 property))
16102 (t ; a non-special property
16103 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16104 (setq range (org-get-property-block beg end 'force))
16105 (goto-char (car range))
16106 (if (re-search-forward
16107 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16108 (progn
16109 (delete-region (match-beginning 1) (match-end 1))
16110 (goto-char (match-beginning 1)))
16111 (goto-char (cdr range))
16112 (insert "\n")
16113 (backward-char 1)
16114 (org-indent-line-function)
16115 (insert ":" property ":"))
16116 (and value (insert " " value))
16117 (org-indent-line-function)))))))
16119 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16120 "Get all property keys in the current buffer.
16121 With INCLUDE-SPECIALS, also list the special properties that relect things
16122 like tags and TODO state.
16123 With INCLUDE-DEFAULTS, also include properties that has special meaning
16124 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16125 With INCLUDE-COLUMNS, also include property names given in COLUMN
16126 formats in the current buffer."
16127 (let (rtn range cfmt cols s p)
16128 (save-excursion
16129 (save-restriction
16130 (widen)
16131 (goto-char (point-min))
16132 (while (re-search-forward org-property-start-re nil t)
16133 (setq range (org-get-property-block))
16134 (goto-char (car range))
16135 (while (re-search-forward
16136 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16137 (cdr range) t)
16138 (add-to-list 'rtn (org-match-string-no-properties 1)))
16139 (outline-next-heading))))
16141 (when include-specials
16142 (setq rtn (append org-special-properties rtn)))
16144 (when include-defaults
16145 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16147 (when include-columns
16148 (save-excursion
16149 (save-restriction
16150 (widen)
16151 (goto-char (point-min))
16152 (while (re-search-forward
16153 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16154 nil t)
16155 (setq cfmt (match-string 2) s 0)
16156 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16157 cfmt s)
16158 (setq s (match-end 0)
16159 p (match-string 1 cfmt))
16160 (unless (or (equal p "ITEM")
16161 (member p org-special-properties))
16162 (add-to-list 'rtn (match-string 1 cfmt))))))))
16164 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16166 (defun org-property-values (key)
16167 "Return a list of all values of property KEY."
16168 (save-excursion
16169 (save-restriction
16170 (widen)
16171 (goto-char (point-min))
16172 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16173 values)
16174 (while (re-search-forward re nil t)
16175 (add-to-list 'values (org-trim (match-string 1))))
16176 (delete "" values)))))
16178 (defun org-insert-property-drawer ()
16179 "Insert a property drawer into the current entry."
16180 (interactive)
16181 (org-back-to-heading t)
16182 (looking-at outline-regexp)
16183 (let ((indent (- (match-end 0)(match-beginning 0)))
16184 (beg (point))
16185 (re (concat "^[ \t]*" org-keyword-time-regexp))
16186 end hiddenp)
16187 (outline-next-heading)
16188 (setq end (point))
16189 (goto-char beg)
16190 (while (re-search-forward re end t))
16191 (setq hiddenp (org-invisible-p))
16192 (end-of-line 1)
16193 (and (equal (char-after) ?\n) (forward-char 1))
16194 (org-skip-over-state-notes)
16195 (skip-chars-backward " \t\n\r")
16196 (if (eq (char-before) ?*) (forward-char 1))
16197 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16198 (beginning-of-line 0)
16199 (indent-to-column indent)
16200 (beginning-of-line 2)
16201 (indent-to-column indent)
16202 (beginning-of-line 0)
16203 (if hiddenp
16204 (save-excursion
16205 (org-back-to-heading t)
16206 (hide-entry))
16207 (org-flag-drawer t))))
16209 (defun org-set-property (property value)
16210 "In the current entry, set PROPERTY to VALUE.
16211 When called interactively, this will prompt for a property name, offering
16212 completion on existing and default properties. And then it will prompt
16213 for a value, offering competion either on allowed values (via an inherited
16214 xxx_ALL property) or on existing values in other instances of this property
16215 in the current file."
16216 (interactive
16217 (let* ((prop (completing-read
16218 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16219 (cur (org-entry-get nil prop))
16220 (allowed (org-property-get-allowed-values nil prop 'table))
16221 (existing (mapcar 'list (org-property-values prop)))
16222 (val (if allowed
16223 (completing-read "Value: " allowed nil 'req-match)
16224 (completing-read
16225 (concat "Value" (if (and cur (string-match "\\S-" cur))
16226 (concat "[" cur "]") "")
16227 ": ")
16228 existing nil nil "" nil cur))))
16229 (list prop (if (equal val "") cur val))))
16230 (unless (equal (org-entry-get nil property) value)
16231 (org-entry-put nil property value)))
16233 (defun org-delete-property (property)
16234 "In the current entry, delete PROPERTY."
16235 (interactive
16236 (let* ((prop (completing-read
16237 "Property: " (org-entry-properties nil 'standard))))
16238 (list prop)))
16239 (message "Property %s %s" property
16240 (if (org-entry-delete nil property)
16241 "deleted"
16242 "was not present in the entry")))
16244 (defun org-delete-property-globally (property)
16245 "Remove PROPERTY globally, from all entries."
16246 (interactive
16247 (let* ((prop (completing-read
16248 "Globally remove property: "
16249 (mapcar 'list (org-buffer-property-keys)))))
16250 (list prop)))
16251 (save-excursion
16252 (save-restriction
16253 (widen)
16254 (goto-char (point-min))
16255 (let ((cnt 0))
16256 (while (re-search-forward
16257 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16258 nil t)
16259 (setq cnt (1+ cnt))
16260 (replace-match ""))
16261 (message "Property \"%s\" removed from %d entries" property cnt)))))
16263 (defvar org-columns-current-fmt-compiled) ; defined below
16265 (defun org-compute-property-at-point ()
16266 "Compute the property at point.
16267 This looks for an enclosing column format, extracts the operator and
16268 then applies it to the proerty in the column format's scope."
16269 (interactive)
16270 (unless (org-at-property-p)
16271 (error "Not at a property"))
16272 (let ((prop (org-match-string-no-properties 2)))
16273 (org-columns-get-format-and-top-level)
16274 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16275 (error "No operator defined for property %s" prop))
16276 (org-columns-compute prop)))
16278 (defun org-property-get-allowed-values (pom property &optional table)
16279 "Get allowed values for the property PROPERTY.
16280 When TABLE is non-nil, return an alist that can directly be used for
16281 completion."
16282 (let (vals)
16283 (cond
16284 ((equal property "TODO")
16285 (setq vals (org-with-point-at pom
16286 (append org-todo-keywords-1 '("")))))
16287 ((equal property "PRIORITY")
16288 (let ((n org-lowest-priority))
16289 (while (>= n org-highest-priority)
16290 (push (char-to-string n) vals)
16291 (setq n (1- n)))))
16292 ((member property org-special-properties))
16294 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16296 (when (and vals (string-match "\\S-" vals))
16297 (setq vals (car (read-from-string (concat "(" vals ")"))))
16298 (setq vals (mapcar (lambda (x)
16299 (cond ((stringp x) x)
16300 ((numberp x) (number-to-string x))
16301 ((symbolp x) (symbol-name x))
16302 (t "???")))
16303 vals)))))
16304 (if table (mapcar 'list vals) vals)))
16306 (defun org-property-previous-allowed-value (&optional previous)
16307 "Switch to the next allowed value for this property."
16308 (interactive)
16309 (org-property-next-allowed-value t))
16311 (defun org-property-next-allowed-value (&optional previous)
16312 "Switch to the next allowed value for this property."
16313 (interactive)
16314 (unless (org-at-property-p)
16315 (error "Not at a property"))
16316 (let* ((key (match-string 2))
16317 (value (match-string 3))
16318 (allowed (or (org-property-get-allowed-values (point) key)
16319 (and (member value '("[ ]" "[-]" "[X]"))
16320 '("[ ]" "[X]"))))
16321 nval)
16322 (unless allowed
16323 (error "Allowed values for this property have not been defined"))
16324 (if previous (setq allowed (reverse allowed)))
16325 (if (member value allowed)
16326 (setq nval (car (cdr (member value allowed)))))
16327 (setq nval (or nval (car allowed)))
16328 (if (equal nval value)
16329 (error "Only one allowed value for this property"))
16330 (org-at-property-p)
16331 (replace-match (concat " :" key ": " nval) t t)
16332 (org-indent-line-function)
16333 (beginning-of-line 1)
16334 (skip-chars-forward " \t")))
16336 (defun org-find-entry-with-id (ident)
16337 "Locate the entry that contains the ID property with exact value IDENT.
16338 IDENT can be a string, a symbol or a number, this function will search for
16339 the string representation of it.
16340 Return the position where this entry starts, or nil if there is no such entry."
16341 (let ((id (cond
16342 ((stringp ident) ident)
16343 ((symbol-name ident) (symbol-name ident))
16344 ((numberp ident) (number-to-string ident))
16345 (t (error "IDENT %s must be a string, symbol or number" ident))))
16346 (case-fold-search nil))
16347 (save-excursion
16348 (save-restriction
16349 (widen)
16350 (goto-char (point-min))
16351 (when (re-search-forward
16352 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16353 nil t)
16354 (org-back-to-heading)
16355 (point))))))
16357 ;;; Column View
16359 (defvar org-columns-overlays nil
16360 "Holds the list of current column overlays.")
16362 (defvar org-columns-current-fmt nil
16363 "Local variable, holds the currently active column format.")
16364 (defvar org-columns-current-fmt-compiled nil
16365 "Local variable, holds the currently active column format.
16366 This is the compiled version of the format.")
16367 (defvar org-columns-current-widths nil
16368 "Loval variable, holds the currently widths of fields.")
16369 (defvar org-columns-current-maxwidths nil
16370 "Loval variable, holds the currently active maximum column widths.")
16371 (defvar org-columns-begin-marker (make-marker)
16372 "Points to the position where last a column creation command was called.")
16373 (defvar org-columns-top-level-marker (make-marker)
16374 "Points to the position where current columns region starts.")
16376 (defvar org-columns-map (make-sparse-keymap)
16377 "The keymap valid in column display.")
16379 (defun org-columns-content ()
16380 "Switch to contents view while in columns view."
16381 (interactive)
16382 (org-overview)
16383 (org-content))
16385 (org-defkey org-columns-map "c" 'org-columns-content)
16386 (org-defkey org-columns-map "o" 'org-overview)
16387 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16388 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16389 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16390 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16391 (org-defkey org-columns-map "v" 'org-columns-show-value)
16392 (org-defkey org-columns-map "q" 'org-columns-quit)
16393 (org-defkey org-columns-map "r" 'org-columns-redo)
16394 (org-defkey org-columns-map "g" 'org-columns-redo)
16395 (org-defkey org-columns-map [left] 'backward-char)
16396 (org-defkey org-columns-map "\M-b" 'backward-char)
16397 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16398 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16399 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16400 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16401 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16402 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16403 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16404 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16405 (org-defkey org-columns-map "<" 'org-columns-narrow)
16406 (org-defkey org-columns-map ">" 'org-columns-widen)
16407 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16408 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16409 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16410 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16412 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16413 '("Column"
16414 ["Edit property" org-columns-edit-value t]
16415 ["Next allowed value" org-columns-next-allowed-value t]
16416 ["Previous allowed value" org-columns-previous-allowed-value t]
16417 ["Show full value" org-columns-show-value t]
16418 ["Edit allowed values" org-columns-edit-allowed t]
16419 "--"
16420 ["Edit column attributes" org-columns-edit-attributes t]
16421 ["Increase column width" org-columns-widen t]
16422 ["Decrease column width" org-columns-narrow t]
16423 "--"
16424 ["Move column right" org-columns-move-right t]
16425 ["Move column left" org-columns-move-left t]
16426 ["Add column" org-columns-new t]
16427 ["Delete column" org-columns-delete t]
16428 "--"
16429 ["CONTENTS" org-columns-content t]
16430 ["OVERVIEW" org-overview t]
16431 ["Refresh columns display" org-columns-redo t]
16432 "--"
16433 ["Open link" org-columns-open-link t]
16434 "--"
16435 ["Quit" org-columns-quit t]))
16437 (defun org-columns-new-overlay (beg end &optional string face)
16438 "Create a new column overlay and add it to the list."
16439 (let ((ov (org-make-overlay beg end)))
16440 (org-overlay-put ov 'face (or face 'secondary-selection))
16441 (org-overlay-display ov string face)
16442 (push ov org-columns-overlays)
16443 ov))
16445 (defun org-columns-display-here (&optional props)
16446 "Overlay the current line with column display."
16447 (interactive)
16448 (let* ((fmt org-columns-current-fmt-compiled)
16449 (beg (point-at-bol))
16450 (level-face (save-excursion
16451 (beginning-of-line 1)
16452 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16453 (org-get-level-face 2))))
16454 (color (list :foreground
16455 (face-attribute (or level-face 'default) :foreground)))
16456 props pom property ass width f string ov column val modval)
16457 ;; Check if the entry is in another buffer.
16458 (unless props
16459 (if (eq major-mode 'org-agenda-mode)
16460 (setq pom (or (get-text-property (point) 'org-hd-marker)
16461 (get-text-property (point) 'org-marker))
16462 props (if pom (org-entry-properties pom) nil))
16463 (setq props (org-entry-properties nil))))
16464 ;; Walk the format
16465 (while (setq column (pop fmt))
16466 (setq property (car column)
16467 ass (if (equal property "ITEM")
16468 (cons "ITEM"
16469 (save-match-data
16470 (org-no-properties
16471 (org-remove-tabs
16472 (buffer-substring-no-properties
16473 (point-at-bol) (point-at-eol))))))
16474 (assoc property props))
16475 width (or (cdr (assoc property org-columns-current-maxwidths))
16476 (nth 2 column)
16477 (length property))
16478 f (format "%%-%d.%ds | " width width)
16479 val (or (cdr ass) "")
16480 modval (if (equal property "ITEM")
16481 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16482 string (format f (or modval val)))
16483 ;; Create the overlay
16484 (org-unmodified
16485 (setq ov (org-columns-new-overlay
16486 beg (setq beg (1+ beg)) string
16487 (list color 'org-column)))
16488 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16489 (org-overlay-put ov 'keymap org-columns-map)
16490 (org-overlay-put ov 'org-columns-key property)
16491 (org-overlay-put ov 'org-columns-value (cdr ass))
16492 (org-overlay-put ov 'org-columns-value-modified modval)
16493 (org-overlay-put ov 'org-columns-pom pom)
16494 (org-overlay-put ov 'org-columns-format f))
16495 (if (or (not (char-after beg))
16496 (equal (char-after beg) ?\n))
16497 (let ((inhibit-read-only t))
16498 (save-excursion
16499 (goto-char beg)
16500 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16501 ;; Make the rest of the line disappear.
16502 (org-unmodified
16503 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16504 (org-overlay-put ov 'invisible t)
16505 (org-overlay-put ov 'keymap org-columns-map)
16506 (org-overlay-put ov 'intangible t)
16507 (push ov org-columns-overlays)
16508 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16509 (org-overlay-put ov 'keymap org-columns-map)
16510 (push ov org-columns-overlays)
16511 (let ((inhibit-read-only t))
16512 (put-text-property (max (point-min) (1- (point-at-bol)))
16513 (min (point-max) (1+ (point-at-eol)))
16514 'read-only "Type `e' to edit property")))))
16516 (defvar org-previous-header-line-format nil
16517 "The header line format before column view was turned on.")
16518 (defvar org-columns-inhibit-recalculation nil
16519 "Inhibit recomputing of columns on column view startup.")
16522 (defvar header-line-format)
16523 (defun org-columns-display-here-title ()
16524 "Overlay the newline before the current line with the table title."
16525 (interactive)
16526 (let ((fmt org-columns-current-fmt-compiled)
16527 string (title "")
16528 property width f column str widths)
16529 (while (setq column (pop fmt))
16530 (setq property (car column)
16531 str (or (nth 1 column) property)
16532 width (or (cdr (assoc property org-columns-current-maxwidths))
16533 (nth 2 column)
16534 (length str))
16535 widths (push width widths)
16536 f (format "%%-%d.%ds | " width width)
16537 string (format f str)
16538 title (concat title string)))
16539 (setq title (concat
16540 (org-add-props " " nil 'display '(space :align-to 0))
16541 (org-add-props title nil 'face '(:weight bold :underline t))))
16542 (org-set-local 'org-previous-header-line-format header-line-format)
16543 (org-set-local 'org-columns-current-widths (nreverse widths))
16544 (setq header-line-format title)))
16546 (defun org-columns-remove-overlays ()
16547 "Remove all currently active column overlays."
16548 (interactive)
16549 (when (marker-buffer org-columns-begin-marker)
16550 (with-current-buffer (marker-buffer org-columns-begin-marker)
16551 (when (local-variable-p 'org-previous-header-line-format)
16552 (setq header-line-format org-previous-header-line-format)
16553 (kill-local-variable 'org-previous-header-line-format))
16554 (move-marker org-columns-begin-marker nil)
16555 (move-marker org-columns-top-level-marker nil)
16556 (org-unmodified
16557 (mapc 'org-delete-overlay org-columns-overlays)
16558 (setq org-columns-overlays nil)
16559 (let ((inhibit-read-only t))
16560 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16562 (defun org-columns-cleanup-item (item fmt)
16563 "Remove from ITEM what is a column in the format FMT."
16564 (if (not org-complex-heading-regexp)
16565 item
16566 (when (string-match org-complex-heading-regexp item)
16567 (concat
16568 (org-add-props (concat (match-string 1 item) " ") nil
16569 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16570 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16571 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16572 " " (match-string 4 item)
16573 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16575 (defun org-columns-show-value ()
16576 "Show the full value of the property."
16577 (interactive)
16578 (let ((value (get-char-property (point) 'org-columns-value)))
16579 (message "Value is: %s" (or value ""))))
16581 (defun org-columns-quit ()
16582 "Remove the column overlays and in this way exit column editing."
16583 (interactive)
16584 (org-unmodified
16585 (org-columns-remove-overlays)
16586 (let ((inhibit-read-only t))
16587 (remove-text-properties (point-min) (point-max) '(read-only t))))
16588 (when (eq major-mode 'org-agenda-mode)
16589 (message
16590 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16592 (defun org-columns-check-computed ()
16593 "Check if this column value is computed.
16594 If yes, throw an error indicating that changing it does not make sense."
16595 (let ((val (get-char-property (point) 'org-columns-value)))
16596 (when (and (stringp val)
16597 (get-char-property 0 'org-computed val))
16598 (error "This value is computed from the entry's children"))))
16600 (defun org-columns-todo (&optional arg)
16601 "Change the TODO state during column view."
16602 (interactive "P")
16603 (org-columns-edit-value "TODO"))
16605 (defun org-columns-set-tags-or-toggle (&optional arg)
16606 "Toggle checkbox at point, or set tags for current headline."
16607 (interactive "P")
16608 (if (string-match "\\`\\[[ xX-]\\]\\'"
16609 (get-char-property (point) 'org-columns-value))
16610 (org-columns-next-allowed-value)
16611 (org-columns-edit-value "TAGS")))
16613 (defun org-columns-edit-value (&optional key)
16614 "Edit the value of the property at point in column view.
16615 Where possible, use the standard interface for changing this line."
16616 (interactive)
16617 (org-columns-check-computed)
16618 (let* ((external-key key)
16619 (col (current-column))
16620 (key (or key (get-char-property (point) 'org-columns-key)))
16621 (value (get-char-property (point) 'org-columns-value))
16622 (bol (point-at-bol)) (eol (point-at-eol))
16623 (pom (or (get-text-property bol 'org-hd-marker)
16624 (point))) ; keep despite of compiler waring
16625 (line-overlays
16626 (delq nil (mapcar (lambda (x)
16627 (and (eq (overlay-buffer x) (current-buffer))
16628 (>= (overlay-start x) bol)
16629 (<= (overlay-start x) eol)
16631 org-columns-overlays)))
16632 nval eval allowed)
16633 (cond
16634 ((equal key "CLOCKSUM")
16635 (error "This special column cannot be edited"))
16636 ((equal key "ITEM")
16637 (setq eval '(org-with-point-at pom
16638 (org-edit-headline))))
16639 ((equal key "TODO")
16640 (setq eval '(org-with-point-at pom
16641 (let ((current-prefix-arg
16642 (if external-key current-prefix-arg '(4))))
16643 (call-interactively 'org-todo)))))
16644 ((equal key "PRIORITY")
16645 (setq eval '(org-with-point-at pom
16646 (call-interactively 'org-priority))))
16647 ((equal key "TAGS")
16648 (setq eval '(org-with-point-at pom
16649 (let ((org-fast-tag-selection-single-key
16650 (if (eq org-fast-tag-selection-single-key 'expert)
16651 t org-fast-tag-selection-single-key)))
16652 (call-interactively 'org-set-tags)))))
16653 ((equal key "DEADLINE")
16654 (setq eval '(org-with-point-at pom
16655 (call-interactively 'org-deadline))))
16656 ((equal key "SCHEDULED")
16657 (setq eval '(org-with-point-at pom
16658 (call-interactively 'org-schedule))))
16660 (setq allowed (org-property-get-allowed-values pom key 'table))
16661 (if allowed
16662 (setq nval (completing-read "Value: " allowed nil t))
16663 (setq nval (read-string "Edit: " value)))
16664 (setq nval (org-trim nval))
16665 (when (not (equal nval value))
16666 (setq eval '(org-entry-put pom key nval)))))
16667 (when eval
16668 (let ((inhibit-read-only t))
16669 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16670 (unwind-protect
16671 (progn
16672 (setq org-columns-overlays
16673 (org-delete-all line-overlays org-columns-overlays))
16674 (mapc 'org-delete-overlay line-overlays)
16675 (org-columns-eval eval))
16676 (org-columns-display-here))))
16677 (move-to-column col)
16678 (if (and (org-mode-p)
16679 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16680 (org-columns-update key))))
16682 (defun org-edit-headline () ; FIXME: this is not columns specific
16683 "Edit the current headline, the part without TODO keyword, TAGS."
16684 (org-back-to-heading)
16685 (when (looking-at org-todo-line-regexp)
16686 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16687 (txt (match-string 3))
16688 (post "")
16689 txt2)
16690 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16691 (setq post (match-string 0 txt)
16692 txt (substring txt 0 (match-beginning 0))))
16693 (setq txt2 (read-string "Edit: " txt))
16694 (when (not (equal txt txt2))
16695 (beginning-of-line 1)
16696 (insert pre txt2 post)
16697 (delete-region (point) (point-at-eol))
16698 (org-set-tags nil t)))))
16700 (defun org-columns-edit-allowed ()
16701 "Edit the list of allowed values for the current property."
16702 (interactive)
16703 (let* ((key (get-char-property (point) 'org-columns-key))
16704 (key1 (concat key "_ALL"))
16705 (allowed (org-entry-get (point) key1 t))
16706 nval)
16707 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16708 (setq nval (read-string "Allowed: " allowed))
16709 (org-entry-put
16710 (cond ((marker-position org-entry-property-inherited-from)
16711 org-entry-property-inherited-from)
16712 ((marker-position org-columns-top-level-marker)
16713 org-columns-top-level-marker))
16714 key1 nval)))
16716 (defmacro org-no-warnings (&rest body)
16717 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16719 (defun org-columns-eval (form)
16720 (let (hidep)
16721 (save-excursion
16722 (beginning-of-line 1)
16723 ;; `next-line' is needed here, because it skips invisible line.
16724 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16725 (setq hidep (org-on-heading-p 1)))
16726 (eval form)
16727 (and hidep (hide-entry))))
16729 (defun org-columns-previous-allowed-value ()
16730 "Switch to the previous allowed value for this column."
16731 (interactive)
16732 (org-columns-next-allowed-value t))
16734 (defun org-columns-next-allowed-value (&optional previous)
16735 "Switch to the next allowed value for this column."
16736 (interactive)
16737 (org-columns-check-computed)
16738 (let* ((col (current-column))
16739 (key (get-char-property (point) 'org-columns-key))
16740 (value (get-char-property (point) 'org-columns-value))
16741 (bol (point-at-bol)) (eol (point-at-eol))
16742 (pom (or (get-text-property bol 'org-hd-marker)
16743 (point))) ; keep despite of compiler waring
16744 (line-overlays
16745 (delq nil (mapcar (lambda (x)
16746 (and (eq (overlay-buffer x) (current-buffer))
16747 (>= (overlay-start x) bol)
16748 (<= (overlay-start x) eol)
16750 org-columns-overlays)))
16751 (allowed (or (org-property-get-allowed-values pom key)
16752 (and (memq
16753 (nth 4 (assoc key org-columns-current-fmt-compiled))
16754 '(checkbox checkbox-n-of-m checkbox-percent))
16755 '("[ ]" "[X]"))))
16756 nval)
16757 (when (equal key "ITEM")
16758 (error "Cannot edit item headline from here"))
16759 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16760 (error "Allowed values for this property have not been defined"))
16761 (if (member key '("SCHEDULED" "DEADLINE"))
16762 (setq nval (if previous 'earlier 'later))
16763 (if previous (setq allowed (reverse allowed)))
16764 (if (member value allowed)
16765 (setq nval (car (cdr (member value allowed)))))
16766 (setq nval (or nval (car allowed)))
16767 (if (equal nval value)
16768 (error "Only one allowed value for this property")))
16769 (let ((inhibit-read-only t))
16770 (remove-text-properties (1- bol) eol '(read-only t))
16771 (unwind-protect
16772 (progn
16773 (setq org-columns-overlays
16774 (org-delete-all line-overlays org-columns-overlays))
16775 (mapc 'org-delete-overlay line-overlays)
16776 (org-columns-eval '(org-entry-put pom key nval)))
16777 (org-columns-display-here)))
16778 (move-to-column col)
16779 (if (and (org-mode-p)
16780 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16781 (org-columns-update key))))
16783 (defun org-verify-version (task)
16784 (cond
16785 ((eq task 'columns)
16786 (if (or (featurep 'xemacs)
16787 (< emacs-major-version 22))
16788 (error "Emacs 22 is required for the columns feature")))))
16790 (defun org-columns-open-link (&optional arg)
16791 (interactive "P")
16792 (let ((value (get-char-property (point) 'org-columns-value)))
16793 (org-open-link-from-string value arg)))
16795 (defun org-open-link-from-string (s &optional arg)
16796 "Open a link in the string S, as if it was in Org-mode."
16797 (interactive)
16798 (with-temp-buffer
16799 (let ((org-inhibit-startup t))
16800 (org-mode)
16801 (insert s)
16802 (goto-char (point-min))
16803 (org-open-at-point arg))))
16805 (defun org-columns-get-format-and-top-level ()
16806 (let (fmt)
16807 (when (condition-case nil (org-back-to-heading) (error nil))
16808 (move-marker org-entry-property-inherited-from nil)
16809 (setq fmt (org-entry-get nil "COLUMNS" t)))
16810 (setq fmt (or fmt org-columns-default-format))
16811 (org-set-local 'org-columns-current-fmt fmt)
16812 (org-columns-compile-format fmt)
16813 (if (marker-position org-entry-property-inherited-from)
16814 (move-marker org-columns-top-level-marker
16815 org-entry-property-inherited-from)
16816 (move-marker org-columns-top-level-marker (point)))
16817 fmt))
16819 (defun org-columns ()
16820 "Turn on column view on an org-mode file."
16821 (interactive)
16822 (org-verify-version 'columns)
16823 (org-columns-remove-overlays)
16824 (move-marker org-columns-begin-marker (point))
16825 (let (beg end fmt cache maxwidths)
16826 (setq fmt (org-columns-get-format-and-top-level))
16827 (save-excursion
16828 (goto-char org-columns-top-level-marker)
16829 (setq beg (point))
16830 (unless org-columns-inhibit-recalculation
16831 (org-columns-compute-all))
16832 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16833 (point-max)))
16834 ;; Get and cache the properties
16835 (goto-char beg)
16836 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
16837 (save-excursion
16838 (save-restriction
16839 (narrow-to-region beg end)
16840 (org-clock-sum))))
16841 (while (re-search-forward (concat "^" outline-regexp) end t)
16842 (push (cons (org-current-line) (org-entry-properties)) cache))
16843 (when cache
16844 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16845 (org-set-local 'org-columns-current-maxwidths maxwidths)
16846 (org-columns-display-here-title)
16847 (mapc (lambda (x)
16848 (goto-line (car x))
16849 (org-columns-display-here (cdr x)))
16850 cache)))))
16852 (defun org-columns-new (&optional prop title width op fmt &rest rest)
16853 "Insert a new column, to the leeft o the current column."
16854 (interactive)
16855 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16856 cell)
16857 (setq prop (completing-read
16858 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
16859 nil nil prop))
16860 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16861 (setq width (read-string "Column width: " (if width (number-to-string width))))
16862 (if (string-match "\\S-" width)
16863 (setq width (string-to-number width))
16864 (setq width nil))
16865 (setq fmt (completing-read "Summary [none]: "
16866 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
16867 nil t))
16868 (if (string-match "\\S-" fmt)
16869 (setq fmt (intern fmt))
16870 (setq fmt nil))
16871 (if (eq fmt 'none) (setq fmt nil))
16872 (if editp
16873 (progn
16874 (setcar editp prop)
16875 (setcdr editp (list title width nil fmt)))
16876 (setq cell (nthcdr (1- (current-column))
16877 org-columns-current-fmt-compiled))
16878 (setcdr cell (cons (list prop title width nil fmt)
16879 (cdr cell))))
16880 (org-columns-store-format)
16881 (org-columns-redo)))
16883 (defun org-columns-delete ()
16884 "Delete the column at point from columns view."
16885 (interactive)
16886 (let* ((n (current-column))
16887 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16888 (when (y-or-n-p
16889 (format "Are you sure you want to remove column \"%s\"? " title))
16890 (setq org-columns-current-fmt-compiled
16891 (delq (nth n org-columns-current-fmt-compiled)
16892 org-columns-current-fmt-compiled))
16893 (org-columns-store-format)
16894 (org-columns-redo)
16895 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16896 (backward-char 1)))))
16898 (defun org-columns-edit-attributes ()
16899 "Edit the attributes of the current column."
16900 (interactive)
16901 (let* ((n (current-column))
16902 (info (nth n org-columns-current-fmt-compiled)))
16903 (apply 'org-columns-new info)))
16905 (defun org-columns-widen (arg)
16906 "Make the column wider by ARG characters."
16907 (interactive "p")
16908 (let* ((n (current-column))
16909 (entry (nth n org-columns-current-fmt-compiled))
16910 (width (or (nth 2 entry)
16911 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16912 (setq width (max 1 (+ width arg)))
16913 (setcar (nthcdr 2 entry) width)
16914 (org-columns-store-format)
16915 (org-columns-redo)))
16917 (defun org-columns-narrow (arg)
16918 "Make the column nrrower by ARG characters."
16919 (interactive "p")
16920 (org-columns-widen (- arg)))
16922 (defun org-columns-move-right ()
16923 "Swap this column with the one to the right."
16924 (interactive)
16925 (let* ((n (current-column))
16926 (cell (nthcdr n org-columns-current-fmt-compiled))
16928 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16929 (error "Cannot shift this column further to the right"))
16930 (setq e (car cell))
16931 (setcar cell (car (cdr cell)))
16932 (setcdr cell (cons e (cdr (cdr cell))))
16933 (org-columns-store-format)
16934 (org-columns-redo)
16935 (forward-char 1)))
16937 (defun org-columns-move-left ()
16938 "Swap this column with the one to the left."
16939 (interactive)
16940 (let* ((n (current-column)))
16941 (when (= n 0)
16942 (error "Cannot shift this column further to the left"))
16943 (backward-char 1)
16944 (org-columns-move-right)
16945 (backward-char 1)))
16947 (defun org-columns-store-format ()
16948 "Store the text version of the current columns format in appropriate place.
16949 This is either in the COLUMNS property of the node starting the current column
16950 display, or in the #+COLUMNS line of the current buffer."
16951 (let (fmt (cnt 0))
16952 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16953 (org-set-local 'org-columns-current-fmt fmt)
16954 (if (marker-position org-columns-top-level-marker)
16955 (save-excursion
16956 (goto-char org-columns-top-level-marker)
16957 (if (and (org-at-heading-p)
16958 (org-entry-get nil "COLUMNS"))
16959 (org-entry-put nil "COLUMNS" fmt)
16960 (goto-char (point-min))
16961 ;; Overwrite all #+COLUMNS lines....
16962 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16963 (setq cnt (1+ cnt))
16964 (replace-match (concat "#+COLUMNS: " fmt) t t))
16965 (unless (> cnt 0)
16966 (goto-char (point-min))
16967 (or (org-on-heading-p t) (outline-next-heading))
16968 (let ((inhibit-read-only t))
16969 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16970 (org-set-local 'org-columns-default-format fmt))))))
16972 (defvar org-overriding-columns-format nil
16973 "When set, overrides any other definition.")
16974 (defvar org-agenda-view-columns-initially nil
16975 "When set, switch to columns view immediately after creating the agenda.")
16977 (defun org-agenda-columns ()
16978 "Turn on column view in the agenda."
16979 (interactive)
16980 (org-verify-version 'columns)
16981 (org-columns-remove-overlays)
16982 (move-marker org-columns-begin-marker (point))
16983 (let (fmt cache maxwidths m)
16984 (cond
16985 ((and (local-variable-p 'org-overriding-columns-format)
16986 org-overriding-columns-format)
16987 (setq fmt org-overriding-columns-format))
16988 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16989 (setq fmt (org-entry-get m "COLUMNS" t)))
16990 ((and (boundp 'org-columns-current-fmt)
16991 (local-variable-p 'org-columns-current-fmt)
16992 org-columns-current-fmt)
16993 (setq fmt org-columns-current-fmt))
16994 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16995 (setq m (get-text-property m 'org-hd-marker))
16996 (setq fmt (org-entry-get m "COLUMNS" t))))
16997 (setq fmt (or fmt org-columns-default-format))
16998 (org-set-local 'org-columns-current-fmt fmt)
16999 (org-columns-compile-format fmt)
17000 (save-excursion
17001 ;; Get and cache the properties
17002 (goto-char (point-min))
17003 (while (not (eobp))
17004 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17005 (get-text-property (point) 'org-marker)))
17006 (push (cons (org-current-line) (org-entry-properties m)) cache))
17007 (beginning-of-line 2))
17008 (when cache
17009 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17010 (org-set-local 'org-columns-current-maxwidths maxwidths)
17011 (org-columns-display-here-title)
17012 (mapc (lambda (x)
17013 (goto-line (car x))
17014 (org-columns-display-here (cdr x)))
17015 cache)))))
17017 (defun org-columns-get-autowidth-alist (s cache)
17018 "Derive the maximum column widths from the format and the cache."
17019 (let ((start 0) rtn)
17020 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17021 (push (cons (match-string 1 s) 1) rtn)
17022 (setq start (match-end 0)))
17023 (mapc (lambda (x)
17024 (setcdr x (apply 'max
17025 (mapcar
17026 (lambda (y)
17027 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17028 cache))))
17029 rtn)
17030 rtn))
17032 (defun org-columns-compute-all ()
17033 "Compute all columns that have operators defined."
17034 (org-unmodified
17035 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17036 (let ((columns org-columns-current-fmt-compiled) col)
17037 (while (setq col (pop columns))
17038 (when (nth 3 col)
17039 (save-excursion
17040 (org-columns-compute (car col)))))))
17042 (defun org-columns-update (property)
17043 "Recompute PROPERTY, and update the columns display for it."
17044 (org-columns-compute property)
17045 (let (fmt val pos)
17046 (save-excursion
17047 (mapc (lambda (ov)
17048 (when (equal (org-overlay-get ov 'org-columns-key) property)
17049 (setq pos (org-overlay-start ov))
17050 (goto-char pos)
17051 (when (setq val (cdr (assoc property
17052 (get-text-property
17053 (point-at-bol) 'org-summaries))))
17054 (setq fmt (org-overlay-get ov 'org-columns-format))
17055 (org-overlay-put ov 'org-columns-value val)
17056 (org-overlay-put ov 'display (format fmt val)))))
17057 org-columns-overlays))))
17059 (defun org-columns-compute (property)
17060 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17061 (interactive)
17062 (let* ((re (concat "^" outline-regexp))
17063 (lmax 30) ; Does anyone use deeper levels???
17064 (lsum (make-vector lmax 0))
17065 (lflag (make-vector lmax nil))
17066 (level 0)
17067 (ass (assoc property org-columns-current-fmt-compiled))
17068 (format (nth 4 ass))
17069 (printf (nth 5 ass))
17070 (beg org-columns-top-level-marker)
17071 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17072 (save-excursion
17073 ;; Find the region to compute
17074 (goto-char beg)
17075 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17076 (goto-char end)
17077 ;; Walk the tree from the back and do the computations
17078 (while (re-search-backward re beg t)
17079 (setq sumpos (match-beginning 0)
17080 last-level level
17081 level (org-outline-level)
17082 val (org-entry-get nil property)
17083 valflag (and val (string-match "\\S-" val)))
17084 (cond
17085 ((< level last-level)
17086 ;; put the sum of lower levels here as a property
17087 (setq sum (aref lsum last-level) ; current sum
17088 flag (aref lflag last-level) ; any valid entries from children?
17089 str (org-column-number-to-string sum format printf)
17090 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17091 useval (if flag str1 (if valflag val ""))
17092 sum-alist (get-text-property sumpos 'org-summaries))
17093 (if (assoc property sum-alist)
17094 (setcdr (assoc property sum-alist) useval)
17095 (push (cons property useval) sum-alist)
17096 (org-unmodified
17097 (add-text-properties sumpos (1+ sumpos)
17098 (list 'org-summaries sum-alist))))
17099 (when val
17100 (org-entry-put nil property (if flag str val)))
17101 ;; add current to current level accumulator
17102 (when (or flag valflag)
17103 (aset lsum level (+ (aref lsum level)
17104 (if flag sum (org-column-string-to-number
17105 (if flag str val) format))))
17106 (aset lflag level t))
17107 ;; clear accumulators for deeper levels
17108 (loop for l from (1+ level) to (1- lmax) do
17109 (aset lsum l 0)
17110 (aset lflag l nil)))
17111 ((>= level last-level)
17112 ;; add what we have here to the accumulator for this level
17113 (aset lsum level (+ (aref lsum level)
17114 (org-column-string-to-number (or val "0") format)))
17115 (and valflag (aset lflag level t)))
17116 (t (error "This should not happen")))))))
17118 (defun org-columns-redo ()
17119 "Construct the column display again."
17120 (interactive)
17121 (message "Recomputing columns...")
17122 (save-excursion
17123 (if (marker-position org-columns-begin-marker)
17124 (goto-char org-columns-begin-marker))
17125 (org-columns-remove-overlays)
17126 (if (org-mode-p)
17127 (call-interactively 'org-columns)
17128 (call-interactively 'org-agenda-columns)))
17129 (message "Recomputing columns...done"))
17131 (defun org-columns-not-in-agenda ()
17132 (if (eq major-mode 'org-agenda-mode)
17133 (error "This command is only allowed in Org-mode buffers")))
17136 (defun org-string-to-number (s)
17137 "Convert string to number, and interpret hh:mm:ss."
17138 (if (not (string-match ":" s))
17139 (string-to-number s)
17140 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17141 (while l
17142 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17143 sum)))
17145 (defun org-column-number-to-string (n fmt &optional printf)
17146 "Convert a computed column number to a string value, according to FMT."
17147 (cond
17148 ((eq fmt 'add_times)
17149 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17150 (format "%d:%02d" h m)))
17151 ((eq fmt 'checkbox)
17152 (cond ((= n (floor n)) "[X]")
17153 ((> n 1.) "[-]")
17154 (t "[ ]")))
17155 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17156 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17157 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17158 (printf (format printf n))
17159 ((eq fmt 'currency)
17160 (format "%.2f" n))
17161 (t (number-to-string n))))
17163 (defun org-nofm-to-completion (n m &optional percent)
17164 (if (not percent)
17165 (format "[%d/%d]" n m)
17166 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17168 (defun org-column-string-to-number (s fmt)
17169 "Convert a column value to a number that can be used for column computing."
17170 (cond
17171 ((string-match ":" s)
17172 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17173 (while l
17174 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17175 sum))
17176 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17177 (if (equal s "[X]") 1. 0.000001))
17178 (t (string-to-number s))))
17180 (defun org-columns-uncompile-format (cfmt)
17181 "Turn the compiled columns format back into a string representation."
17182 (let ((rtn "") e s prop title op width fmt printf)
17183 (while (setq e (pop cfmt))
17184 (setq prop (car e)
17185 title (nth 1 e)
17186 width (nth 2 e)
17187 op (nth 3 e)
17188 fmt (nth 4 e)
17189 printf (nth 5 e))
17190 (cond
17191 ((eq fmt 'add_times) (setq op ":"))
17192 ((eq fmt 'checkbox) (setq op "X"))
17193 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17194 ((eq fmt 'checkbox-percent) (setq op "X%"))
17195 ((eq fmt 'add_numbers) (setq op "+"))
17196 ((eq fmt 'currency) (setq op "$")))
17197 (if (and op printf) (setq op (concat op ";" printf)))
17198 (if (equal title prop) (setq title nil))
17199 (setq s (concat "%" (if width (number-to-string width))
17200 prop
17201 (if title (concat "(" title ")"))
17202 (if op (concat "{" op "}"))))
17203 (setq rtn (concat rtn " " s)))
17204 (org-trim rtn)))
17206 (defun org-columns-compile-format (fmt)
17207 "Turn a column format string into an alist of specifications.
17208 The alist has one entry for each column in the format. The elements of
17209 that list are:
17210 property the property
17211 title the title field for the columns
17212 width the column width in characters, can be nil for automatic
17213 operator the operator if any
17214 format the output format for computed results, derived from operator
17215 printf a printf format for computed values"
17216 (let ((start 0) width prop title op f printf)
17217 (setq org-columns-current-fmt-compiled nil)
17218 (while (string-match
17219 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17220 fmt start)
17221 (setq start (match-end 0)
17222 width (match-string 1 fmt)
17223 prop (match-string 2 fmt)
17224 title (or (match-string 3 fmt) prop)
17225 op (match-string 4 fmt)
17226 f nil
17227 printf nil)
17228 (if width (setq width (string-to-number width)))
17229 (when (and op (string-match ";" op))
17230 (setq printf (substring op (match-end 0))
17231 op (substring op 0 (match-beginning 0))))
17232 (cond
17233 ((equal op "+") (setq f 'add_numbers))
17234 ((equal op "$") (setq f 'currency))
17235 ((equal op ":") (setq f 'add_times))
17236 ((equal op "X") (setq f 'checkbox))
17237 ((equal op "X/") (setq f 'checkbox-n-of-m))
17238 ((equal op "X%") (setq f 'checkbox-percent))
17240 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17241 (setq org-columns-current-fmt-compiled
17242 (nreverse org-columns-current-fmt-compiled))))
17245 ;;; Dynamic block for Column view
17247 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17248 "Get the column view of the current buffer or subtree.
17249 The first optional argument MAXLEVEL sets the level limit. A
17250 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17251 empty rows, an empty row being one where all the column view
17252 specifiers except ITEM are empty. This function returns a list
17253 containing the title row and all other rows. Each row is a list
17254 of fields."
17255 (save-excursion
17256 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17257 (n (length title)) row tbl)
17258 (goto-char (point-min))
17259 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17260 (or (null maxlevel)
17261 (>= maxlevel
17262 (if org-odd-levels-only
17263 (/ (1+ (length (match-string 1))) 2)
17264 (length (match-string 1))))))
17265 (when (get-char-property (match-beginning 0) 'org-columns-key)
17266 (setq row nil)
17267 (loop for i from 0 to (1- n) do
17268 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17269 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17271 row))
17272 (setq row (nreverse row))
17273 (unless (and skip-empty-rows
17274 (eq 1 (length (delete "" (delete-dups row)))))
17275 (push row tbl))))
17276 (append (list title 'hline) (nreverse tbl)))))
17278 (defun org-dblock-write:columnview (params)
17279 "Write the column view table.
17280 PARAMS is a property list of parameters:
17282 :width enforce same column widths with <N> specifiers.
17283 :id the :ID: property of the entry where the columns view
17284 should be built, as a string. When `local', call locally.
17285 When `global' call column view with the cursor at the beginning
17286 of the buffer (usually this means that the whole buffer switches
17287 to column view).
17288 :hlines When t, insert a hline before each item. When a number, insert
17289 a hline before each level <= that number.
17290 :vlines When t, make each column a colgroup to enforce vertical lines.
17291 :maxlevel When set to a number, don't capture headlines below this level.
17292 :skip-empty-rows
17293 When t, skip rows where all specifiers other than ITEM are empty."
17294 (let ((pos (move-marker (make-marker) (point)))
17295 (hlines (plist-get params :hlines))
17296 (vlines (plist-get params :vlines))
17297 (maxlevel (plist-get params :maxlevel))
17298 (skip-empty-rows (plist-get params :skip-empty-rows))
17299 tbl id idpos nfields tmp)
17300 (save-excursion
17301 (save-restriction
17302 (when (setq id (plist-get params :id))
17303 (cond ((not id) nil)
17304 ((eq id 'global) (goto-char (point-min)))
17305 ((eq id 'local) nil)
17306 ((setq idpos (org-find-entry-with-id id))
17307 (goto-char idpos))
17308 (t (error "Cannot find entry with :ID: %s" id))))
17309 (org-columns)
17310 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17311 (setq nfields (length (car tbl)))
17312 (org-columns-quit)))
17313 (goto-char pos)
17314 (move-marker pos nil)
17315 (when tbl
17316 (when (plist-get params :hlines)
17317 (setq tmp nil)
17318 (while tbl
17319 (if (eq (car tbl) 'hline)
17320 (push (pop tbl) tmp)
17321 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17322 (if (and (not (eq (car tmp) 'hline))
17323 (or (eq hlines t)
17324 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17325 (push 'hline tmp)))
17326 (push (pop tbl) tmp)))
17327 (setq tbl (nreverse tmp)))
17328 (when vlines
17329 (setq tbl (mapcar (lambda (x)
17330 (if (eq 'hline x) x (cons "" x)))
17331 tbl))
17332 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17333 (setq pos (point))
17334 (insert (org-listtable-to-string tbl))
17335 (when (plist-get params :width)
17336 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17337 org-columns-current-widths "|")))
17338 (goto-char pos)
17339 (org-table-align))))
17341 (defun org-listtable-to-string (tbl)
17342 "Convert a listtable TBL to a string that contains the Org-mode table.
17343 The table still need to be alligned. The resulting string has no leading
17344 and tailing newline characters."
17345 (mapconcat
17346 (lambda (x)
17347 (cond
17348 ((listp x)
17349 (concat "|" (mapconcat 'identity x "|") "|"))
17350 ((eq x 'hline) "|-|")
17351 (t (error "Garbage in listtable: %s" x))))
17352 tbl "\n"))
17354 (defun org-insert-columns-dblock ()
17355 "Create a dynamic block capturing a column view table."
17356 (interactive)
17357 (let ((defaults '(:name "columnview" :hlines 1))
17358 (id (completing-read
17359 "Capture columns (local, global, entry with :ID: property) [local]: "
17360 (append '(("global") ("local"))
17361 (mapcar 'list (org-property-values "ID"))))))
17362 (if (equal id "") (setq id 'local))
17363 (if (equal id "global") (setq id 'global))
17364 (setq defaults (append defaults (list :id id)))
17365 (org-create-dblock defaults)
17366 (org-update-dblock)))
17368 ;;;; Timestamps
17370 (defvar org-last-changed-timestamp nil)
17371 (defvar org-time-was-given) ; dynamically scoped parameter
17372 (defvar org-end-time-was-given) ; dynamically scoped parameter
17373 (defvar org-ts-what) ; dynamically scoped parameter
17375 (defun org-time-stamp (arg)
17376 "Prompt for a date/time and insert a time stamp.
17377 If the user specifies a time like HH:MM, or if this command is called
17378 with a prefix argument, the time stamp will contain date and time.
17379 Otherwise, only the date will be included. All parts of a date not
17380 specified by the user will be filled in from the current date/time.
17381 So if you press just return without typing anything, the time stamp
17382 will represent the current date/time. If there is already a timestamp
17383 at the cursor, it will be modified."
17384 (interactive "P")
17385 (let* ((ts nil)
17386 (default-time
17387 ;; Default time is either today, or, when entering a range,
17388 ;; the range start.
17389 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17390 (save-excursion
17391 (re-search-backward
17392 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17393 (- (point) 20) t)))
17394 (apply 'encode-time (org-parse-time-string (match-string 1)))
17395 (current-time)))
17396 (default-input (and ts (org-get-compact-tod ts)))
17397 org-time-was-given org-end-time-was-given time)
17398 (cond
17399 ((and (org-at-timestamp-p)
17400 (eq last-command 'org-time-stamp)
17401 (eq this-command 'org-time-stamp))
17402 (insert "--")
17403 (setq time (let ((this-command this-command))
17404 (org-read-date arg 'totime nil nil default-time default-input)))
17405 (org-insert-time-stamp time (or org-time-was-given arg)))
17406 ((org-at-timestamp-p)
17407 (setq time (let ((this-command this-command))
17408 (org-read-date arg 'totime nil nil default-time default-input)))
17409 (when (org-at-timestamp-p) ; just to get the match data
17410 (replace-match "")
17411 (setq org-last-changed-timestamp
17412 (org-insert-time-stamp
17413 time (or org-time-was-given arg)
17414 nil nil nil (list org-end-time-was-given))))
17415 (message "Timestamp updated"))
17417 (setq time (let ((this-command this-command))
17418 (org-read-date arg 'totime nil nil default-time default-input)))
17419 (org-insert-time-stamp time (or org-time-was-given arg)
17420 nil nil nil (list org-end-time-was-given))))))
17422 ;; FIXME: can we use this for something else????
17423 ;; like computing time differences?????
17424 (defun org-get-compact-tod (s)
17425 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17426 (let* ((t1 (match-string 1 s))
17427 (h1 (string-to-number (match-string 2 s)))
17428 (m1 (string-to-number (match-string 3 s)))
17429 (t2 (and (match-end 4) (match-string 5 s)))
17430 (h2 (and t2 (string-to-number (match-string 6 s))))
17431 (m2 (and t2 (string-to-number (match-string 7 s))))
17432 dh dm)
17433 (if (not t2)
17435 (setq dh (- h2 h1) dm (- m2 m1))
17436 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17437 (concat t1 "+" (number-to-string dh)
17438 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17440 (defun org-time-stamp-inactive (&optional arg)
17441 "Insert an inactive time stamp.
17442 An inactive time stamp is enclosed in square brackets instead of angle
17443 brackets. It is inactive in the sense that it does not trigger agenda entries,
17444 does not link to the calendar and cannot be changed with the S-cursor keys.
17445 So these are more for recording a certain time/date."
17446 (interactive "P")
17447 (let (org-time-was-given org-end-time-was-given time)
17448 (setq time (org-read-date arg 'totime))
17449 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17450 nil nil (list org-end-time-was-given))))
17452 (defvar org-date-ovl (org-make-overlay 1 1))
17453 (org-overlay-put org-date-ovl 'face 'org-warning)
17454 (org-detach-overlay org-date-ovl)
17456 (defvar org-ans1) ; dynamically scoped parameter
17457 (defvar org-ans2) ; dynamically scoped parameter
17459 (defvar org-plain-time-of-day-regexp) ; defined below
17461 (defvar org-read-date-overlay nil)
17462 (defvar org-dcst nil) ; dynamically scoped
17464 (defun org-read-date (&optional with-time to-time from-string prompt
17465 default-time default-input)
17466 "Read a date, possibly a time, and make things smooth for the user.
17467 The prompt will suggest to enter an ISO date, but you can also enter anything
17468 which will at least partially be understood by `parse-time-string'.
17469 Unrecognized parts of the date will default to the current day, month, year,
17470 hour and minute. If this command is called to replace a timestamp at point,
17471 of to enter the second timestamp of a range, the default time is taken from the
17472 existing stamp. For example,
17473 3-2-5 --> 2003-02-05
17474 feb 15 --> currentyear-02-15
17475 sep 12 9 --> 2009-09-12
17476 12:45 --> today 12:45
17477 22 sept 0:34 --> currentyear-09-22 0:34
17478 12 --> currentyear-currentmonth-12
17479 Fri --> nearest Friday (today or later)
17480 etc.
17482 Furthermore you can specify a relative date by giving, as the *first* thing
17483 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17484 change in days weeks, months, years.
17485 With a single plus or minus, the date is relative to today. With a double
17486 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17487 +4d --> four days from today
17488 +4 --> same as above
17489 +2w --> two weeks from today
17490 ++5 --> five days from default date
17492 The function understands only English month and weekday abbreviations,
17493 but this can be configured with the variables `parse-time-months' and
17494 `parse-time-weekdays'.
17496 While prompting, a calendar is popped up - you can also select the
17497 date with the mouse (button 1). The calendar shows a period of three
17498 months. To scroll it to other months, use the keys `>' and `<'.
17499 If you don't like the calendar, turn it off with
17500 \(setq org-read-date-popup-calendar nil)
17502 With optional argument TO-TIME, the date will immediately be converted
17503 to an internal time.
17504 With an optional argument WITH-TIME, the prompt will suggest to also
17505 insert a time. Note that when WITH-TIME is not set, you can still
17506 enter a time, and this function will inform the calling routine about
17507 this change. The calling routine may then choose to change the format
17508 used to insert the time stamp into the buffer to include the time.
17509 With optional argument FROM-STRING, read from this string instead from
17510 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17511 the time/date that is used for everything that is not specified by the
17512 user."
17513 (require 'parse-time)
17514 (let* ((org-time-stamp-rounding-minutes
17515 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17516 (org-dcst org-display-custom-times)
17517 (ct (org-current-time))
17518 (def (or default-time ct))
17519 (defdecode (decode-time def))
17520 (dummy (progn
17521 (when (< (nth 2 defdecode) org-extend-today-until)
17522 (setcar (nthcdr 2 defdecode) -1)
17523 (setcar (nthcdr 1 defdecode) 59)
17524 (setq def (apply 'encode-time defdecode)
17525 defdecode (decode-time def)))))
17526 (calendar-move-hook nil)
17527 (view-diary-entries-initially nil)
17528 (view-calendar-holidays-initially nil)
17529 (timestr (format-time-string
17530 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17531 (prompt (concat (if prompt (concat prompt " ") "")
17532 (format "Date+time [%s]: " timestr)))
17533 ans (org-ans0 "") org-ans1 org-ans2 final)
17535 (cond
17536 (from-string (setq ans from-string))
17537 (org-read-date-popup-calendar
17538 (save-excursion
17539 (save-window-excursion
17540 (calendar)
17541 (calendar-forward-day (- (time-to-days def)
17542 (calendar-absolute-from-gregorian
17543 (calendar-current-date))))
17544 (org-eval-in-calendar nil t)
17545 (let* ((old-map (current-local-map))
17546 (map (copy-keymap calendar-mode-map))
17547 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17548 (org-defkey map (kbd "RET") 'org-calendar-select)
17549 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17550 'org-calendar-select-mouse)
17551 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17552 'org-calendar-select-mouse)
17553 (org-defkey minibuffer-local-map [(meta shift left)]
17554 (lambda () (interactive)
17555 (org-eval-in-calendar '(calendar-backward-month 1))))
17556 (org-defkey minibuffer-local-map [(meta shift right)]
17557 (lambda () (interactive)
17558 (org-eval-in-calendar '(calendar-forward-month 1))))
17559 (org-defkey minibuffer-local-map [(meta shift up)]
17560 (lambda () (interactive)
17561 (org-eval-in-calendar '(calendar-backward-year 1))))
17562 (org-defkey minibuffer-local-map [(meta shift down)]
17563 (lambda () (interactive)
17564 (org-eval-in-calendar '(calendar-forward-year 1))))
17565 (org-defkey minibuffer-local-map [(shift up)]
17566 (lambda () (interactive)
17567 (org-eval-in-calendar '(calendar-backward-week 1))))
17568 (org-defkey minibuffer-local-map [(shift down)]
17569 (lambda () (interactive)
17570 (org-eval-in-calendar '(calendar-forward-week 1))))
17571 (org-defkey minibuffer-local-map [(shift left)]
17572 (lambda () (interactive)
17573 (org-eval-in-calendar '(calendar-backward-day 1))))
17574 (org-defkey minibuffer-local-map [(shift right)]
17575 (lambda () (interactive)
17576 (org-eval-in-calendar '(calendar-forward-day 1))))
17577 (org-defkey minibuffer-local-map ">"
17578 (lambda () (interactive)
17579 (org-eval-in-calendar '(scroll-calendar-left 1))))
17580 (org-defkey minibuffer-local-map "<"
17581 (lambda () (interactive)
17582 (org-eval-in-calendar '(scroll-calendar-right 1))))
17583 (unwind-protect
17584 (progn
17585 (use-local-map map)
17586 (add-hook 'post-command-hook 'org-read-date-display)
17587 (setq org-ans0 (read-string prompt default-input nil nil))
17588 ;; org-ans0: from prompt
17589 ;; org-ans1: from mouse click
17590 ;; org-ans2: from calendar motion
17591 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17592 (remove-hook 'post-command-hook 'org-read-date-display)
17593 (use-local-map old-map)
17594 (when org-read-date-overlay
17595 (org-delete-overlay org-read-date-overlay)
17596 (setq org-read-date-overlay nil)))))))
17598 (t ; Naked prompt only
17599 (unwind-protect
17600 (setq ans (read-string prompt default-input nil timestr))
17601 (when org-read-date-overlay
17602 (org-delete-overlay org-read-date-overlay)
17603 (setq org-read-date-overlay nil)))))
17605 (setq final (org-read-date-analyze ans def defdecode))
17607 (if to-time
17608 (apply 'encode-time final)
17609 (if (and (boundp 'org-time-was-given) org-time-was-given)
17610 (format "%04d-%02d-%02d %02d:%02d"
17611 (nth 5 final) (nth 4 final) (nth 3 final)
17612 (nth 2 final) (nth 1 final))
17613 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17614 (defvar def)
17615 (defvar defdecode)
17616 (defvar with-time)
17617 (defun org-read-date-display ()
17618 "Display the currrent date prompt interpretation in the minibuffer."
17619 (when org-read-date-display-live
17620 (when org-read-date-overlay
17621 (org-delete-overlay org-read-date-overlay))
17622 (let ((p (point)))
17623 (end-of-line 1)
17624 (while (not (equal (buffer-substring
17625 (max (point-min) (- (point) 4)) (point))
17626 " "))
17627 (insert " "))
17628 (goto-char p))
17629 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17630 " " (or org-ans1 org-ans2)))
17631 (org-end-time-was-given nil)
17632 (f (org-read-date-analyze ans def defdecode))
17633 (fmts (if org-dcst
17634 org-time-stamp-custom-formats
17635 org-time-stamp-formats))
17636 (fmt (if (or with-time
17637 (and (boundp 'org-time-was-given) org-time-was-given))
17638 (cdr fmts)
17639 (car fmts)))
17640 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17641 (when (and org-end-time-was-given
17642 (string-match org-plain-time-of-day-regexp txt))
17643 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17644 org-end-time-was-given
17645 (substring txt (match-end 0)))))
17646 (setq org-read-date-overlay
17647 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17648 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17650 (defun org-read-date-analyze (ans def defdecode)
17651 "Analyze the combined answer of the date prompt."
17652 ;; FIXME: cleanup and comment
17653 (let (delta deltan deltaw deltadef year month day
17654 hour minute second wday pm h2 m2 tl wday1)
17656 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17657 (setq ans (replace-match "" t t ans)
17658 deltan (car delta)
17659 deltaw (nth 1 delta)
17660 deltadef (nth 2 delta)))
17662 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17663 (when (string-match
17664 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17665 (setq year (if (match-end 2)
17666 (string-to-number (match-string 2 ans))
17667 (string-to-number (format-time-string "%Y")))
17668 month (string-to-number (match-string 3 ans))
17669 day (string-to-number (match-string 4 ans)))
17670 (if (< year 100) (setq year (+ 2000 year)))
17671 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17672 t nil ans)))
17673 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17674 ;; If there is a time with am/pm, and *no* time without it, we convert
17675 ;; so that matching will be successful.
17676 (loop for i from 1 to 2 do ; twice, for end time as well
17677 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17678 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17679 (setq hour (string-to-number (match-string 1 ans))
17680 minute (if (match-end 3)
17681 (string-to-number (match-string 3 ans))
17683 pm (equal ?p
17684 (string-to-char (downcase (match-string 4 ans)))))
17685 (if (and (= hour 12) (not pm))
17686 (setq hour 0)
17687 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17688 (setq ans (replace-match (format "%02d:%02d" hour minute)
17689 t t ans))))
17691 ;; Check if a time range is given as a duration
17692 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17693 (setq hour (string-to-number (match-string 1 ans))
17694 h2 (+ hour (string-to-number (match-string 3 ans)))
17695 minute (string-to-number (match-string 2 ans))
17696 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17697 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17698 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17700 ;; Check if there is a time range
17701 (when (boundp 'org-end-time-was-given)
17702 (setq org-time-was-given nil)
17703 (when (and (string-match org-plain-time-of-day-regexp ans)
17704 (match-end 8))
17705 (setq org-end-time-was-given (match-string 8 ans))
17706 (setq ans (concat (substring ans 0 (match-beginning 7))
17707 (substring ans (match-end 7))))))
17709 (setq tl (parse-time-string ans)
17710 day (or (nth 3 tl) (nth 3 defdecode))
17711 month (or (nth 4 tl)
17712 (if (and org-read-date-prefer-future
17713 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17714 (1+ (nth 4 defdecode))
17715 (nth 4 defdecode)))
17716 year (or (nth 5 tl)
17717 (if (and org-read-date-prefer-future
17718 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17719 (1+ (nth 5 defdecode))
17720 (nth 5 defdecode)))
17721 hour (or (nth 2 tl) (nth 2 defdecode))
17722 minute (or (nth 1 tl) (nth 1 defdecode))
17723 second (or (nth 0 tl) 0)
17724 wday (nth 6 tl))
17725 (when deltan
17726 (unless deltadef
17727 (let ((now (decode-time (current-time))))
17728 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17729 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17730 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17731 ((equal deltaw "m") (setq month (+ month deltan)))
17732 ((equal deltaw "y") (setq year (+ year deltan)))))
17733 (when (and wday (not (nth 3 tl)))
17734 ;; Weekday was given, but no day, so pick that day in the week
17735 ;; on or after the derived date.
17736 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17737 (unless (equal wday wday1)
17738 (setq day (+ day (% (- wday wday1 -7) 7)))))
17739 (if (and (boundp 'org-time-was-given)
17740 (nth 2 tl))
17741 (setq org-time-was-given t))
17742 (if (< year 100) (setq year (+ 2000 year)))
17743 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17744 (list second minute hour day month year)))
17746 (defvar parse-time-weekdays)
17748 (defun org-read-date-get-relative (s today default)
17749 "Check string S for special relative date string.
17750 TODAY and DEFAULT are internal times, for today and for a default.
17751 Return shift list (N what def-flag)
17752 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17753 N is the number of WHATs to shift.
17754 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17755 the DEFAULT date rather than TODAY."
17756 (when (string-match
17757 (concat
17758 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17759 "\\([0-9]+\\)?"
17760 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17761 "\\([ \t]\\|$\\)") s)
17762 (let* ((dir (if (match-end 1)
17763 (string-to-char (substring (match-string 1 s) -1))
17764 ?+))
17765 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17766 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17767 (what (if (match-end 3) (match-string 3 s) "d"))
17768 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17769 (date (if rel default today))
17770 (wday (nth 6 (decode-time date)))
17771 delta)
17772 (if wday1
17773 (progn
17774 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17775 (if (= dir ?-) (setq delta (- delta 7)))
17776 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17777 (list delta "d" rel))
17778 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17780 (defun org-eval-in-calendar (form &optional keepdate)
17781 "Eval FORM in the calendar window and return to current window.
17782 Also, store the cursor date in variable org-ans2."
17783 (let ((sw (selected-window)))
17784 (select-window (get-buffer-window "*Calendar*"))
17785 (eval form)
17786 (when (and (not keepdate) (calendar-cursor-to-date))
17787 (let* ((date (calendar-cursor-to-date))
17788 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17789 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17790 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17791 (select-window sw)))
17793 ; ;; Update the prompt to show new default date
17794 ; (save-excursion
17795 ; (goto-char (point-min))
17796 ; (when (and org-ans2
17797 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17798 ; (get-text-property (match-end 0) 'field))
17799 ; (let ((inhibit-read-only t))
17800 ; (replace-match (concat "[" org-ans2 "]") t t)
17801 ; (add-text-properties (point-min) (1+ (match-end 0))
17802 ; (text-properties-at (1+ (point-min)))))))))
17804 (defun org-calendar-select ()
17805 "Return to `org-read-date' with the date currently selected.
17806 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17807 (interactive)
17808 (when (calendar-cursor-to-date)
17809 (let* ((date (calendar-cursor-to-date))
17810 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17811 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17812 (if (active-minibuffer-window) (exit-minibuffer))))
17814 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17815 "Insert a date stamp for the date given by the internal TIME.
17816 WITH-HM means, use the stamp format that includes the time of the day.
17817 INACTIVE means use square brackets instead of angular ones, so that the
17818 stamp will not contribute to the agenda.
17819 PRE and POST are optional strings to be inserted before and after the
17820 stamp.
17821 The command returns the inserted time stamp."
17822 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17823 stamp)
17824 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17825 (insert-before-markers (or pre ""))
17826 (insert-before-markers (setq stamp (format-time-string fmt time)))
17827 (when (listp extra)
17828 (setq extra (car extra))
17829 (if (and (stringp extra)
17830 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17831 (setq extra (format "-%02d:%02d"
17832 (string-to-number (match-string 1 extra))
17833 (string-to-number (match-string 2 extra))))
17834 (setq extra nil)))
17835 (when extra
17836 (backward-char 1)
17837 (insert-before-markers extra)
17838 (forward-char 1))
17839 (insert-before-markers (or post ""))
17840 stamp))
17842 (defun org-toggle-time-stamp-overlays ()
17843 "Toggle the use of custom time stamp formats."
17844 (interactive)
17845 (setq org-display-custom-times (not org-display-custom-times))
17846 (unless org-display-custom-times
17847 (let ((p (point-min)) (bmp (buffer-modified-p)))
17848 (while (setq p (next-single-property-change p 'display))
17849 (if (and (get-text-property p 'display)
17850 (eq (get-text-property p 'face) 'org-date))
17851 (remove-text-properties
17852 p (setq p (next-single-property-change p 'display))
17853 '(display t))))
17854 (set-buffer-modified-p bmp)))
17855 (if (featurep 'xemacs)
17856 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17857 (org-restart-font-lock)
17858 (setq org-table-may-need-update t)
17859 (if org-display-custom-times
17860 (message "Time stamps are overlayed with custom format")
17861 (message "Time stamp overlays removed")))
17863 (defun org-display-custom-time (beg end)
17864 "Overlay modified time stamp format over timestamp between BED and END."
17865 (let* ((ts (buffer-substring beg end))
17866 t1 w1 with-hm tf time str w2 (off 0))
17867 (save-match-data
17868 (setq t1 (org-parse-time-string ts t))
17869 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
17870 (setq off (- (match-end 0) (match-beginning 0)))))
17871 (setq end (- end off))
17872 (setq w1 (- end beg)
17873 with-hm (and (nth 1 t1) (nth 2 t1))
17874 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17875 time (org-fix-decoded-time t1)
17876 str (org-add-props
17877 (format-time-string
17878 (substring tf 1 -1) (apply 'encode-time time))
17879 nil 'mouse-face 'highlight)
17880 w2 (length str))
17881 (if (not (= w2 w1))
17882 (add-text-properties (1+ beg) (+ 2 beg)
17883 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17884 (if (featurep 'xemacs)
17885 (progn
17886 (put-text-property beg end 'invisible t)
17887 (put-text-property beg end 'end-glyph (make-glyph str)))
17888 (put-text-property beg end 'display str))))
17890 (defun org-translate-time (string)
17891 "Translate all timestamps in STRING to custom format.
17892 But do this only if the variable `org-display-custom-times' is set."
17893 (when org-display-custom-times
17894 (save-match-data
17895 (let* ((start 0)
17896 (re org-ts-regexp-both)
17897 t1 with-hm inactive tf time str beg end)
17898 (while (setq start (string-match re string start))
17899 (setq beg (match-beginning 0)
17900 end (match-end 0)
17901 t1 (save-match-data
17902 (org-parse-time-string (substring string beg end) t))
17903 with-hm (and (nth 1 t1) (nth 2 t1))
17904 inactive (equal (substring string beg (1+ beg)) "[")
17905 tf (funcall (if with-hm 'cdr 'car)
17906 org-time-stamp-custom-formats)
17907 time (org-fix-decoded-time t1)
17908 str (format-time-string
17909 (concat
17910 (if inactive "[" "<") (substring tf 1 -1)
17911 (if inactive "]" ">"))
17912 (apply 'encode-time time))
17913 string (replace-match str t t string)
17914 start (+ start (length str)))))))
17915 string)
17917 (defun org-fix-decoded-time (time)
17918 "Set 0 instead of nil for the first 6 elements of time.
17919 Don't touch the rest."
17920 (let ((n 0))
17921 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17923 (defun org-days-to-time (timestamp-string)
17924 "Difference between TIMESTAMP-STRING and now in days."
17925 (- (time-to-days (org-time-string-to-time timestamp-string))
17926 (time-to-days (current-time))))
17928 (defun org-deadline-close (timestamp-string &optional ndays)
17929 "Is the time in TIMESTAMP-STRING close to the current date?"
17930 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17931 (and (< (org-days-to-time timestamp-string) ndays)
17932 (not (org-entry-is-done-p))))
17934 (defun org-get-wdays (ts)
17935 "Get the deadline lead time appropriate for timestring TS."
17936 (cond
17937 ((<= org-deadline-warning-days 0)
17938 ;; 0 or negative, enforce this value no matter what
17939 (- org-deadline-warning-days))
17940 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17941 ;; lead time is specified.
17942 (floor (* (string-to-number (match-string 1 ts))
17943 (cdr (assoc (match-string 2 ts)
17944 '(("d" . 1) ("w" . 7)
17945 ("m" . 30.4) ("y" . 365.25)))))))
17946 ;; go for the default.
17947 (t org-deadline-warning-days)))
17949 (defun org-calendar-select-mouse (ev)
17950 "Return to `org-read-date' with the date currently selected.
17951 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17952 (interactive "e")
17953 (mouse-set-point ev)
17954 (when (calendar-cursor-to-date)
17955 (let* ((date (calendar-cursor-to-date))
17956 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17957 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17958 (if (active-minibuffer-window) (exit-minibuffer))))
17960 (defun org-check-deadlines (ndays)
17961 "Check if there are any deadlines due or past due.
17962 A deadline is considered due if it happens within `org-deadline-warning-days'
17963 days from today's date. If the deadline appears in an entry marked DONE,
17964 it is not shown. The prefix arg NDAYS can be used to test that many
17965 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17966 (interactive "P")
17967 (let* ((org-warn-days
17968 (cond
17969 ((equal ndays '(4)) 100000)
17970 (ndays (prefix-numeric-value ndays))
17971 (t (abs org-deadline-warning-days))))
17972 (case-fold-search nil)
17973 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17974 (callback
17975 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17977 (message "%d deadlines past-due or due within %d days"
17978 (org-occur regexp nil callback)
17979 org-warn-days)))
17981 (defun org-check-before-date (date)
17982 "Check if there are deadlines or scheduled entries before DATE."
17983 (interactive (list (org-read-date)))
17984 (let ((case-fold-search nil)
17985 (regexp (concat "\\<\\(" org-deadline-string
17986 "\\|" org-scheduled-string
17987 "\\) *<\\([^>]+\\)>"))
17988 (callback
17989 (lambda () (time-less-p
17990 (org-time-string-to-time (match-string 2))
17991 (org-time-string-to-time date)))))
17992 (message "%d entries before %s"
17993 (org-occur regexp nil callback) date)))
17995 (defun org-evaluate-time-range (&optional to-buffer)
17996 "Evaluate a time range by computing the difference between start and end.
17997 Normally the result is just printed in the echo area, but with prefix arg
17998 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17999 If the time range is actually in a table, the result is inserted into the
18000 next column.
18001 For time difference computation, a year is assumed to be exactly 365
18002 days in order to avoid rounding problems."
18003 (interactive "P")
18005 (org-clock-update-time-maybe)
18006 (save-excursion
18007 (unless (org-at-date-range-p t)
18008 (goto-char (point-at-bol))
18009 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18010 (if (not (org-at-date-range-p t))
18011 (error "Not at a time-stamp range, and none found in current line")))
18012 (let* ((ts1 (match-string 1))
18013 (ts2 (match-string 2))
18014 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18015 (match-end (match-end 0))
18016 (time1 (org-time-string-to-time ts1))
18017 (time2 (org-time-string-to-time ts2))
18018 (t1 (time-to-seconds time1))
18019 (t2 (time-to-seconds time2))
18020 (diff (abs (- t2 t1)))
18021 (negative (< (- t2 t1) 0))
18022 ;; (ys (floor (* 365 24 60 60)))
18023 (ds (* 24 60 60))
18024 (hs (* 60 60))
18025 (fy "%dy %dd %02d:%02d")
18026 (fy1 "%dy %dd")
18027 (fd "%dd %02d:%02d")
18028 (fd1 "%dd")
18029 (fh "%02d:%02d")
18030 y d h m align)
18031 (if havetime
18032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18034 d (floor (/ diff ds)) diff (mod diff ds)
18035 h (floor (/ diff hs)) diff (mod diff hs)
18036 m (floor (/ diff 60)))
18037 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18039 d (floor (+ (/ diff ds) 0.5))
18040 h 0 m 0))
18041 (if (not to-buffer)
18042 (message "%s" (org-make-tdiff-string y d h m))
18043 (if (org-at-table-p)
18044 (progn
18045 (goto-char match-end)
18046 (setq align t)
18047 (and (looking-at " *|") (goto-char (match-end 0))))
18048 (goto-char match-end))
18049 (if (looking-at
18050 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18051 (replace-match ""))
18052 (if negative (insert " -"))
18053 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18054 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18055 (insert " " (format fh h m))))
18056 (if align (org-table-align))
18057 (message "Time difference inserted")))))
18059 (defun org-make-tdiff-string (y d h m)
18060 (let ((fmt "")
18061 (l nil))
18062 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18063 l (push y l)))
18064 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18065 l (push d l)))
18066 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18067 l (push h l)))
18068 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18069 l (push m l)))
18070 (apply 'format fmt (nreverse l))))
18072 (defun org-time-string-to-time (s)
18073 (apply 'encode-time (org-parse-time-string s)))
18075 (defun org-time-string-to-absolute (s &optional daynr prefer)
18076 "Convert a time stamp to an absolute day number.
18077 If there is a specifyer for a cyclic time stamp, get the closest date to
18078 DAYNR."
18079 (cond
18080 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18081 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18082 daynr
18083 (+ daynr 1000)))
18084 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18085 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18086 (time-to-days (current-time))) (match-string 0 s)
18087 prefer))
18088 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18090 (defun org-time-from-absolute (d)
18091 "Return the time corresponding to date D.
18092 D may be an absolute day number, or a calendar-type list (month day year)."
18093 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18094 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18096 (defun org-calendar-holiday ()
18097 "List of holidays, for Diary display in Org-mode."
18098 (require 'holidays)
18099 (let ((hl (funcall
18100 (if (fboundp 'calendar-check-holidays)
18101 'calendar-check-holidays 'check-calendar-holidays) date)))
18102 (if hl (mapconcat 'identity hl "; "))))
18104 (defun org-diary-sexp-entry (sexp entry date)
18105 "Process a SEXP diary ENTRY for DATE."
18106 (require 'diary-lib)
18107 (let ((result (if calendar-debug-sexp
18108 (let ((stack-trace-on-error t))
18109 (eval (car (read-from-string sexp))))
18110 (condition-case nil
18111 (eval (car (read-from-string sexp)))
18112 (error
18113 (beep)
18114 (message "Bad sexp at line %d in %s: %s"
18115 (org-current-line)
18116 (buffer-file-name) sexp)
18117 (sleep-for 2))))))
18118 (cond ((stringp result) result)
18119 ((and (consp result)
18120 (stringp (cdr result))) (cdr result))
18121 (result entry)
18122 (t nil))))
18124 (defun org-diary-to-ical-string (frombuf)
18125 "Get iCalendar entries from diary entries in buffer FROMBUF.
18126 This uses the icalendar.el library."
18127 (let* ((tmpdir (if (featurep 'xemacs)
18128 (temp-directory)
18129 temporary-file-directory))
18130 (tmpfile (make-temp-name
18131 (expand-file-name "orgics" tmpdir)))
18132 buf rtn b e)
18133 (save-excursion
18134 (set-buffer frombuf)
18135 (icalendar-export-region (point-min) (point-max) tmpfile)
18136 (setq buf (find-buffer-visiting tmpfile))
18137 (set-buffer buf)
18138 (goto-char (point-min))
18139 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18140 (setq b (match-beginning 0)))
18141 (goto-char (point-max))
18142 (if (re-search-backward "^END:VEVENT" nil t)
18143 (setq e (match-end 0)))
18144 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18145 (kill-buffer buf)
18146 (kill-buffer frombuf)
18147 (delete-file tmpfile)
18148 rtn))
18150 (defun org-closest-date (start current change prefer)
18151 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18152 When PREFER is `past' return a date that is either CURRENT or past.
18153 When PREFER is `future', return a date that is either CURRENT or future."
18154 ;; Make the proper lists from the dates
18155 (catch 'exit
18156 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18157 dn dw sday cday n1 n2
18158 d m y y1 y2 date1 date2 nmonths nm ny m2)
18160 (setq start (org-date-to-gregorian start)
18161 current (org-date-to-gregorian
18162 (if org-agenda-repeating-timestamp-show-all
18163 current
18164 (time-to-days (current-time))))
18165 sday (calendar-absolute-from-gregorian start)
18166 cday (calendar-absolute-from-gregorian current))
18168 (if (<= cday sday) (throw 'exit sday))
18170 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18171 (setq dn (string-to-number (match-string 1 change))
18172 dw (cdr (assoc (match-string 2 change) a1)))
18173 (error "Invalid change specifyer: %s" change))
18174 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18175 (cond
18176 ((eq dw 'day)
18177 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18178 n2 (+ n1 dn)))
18179 ((eq dw 'year)
18180 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18181 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18182 (setq date1 (list m d y1)
18183 n1 (calendar-absolute-from-gregorian date1)
18184 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18185 n2 (calendar-absolute-from-gregorian date2)))
18186 ((eq dw 'month)
18187 ;; approx number of month between the tow dates
18188 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18189 ;; How often does dn fit in there?
18190 (setq d (nth 1 start) m (car start) y (nth 2 start)
18191 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18192 m (+ m nm)
18193 ny (floor (/ m 12))
18194 y (+ y ny)
18195 m (- m (* ny 12)))
18196 (while (> m 12) (setq m (- m 12) y (1+ y)))
18197 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18198 (setq m2 (+ m dn) y2 y)
18199 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18200 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18201 (while (< n2 cday)
18202 (setq n1 n2 m m2 y y2)
18203 (setq m2 (+ m dn) y2 y)
18204 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18205 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18207 (if org-agenda-repeating-timestamp-show-all
18208 (cond
18209 ((eq prefer 'past) n1)
18210 ((eq prefer 'future) (if (= cday n1) n1 n2))
18211 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18212 (cond
18213 ((eq prefer 'past) n1)
18214 ((eq prefer 'future) (if (= cday n1) n1 n2))
18215 (t (if (= cday n1) n1 n2)))))))
18217 (defun org-date-to-gregorian (date)
18218 "Turn any specification of DATE into a gregorian date for the calendar."
18219 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18220 ((and (listp date) (= (length date) 3)) date)
18221 ((stringp date)
18222 (setq date (org-parse-time-string date))
18223 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18224 ((listp date)
18225 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18227 (defun org-parse-time-string (s &optional nodefault)
18228 "Parse the standard Org-mode time string.
18229 This should be a lot faster than the normal `parse-time-string'.
18230 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18231 hour and minute fields will be nil if not given."
18232 (if (string-match org-ts-regexp0 s)
18233 (list 0
18234 (if (or (match-beginning 8) (not nodefault))
18235 (string-to-number (or (match-string 8 s) "0")))
18236 (if (or (match-beginning 7) (not nodefault))
18237 (string-to-number (or (match-string 7 s) "0")))
18238 (string-to-number (match-string 4 s))
18239 (string-to-number (match-string 3 s))
18240 (string-to-number (match-string 2 s))
18241 nil nil nil)
18242 (make-list 9 0)))
18244 (defun org-timestamp-up (&optional arg)
18245 "Increase the date item at the cursor by one.
18246 If the cursor is on the year, change the year. If it is on the month or
18247 the day, change that.
18248 With prefix ARG, change by that many units."
18249 (interactive "p")
18250 (org-timestamp-change (prefix-numeric-value arg)))
18252 (defun org-timestamp-down (&optional arg)
18253 "Decrease the date item at the cursor by one.
18254 If the cursor is on the year, change the year. If it is on the month or
18255 the day, change that.
18256 With prefix ARG, change by that many units."
18257 (interactive "p")
18258 (org-timestamp-change (- (prefix-numeric-value arg))))
18260 (defun org-timestamp-up-day (&optional arg)
18261 "Increase the date in the time stamp by one day.
18262 With prefix ARG, change that many days."
18263 (interactive "p")
18264 (if (and (not (org-at-timestamp-p t))
18265 (org-on-heading-p))
18266 (org-todo 'up)
18267 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18269 (defun org-timestamp-down-day (&optional arg)
18270 "Decrease the date in the time stamp by one day.
18271 With prefix ARG, change that many days."
18272 (interactive "p")
18273 (if (and (not (org-at-timestamp-p t))
18274 (org-on-heading-p))
18275 (org-todo 'down)
18276 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18278 (defsubst org-pos-in-match-range (pos n)
18279 (and (match-beginning n)
18280 (<= (match-beginning n) pos)
18281 (>= (match-end n) pos)))
18283 (defun org-at-timestamp-p (&optional inactive-ok)
18284 "Determine if the cursor is in or at a timestamp."
18285 (interactive)
18286 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18287 (pos (point))
18288 (ans (or (looking-at tsr)
18289 (save-excursion
18290 (skip-chars-backward "^[<\n\r\t")
18291 (if (> (point) (point-min)) (backward-char 1))
18292 (and (looking-at tsr)
18293 (> (- (match-end 0) pos) -1))))))
18294 (and ans
18295 (boundp 'org-ts-what)
18296 (setq org-ts-what
18297 (cond
18298 ((= pos (match-beginning 0)) 'bracket)
18299 ((= pos (1- (match-end 0))) 'bracket)
18300 ((org-pos-in-match-range pos 2) 'year)
18301 ((org-pos-in-match-range pos 3) 'month)
18302 ((org-pos-in-match-range pos 7) 'hour)
18303 ((org-pos-in-match-range pos 8) 'minute)
18304 ((or (org-pos-in-match-range pos 4)
18305 (org-pos-in-match-range pos 5)) 'day)
18306 ((and (> pos (or (match-end 8) (match-end 5)))
18307 (< pos (match-end 0)))
18308 (- pos (or (match-end 8) (match-end 5))))
18309 (t 'day))))
18310 ans))
18312 (defun org-toggle-timestamp-type ()
18313 "Toggle the type (<active> or [inactive]) of a time stamp."
18314 (interactive)
18315 (when (org-at-timestamp-p t)
18316 (save-excursion
18317 (goto-char (match-beginning 0))
18318 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18319 (goto-char (1- (match-end 0)))
18320 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18321 (message "Timestamp is now %sactive"
18322 (if (equal (char-before) ?>) "in" ""))))
18324 (defun org-timestamp-change (n &optional what)
18325 "Change the date in the time stamp at point.
18326 The date will be changed by N times WHAT. WHAT can be `day', `month',
18327 `year', `minute', `second'. If WHAT is not given, the cursor position
18328 in the timestamp determines what will be changed."
18329 (let ((pos (point))
18330 with-hm inactive
18331 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18332 org-ts-what
18333 extra rem
18334 ts time time0)
18335 (if (not (org-at-timestamp-p t))
18336 (error "Not at a timestamp"))
18337 (if (and (not what) (eq org-ts-what 'bracket))
18338 (org-toggle-timestamp-type)
18339 (if (and (not what) (not (eq org-ts-what 'day))
18340 org-display-custom-times
18341 (get-text-property (point) 'display)
18342 (not (get-text-property (1- (point)) 'display)))
18343 (setq org-ts-what 'day))
18344 (setq org-ts-what (or what org-ts-what)
18345 inactive (= (char-after (match-beginning 0)) ?\[)
18346 ts (match-string 0))
18347 (replace-match "")
18348 (if (string-match
18349 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18351 (setq extra (match-string 1 ts)))
18352 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18353 (setq with-hm t))
18354 (setq time0 (org-parse-time-string ts))
18355 (when (and (eq org-ts-what 'minute)
18356 (eq current-prefix-arg nil))
18357 (setq n (* dm (org-no-warnings (signum n))))
18358 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18359 (setcar (cdr time0) (+ (nth 1 time0)
18360 (if (> n 0) (- rem) (- dm rem))))))
18361 (setq time
18362 (encode-time (or (car time0) 0)
18363 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18364 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18365 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18366 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18367 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18368 (nthcdr 6 time0)))
18369 (when (integerp org-ts-what)
18370 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18371 (if (eq what 'calendar)
18372 (let ((cal-date (org-get-date-from-calendar)))
18373 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18374 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18375 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18376 (setcar time0 (or (car time0) 0))
18377 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18378 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18379 (setq time (apply 'encode-time time0))))
18380 (setq org-last-changed-timestamp
18381 (org-insert-time-stamp time with-hm inactive nil nil extra))
18382 (org-clock-update-time-maybe)
18383 (goto-char pos)
18384 ;; Try to recenter the calendar window, if any
18385 (if (and org-calendar-follow-timestamp-change
18386 (get-buffer-window "*Calendar*" t)
18387 (memq org-ts-what '(day month year)))
18388 (org-recenter-calendar (time-to-days time))))))
18390 ;; FIXME: does not yet work for lead times
18391 (defun org-modify-ts-extra (s pos n dm)
18392 "Change the different parts of the lead-time and repeat fields in timestamp."
18393 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18394 ng h m new rem)
18395 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18396 (cond
18397 ((or (org-pos-in-match-range pos 2)
18398 (org-pos-in-match-range pos 3))
18399 (setq m (string-to-number (match-string 3 s))
18400 h (string-to-number (match-string 2 s)))
18401 (if (org-pos-in-match-range pos 2)
18402 (setq h (+ h n))
18403 (setq n (* dm (org-no-warnings (signum n))))
18404 (when (not (= 0 (setq rem (% m dm))))
18405 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18406 (setq m (+ m n)))
18407 (if (< m 0) (setq m (+ m 60) h (1- h)))
18408 (if (> m 59) (setq m (- m 60) h (1+ h)))
18409 (setq h (min 24 (max 0 h)))
18410 (setq ng 1 new (format "-%02d:%02d" h m)))
18411 ((org-pos-in-match-range pos 6)
18412 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18413 ((org-pos-in-match-range pos 5)
18414 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18416 ((org-pos-in-match-range pos 9)
18417 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18418 ((org-pos-in-match-range pos 8)
18419 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18421 (when ng
18422 (setq s (concat
18423 (substring s 0 (match-beginning ng))
18425 (substring s (match-end ng))))))
18428 (defun org-recenter-calendar (date)
18429 "If the calendar is visible, recenter it to DATE."
18430 (let* ((win (selected-window))
18431 (cwin (get-buffer-window "*Calendar*" t))
18432 (calendar-move-hook nil))
18433 (when cwin
18434 (select-window cwin)
18435 (calendar-goto-date (if (listp date) date
18436 (calendar-gregorian-from-absolute date)))
18437 (select-window win))))
18439 (defun org-goto-calendar (&optional arg)
18440 "Go to the Emacs calendar at the current date.
18441 If there is a time stamp in the current line, go to that date.
18442 A prefix ARG can be used to force the current date."
18443 (interactive "P")
18444 (let ((tsr org-ts-regexp) diff
18445 (calendar-move-hook nil)
18446 (view-calendar-holidays-initially nil)
18447 (view-diary-entries-initially nil))
18448 (if (or (org-at-timestamp-p)
18449 (save-excursion
18450 (beginning-of-line 1)
18451 (looking-at (concat ".*" tsr))))
18452 (let ((d1 (time-to-days (current-time)))
18453 (d2 (time-to-days
18454 (org-time-string-to-time (match-string 1)))))
18455 (setq diff (- d2 d1))))
18456 (calendar)
18457 (calendar-goto-today)
18458 (if (and diff (not arg)) (calendar-forward-day diff))))
18460 (defun org-get-date-from-calendar ()
18461 "Return a list (month day year) of date at point in calendar."
18462 (with-current-buffer "*Calendar*"
18463 (save-match-data
18464 (calendar-cursor-to-date))))
18466 (defun org-date-from-calendar ()
18467 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18468 If there is already a time stamp at the cursor position, update it."
18469 (interactive)
18470 (if (org-at-timestamp-p t)
18471 (org-timestamp-change 0 'calendar)
18472 (let ((cal-date (org-get-date-from-calendar)))
18473 (org-insert-time-stamp
18474 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18476 (defvar appt-time-msg-list)
18478 ;;;###autoload
18479 (defun org-agenda-to-appt (&optional refresh filter)
18480 "Activate appointments found in `org-agenda-files'.
18481 With a \\[universal-argument] prefix, refresh the list of
18482 appointements.
18484 If FILTER is t, interactively prompt the user for a regular
18485 expression, and filter out entries that don't match it.
18487 If FILTER is a string, use this string as a regular expression
18488 for filtering entries out.
18490 FILTER can also be an alist with the car of each cell being
18491 either 'headline or 'category. For example:
18493 '((headline \"IMPORTANT\")
18494 (category \"Work\"))
18496 will only add headlines containing IMPORTANT or headlines
18497 belonging to the \"Work\" category."
18498 (interactive "P")
18499 (require 'calendar)
18500 (if refresh (setq appt-time-msg-list nil))
18501 (if (eq filter t)
18502 (setq filter (read-from-minibuffer "Regexp filter: ")))
18503 (let* ((cnt 0) ; count added events
18504 (org-agenda-new-buffers nil)
18505 (org-deadline-warning-days 0)
18506 (today (org-date-to-gregorian
18507 (time-to-days (current-time))))
18508 (files (org-agenda-files)) entries file)
18509 ;; Get all entries which may contain an appt
18510 (while (setq file (pop files))
18511 (setq entries
18512 (append entries
18513 (org-agenda-get-day-entries
18514 file today :timestamp :scheduled :deadline))))
18515 (setq entries (delq nil entries))
18516 ;; Map thru entries and find if we should filter them out
18517 (mapc
18518 (lambda(x)
18519 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18520 (cat (get-text-property 1 'org-category x))
18521 (tod (get-text-property 1 'time-of-day x))
18522 (ok (or (null filter)
18523 (and (stringp filter) (string-match filter evt))
18524 (and (listp filter)
18525 (or (string-match
18526 (cadr (assoc 'category filter)) cat)
18527 (string-match
18528 (cadr (assoc 'headline filter)) evt))))))
18529 ;; FIXME: Shall we remove text-properties for the appt text?
18530 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18531 (when (and ok tod)
18532 (setq tod (number-to-string tod)
18533 tod (when (string-match
18534 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18535 (concat (match-string 1 tod) ":"
18536 (match-string 2 tod))))
18537 (appt-add tod evt)
18538 (setq cnt (1+ cnt))))) entries)
18539 (org-release-buffers org-agenda-new-buffers)
18540 (if (eq cnt 0)
18541 (message "No event to add")
18542 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18544 ;;; The clock for measuring work time.
18546 (defvar org-mode-line-string "")
18547 (put 'org-mode-line-string 'risky-local-variable t)
18549 (defvar org-mode-line-timer nil)
18550 (defvar org-clock-heading "")
18551 (defvar org-clock-start-time "")
18553 (defun org-update-mode-line ()
18554 (let* ((delta (- (time-to-seconds (current-time))
18555 (time-to-seconds org-clock-start-time)))
18556 (h (floor delta 3600))
18557 (m (floor (- delta (* 3600 h)) 60)))
18558 (setq org-mode-line-string
18559 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18560 'help-echo "Org-mode clock is running"))
18561 (force-mode-line-update)))
18563 (defvar org-clock-marker (make-marker)
18564 "Marker recording the last clock-in.")
18565 (defvar org-clock-mode-line-entry nil
18566 "Information for the modeline about the running clock.")
18568 (defun org-clock-in ()
18569 "Start the clock on the current item.
18570 If necessary, clock-out of the currently active clock."
18571 (interactive)
18572 (org-clock-out t)
18573 (let (ts)
18574 (save-excursion
18575 (org-back-to-heading t)
18576 (when (and org-clock-in-switch-to-state
18577 (not (looking-at (concat outline-regexp "[ \t]*"
18578 org-clock-in-switch-to-state
18579 "\\>"))))
18580 (org-todo org-clock-in-switch-to-state))
18581 (if (and org-clock-heading-function
18582 (functionp org-clock-heading-function))
18583 (setq org-clock-heading (funcall org-clock-heading-function))
18584 (if (looking-at org-complex-heading-regexp)
18585 (setq org-clock-heading (match-string 4))
18586 (setq org-clock-heading "???")))
18587 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18588 (org-clock-find-position)
18590 (insert "\n") (backward-char 1)
18591 (indent-relative)
18592 (insert org-clock-string " ")
18593 (setq org-clock-start-time (current-time))
18594 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18595 (move-marker org-clock-marker (point) (buffer-base-buffer))
18596 (or global-mode-string (setq global-mode-string '("")))
18597 (or (memq 'org-mode-line-string global-mode-string)
18598 (setq global-mode-string
18599 (append global-mode-string '(org-mode-line-string))))
18600 (org-update-mode-line)
18601 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18602 (message "Clock started at %s" ts))))
18604 (defun org-clock-find-position ()
18605 "Find the location where the next clock line should be inserted."
18606 (org-back-to-heading t)
18607 (catch 'exit
18608 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18609 (re (concat "^[ \t]*" org-clock-string))
18610 (cnt 0)
18611 first last)
18612 (goto-char beg)
18613 (when (eobp) (newline) (setq end (max (point) end)))
18614 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18615 ;; we seem to have a CLOCK drawer, so go there.
18616 (beginning-of-line 2)
18617 (throw 'exit t))
18618 ;; Lets count the CLOCK lines
18619 (goto-char beg)
18620 (while (re-search-forward re end t)
18621 (setq first (or first (match-beginning 0))
18622 last (match-beginning 0)
18623 cnt (1+ cnt)))
18624 (when (and (integerp org-clock-into-drawer)
18625 (>= (1+ cnt) org-clock-into-drawer))
18626 ;; Wrap current entries into a new drawer
18627 (goto-char last)
18628 (beginning-of-line 2)
18629 (if (org-at-item-p) (org-end-of-item))
18630 (insert ":END:\n")
18631 (beginning-of-line 0)
18632 (org-indent-line-function)
18633 (goto-char first)
18634 (insert ":CLOCK:\n")
18635 (beginning-of-line 0)
18636 (org-indent-line-function)
18637 (org-flag-drawer t)
18638 (beginning-of-line 2)
18639 (throw 'exit nil))
18641 (goto-char beg)
18642 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18643 (not (equal (match-string 1) org-clock-string)))
18644 ;; Planning info, skip to after it
18645 (beginning-of-line 2)
18646 (or (bolp) (newline)))
18647 (when (eq t org-clock-into-drawer)
18648 (insert ":CLOCK:\n:END:\n")
18649 (beginning-of-line -1)
18650 (org-indent-line-function)
18651 (org-flag-drawer t)
18652 (beginning-of-line 2)
18653 (org-indent-line-function)))))
18655 (defun org-clock-out (&optional fail-quietly)
18656 "Stop the currently running clock.
18657 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18658 (interactive)
18659 (catch 'exit
18660 (if (not (marker-buffer org-clock-marker))
18661 (if fail-quietly (throw 'exit t) (error "No active clock")))
18662 (let (ts te s h m)
18663 (save-excursion
18664 (set-buffer (marker-buffer org-clock-marker))
18665 (goto-char org-clock-marker)
18666 (beginning-of-line 1)
18667 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18668 (equal (match-string 1) org-clock-string))
18669 (setq ts (match-string 2))
18670 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18671 (goto-char (match-end 0))
18672 (delete-region (point) (point-at-eol))
18673 (insert "--")
18674 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18675 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18676 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18677 h (floor (/ s 3600))
18678 s (- s (* 3600 h))
18679 m (floor (/ s 60))
18680 s (- s (* 60 s)))
18681 (insert " => " (format "%2d:%02d" h m))
18682 (move-marker org-clock-marker nil)
18683 (when org-log-note-clock-out
18684 (org-add-log-maybe 'clock-out))
18685 (when org-mode-line-timer
18686 (cancel-timer org-mode-line-timer)
18687 (setq org-mode-line-timer nil))
18688 (setq global-mode-string
18689 (delq 'org-mode-line-string global-mode-string))
18690 (force-mode-line-update)
18691 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18693 (defun org-clock-cancel ()
18694 "Cancel the running clock be removing the start timestamp."
18695 (interactive)
18696 (if (not (marker-buffer org-clock-marker))
18697 (error "No active clock"))
18698 (save-excursion
18699 (set-buffer (marker-buffer org-clock-marker))
18700 (goto-char org-clock-marker)
18701 (delete-region (1- (point-at-bol)) (point-at-eol)))
18702 (setq global-mode-string
18703 (delq 'org-mode-line-string global-mode-string))
18704 (force-mode-line-update)
18705 (message "Clock canceled"))
18707 (defun org-clock-goto (&optional delete-windows)
18708 "Go to the currently clocked-in entry."
18709 (interactive "P")
18710 (if (not (marker-buffer org-clock-marker))
18711 (error "No active clock"))
18712 (switch-to-buffer-other-window
18713 (marker-buffer org-clock-marker))
18714 (if delete-windows (delete-other-windows))
18715 (goto-char org-clock-marker)
18716 (org-show-entry)
18717 (org-back-to-heading)
18718 (recenter))
18720 (defvar org-clock-file-total-minutes nil
18721 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18722 (make-variable-buffer-local 'org-clock-file-total-minutes)
18724 (defun org-clock-sum (&optional tstart tend)
18725 "Sum the times for each subtree.
18726 Puts the resulting times in minutes as a text property on each headline."
18727 (interactive)
18728 (let* ((bmp (buffer-modified-p))
18729 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18730 org-clock-string
18731 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18732 (lmax 30)
18733 (ltimes (make-vector lmax 0))
18734 (t1 0)
18735 (level 0)
18736 ts te dt
18737 time)
18738 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18739 (save-excursion
18740 (goto-char (point-max))
18741 (while (re-search-backward re nil t)
18742 (cond
18743 ((match-end 2)
18744 ;; Two time stamps
18745 (setq ts (match-string 2)
18746 te (match-string 3)
18747 ts (time-to-seconds
18748 (apply 'encode-time (org-parse-time-string ts)))
18749 te (time-to-seconds
18750 (apply 'encode-time (org-parse-time-string te)))
18751 ts (if tstart (max ts tstart) ts)
18752 te (if tend (min te tend) te)
18753 dt (- te ts)
18754 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18755 ((match-end 4)
18756 ;; A naket time
18757 (setq t1 (+ t1 (string-to-number (match-string 5))
18758 (* 60 (string-to-number (match-string 4))))))
18759 (t ;; A headline
18760 (setq level (- (match-end 1) (match-beginning 1)))
18761 (when (or (> t1 0) (> (aref ltimes level) 0))
18762 (loop for l from 0 to level do
18763 (aset ltimes l (+ (aref ltimes l) t1)))
18764 (setq t1 0 time (aref ltimes level))
18765 (loop for l from level to (1- lmax) do
18766 (aset ltimes l 0))
18767 (goto-char (match-beginning 0))
18768 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18769 (setq org-clock-file-total-minutes (aref ltimes 0)))
18770 (set-buffer-modified-p bmp)))
18772 (defun org-clock-display (&optional total-only)
18773 "Show subtree times in the entire buffer.
18774 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18775 in the echo area."
18776 (interactive)
18777 (org-remove-clock-overlays)
18778 (let (time h m p)
18779 (org-clock-sum)
18780 (unless total-only
18781 (save-excursion
18782 (goto-char (point-min))
18783 (while (or (and (equal (setq p (point)) (point-min))
18784 (get-text-property p :org-clock-minutes))
18785 (setq p (next-single-property-change
18786 (point) :org-clock-minutes)))
18787 (goto-char p)
18788 (when (setq time (get-text-property p :org-clock-minutes))
18789 (org-put-clock-overlay time (funcall outline-level))))
18790 (setq h (/ org-clock-file-total-minutes 60)
18791 m (- org-clock-file-total-minutes (* 60 h)))
18792 ;; Arrange to remove the overlays upon next change.
18793 (when org-remove-highlights-with-change
18794 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18795 nil 'local))))
18796 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18798 (defvar org-clock-overlays nil)
18799 (make-variable-buffer-local 'org-clock-overlays)
18801 (defun org-put-clock-overlay (time &optional level)
18802 "Put an overlays on the current line, displaying TIME.
18803 If LEVEL is given, prefix time with a corresponding number of stars.
18804 This creates a new overlay and stores it in `org-clock-overlays', so that it
18805 will be easy to remove."
18806 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18807 (l (if level (org-get-valid-level level 0) 0))
18808 (off 0)
18809 ov tx)
18810 (move-to-column c)
18811 (unless (eolp) (skip-chars-backward "^ \t"))
18812 (skip-chars-backward " \t")
18813 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18814 tx (concat (buffer-substring (1- (point)) (point))
18815 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18816 (org-add-props (format "%s %2d:%02d%s"
18817 (make-string l ?*) h m
18818 (make-string (- 16 l) ?\ ))
18819 '(face secondary-selection))
18820 ""))
18821 (if (not (featurep 'xemacs))
18822 (org-overlay-put ov 'display tx)
18823 (org-overlay-put ov 'invisible t)
18824 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18825 (push ov org-clock-overlays)))
18827 (defun org-remove-clock-overlays (&optional beg end noremove)
18828 "Remove the occur highlights from the buffer.
18829 BEG and END are ignored. If NOREMOVE is nil, remove this function
18830 from the `before-change-functions' in the current buffer."
18831 (interactive)
18832 (unless org-inhibit-highlight-removal
18833 (mapc 'org-delete-overlay org-clock-overlays)
18834 (setq org-clock-overlays nil)
18835 (unless noremove
18836 (remove-hook 'before-change-functions
18837 'org-remove-clock-overlays 'local))))
18839 (defun org-clock-out-if-current ()
18840 "Clock out if the current entry contains the running clock.
18841 This is used to stop the clock after a TODO entry is marked DONE,
18842 and is only done if the variable `org-clock-out-when-done' is not nil."
18843 (when (and org-clock-out-when-done
18844 (member state org-done-keywords)
18845 (equal (marker-buffer org-clock-marker) (current-buffer))
18846 (< (point) org-clock-marker)
18847 (> (save-excursion (outline-next-heading) (point))
18848 org-clock-marker))
18849 ;; Clock out, but don't accept a logging message for this.
18850 (let ((org-log-note-clock-out nil))
18851 (org-clock-out))))
18853 (add-hook 'org-after-todo-state-change-hook
18854 'org-clock-out-if-current)
18856 (defun org-check-running-clock ()
18857 "Check if the current buffer contains the running clock.
18858 If yes, offer to stop it and to save the buffer with the changes."
18859 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
18860 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
18861 (buffer-name))))
18862 (org-clock-out)
18863 (when (y-or-n-p "Save changed buffer?")
18864 (save-buffer))))
18866 (defun org-clock-report (&optional arg)
18867 "Create a table containing a report about clocked time.
18868 If the cursor is inside an existing clocktable block, then the table
18869 will be updated. If not, a new clocktable will be inserted.
18870 When called with a prefix argument, move to the first clock table in the
18871 buffer and update it."
18872 (interactive "P")
18873 (org-remove-clock-overlays)
18874 (when arg
18875 (org-find-dblock "clocktable")
18876 (org-show-entry))
18877 (if (org-in-clocktable-p)
18878 (goto-char (org-in-clocktable-p))
18879 (org-create-dblock (list :name "clocktable"
18880 :maxlevel 2 :scope 'file)))
18881 (org-update-dblock))
18883 (defun org-in-clocktable-p ()
18884 "Check if the cursor is in a clocktable."
18885 (let ((pos (point)) start)
18886 (save-excursion
18887 (end-of-line 1)
18888 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
18889 (setq start (match-beginning 0))
18890 (re-search-forward "^#\\+END:.*" nil t)
18891 (>= (match-end 0) pos)
18892 start))))
18894 (defun org-clock-update-time-maybe ()
18895 "If this is a CLOCK line, update it and return t.
18896 Otherwise, return nil."
18897 (interactive)
18898 (save-excursion
18899 (beginning-of-line 1)
18900 (skip-chars-forward " \t")
18901 (when (looking-at org-clock-string)
18902 (let ((re (concat "[ \t]*" org-clock-string
18903 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
18904 "\\([ \t]*=>.*\\)?"))
18905 ts te h m s)
18906 (if (not (looking-at re))
18908 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18909 (end-of-line 1)
18910 (setq ts (match-string 1)
18911 te (match-string 2))
18912 (setq s (- (time-to-seconds
18913 (apply 'encode-time (org-parse-time-string te)))
18914 (time-to-seconds
18915 (apply 'encode-time (org-parse-time-string ts))))
18916 h (floor (/ s 3600))
18917 s (- s (* 3600 h))
18918 m (floor (/ s 60))
18919 s (- s (* 60 s)))
18920 (insert " => " (format "%2d:%02d" h m))
18921 t)))))
18923 (defun org-clock-special-range (key &optional time as-strings)
18924 "Return two times bordering a special time range.
18925 Key is a symbol specifying the range and can be one of `today', `yesterday',
18926 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18927 A week starts Monday 0:00 and ends Sunday 24:00.
18928 The range is determined relative to TIME. TIME defaults to the current time.
18929 The return value is a cons cell with two internal times like the ones
18930 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18931 the returned times will be formatted strings."
18932 (let* ((tm (decode-time (or time (current-time))))
18933 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18934 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18935 (dow (nth 6 tm))
18936 s1 m1 h1 d1 month1 y1 diff ts te fm)
18937 (cond
18938 ((eq key 'today)
18939 (setq h 0 m 0 h1 24 m1 0))
18940 ((eq key 'yesterday)
18941 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18942 ((eq key 'thisweek)
18943 (setq diff (if (= dow 0) 6 (1- dow))
18944 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18945 ((eq key 'lastweek)
18946 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18947 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18948 ((eq key 'thismonth)
18949 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18950 ((eq key 'lastmonth)
18951 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18952 ((eq key 'thisyear)
18953 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18954 ((eq key 'lastyear)
18955 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18956 (t (error "No such time block %s" key)))
18957 (setq ts (encode-time s m h d month y)
18958 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18959 (or d1 d) (or month1 month) (or y1 y)))
18960 (setq fm (cdr org-time-stamp-formats))
18961 (if as-strings
18962 (cons (format-time-string fm ts) (format-time-string fm te))
18963 (cons ts te))))
18965 (defun org-dblock-write:clocktable (params)
18966 "Write the standard clocktable."
18967 (catch 'exit
18968 (let* ((hlchars '((1 . "*") (2 . "/")))
18969 (ins (make-marker))
18970 (total-time nil)
18971 (scope (plist-get params :scope))
18972 (tostring (plist-get params :tostring))
18973 (multifile (plist-get params :multifile))
18974 (header (plist-get params :header))
18975 (maxlevel (or (plist-get params :maxlevel) 3))
18976 (step (plist-get params :step))
18977 (emph (plist-get params :emphasize))
18978 (ts (plist-get params :tstart))
18979 (te (plist-get params :tend))
18980 (block (plist-get params :block))
18981 (link (plist-get params :link))
18982 ipos time h m p level hlc hdl
18983 cc beg end pos tbl)
18984 (when step
18985 (org-clocktable-steps params)
18986 (throw 'exit nil))
18987 (when block
18988 (setq cc (org-clock-special-range block nil t)
18989 ts (car cc) te (cdr cc)))
18990 (if ts (setq ts (time-to-seconds
18991 (apply 'encode-time (org-parse-time-string ts)))))
18992 (if te (setq te (time-to-seconds
18993 (apply 'encode-time (org-parse-time-string te)))))
18994 (move-marker ins (point))
18995 (setq ipos (point))
18997 ;; Get the right scope
18998 (setq pos (point))
18999 (save-restriction
19000 (cond
19001 ((not scope))
19002 ((eq scope 'file) (widen))
19003 ((eq scope 'subtree) (org-narrow-to-subtree))
19004 ((eq scope 'tree)
19005 (while (org-up-heading-safe))
19006 (org-narrow-to-subtree))
19007 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19008 (symbol-name scope)))
19009 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19010 (catch 'exit
19011 (while (org-up-heading-safe)
19012 (looking-at outline-regexp)
19013 (if (<= (org-reduced-level (funcall outline-level)) level)
19014 (throw 'exit nil))))
19015 (org-narrow-to-subtree))
19016 ((or (listp scope) (eq scope 'agenda))
19017 (let* ((files (if (listp scope) scope (org-agenda-files)))
19018 (scope 'agenda)
19019 (p1 (copy-sequence params))
19020 file)
19021 (plist-put p1 :tostring t)
19022 (plist-put p1 :multifile t)
19023 (plist-put p1 :scope 'file)
19024 (org-prepare-agenda-buffers files)
19025 (while (setq file (pop files))
19026 (with-current-buffer (find-buffer-visiting file)
19027 (push (org-clocktable-add-file
19028 file (org-dblock-write:clocktable p1)) tbl)
19029 (setq total-time (+ (or total-time 0)
19030 org-clock-file-total-minutes)))))))
19031 (goto-char pos)
19033 (unless (eq scope 'agenda)
19034 (org-clock-sum ts te)
19035 (goto-char (point-min))
19036 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19037 (goto-char p)
19038 (when (setq time (get-text-property p :org-clock-minutes))
19039 (save-excursion
19040 (beginning-of-line 1)
19041 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19042 (setq level (org-reduced-level
19043 (- (match-end 1) (match-beginning 1))))
19044 (<= level maxlevel))
19045 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19046 hdl (if (not link)
19047 (match-string 2)
19048 (org-make-link-string
19049 (format "file:%s::%s"
19050 (buffer-file-name)
19051 (save-match-data
19052 (org-make-org-heading-search-string
19053 (match-string 2))))
19054 (match-string 2)))
19055 h (/ time 60)
19056 m (- time (* 60 h)))
19057 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19058 (push (concat
19059 "| " (int-to-string level) "|" hlc hdl hlc " |"
19060 (make-string (1- level) ?|)
19061 hlc (format "%d:%02d" h m) hlc
19062 " |") tbl))))))
19063 (setq tbl (nreverse tbl))
19064 (if tostring
19065 (if tbl (mapconcat 'identity tbl "\n") nil)
19066 (goto-char ins)
19067 (insert-before-markers
19068 (or header
19069 (concat
19070 "Clock summary at ["
19071 (substring
19072 (format-time-string (cdr org-time-stamp-formats))
19073 1 -1)
19074 "]."
19075 (if block
19076 (format " Considered range is /%s/." block)
19078 "\n\n"))
19079 (if (eq scope 'agenda) "|File" "")
19080 "|L|Headline|Time|\n")
19081 (setq total-time (or total-time org-clock-file-total-minutes)
19082 h (/ total-time 60)
19083 m (- total-time (* 60 h)))
19084 (insert-before-markers
19085 "|-\n|"
19086 (if (eq scope 'agenda) "|" "")
19088 "*Total time*| "
19089 (format "*%d:%02d*" h m)
19090 "|\n|-\n")
19091 (setq tbl (delq nil tbl))
19092 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19093 (equal (substring (car tbl) 0 2) "|-"))
19094 (pop tbl))
19095 (insert-before-markers (mapconcat
19096 'identity (delq nil tbl)
19097 (if (eq scope 'agenda) "\n|-\n" "\n")))
19098 (backward-delete-char 1)
19099 (goto-char ipos)
19100 (skip-chars-forward "^|")
19101 (org-table-align))))))
19103 (defun org-clocktable-steps (params)
19104 (let* ((p1 (copy-sequence params))
19105 (ts (plist-get p1 :tstart))
19106 (te (plist-get p1 :tend))
19107 (step0 (plist-get p1 :step))
19108 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19109 (block (plist-get p1 :block))
19111 (when block
19112 (setq cc (org-clock-special-range block nil t)
19113 ts (car cc) te (cdr cc)))
19114 (if ts (setq ts (time-to-seconds
19115 (apply 'encode-time (org-parse-time-string ts)))))
19116 (if te (setq te (time-to-seconds
19117 (apply 'encode-time (org-parse-time-string te)))))
19118 (plist-put p1 :header "")
19119 (plist-put p1 :step nil)
19120 (plist-put p1 :block nil)
19121 (while (< ts te)
19122 (or (bolp) (insert "\n"))
19123 (plist-put p1 :tstart (format-time-string
19124 (car org-time-stamp-formats)
19125 (seconds-to-time ts)))
19126 (plist-put p1 :tend (format-time-string
19127 (car org-time-stamp-formats)
19128 (seconds-to-time (setq ts (+ ts step)))))
19129 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19130 (plist-get p1 :tstart) "\n")
19131 (org-dblock-write:clocktable p1)
19132 (re-search-forward "#\\+END:")
19133 (end-of-line 0))))
19136 (defun org-clocktable-add-file (file table)
19137 (if table
19138 (let ((lines (org-split-string table "\n"))
19139 (ff (file-name-nondirectory file)))
19140 (mapconcat 'identity
19141 (mapcar (lambda (x)
19142 (if (string-match org-table-dataline-regexp x)
19143 (concat "|" ff x)
19145 lines)
19146 "\n"))))
19148 ;; FIXME: I don't think anybody uses this, ask David
19149 (defun org-collect-clock-time-entries ()
19150 "Return an internal list with clocking information.
19151 This list has one entry for each CLOCK interval.
19152 FIXME: describe the elements."
19153 (interactive)
19154 (let ((re (concat "^[ \t]*" org-clock-string
19155 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19156 rtn beg end next cont level title total closedp leafp
19157 clockpos titlepos h m donep)
19158 (save-excursion
19159 (org-clock-sum)
19160 (goto-char (point-min))
19161 (while (re-search-forward re nil t)
19162 (setq clockpos (match-beginning 0)
19163 beg (match-string 1) end (match-string 2)
19164 cont (match-end 0))
19165 (setq beg (apply 'encode-time (org-parse-time-string beg))
19166 end (apply 'encode-time (org-parse-time-string end)))
19167 (org-back-to-heading t)
19168 (setq donep (org-entry-is-done-p))
19169 (setq titlepos (point)
19170 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19171 h (/ total 60) m (- total (* 60 h))
19172 total (cons h m))
19173 (looking-at "\\(\\*+\\) +\\(.*\\)")
19174 (setq level (- (match-end 1) (match-beginning 1))
19175 title (org-match-string-no-properties 2))
19176 (save-excursion (outline-next-heading) (setq next (point)))
19177 (setq closedp (re-search-forward org-closed-time-regexp next t))
19178 (goto-char next)
19179 (setq leafp (and (looking-at "^\\*+ ")
19180 (<= (- (match-end 0) (point)) level)))
19181 (push (list beg end clockpos closedp donep
19182 total title titlepos level leafp)
19183 rtn)
19184 (goto-char cont)))
19185 (nreverse rtn)))
19187 ;;;; Agenda, and Diary Integration
19189 ;;; Define the Org-agenda-mode
19191 (defvar org-agenda-mode-map (make-sparse-keymap)
19192 "Keymap for `org-agenda-mode'.")
19194 (defvar org-agenda-menu) ; defined later in this file.
19195 (defvar org-agenda-follow-mode nil)
19196 (defvar org-agenda-show-log nil)
19197 (defvar org-agenda-redo-command nil)
19198 (defvar org-agenda-query-string nil)
19199 (defvar org-agenda-mode-hook nil)
19200 (defvar org-agenda-type nil)
19201 (defvar org-agenda-force-single-file nil)
19203 (defun org-agenda-mode ()
19204 "Mode for time-sorted view on action items in Org-mode files.
19206 The following commands are available:
19208 \\{org-agenda-mode-map}"
19209 (interactive)
19210 (kill-all-local-variables)
19211 (setq org-agenda-undo-list nil
19212 org-agenda-pending-undo-list nil)
19213 (setq major-mode 'org-agenda-mode)
19214 ;; Keep global-font-lock-mode from turning on font-lock-mode
19215 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19216 (setq mode-name "Org-Agenda")
19217 (use-local-map org-agenda-mode-map)
19218 (easy-menu-add org-agenda-menu)
19219 (if org-startup-truncated (setq truncate-lines t))
19220 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19221 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19222 ;; Make sure properties are removed when copying text
19223 (when (boundp 'buffer-substring-filters)
19224 (org-set-local 'buffer-substring-filters
19225 (cons (lambda (x)
19226 (set-text-properties 0 (length x) nil x) x)
19227 buffer-substring-filters)))
19228 (unless org-agenda-keep-modes
19229 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19230 org-agenda-show-log nil))
19231 (easy-menu-change
19232 '("Agenda") "Agenda Files"
19233 (append
19234 (list
19235 (vector
19236 (if (get 'org-agenda-files 'org-restrict)
19237 "Restricted to single file"
19238 "Edit File List")
19239 '(org-edit-agenda-file-list)
19240 (not (get 'org-agenda-files 'org-restrict)))
19241 "--")
19242 (mapcar 'org-file-menu-entry (org-agenda-files))))
19243 (org-agenda-set-mode-name)
19244 (apply
19245 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19246 (list 'org-agenda-mode-hook)))
19248 (substitute-key-definition 'undo 'org-agenda-undo
19249 org-agenda-mode-map global-map)
19250 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19251 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19252 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19253 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19254 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19255 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19256 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19257 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19258 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19259 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19260 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19261 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19262 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19263 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19264 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19265 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19266 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19267 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19268 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19269 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19270 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19271 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19272 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19273 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19274 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19275 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19276 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19277 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19278 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19280 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19281 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19282 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19283 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19284 (while l (org-defkey org-agenda-mode-map
19285 (int-to-string (pop l)) 'digit-argument)))
19287 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19288 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19289 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19290 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19291 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19292 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19293 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19294 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19295 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19296 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19297 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19298 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19299 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19300 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19301 (org-defkey org-agenda-mode-map "n" 'next-line)
19302 (org-defkey org-agenda-mode-map "p" 'previous-line)
19303 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19304 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19305 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19306 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19307 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19308 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19309 (eval-after-load "calendar"
19310 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19311 'org-calendar-goto-agenda))
19312 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19313 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19314 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19315 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19316 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19317 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19318 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19319 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19320 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19321 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19322 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19323 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19324 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19325 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19326 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19327 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19328 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19329 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19330 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19331 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19332 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19333 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19335 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19336 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19337 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19338 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19340 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19341 "Local keymap for agenda entries from Org-mode.")
19343 (org-defkey org-agenda-keymap
19344 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19345 (org-defkey org-agenda-keymap
19346 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19347 (when org-agenda-mouse-1-follows-link
19348 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19349 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19350 '("Agenda"
19351 ("Agenda Files")
19352 "--"
19353 ["Show" org-agenda-show t]
19354 ["Go To (other window)" org-agenda-goto t]
19355 ["Go To (this window)" org-agenda-switch-to t]
19356 ["Follow Mode" org-agenda-follow-mode
19357 :style toggle :selected org-agenda-follow-mode :active t]
19358 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19359 "--"
19360 ["Cycle TODO" org-agenda-todo t]
19361 ["Archive subtree" org-agenda-archive t]
19362 ["Delete subtree" org-agenda-kill t]
19363 "--"
19364 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19365 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19366 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19367 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19368 "--"
19369 ("Tags and Properties"
19370 ["Show all Tags" org-agenda-show-tags t]
19371 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19372 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19373 "--"
19374 ["Column View" org-columns t])
19375 ("Date/Schedule"
19376 ["Schedule" org-agenda-schedule t]
19377 ["Set Deadline" org-agenda-deadline t]
19378 "--"
19379 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19380 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19381 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19382 ("Clock"
19383 ["Clock in" org-agenda-clock-in t]
19384 ["Clock out" org-agenda-clock-out t]
19385 ["Clock cancel" org-agenda-clock-cancel t]
19386 ["Goto running clock" org-clock-goto t])
19387 ("Priority"
19388 ["Set Priority" org-agenda-priority t]
19389 ["Increase Priority" org-agenda-priority-up t]
19390 ["Decrease Priority" org-agenda-priority-down t]
19391 ["Show Priority" org-agenda-show-priority t])
19392 ("Calendar/Diary"
19393 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19394 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19395 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19396 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19397 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19398 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19399 "--"
19400 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19401 "--"
19402 ("View"
19403 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19404 :style radio :selected (equal org-agenda-ndays 1)]
19405 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19406 :style radio :selected (equal org-agenda-ndays 7)]
19407 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19408 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19409 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19410 :style radio :selected (member org-agenda-ndays '(365 366))]
19411 "--"
19412 ["Show Logbook entries" org-agenda-log-mode
19413 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19414 ["Include Diary" org-agenda-toggle-diary
19415 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19416 ["Use Time Grid" org-agenda-toggle-time-grid
19417 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19418 ["Write view to file" org-write-agenda t]
19419 ["Rebuild buffer" org-agenda-redo t]
19420 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19421 "--"
19422 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19423 "--"
19424 ["Quit" org-agenda-quit t]
19425 ["Exit and Release Buffers" org-agenda-exit t]
19428 ;;; Agenda undo
19430 (defvar org-agenda-allow-remote-undo t
19431 "Non-nil means, allow remote undo from the agenda buffer.")
19432 (defvar org-agenda-undo-list nil
19433 "List of undoable operations in the agenda since last refresh.")
19434 (defvar org-agenda-undo-has-started-in nil
19435 "Buffers that have already seen `undo-start' in the current undo sequence.")
19436 (defvar org-agenda-pending-undo-list nil
19437 "In a series of undo commands, this is the list of remaning undo items.")
19439 (defmacro org-if-unprotected (&rest body)
19440 "Execute BODY if there is no `org-protected' text property at point."
19441 (declare (debug t))
19442 `(unless (get-text-property (point) 'org-protected)
19443 ,@body))
19445 (defmacro org-with-remote-undo (_buffer &rest _body)
19446 "Execute BODY while recording undo information in two buffers."
19447 (declare (indent 1) (debug t))
19448 `(let ((_cline (org-current-line))
19449 (_cmd this-command)
19450 (_buf1 (current-buffer))
19451 (_buf2 ,_buffer)
19452 (_undo1 buffer-undo-list)
19453 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19454 _c1 _c2)
19455 ,@_body
19456 (when org-agenda-allow-remote-undo
19457 (setq _c1 (org-verify-change-for-undo
19458 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19459 _c2 (org-verify-change-for-undo
19460 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19461 (when (or _c1 _c2)
19462 ;; make sure there are undo boundaries
19463 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19464 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19465 ;; remember which buffer to undo
19466 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19467 org-agenda-undo-list)))))
19469 (defun org-agenda-undo ()
19470 "Undo a remote editing step in the agenda.
19471 This undoes changes both in the agenda buffer and in the remote buffer
19472 that have been changed along."
19473 (interactive)
19474 (or org-agenda-allow-remote-undo
19475 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19476 (if (not (eq this-command last-command))
19477 (setq org-agenda-undo-has-started-in nil
19478 org-agenda-pending-undo-list org-agenda-undo-list))
19479 (if (not org-agenda-pending-undo-list)
19480 (error "No further undo information"))
19481 (let* ((entry (pop org-agenda-pending-undo-list))
19482 buf line cmd rembuf)
19483 (setq cmd (pop entry) line (pop entry))
19484 (setq rembuf (nth 2 entry))
19485 (org-with-remote-undo rembuf
19486 (while (bufferp (setq buf (pop entry)))
19487 (if (pop entry)
19488 (with-current-buffer buf
19489 (let ((last-undo-buffer buf)
19490 (inhibit-read-only t))
19491 (unless (memq buf org-agenda-undo-has-started-in)
19492 (push buf org-agenda-undo-has-started-in)
19493 (make-local-variable 'pending-undo-list)
19494 (undo-start))
19495 (while (and pending-undo-list
19496 (listp pending-undo-list)
19497 (not (car pending-undo-list)))
19498 (pop pending-undo-list))
19499 (undo-more 1))))))
19500 (goto-line line)
19501 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19503 (defun org-verify-change-for-undo (l1 l2)
19504 "Verify that a real change occurred between the undo lists L1 and L2."
19505 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19506 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19507 (not (eq l1 l2)))
19509 ;;; Agenda dispatch
19511 (defvar org-agenda-restrict nil)
19512 (defvar org-agenda-restrict-begin (make-marker))
19513 (defvar org-agenda-restrict-end (make-marker))
19514 (defvar org-agenda-last-dispatch-buffer nil)
19515 (defvar org-agenda-overriding-restriction nil)
19517 ;;;###autoload
19518 (defun org-agenda (arg &optional keys restriction)
19519 "Dispatch agenda commands to collect entries to the agenda buffer.
19520 Prompts for a command to execute. Any prefix arg will be passed
19521 on to the selected command. The default selections are:
19523 a Call `org-agenda-list' to display the agenda for current day or week.
19524 t Call `org-todo-list' to display the global todo list.
19525 T Call `org-todo-list' to display the global todo list, select only
19526 entries with a specific TODO keyword (the user gets a prompt).
19527 m Call `org-tags-view' to display headlines with tags matching
19528 a condition (the user is prompted for the condition).
19529 M Like `m', but select only TODO entries, no ordinary headlines.
19530 L Create a timeline for the current buffer.
19531 e Export views to associated files.
19533 More commands can be added by configuring the variable
19534 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19535 searches can be pre-defined in this way.
19537 If the current buffer is in Org-mode and visiting a file, you can also
19538 first press `<' once to indicate that the agenda should be temporarily
19539 \(until the next use of \\[org-agenda]) restricted to the current file.
19540 Pressing `<' twice means to restrict to the current subtree or region
19541 \(if active)."
19542 (interactive "P")
19543 (catch 'exit
19544 (let* ((prefix-descriptions nil)
19545 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19546 (org-agenda-custom-commands
19547 ;; normalize different versions
19548 (delq nil
19549 (mapcar
19550 (lambda (x)
19551 (cond ((stringp (cdr x))
19552 (push x prefix-descriptions)
19553 nil)
19554 ((stringp (nth 1 x)) x)
19555 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19556 (t (cons (car x) (cons "" (cdr x))))))
19557 org-agenda-custom-commands)))
19558 (buf (current-buffer))
19559 (bfn (buffer-file-name (buffer-base-buffer)))
19560 entry key type match lprops ans)
19561 ;; Turn off restriction unless there is an overriding one
19562 (unless org-agenda-overriding-restriction
19563 (put 'org-agenda-files 'org-restrict nil)
19564 (setq org-agenda-restrict nil)
19565 (move-marker org-agenda-restrict-begin nil)
19566 (move-marker org-agenda-restrict-end nil))
19567 ;; Delete old local properties
19568 (put 'org-agenda-redo-command 'org-lprops nil)
19569 ;; Remember where this call originated
19570 (setq org-agenda-last-dispatch-buffer (current-buffer))
19571 (unless keys
19572 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19573 keys (car ans)
19574 restriction (cdr ans)))
19575 ;; Estabish the restriction, if any
19576 (when (and (not org-agenda-overriding-restriction) restriction)
19577 (put 'org-agenda-files 'org-restrict (list bfn))
19578 (cond
19579 ((eq restriction 'region)
19580 (setq org-agenda-restrict t)
19581 (move-marker org-agenda-restrict-begin (region-beginning))
19582 (move-marker org-agenda-restrict-end (region-end)))
19583 ((eq restriction 'subtree)
19584 (save-excursion
19585 (setq org-agenda-restrict t)
19586 (org-back-to-heading t)
19587 (move-marker org-agenda-restrict-begin (point))
19588 (move-marker org-agenda-restrict-end
19589 (progn (org-end-of-subtree t)))))))
19591 (require 'calendar) ; FIXME: can we avoid this for some commands?
19592 ;; For example the todo list should not need it (but does...)
19593 (cond
19594 ((setq entry (assoc keys org-agenda-custom-commands))
19595 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19596 (progn
19597 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19598 (put 'org-agenda-redo-command 'org-lprops lprops)
19599 (cond
19600 ((eq type 'agenda)
19601 (org-let lprops '(org-agenda-list current-prefix-arg)))
19602 ((eq type 'alltodo)
19603 (org-let lprops '(org-todo-list current-prefix-arg)))
19604 ((eq type 'search)
19605 (org-let lprops '(org-search-view current-prefix-arg match nil)))
19606 ((eq type 'stuck)
19607 (org-let lprops '(org-agenda-list-stuck-projects
19608 current-prefix-arg)))
19609 ((eq type 'tags)
19610 (org-let lprops '(org-tags-view current-prefix-arg match)))
19611 ((eq type 'tags-todo)
19612 (org-let lprops '(org-tags-view '(4) match)))
19613 ((eq type 'todo)
19614 (org-let lprops '(org-todo-list match)))
19615 ((eq type 'tags-tree)
19616 (org-check-for-org-mode)
19617 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19618 ((eq type 'todo-tree)
19619 (org-check-for-org-mode)
19620 (org-let lprops
19621 '(org-occur (concat "^" outline-regexp "[ \t]*"
19622 (regexp-quote match) "\\>"))))
19623 ((eq type 'occur-tree)
19624 (org-check-for-org-mode)
19625 (org-let lprops '(org-occur match)))
19626 ((functionp type)
19627 (org-let lprops '(funcall type match)))
19628 ((fboundp type)
19629 (org-let lprops '(funcall type match)))
19630 (t (error "Invalid custom agenda command type %s" type))))
19631 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19632 ((equal keys "C")
19633 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19634 (customize-variable 'org-agenda-custom-commands))
19635 ((equal keys "a") (call-interactively 'org-agenda-list))
19636 ((equal keys "s") (call-interactively 'org-search-view))
19637 ((equal keys "t") (call-interactively 'org-todo-list))
19638 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19639 ((equal keys "m") (call-interactively 'org-tags-view))
19640 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19641 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19642 ((equal keys "L")
19643 (unless (org-mode-p)
19644 (error "This is not an Org-mode file"))
19645 (unless restriction
19646 (put 'org-agenda-files 'org-restrict (list bfn))
19647 (org-call-with-arg 'org-timeline arg)))
19648 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19649 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19650 ((equal keys "!") (customize-variable 'org-stuck-projects))
19651 (t (error "Invalid agenda key"))))))
19653 (defun org-agenda-normalize-custom-commands (cmds)
19654 (delq nil
19655 (mapcar
19656 (lambda (x)
19657 (cond ((stringp (cdr x)) nil)
19658 ((stringp (nth 1 x)) x)
19659 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19660 (t (cons (car x) (cons "" (cdr x))))))
19661 cmds)))
19663 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19664 "The user interface for selecting an agenda command."
19665 (catch 'exit
19666 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19667 (restrict-ok (and bfn (org-mode-p)))
19668 (region-p (org-region-active-p))
19669 (custom org-agenda-custom-commands)
19670 (selstring "")
19671 restriction second-time
19672 c entry key type match prefixes rmheader header-end custom1 desc)
19673 (save-window-excursion
19674 (delete-other-windows)
19675 (org-switch-to-buffer-other-window " *Agenda Commands*")
19676 (erase-buffer)
19677 (insert (eval-when-compile
19678 (let ((header
19680 Press key for an agenda command: < Buffer,subtree/region restriction
19681 -------------------------------- > Remove restriction
19682 a Agenda for current week or day e Export agenda views
19683 t List of all TODO entries T Entries with special TODO kwd
19684 m Match a TAGS query M Like m, but only TODO entries
19685 L Timeline for current buffer # List stuck projects (!=configure)
19686 s Search for keywords C Configure custom agenda commands
19687 / Multi-occur
19689 (start 0))
19690 (while (string-match
19691 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19692 header start)
19693 (setq start (match-end 0))
19694 (add-text-properties (match-beginning 2) (match-end 2)
19695 '(face bold) header))
19696 header)))
19697 (setq header-end (move-marker (make-marker) (point)))
19698 (while t
19699 (setq custom1 custom)
19700 (when (eq rmheader t)
19701 (goto-line 1)
19702 (re-search-forward ":" nil t)
19703 (delete-region (match-end 0) (point-at-eol))
19704 (forward-char 1)
19705 (looking-at "-+")
19706 (delete-region (match-end 0) (point-at-eol))
19707 (move-marker header-end (match-end 0)))
19708 (goto-char header-end)
19709 (delete-region (point) (point-max))
19710 (while (setq entry (pop custom1))
19711 (setq key (car entry) desc (nth 1 entry)
19712 type (nth 2 entry) match (nth 3 entry))
19713 (if (> (length key) 1)
19714 (add-to-list 'prefixes (string-to-char key))
19715 (insert
19716 (format
19717 "\n%-4s%-14s: %s"
19718 (org-add-props (copy-sequence key)
19719 '(face bold))
19720 (cond
19721 ((string-match "\\S-" desc) desc)
19722 ((eq type 'agenda) "Agenda for current week or day")
19723 ((eq type 'alltodo) "List of all TODO entries")
19724 ((eq type 'search) "Word search")
19725 ((eq type 'stuck) "List of stuck projects")
19726 ((eq type 'todo) "TODO keyword")
19727 ((eq type 'tags) "Tags query")
19728 ((eq type 'tags-todo) "Tags (TODO)")
19729 ((eq type 'tags-tree) "Tags tree")
19730 ((eq type 'todo-tree) "TODO kwd tree")
19731 ((eq type 'occur-tree) "Occur tree")
19732 ((functionp type) (if (symbolp type)
19733 (symbol-name type)
19734 "Lambda expression"))
19735 (t "???"))
19736 (cond
19737 ((stringp match)
19738 (org-add-props match nil 'face 'org-warning))
19739 (match
19740 (format "set of %d commands" (length match)))
19741 (t ""))))))
19742 (when prefixes
19743 (mapc (lambda (x)
19744 (insert
19745 (format "\n%s %s"
19746 (org-add-props (char-to-string x)
19747 nil 'face 'bold)
19748 (or (cdr (assoc (concat selstring (char-to-string x))
19749 prefix-descriptions))
19750 "Prefix key"))))
19751 prefixes))
19752 (goto-char (point-min))
19753 (when (fboundp 'fit-window-to-buffer)
19754 (if second-time
19755 (if (not (pos-visible-in-window-p (point-max)))
19756 (fit-window-to-buffer))
19757 (setq second-time t)
19758 (fit-window-to-buffer)))
19759 (message "Press key for agenda command%s:"
19760 (if (or restrict-ok org-agenda-overriding-restriction)
19761 (if org-agenda-overriding-restriction
19762 " (restriction lock active)"
19763 (if restriction
19764 (format " (restricted to %s)" restriction)
19765 " (unrestricted)"))
19766 ""))
19767 (setq c (read-char-exclusive))
19768 (message "")
19769 (cond
19770 ((assoc (char-to-string c) custom)
19771 (setq selstring (concat selstring (char-to-string c)))
19772 (throw 'exit (cons selstring restriction)))
19773 ((memq c prefixes)
19774 (setq selstring (concat selstring (char-to-string c))
19775 prefixes nil
19776 rmheader (or rmheader t)
19777 custom (delq nil (mapcar
19778 (lambda (x)
19779 (if (or (= (length (car x)) 1)
19780 (/= (string-to-char (car x)) c))
19782 (cons (substring (car x) 1) (cdr x))))
19783 custom))))
19784 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19785 (message "Restriction is only possible in Org-mode buffers")
19786 (ding) (sit-for 1))
19787 ((eq c ?1)
19788 (org-agenda-remove-restriction-lock 'noupdate)
19789 (setq restriction 'buffer))
19790 ((eq c ?0)
19791 (org-agenda-remove-restriction-lock 'noupdate)
19792 (setq restriction (if region-p 'region 'subtree)))
19793 ((eq c ?<)
19794 (org-agenda-remove-restriction-lock 'noupdate)
19795 (setq restriction
19796 (cond
19797 ((eq restriction 'buffer)
19798 (if region-p 'region 'subtree))
19799 ((memq restriction '(subtree region))
19800 nil)
19801 (t 'buffer))))
19802 ((eq c ?>)
19803 (org-agenda-remove-restriction-lock 'noupdate)
19804 (setq restriction nil))
19805 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19806 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19807 ((and (> (length selstring) 0) (eq c ?\d))
19808 (delete-window)
19809 (org-agenda-get-restriction-and-command prefix-descriptions))
19811 ((equal c ?q) (error "Abort"))
19812 (t (error "Invalid key %c" c))))))))
19814 (defun org-run-agenda-series (name series)
19815 (org-prepare-agenda name)
19816 (let* ((org-agenda-multi t)
19817 (redo (list 'org-run-agenda-series name (list 'quote series)))
19818 (cmds (car series))
19819 (gprops (nth 1 series))
19820 match ;; The byte compiler incorrectly complains about this. Keep it!
19821 cmd type lprops)
19822 (while (setq cmd (pop cmds))
19823 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19824 (cond
19825 ((eq type 'agenda)
19826 (org-let2 gprops lprops
19827 '(call-interactively 'org-agenda-list)))
19828 ((eq type 'alltodo)
19829 (org-let2 gprops lprops
19830 '(call-interactively 'org-todo-list)))
19831 ((eq type 'search)
19832 (org-let2 gprops lprops
19833 '(org-search-view current-prefix-arg match nil)))
19834 ((eq type 'stuck)
19835 (org-let2 gprops lprops
19836 '(call-interactively 'org-agenda-list-stuck-projects)))
19837 ((eq type 'tags)
19838 (org-let2 gprops lprops
19839 '(org-tags-view current-prefix-arg match)))
19840 ((eq type 'tags-todo)
19841 (org-let2 gprops lprops
19842 '(org-tags-view '(4) match)))
19843 ((eq type 'todo)
19844 (org-let2 gprops lprops
19845 '(org-todo-list match)))
19846 ((fboundp type)
19847 (org-let2 gprops lprops
19848 '(funcall type match)))
19849 (t (error "Invalid type in command series"))))
19850 (widen)
19851 (setq org-agenda-redo-command redo)
19852 (goto-char (point-min)))
19853 (org-finalize-agenda))
19855 ;;;###autoload
19856 (defmacro org-batch-agenda (cmd-key &rest parameters)
19857 "Run an agenda command in batch mode and send the result to STDOUT.
19858 If CMD-KEY is a string of length 1, it is used as a key in
19859 `org-agenda-custom-commands' and triggers this command. If it is a
19860 longer string it is used as a tags/todo match string.
19861 Paramters are alternating variable names and values that will be bound
19862 before running the agenda command."
19863 (let (pars)
19864 (while parameters
19865 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19866 (if (> (length cmd-key) 2)
19867 (eval (list 'let (nreverse pars)
19868 (list 'org-tags-view nil cmd-key)))
19869 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19870 (set-buffer org-agenda-buffer-name)
19871 (princ (org-encode-for-stdout (buffer-string)))))
19873 (defun org-encode-for-stdout (string)
19874 (if (fboundp 'encode-coding-string)
19875 (encode-coding-string string buffer-file-coding-system)
19876 string))
19878 (defvar org-agenda-info nil)
19880 ;;;###autoload
19881 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
19882 "Run an agenda command in batch mode and send the result to STDOUT.
19883 If CMD-KEY is a string of length 1, it is used as a key in
19884 `org-agenda-custom-commands' and triggers this command. If it is a
19885 longer string it is used as a tags/todo match string.
19886 Paramters are alternating variable names and values that will be bound
19887 before running the agenda command.
19889 The output gives a line for each selected agenda item. Each
19890 item is a list of comma-separated values, like this:
19892 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
19894 category The category of the item
19895 head The headline, without TODO kwd, TAGS and PRIORITY
19896 type The type of the agenda entry, can be
19897 todo selected in TODO match
19898 tagsmatch selected in tags match
19899 diary imported from diary
19900 deadline a deadline on given date
19901 scheduled scheduled on given date
19902 timestamp entry has timestamp on given date
19903 closed entry was closed on given date
19904 upcoming-deadline warning about deadline
19905 past-scheduled forwarded scheduled item
19906 block entry has date block including g. date
19907 todo The todo keyword, if any
19908 tags All tags including inherited ones, separated by colons
19909 date The relevant date, like 2007-2-14
19910 time The time, like 15:00-16:50
19911 extra Sting with extra planning info
19912 priority-l The priority letter if any was given
19913 priority-n The computed numerical priority
19914 agenda-day The day in the agenda where this is listed"
19916 (let (pars)
19917 (while parameters
19918 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19919 (push (list 'org-agenda-remove-tags t) pars)
19920 (if (> (length cmd-key) 2)
19921 (eval (list 'let (nreverse pars)
19922 (list 'org-tags-view nil cmd-key)))
19923 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
19924 (set-buffer org-agenda-buffer-name)
19925 (let* ((lines (org-split-string (buffer-string) "\n"))
19926 line)
19927 (while (setq line (pop lines))
19928 (catch 'next
19929 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
19930 (setq org-agenda-info
19931 (org-fix-agenda-info (text-properties-at 0 line)))
19932 (princ
19933 (org-encode-for-stdout
19934 (mapconcat 'org-agenda-export-csv-mapper
19935 '(org-category txt type todo tags date time-of-day extra
19936 priority-letter priority agenda-day)
19937 ",")))
19938 (princ "\n"))))))
19940 (defun org-fix-agenda-info (props)
19941 "Make sure all properties on an agenda item have a canonical form,
19942 so the export commands can easily use it."
19943 (let (tmp re)
19944 (when (setq tmp (plist-get props 'tags))
19945 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
19946 (when (setq tmp (plist-get props 'date))
19947 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19948 (let ((calendar-date-display-form '(year "-" month "-" day)))
19949 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
19951 (setq tmp (calendar-date-string tmp)))
19952 (setq props (plist-put props 'date tmp)))
19953 (when (setq tmp (plist-get props 'day))
19954 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
19955 (let ((calendar-date-display-form '(year "-" month "-" day)))
19956 (setq tmp (calendar-date-string tmp)))
19957 (setq props (plist-put props 'day tmp))
19958 (setq props (plist-put props 'agenda-day tmp)))
19959 (when (setq tmp (plist-get props 'txt))
19960 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
19961 (plist-put props 'priority-letter (match-string 1 tmp))
19962 (setq tmp (replace-match "" t t tmp)))
19963 (when (and (setq re (plist-get props 'org-todo-regexp))
19964 (setq re (concat "\\`\\.*" re " ?"))
19965 (string-match re tmp))
19966 (plist-put props 'todo (match-string 1 tmp))
19967 (setq tmp (replace-match "" t t tmp)))
19968 (plist-put props 'txt tmp)))
19969 props)
19971 (defun org-agenda-export-csv-mapper (prop)
19972 (let ((res (plist-get org-agenda-info prop)))
19973 (setq res
19974 (cond
19975 ((not res) "")
19976 ((stringp res) res)
19977 (t (prin1-to-string res))))
19978 (while (string-match "," res)
19979 (setq res (replace-match ";" t t res)))
19980 (org-trim res)))
19983 ;;;###autoload
19984 (defun org-store-agenda-views (&rest parameters)
19985 (interactive)
19986 (eval (list 'org-batch-store-agenda-views)))
19988 ;; FIXME, why is this a macro?????
19989 ;;;###autoload
19990 (defmacro org-batch-store-agenda-views (&rest parameters)
19991 "Run all custom agenda commands that have a file argument."
19992 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
19993 (pop-up-frames nil)
19994 (dir default-directory)
19995 pars cmd thiscmdkey files opts)
19996 (while parameters
19997 (push (list (pop parameters) (if parameters (pop parameters))) pars))
19998 (setq pars (reverse pars))
19999 (save-window-excursion
20000 (while cmds
20001 (setq cmd (pop cmds)
20002 thiscmdkey (car cmd)
20003 opts (nth 4 cmd)
20004 files (nth 5 cmd))
20005 (if (stringp files) (setq files (list files)))
20006 (when files
20007 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20008 (list 'org-agenda nil thiscmdkey)))
20009 (set-buffer org-agenda-buffer-name)
20010 (while files
20011 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20012 (list 'org-write-agenda
20013 (expand-file-name (pop files) dir) t))))
20014 (and (get-buffer org-agenda-buffer-name)
20015 (kill-buffer org-agenda-buffer-name)))))))
20017 (defun org-write-agenda (file &optional nosettings)
20018 "Write the current buffer (an agenda view) as a file.
20019 Depending on the extension of the file name, plain text (.txt),
20020 HTML (.html or .htm) or Postscript (.ps) is produced.
20021 If the extension is .ics, run icalendar export over all files used
20022 to construct the agenda and limit the export to entries listed in the
20023 agenda now.
20024 If NOSETTINGS is given, do not scope the settings of
20025 `org-agenda-exporter-settings' into the export commands. This is used when
20026 the settings have already been scoped and we do not wish to overrule other,
20027 higher priority settings."
20028 (interactive "FWrite agenda to file: ")
20029 (if (not (file-writable-p file))
20030 (error "Cannot write agenda to file %s" file))
20031 (cond
20032 ((string-match "\\.html?\\'" file) (require 'htmlize))
20033 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20034 (org-let (if nosettings nil org-agenda-exporter-settings)
20035 '(save-excursion
20036 (save-window-excursion
20037 (cond
20038 ((string-match "\\.html?\\'" file)
20039 (set-buffer (htmlize-buffer (current-buffer)))
20041 (when (and org-agenda-export-html-style
20042 (string-match "<style>" org-agenda-export-html-style))
20043 ;; replace <style> section with org-agenda-export-html-style
20044 (goto-char (point-min))
20045 (kill-region (- (search-forward "<style") 6)
20046 (search-forward "</style>"))
20047 (insert org-agenda-export-html-style))
20048 (write-file file)
20049 (kill-buffer (current-buffer))
20050 (message "HTML written to %s" file))
20051 ((string-match "\\.ps\\'" file)
20052 (ps-print-buffer-with-faces file)
20053 (message "Postscript written to %s" file))
20054 ((string-match "\\.ics\\'" file)
20055 (let ((org-agenda-marker-table
20056 (org-create-marker-find-array
20057 (org-agenda-collect-markers)))
20058 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20059 (org-combined-agenda-icalendar-file file))
20060 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20062 (let ((bs (buffer-string)))
20063 (find-file file)
20064 (insert bs)
20065 (save-buffer 0)
20066 (kill-buffer (current-buffer))
20067 (message "Plain text written to %s" file))))))
20068 (set-buffer org-agenda-buffer-name)))
20070 (defun org-agenda-collect-markers ()
20071 "Collect the markers pointing to entries in the agenda buffer."
20072 (let (m markers)
20073 (save-excursion
20074 (goto-char (point-min))
20075 (while (not (eobp))
20076 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20077 (get-text-property (point) 'org-marker)))
20078 (push m markers))
20079 (beginning-of-line 2)))
20080 (nreverse markers)))
20082 (defun org-create-marker-find-array (marker-list)
20083 "Create a alist of files names with all marker positions in that file."
20084 (let (f tbl m a p)
20085 (while (setq m (pop marker-list))
20086 (setq p (marker-position m)
20087 f (buffer-file-name (or (buffer-base-buffer
20088 (marker-buffer m))
20089 (marker-buffer m))))
20090 (if (setq a (assoc f tbl))
20091 (push (marker-position m) (cdr a))
20092 (push (list f p) tbl)))
20093 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20094 tbl)))
20096 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20097 (defun org-check-agenda-marker-table ()
20098 "Check of the current entry is on the marker list."
20099 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20101 (and (setq a (assoc file org-agenda-marker-table))
20102 (save-match-data
20103 (save-excursion
20104 (org-back-to-heading t)
20105 (member (point) (cdr a)))))))
20107 (defmacro org-no-read-only (&rest body)
20108 "Inhibit read-only for BODY."
20109 `(let ((inhibit-read-only t)) ,@body))
20111 (defun org-check-for-org-mode ()
20112 "Make sure current buffer is in org-mode. Error if not."
20113 (or (org-mode-p)
20114 (error "Cannot execute org-mode agenda command on buffer in %s."
20115 major-mode)))
20117 (defun org-fit-agenda-window ()
20118 "Fit the window to the buffer size."
20119 (and (memq org-agenda-window-setup '(reorganize-frame))
20120 (fboundp 'fit-window-to-buffer)
20121 (fit-window-to-buffer
20123 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20124 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20126 ;;; Agenda file list
20128 (defun org-agenda-files (&optional unrestricted)
20129 "Get the list of agenda files.
20130 Optional UNRESTRICTED means return the full list even if a restriction
20131 is currently in place."
20132 (let ((files
20133 (cond
20134 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20135 ((stringp org-agenda-files) (org-read-agenda-file-list))
20136 ((listp org-agenda-files) org-agenda-files)
20137 (t (error "Invalid value of `org-agenda-files'")))))
20138 (setq files (apply 'append
20139 (mapcar (lambda (f)
20140 (if (file-directory-p f)
20141 (directory-files f t
20142 org-agenda-file-regexp)
20143 (list f)))
20144 files)))
20145 (if org-agenda-skip-unavailable-files
20146 (delq nil
20147 (mapcar (function
20148 (lambda (file)
20149 (and (file-readable-p file) file)))
20150 files))
20151 files))) ; `org-check-agenda-file' will remove them from the list
20153 (defun org-edit-agenda-file-list ()
20154 "Edit the list of agenda files.
20155 Depending on setup, this either uses customize to edit the variable
20156 `org-agenda-files', or it visits the file that is holding the list. In the
20157 latter case, the buffer is set up in a way that saving it automatically kills
20158 the buffer and restores the previous window configuration."
20159 (interactive)
20160 (if (stringp org-agenda-files)
20161 (let ((cw (current-window-configuration)))
20162 (find-file org-agenda-files)
20163 (org-set-local 'org-window-configuration cw)
20164 (org-add-hook 'after-save-hook
20165 (lambda ()
20166 (set-window-configuration
20167 (prog1 org-window-configuration
20168 (kill-buffer (current-buffer))))
20169 (org-install-agenda-files-menu)
20170 (message "New agenda file list installed"))
20171 nil 'local)
20172 (message "%s" (substitute-command-keys
20173 "Edit list and finish with \\[save-buffer]")))
20174 (customize-variable 'org-agenda-files)))
20176 (defun org-store-new-agenda-file-list (list)
20177 "Set new value for the agenda file list and save it correcly."
20178 (if (stringp org-agenda-files)
20179 (let ((f org-agenda-files) b)
20180 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20181 (with-temp-file f
20182 (insert (mapconcat 'identity list "\n") "\n")))
20183 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20184 (setq org-agenda-files list)
20185 (customize-save-variable 'org-agenda-files org-agenda-files))))
20187 (defun org-read-agenda-file-list ()
20188 "Read the list of agenda files from a file."
20189 (when (stringp org-agenda-files)
20190 (with-temp-buffer
20191 (insert-file-contents org-agenda-files)
20192 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20195 ;;;###autoload
20196 (defun org-cycle-agenda-files ()
20197 "Cycle through the files in `org-agenda-files'.
20198 If the current buffer visits an agenda file, find the next one in the list.
20199 If the current buffer does not, find the first agenda file."
20200 (interactive)
20201 (let* ((fs (org-agenda-files t))
20202 (files (append fs (list (car fs))))
20203 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20204 file)
20205 (unless files (error "No agenda files"))
20206 (catch 'exit
20207 (while (setq file (pop files))
20208 (if (equal (file-truename file) tcf)
20209 (when (car files)
20210 (find-file (car files))
20211 (throw 'exit t))))
20212 (find-file (car fs)))
20213 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20215 (defun org-agenda-file-to-front (&optional to-end)
20216 "Move/add the current file to the top of the agenda file list.
20217 If the file is not present in the list, it is added to the front. If it is
20218 present, it is moved there. With optional argument TO-END, add/move to the
20219 end of the list."
20220 (interactive "P")
20221 (let ((org-agenda-skip-unavailable-files nil)
20222 (file-alist (mapcar (lambda (x)
20223 (cons (file-truename x) x))
20224 (org-agenda-files t)))
20225 (ctf (file-truename buffer-file-name))
20226 x had)
20227 (setq x (assoc ctf file-alist) had x)
20229 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20230 (if to-end
20231 (setq file-alist (append (delq x file-alist) (list x)))
20232 (setq file-alist (cons x (delq x file-alist))))
20233 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20234 (org-install-agenda-files-menu)
20235 (message "File %s to %s of agenda file list"
20236 (if had "moved" "added") (if to-end "end" "front"))))
20238 (defun org-remove-file (&optional file)
20239 "Remove current file from the list of files in variable `org-agenda-files'.
20240 These are the files which are being checked for agenda entries.
20241 Optional argument FILE means, use this file instead of the current."
20242 (interactive)
20243 (let* ((org-agenda-skip-unavailable-files nil)
20244 (file (or file buffer-file-name))
20245 (true-file (file-truename file))
20246 (afile (abbreviate-file-name file))
20247 (files (delq nil (mapcar
20248 (lambda (x)
20249 (if (equal true-file
20250 (file-truename x))
20251 nil x))
20252 (org-agenda-files t)))))
20253 (if (not (= (length files) (length (org-agenda-files t))))
20254 (progn
20255 (org-store-new-agenda-file-list files)
20256 (org-install-agenda-files-menu)
20257 (message "Removed file: %s" afile))
20258 (message "File was not in list: %s (not removed)" afile))))
20260 (defun org-file-menu-entry (file)
20261 (vector file (list 'find-file file) t))
20263 (defun org-check-agenda-file (file)
20264 "Make sure FILE exists. If not, ask user what to do."
20265 (when (not (file-exists-p file))
20266 (message "non-existent file %s. [R]emove from list or [A]bort?"
20267 (abbreviate-file-name file))
20268 (let ((r (downcase (read-char-exclusive))))
20269 (cond
20270 ((equal r ?r)
20271 (org-remove-file file)
20272 (throw 'nextfile t))
20273 (t (error "Abort"))))))
20275 ;;; Agenda prepare and finalize
20277 (defvar org-agenda-multi nil) ; dynammically scoped
20278 (defvar org-agenda-buffer-name "*Org Agenda*")
20279 (defvar org-pre-agenda-window-conf nil)
20280 (defvar org-agenda-name nil)
20281 (defun org-prepare-agenda (&optional name)
20282 (setq org-todo-keywords-for-agenda nil)
20283 (setq org-done-keywords-for-agenda nil)
20284 (if org-agenda-multi
20285 (progn
20286 (setq buffer-read-only nil)
20287 (goto-char (point-max))
20288 (unless (or (bobp) org-agenda-compact-blocks)
20289 (insert "\n" (make-string (window-width) ?=) "\n"))
20290 (narrow-to-region (point) (point-max)))
20291 (org-agenda-reset-markers)
20292 (org-prepare-agenda-buffers (org-agenda-files))
20293 (setq org-todo-keywords-for-agenda
20294 (org-uniquify org-todo-keywords-for-agenda))
20295 (setq org-done-keywords-for-agenda
20296 (org-uniquify org-done-keywords-for-agenda))
20297 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20298 (awin (get-buffer-window abuf)))
20299 (cond
20300 ((equal (current-buffer) abuf) nil)
20301 (awin (select-window awin))
20302 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20303 ((equal org-agenda-window-setup 'current-window)
20304 (switch-to-buffer abuf))
20305 ((equal org-agenda-window-setup 'other-window)
20306 (org-switch-to-buffer-other-window abuf))
20307 ((equal org-agenda-window-setup 'other-frame)
20308 (switch-to-buffer-other-frame abuf))
20309 ((equal org-agenda-window-setup 'reorganize-frame)
20310 (delete-other-windows)
20311 (org-switch-to-buffer-other-window abuf))))
20312 (setq buffer-read-only nil)
20313 (erase-buffer)
20314 (org-agenda-mode)
20315 (and name (not org-agenda-name)
20316 (org-set-local 'org-agenda-name name)))
20317 (setq buffer-read-only nil))
20319 (defun org-finalize-agenda ()
20320 "Finishing touch for the agenda buffer, called just before displaying it."
20321 (unless org-agenda-multi
20322 (save-excursion
20323 (let ((inhibit-read-only t))
20324 (goto-char (point-min))
20325 (while (org-activate-bracket-links (point-max))
20326 (add-text-properties (match-beginning 0) (match-end 0)
20327 '(face org-link)))
20328 (org-agenda-align-tags)
20329 (unless org-agenda-with-colors
20330 (remove-text-properties (point-min) (point-max) '(face nil))))
20331 (if (and (boundp 'org-overriding-columns-format)
20332 org-overriding-columns-format)
20333 (org-set-local 'org-overriding-columns-format
20334 org-overriding-columns-format))
20335 (if (and (boundp 'org-agenda-view-columns-initially)
20336 org-agenda-view-columns-initially)
20337 (org-agenda-columns))
20338 (when org-agenda-fontify-priorities
20339 (org-fontify-priorities))
20340 (run-hooks 'org-finalize-agenda-hook)
20341 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20344 (defun org-fontify-priorities ()
20345 "Make highest priority lines bold, and lowest italic."
20346 (interactive)
20347 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20348 (org-delete-overlay o)))
20349 (org-overlays-in (point-min) (point-max)))
20350 (save-excursion
20351 (let ((inhibit-read-only t)
20352 b e p ov h l)
20353 (goto-char (point-min))
20354 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20355 (setq h (or (get-char-property (point) 'org-highest-priority)
20356 org-highest-priority)
20357 l (or (get-char-property (point) 'org-lowest-priority)
20358 org-lowest-priority)
20359 p (string-to-char (match-string 1))
20360 b (match-beginning 0) e (point-at-eol)
20361 ov (org-make-overlay b e))
20362 (org-overlay-put
20363 ov 'face
20364 (cond ((listp org-agenda-fontify-priorities)
20365 (cdr (assoc p org-agenda-fontify-priorities)))
20366 ((equal p l) 'italic)
20367 ((equal p h) 'bold)))
20368 (org-overlay-put ov 'org-type 'org-priority)))))
20370 (defun org-prepare-agenda-buffers (files)
20371 "Create buffers for all agenda files, protect archived trees and comments."
20372 (interactive)
20373 (let ((pa '(:org-archived t))
20374 (pc '(:org-comment t))
20375 (pall '(:org-archived t :org-comment t))
20376 (inhibit-read-only t)
20377 (rea (concat ":" org-archive-tag ":"))
20378 bmp file re)
20379 (save-excursion
20380 (save-restriction
20381 (while (setq file (pop files))
20382 (if (bufferp file)
20383 (set-buffer file)
20384 (org-check-agenda-file file)
20385 (set-buffer (org-get-agenda-file-buffer file)))
20386 (widen)
20387 (setq bmp (buffer-modified-p))
20388 (org-refresh-category-properties)
20389 (setq org-todo-keywords-for-agenda
20390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20391 (setq org-done-keywords-for-agenda
20392 (append org-done-keywords-for-agenda org-done-keywords))
20393 (save-excursion
20394 (remove-text-properties (point-min) (point-max) pall)
20395 (when org-agenda-skip-archived-trees
20396 (goto-char (point-min))
20397 (while (re-search-forward rea nil t)
20398 (if (org-on-heading-p t)
20399 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20400 (goto-char (point-min))
20401 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20402 (while (re-search-forward re nil t)
20403 (add-text-properties
20404 (match-beginning 0) (org-end-of-subtree t) pc)))
20405 (set-buffer-modified-p bmp))))))
20407 (defvar org-agenda-skip-function nil
20408 "Function to be called at each match during agenda construction.
20409 If this function returns nil, the current match should not be skipped.
20410 Otherwise, the function must return a position from where the search
20411 should be continued.
20412 This may also be a Lisp form, it will be evaluated.
20413 Never set this variable using `setq' or so, because then it will apply
20414 to all future agenda commands. Instead, bind it with `let' to scope
20415 it dynamically into the agenda-constructing command. A good way to set
20416 it is through options in org-agenda-custom-commands.")
20418 (defun org-agenda-skip ()
20419 "Throw to `:skip' in places that should be skipped.
20420 Also moves point to the end of the skipped region, so that search can
20421 continue from there."
20422 (let ((p (point-at-bol)) to fp)
20423 (and org-agenda-skip-archived-trees
20424 (get-text-property p :org-archived)
20425 (org-end-of-subtree t)
20426 (throw :skip t))
20427 (and (get-text-property p :org-comment)
20428 (org-end-of-subtree t)
20429 (throw :skip t))
20430 (if (equal (char-after p) ?#) (throw :skip t))
20431 (when (and (or (setq fp (functionp org-agenda-skip-function))
20432 (consp org-agenda-skip-function))
20433 (setq to (save-excursion
20434 (save-match-data
20435 (if fp
20436 (funcall org-agenda-skip-function)
20437 (eval org-agenda-skip-function))))))
20438 (goto-char to)
20439 (throw :skip t))))
20441 (defvar org-agenda-markers nil
20442 "List of all currently active markers created by `org-agenda'.")
20443 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20444 "Creation time of the last agenda marker.")
20446 (defun org-agenda-new-marker (&optional pos)
20447 "Return a new agenda marker.
20448 Org-mode keeps a list of these markers and resets them when they are
20449 no longer in use."
20450 (let ((m (copy-marker (or pos (point)))))
20451 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20452 (push m org-agenda-markers)
20455 (defun org-agenda-reset-markers ()
20456 "Reset markers created by `org-agenda'."
20457 (while org-agenda-markers
20458 (move-marker (pop org-agenda-markers) nil)))
20460 (defun org-get-agenda-file-buffer (file)
20461 "Get a buffer visiting FILE. If the buffer needs to be created, add
20462 it to the list of buffers which might be released later."
20463 (let ((buf (org-find-base-buffer-visiting file)))
20464 (if buf
20465 buf ; just return it
20466 ;; Make a new buffer and remember it
20467 (setq buf (find-file-noselect file))
20468 (if buf (push buf org-agenda-new-buffers))
20469 buf)))
20471 (defun org-release-buffers (blist)
20472 "Release all buffers in list, asking the user for confirmation when needed.
20473 When a buffer is unmodified, it is just killed. When modified, it is saved
20474 \(if the user agrees) and then killed."
20475 (let (buf file)
20476 (while (setq buf (pop blist))
20477 (setq file (buffer-file-name buf))
20478 (when (and (buffer-modified-p buf)
20479 file
20480 (y-or-n-p (format "Save file %s? " file)))
20481 (with-current-buffer buf (save-buffer)))
20482 (kill-buffer buf))))
20484 (defun org-get-category (&optional pos)
20485 "Get the category applying to position POS."
20486 (get-text-property (or pos (point)) 'org-category))
20488 ;;; Agenda timeline
20490 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20492 (defun org-timeline (&optional include-all)
20493 "Show a time-sorted view of the entries in the current org file.
20494 Only entries with a time stamp of today or later will be listed. With
20495 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20496 under the current date.
20497 If the buffer contains an active region, only check the region for
20498 dates."
20499 (interactive "P")
20500 (require 'calendar)
20501 (org-compile-prefix-format 'timeline)
20502 (org-set-sorting-strategy 'timeline)
20503 (let* ((dopast t)
20504 (dotodo include-all)
20505 (doclosed org-agenda-show-log)
20506 (entry buffer-file-name)
20507 (date (calendar-current-date))
20508 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20509 (end (if (org-region-active-p) (region-end) (point-max)))
20510 (day-numbers (org-get-all-dates beg end 'no-ranges
20511 t doclosed ; always include today
20512 org-timeline-show-empty-dates))
20513 (org-deadline-warning-days 0)
20514 (org-agenda-only-exact-dates t)
20515 (today (time-to-days (current-time)))
20516 (past t)
20517 args
20518 s e rtn d emptyp)
20519 (setq org-agenda-redo-command
20520 (list 'progn
20521 (list 'org-switch-to-buffer-other-window (current-buffer))
20522 (list 'org-timeline (list 'quote include-all))))
20523 (if (not dopast)
20524 ;; Remove past dates from the list of dates.
20525 (setq day-numbers (delq nil (mapcar (lambda(x)
20526 (if (>= x today) x nil))
20527 day-numbers))))
20528 (org-prepare-agenda (concat "Timeline "
20529 (file-name-nondirectory buffer-file-name)))
20530 (if doclosed (push :closed args))
20531 (push :timestamp args)
20532 (push :deadline args)
20533 (push :scheduled args)
20534 (push :sexp args)
20535 (if dotodo (push :todo args))
20536 (while (setq d (pop day-numbers))
20537 (if (and (listp d) (eq (car d) :omitted))
20538 (progn
20539 (setq s (point))
20540 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20541 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20542 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20543 (if (and (>= d today)
20544 dopast
20545 past)
20546 (progn
20547 (setq past nil)
20548 (insert (make-string 79 ?-) "\n")))
20549 (setq date (calendar-gregorian-from-absolute d))
20550 (setq s (point))
20551 (setq rtn (and (not emptyp)
20552 (apply 'org-agenda-get-day-entries entry
20553 date args)))
20554 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20555 (progn
20556 (insert
20557 (if (stringp org-agenda-format-date)
20558 (format-time-string org-agenda-format-date
20559 (org-time-from-absolute date))
20560 (funcall org-agenda-format-date date))
20561 "\n")
20562 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20563 (put-text-property s (1- (point)) 'org-date-line t)
20564 (if (equal d today)
20565 (put-text-property s (1- (point)) 'org-today t))
20566 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20567 (put-text-property s (1- (point)) 'day d)))))
20568 (goto-char (point-min))
20569 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20570 (point-min)))
20571 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20572 (org-finalize-agenda)
20573 (setq buffer-read-only t)))
20575 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20576 "Return a list of all relevant day numbers from BEG to END buffer positions.
20577 If NO-RANGES is non-nil, include only the start and end dates of a range,
20578 not every single day in the range. If FORCE-TODAY is non-nil, make
20579 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20580 inactive time stamps (those in square brackets) are included.
20581 When EMPTY is non-nil, also include days without any entries."
20582 (let ((re (concat
20583 (if pre-re pre-re "")
20584 (if inactive org-ts-regexp-both org-ts-regexp)))
20585 dates dates1 date day day1 day2 ts1 ts2)
20586 (if force-today
20587 (setq dates (list (time-to-days (current-time)))))
20588 (save-excursion
20589 (goto-char beg)
20590 (while (re-search-forward re end t)
20591 (setq day (time-to-days (org-time-string-to-time
20592 (substring (match-string 1) 0 10))))
20593 (or (memq day dates) (push day dates)))
20594 (unless no-ranges
20595 (goto-char beg)
20596 (while (re-search-forward org-tr-regexp end t)
20597 (setq ts1 (substring (match-string 1) 0 10)
20598 ts2 (substring (match-string 2) 0 10)
20599 day1 (time-to-days (org-time-string-to-time ts1))
20600 day2 (time-to-days (org-time-string-to-time ts2)))
20601 (while (< (setq day1 (1+ day1)) day2)
20602 (or (memq day1 dates) (push day1 dates)))))
20603 (setq dates (sort dates '<))
20604 (when empty
20605 (while (setq day (pop dates))
20606 (setq day2 (car dates))
20607 (push day dates1)
20608 (when (and day2 empty)
20609 (if (or (eq empty t)
20610 (and (numberp empty) (<= (- day2 day) empty)))
20611 (while (< (setq day (1+ day)) day2)
20612 (push (list day) dates1))
20613 (push (cons :omitted (- day2 day)) dates1))))
20614 (setq dates (nreverse dates1)))
20615 dates)))
20617 ;;; Agenda Daily/Weekly
20619 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20620 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20621 (defvar org-agenda-last-arguments nil
20622 "The arguments of the previous call to org-agenda")
20623 (defvar org-starting-day nil) ; local variable in the agenda buffer
20624 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20625 (defvar org-include-all-loc nil) ; local variable
20626 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20628 ;;;###autoload
20629 (defun org-agenda-list (&optional include-all start-day ndays)
20630 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20631 The view will be for the current day or week, but from the overview buffer
20632 you will be able to go to other days/weeks.
20634 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20635 all unfinished TODO items will also be shown, before the agenda.
20636 This feature is considered obsolete, please use the TODO list or a block
20637 agenda instead.
20639 With a numeric prefix argument in an interactive call, the agenda will
20640 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20641 the number of days. NDAYS defaults to `org-agenda-ndays'.
20643 START-DAY defaults to TODAY, or to the most recent match for the weekday
20644 given in `org-agenda-start-on-weekday'."
20645 (interactive "P")
20646 (if (and (integerp include-all) (> include-all 0))
20647 (setq ndays include-all include-all nil))
20648 (setq ndays (or ndays org-agenda-ndays)
20649 start-day (or start-day org-agenda-start-day))
20650 (if org-agenda-overriding-arguments
20651 (setq include-all (car org-agenda-overriding-arguments)
20652 start-day (nth 1 org-agenda-overriding-arguments)
20653 ndays (nth 2 org-agenda-overriding-arguments)))
20654 (if (stringp start-day)
20655 ;; Convert to an absolute day number
20656 (setq start-day (time-to-days (org-read-date nil t start-day))))
20657 (setq org-agenda-last-arguments (list include-all start-day ndays))
20658 (org-compile-prefix-format 'agenda)
20659 (org-set-sorting-strategy 'agenda)
20660 (require 'calendar)
20661 (let* ((org-agenda-start-on-weekday
20662 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20663 org-agenda-start-on-weekday nil))
20664 (thefiles (org-agenda-files))
20665 (files thefiles)
20666 (today (time-to-days
20667 (time-subtract (current-time)
20668 (list 0 (* 3600 org-extend-today-until) 0))))
20669 (sd (or start-day today))
20670 (start (if (or (null org-agenda-start-on-weekday)
20671 (< org-agenda-ndays 7))
20673 (let* ((nt (calendar-day-of-week
20674 (calendar-gregorian-from-absolute sd)))
20675 (n1 org-agenda-start-on-weekday)
20676 (d (- nt n1)))
20677 (- sd (+ (if (< d 0) 7 0) d)))))
20678 (day-numbers (list start))
20679 (day-cnt 0)
20680 (inhibit-redisplay (not debug-on-error))
20681 s e rtn rtnall file date d start-pos end-pos todayp nd)
20682 (setq org-agenda-redo-command
20683 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20684 ;; Make the list of days
20685 (setq ndays (or ndays org-agenda-ndays)
20686 nd ndays)
20687 (while (> ndays 1)
20688 (push (1+ (car day-numbers)) day-numbers)
20689 (setq ndays (1- ndays)))
20690 (setq day-numbers (nreverse day-numbers))
20691 (org-prepare-agenda "Day/Week")
20692 (org-set-local 'org-starting-day (car day-numbers))
20693 (org-set-local 'org-include-all-loc include-all)
20694 (org-set-local 'org-agenda-span
20695 (org-agenda-ndays-to-span nd))
20696 (when (and (or include-all org-agenda-include-all-todo)
20697 (member today day-numbers))
20698 (setq files thefiles
20699 rtnall nil)
20700 (while (setq file (pop files))
20701 (catch 'nextfile
20702 (org-check-agenda-file file)
20703 (setq date (calendar-gregorian-from-absolute today)
20704 rtn (org-agenda-get-day-entries
20705 file date :todo))
20706 (setq rtnall (append rtnall rtn))))
20707 (when rtnall
20708 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20709 (add-text-properties (point-min) (1- (point))
20710 (list 'face 'org-agenda-structure))
20711 (insert (org-finalize-agenda-entries rtnall) "\n")))
20712 (unless org-agenda-compact-blocks
20713 (setq s (point))
20714 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20715 "-agenda:\n")
20716 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20717 'org-date-line t)))
20718 (while (setq d (pop day-numbers))
20719 (setq date (calendar-gregorian-from-absolute d)
20720 s (point))
20721 (if (or (setq todayp (= d today))
20722 (and (not start-pos) (= d sd)))
20723 (setq start-pos (point))
20724 (if (and start-pos (not end-pos))
20725 (setq end-pos (point))))
20726 (setq files thefiles
20727 rtnall nil)
20728 (while (setq file (pop files))
20729 (catch 'nextfile
20730 (org-check-agenda-file file)
20731 (if org-agenda-show-log
20732 (setq rtn (org-agenda-get-day-entries
20733 file date
20734 :deadline :scheduled :timestamp :sexp :closed))
20735 (setq rtn (org-agenda-get-day-entries
20736 file date
20737 :deadline :scheduled :sexp :timestamp)))
20738 (setq rtnall (append rtnall rtn))))
20739 (if org-agenda-include-diary
20740 (progn
20741 (require 'diary-lib)
20742 (setq rtn (org-get-entries-from-diary date))
20743 (setq rtnall (append rtnall rtn))))
20744 (if (or rtnall org-agenda-show-all-dates)
20745 (progn
20746 (setq day-cnt (1+ day-cnt))
20747 (insert
20748 (if (stringp org-agenda-format-date)
20749 (format-time-string org-agenda-format-date
20750 (org-time-from-absolute date))
20751 (funcall org-agenda-format-date date))
20752 "\n")
20753 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20754 (put-text-property s (1- (point)) 'org-date-line t)
20755 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20756 (if todayp (put-text-property s (1- (point)) 'org-today t))
20757 (if rtnall (insert
20758 (org-finalize-agenda-entries
20759 (org-agenda-add-time-grid-maybe
20760 rtnall nd todayp))
20761 "\n"))
20762 (put-text-property s (1- (point)) 'day d)
20763 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20764 (goto-char (point-min))
20765 (org-fit-agenda-window)
20766 (unless (and (pos-visible-in-window-p (point-min))
20767 (pos-visible-in-window-p (point-max)))
20768 (goto-char (1- (point-max)))
20769 (recenter -1)
20770 (if (not (pos-visible-in-window-p (or start-pos 1)))
20771 (progn
20772 (goto-char (or start-pos 1))
20773 (recenter 1))))
20774 (goto-char (or start-pos 1))
20775 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20776 (org-finalize-agenda)
20777 (setq buffer-read-only t)
20778 (message "")))
20780 (defun org-agenda-ndays-to-span (n)
20781 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20783 ;;; Agenda word search
20785 (defvar org-agenda-search-history nil)
20786 (defvar org-todo-only nil)
20788 (defvar org-search-syntax-table nil
20789 "Special syntax table for org-mode search.
20790 In this table, we have single quotes not as word constituents, to
20791 that when \"+Ameli\" is searchd as a work, it will also match \"Ameli's\"")
20793 (defun org-search-syntax-table ()
20794 (unless org-search-syntax-table
20795 (setq org-search-syntax-table (copy-syntax-table org-mode-syntax-table))
20796 (modify-syntax-entry ?' "." org-search-syntax-table)
20797 (modify-syntax-entry ?` "." org-search-syntax-table))
20798 org-search-syntax-table)
20800 ;;;###autoload
20801 (defun org-search-view (&optional todo-only string edit-at)
20802 "Show all entries that contain words or regular expressions.
20803 If the first character of the search string is an asterisks,
20804 search only the headlines.
20806 With optional prefix argument TODO-ONLY, only consider entries that are
20807 TODO entries. The argument STRING can be used to pass a default search
20808 string into this function. If EDIT-AT is non-nil, it means that the
20809 user should get a chance to edit this string, with cursor at position
20810 EDIT-AT.
20812 The search string is broken into \"words\" by splitting at whitespace.
20813 The individual words are then interpreted as a boolean expression with
20814 logical AND. Words prefixed with a minus must not occur in the entry.
20815 Words without a prefix or prefixed with a plus must occur in the entry.
20816 Matching is case-insensitive and the words are enclosed by word delimiters.
20818 Words enclosed by curly braces are interpreted as regular expressions
20819 that must or must not match in the entry.
20821 If the search string starts with an asterisk, search only in headlines.
20822 If (possibly after the leading star) the search string starts with an
20823 exclamation mark, this also means to look at TODO entries only, an effect
20824 that can also be achieved with a prefix argument.
20826 This command searches the agenda files, and in addition the files listed
20827 in `org-agenda-text-search-extra-files'."
20828 (interactive "P")
20829 (org-compile-prefix-format 'search)
20830 (org-set-sorting-strategy 'search)
20831 (org-prepare-agenda "SEARCH")
20832 (let* ((props (list 'face nil
20833 'done-face 'org-done
20834 'org-not-done-regexp org-not-done-regexp
20835 'org-todo-regexp org-todo-regexp
20836 'mouse-face 'highlight
20837 'keymap org-agenda-keymap
20838 'help-echo (format "mouse-2 or RET jump to location")))
20839 regexp rtn rtnall files file pos
20840 marker priority category tags c neg re
20841 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20842 (unless (and (not edit-at)
20843 (stringp string)
20844 (string-match "\\S-" string))
20845 (setq string (read-string "[+-]Word/{Regexp} ...: "
20846 (cond
20847 ((integerp edit-at) (cons string edit-at))
20848 (edit-at string))
20849 'org-agenda-search-history)))
20850 (org-set-local 'org-todo-only todo-only)
20851 (setq org-agenda-redo-command
20852 (list 'org-search-view (if todo-only t nil) string
20853 '(if current-prefix-arg 1 nil)))
20854 (setq org-agenda-query-string string)
20856 (if (equal (string-to-char string) ?*)
20857 (setq hdl-only t
20858 words (substring string 1))
20859 (setq words string))
20860 (when (equal (string-to-char words) ?!)
20861 (setq todo-only t
20862 words (substring words 1)))
20863 (setq words (org-split-string words))
20864 (mapc (lambda (w)
20865 (setq c (string-to-char w))
20866 (if (equal c ?-)
20867 (setq neg t w (substring w 1))
20868 (if (equal c ?+)
20869 (setq neg nil w (substring w 1))
20870 (setq neg nil)))
20871 (if (string-match "\\`{.*}\\'" w)
20872 (setq re (substring w 1 -1))
20873 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20874 (if neg (push re regexps-) (push re regexps+)))
20875 words)
20876 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20877 (if (not regexps+)
20878 (setq regexp (concat "^" org-outline-regexp))
20879 (setq regexp (pop regexps+))
20880 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20881 regexp))))
20882 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20883 rtnall nil)
20884 (while (setq file (pop files))
20885 (setq ee nil)
20886 (catch 'nextfile
20887 (org-check-agenda-file file)
20888 (setq buffer (if (file-exists-p file)
20889 (org-get-agenda-file-buffer file)
20890 (error "No such file %s" file)))
20891 (if (not buffer)
20892 ;; If file does not exist, make sure an error message is sent
20893 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20894 file))))
20895 (with-current-buffer buffer
20896 (with-syntax-table (org-search-syntax-table)
20897 (unless (org-mode-p)
20898 (error "Agenda file %s is not in `org-mode'" file))
20899 (let ((case-fold-search t))
20900 (save-excursion
20901 (save-restriction
20902 (if org-agenda-restrict
20903 (narrow-to-region org-agenda-restrict-begin
20904 org-agenda-restrict-end)
20905 (widen))
20906 (goto-char (point-min))
20907 (unless (or (org-on-heading-p)
20908 (outline-next-heading))
20909 (throw 'nextfile t))
20910 (goto-char (max (point-min) (1- (point))))
20911 (while (re-search-forward regexp nil t)
20912 (org-back-to-heading t)
20913 (skip-chars-forward "* ")
20914 (setq beg (point-at-bol)
20915 beg1 (point)
20916 end (progn (outline-next-heading) (point)))
20917 (catch :skip
20918 (goto-char beg)
20919 (org-agenda-skip)
20920 (setq str (buffer-substring-no-properties
20921 (point-at-bol)
20922 (if hdl-only (point-at-eol) end)))
20923 (mapc (lambda (wr) (when (string-match wr str)
20924 (goto-char (1- end))
20925 (throw :skip t)))
20926 regexps-)
20927 (mapc (lambda (wr) (unless (string-match wr str)
20928 (goto-char (1- end))
20929 (throw :skip t)))
20930 (if todo-only
20931 (cons (concat "^\*+[ \t]+" org-not-done-regexp)
20932 regexps+)
20933 regexps+))
20934 (goto-char beg)
20935 (setq marker (org-agenda-new-marker (point))
20936 category (org-get-category)
20937 tags (org-get-tags-at (point))
20938 txt (org-format-agenda-item
20940 (buffer-substring-no-properties
20941 beg1 (point-at-eol))
20942 category tags))
20943 (org-add-props txt props
20944 'org-marker marker 'org-hd-marker marker
20945 'org-todo-regexp org-todo-regexp
20946 'priority 1000 'org-category category
20947 'type "search")
20948 (push txt ee)
20949 (goto-char (1- end))))))))))
20950 (setq rtn (nreverse ee))
20951 (setq rtnall (append rtnall rtn)))
20952 (if org-agenda-overriding-header
20953 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
20954 nil 'face 'org-agenda-structure) "\n")
20955 (insert "Search words: ")
20956 (add-text-properties (point-min) (1- (point))
20957 (list 'face 'org-agenda-structure))
20958 (setq pos (point))
20959 (insert string "\n")
20960 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
20961 (setq pos (point))
20962 (unless org-agenda-multi
20963 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
20964 (add-text-properties pos (1- (point))
20965 (list 'face 'org-agenda-structure))))
20966 (when rtnall
20967 (insert (org-finalize-agenda-entries rtnall) "\n"))
20968 (goto-char (point-min))
20969 (org-fit-agenda-window)
20970 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
20971 (org-finalize-agenda)
20972 (setq buffer-read-only t)))
20974 ;;; Agenda TODO list
20976 (defvar org-select-this-todo-keyword nil)
20977 (defvar org-last-arg nil)
20979 ;;;###autoload
20980 (defun org-todo-list (arg)
20981 "Show all TODO entries from all agenda file in a single list.
20982 The prefix arg can be used to select a specific TODO keyword and limit
20983 the list to these. When using \\[universal-argument], you will be prompted
20984 for a keyword. A numeric prefix directly selects the Nth keyword in
20985 `org-todo-keywords-1'."
20986 (interactive "P")
20987 (require 'calendar)
20988 (org-compile-prefix-format 'todo)
20989 (org-set-sorting-strategy 'todo)
20990 (org-prepare-agenda "TODO")
20991 (let* ((today (time-to-days (current-time)))
20992 (date (calendar-gregorian-from-absolute today))
20993 (kwds org-todo-keywords-for-agenda)
20994 (completion-ignore-case t)
20995 (org-select-this-todo-keyword
20996 (if (stringp arg) arg
20997 (and arg (integerp arg) (> arg 0)
20998 (nth (1- arg) kwds))))
20999 rtn rtnall files file pos)
21000 (when (equal arg '(4))
21001 (setq org-select-this-todo-keyword
21002 (completing-read "Keyword (or KWD1|K2D2|...): "
21003 (mapcar 'list kwds) nil nil)))
21004 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21005 (org-set-local 'org-last-arg arg)
21006 (setq org-agenda-redo-command
21007 '(org-todo-list (or current-prefix-arg org-last-arg)))
21008 (setq files (org-agenda-files)
21009 rtnall nil)
21010 (while (setq file (pop files))
21011 (catch 'nextfile
21012 (org-check-agenda-file file)
21013 (setq rtn (org-agenda-get-day-entries file date :todo))
21014 (setq rtnall (append rtnall rtn))))
21015 (if org-agenda-overriding-header
21016 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21017 nil 'face 'org-agenda-structure) "\n")
21018 (insert "Global list of TODO items of type: ")
21019 (add-text-properties (point-min) (1- (point))
21020 (list 'face 'org-agenda-structure))
21021 (setq pos (point))
21022 (insert (or org-select-this-todo-keyword "ALL") "\n")
21023 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21024 (setq pos (point))
21025 (unless org-agenda-multi
21026 (insert "Available with `N r': (0)ALL")
21027 (let ((n 0) s)
21028 (mapc (lambda (x)
21029 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21030 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21031 (insert "\n "))
21032 (insert " " s))
21033 kwds))
21034 (insert "\n"))
21035 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21036 (when rtnall
21037 (insert (org-finalize-agenda-entries rtnall) "\n"))
21038 (goto-char (point-min))
21039 (org-fit-agenda-window)
21040 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21041 (org-finalize-agenda)
21042 (setq buffer-read-only t)))
21044 ;;; Agenda tags match
21046 ;;;###autoload
21047 (defun org-tags-view (&optional todo-only match)
21048 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21049 The prefix arg TODO-ONLY limits the search to TODO entries."
21050 (interactive "P")
21051 (org-compile-prefix-format 'tags)
21052 (org-set-sorting-strategy 'tags)
21053 (let* ((org-tags-match-list-sublevels
21054 (if todo-only t org-tags-match-list-sublevels))
21055 (completion-ignore-case t)
21056 rtn rtnall files file pos matcher
21057 buffer)
21058 (setq matcher (org-make-tags-matcher match)
21059 match (car matcher) matcher (cdr matcher))
21060 (org-prepare-agenda (concat "TAGS " match))
21061 (setq org-agenda-query-string match)
21062 (setq org-agenda-redo-command
21063 (list 'org-tags-view (list 'quote todo-only)
21064 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21065 (setq files (org-agenda-files)
21066 rtnall nil)
21067 (while (setq file (pop files))
21068 (catch 'nextfile
21069 (org-check-agenda-file file)
21070 (setq buffer (if (file-exists-p file)
21071 (org-get-agenda-file-buffer file)
21072 (error "No such file %s" file)))
21073 (if (not buffer)
21074 ;; If file does not exist, merror message to agenda
21075 (setq rtn (list
21076 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21077 rtnall (append rtnall rtn))
21078 (with-current-buffer buffer
21079 (unless (org-mode-p)
21080 (error "Agenda file %s is not in `org-mode'" file))
21081 (save-excursion
21082 (save-restriction
21083 (if org-agenda-restrict
21084 (narrow-to-region org-agenda-restrict-begin
21085 org-agenda-restrict-end)
21086 (widen))
21087 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21088 (setq rtnall (append rtnall rtn))))))))
21089 (if org-agenda-overriding-header
21090 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21091 nil 'face 'org-agenda-structure) "\n")
21092 (insert "Headlines with TAGS match: ")
21093 (add-text-properties (point-min) (1- (point))
21094 (list 'face 'org-agenda-structure))
21095 (setq pos (point))
21096 (insert match "\n")
21097 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21098 (setq pos (point))
21099 (unless org-agenda-multi
21100 (insert "Press `C-u r' to search again with new search string\n"))
21101 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21102 (when rtnall
21103 (insert (org-finalize-agenda-entries rtnall) "\n"))
21104 (goto-char (point-min))
21105 (org-fit-agenda-window)
21106 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21107 (org-finalize-agenda)
21108 (setq buffer-read-only t)))
21110 ;;; Agenda Finding stuck projects
21112 (defvar org-agenda-skip-regexp nil
21113 "Regular expression used in skipping subtrees for the agenda.
21114 This is basically a temporary global variable that can be set and then
21115 used by user-defined selections using `org-agenda-skip-function'.")
21117 (defvar org-agenda-overriding-header nil
21118 "When this is set during todo and tags searches, will replace header.")
21120 (defun org-agenda-skip-subtree-when-regexp-matches ()
21121 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21122 If yes, it returns the end position of this tree, causing agenda commands
21123 to skip this subtree. This is a function that can be put into
21124 `org-agenda-skip-function' for the duration of a command."
21125 (let ((end (save-excursion (org-end-of-subtree t)))
21126 skip)
21127 (save-excursion
21128 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21129 (and skip end)))
21131 (defun org-agenda-skip-entry-if (&rest conditions)
21132 "Skip entry if any of CONDITIONS is true.
21133 See `org-agenda-skip-if' for details."
21134 (org-agenda-skip-if nil conditions))
21136 (defun org-agenda-skip-subtree-if (&rest conditions)
21137 "Skip entry if any of CONDITIONS is true.
21138 See `org-agenda-skip-if' for details."
21139 (org-agenda-skip-if t conditions))
21141 (defun org-agenda-skip-if (subtree conditions)
21142 "Checks current entity for CONDITIONS.
21143 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21144 the entry, i.e. the text before the next heading is checked.
21146 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21147 from different tests. Valid conditions are:
21149 scheduled Check if there is a scheduled cookie
21150 notscheduled Check if there is no scheduled cookie
21151 deadline Check if there is a deadline
21152 notdeadline Check if there is no deadline
21153 regexp Check if regexp matches
21154 notregexp Check if regexp does not match.
21156 The regexp is taken from the conditions list, it must come right after
21157 the `regexp' or `notregexp' element.
21159 If any of these conditions is met, this function returns the end point of
21160 the entity, causing the search to continue from there. This is a function
21161 that can be put into `org-agenda-skip-function' for the duration of a command."
21162 (let (beg end m)
21163 (org-back-to-heading t)
21164 (setq beg (point)
21165 end (if subtree
21166 (progn (org-end-of-subtree t) (point))
21167 (progn (outline-next-heading) (1- (point)))))
21168 (goto-char beg)
21169 (and
21171 (and (memq 'scheduled conditions)
21172 (re-search-forward org-scheduled-time-regexp end t))
21173 (and (memq 'notscheduled conditions)
21174 (not (re-search-forward org-scheduled-time-regexp end t)))
21175 (and (memq 'deadline conditions)
21176 (re-search-forward org-deadline-time-regexp end t))
21177 (and (memq 'notdeadline conditions)
21178 (not (re-search-forward org-deadline-time-regexp end t)))
21179 (and (setq m (memq 'regexp conditions))
21180 (stringp (nth 1 m))
21181 (re-search-forward (nth 1 m) end t))
21182 (and (setq m (memq 'notregexp conditions))
21183 (stringp (nth 1 m))
21184 (not (re-search-forward (nth 1 m) end t))))
21185 end)))
21187 ;;;###autoload
21188 (defun org-agenda-list-stuck-projects (&rest ignore)
21189 "Create agenda view for projects that are stuck.
21190 Stuck projects are project that have no next actions. For the definitions
21191 of what a project is and how to check if it stuck, customize the variable
21192 `org-stuck-projects'.
21193 MATCH is being ignored."
21194 (interactive)
21195 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21196 ;; FIXME: we could have used org-agenda-skip-if here.
21197 (org-agenda-overriding-header "List of stuck projects: ")
21198 (matcher (nth 0 org-stuck-projects))
21199 (todo (nth 1 org-stuck-projects))
21200 (todo-wds (if (member "*" todo)
21201 (progn
21202 (org-prepare-agenda-buffers (org-agenda-files))
21203 (org-delete-all
21204 org-done-keywords-for-agenda
21205 (copy-sequence org-todo-keywords-for-agenda)))
21206 todo))
21207 (todo-re (concat "^\\*+[ \t]+\\("
21208 (mapconcat 'identity todo-wds "\\|")
21209 "\\)\\>"))
21210 (tags (nth 2 org-stuck-projects))
21211 (tags-re (if (member "*" tags)
21212 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21213 (concat "^\\*+ .*:\\("
21214 (mapconcat 'identity tags "\\|")
21215 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21216 (gen-re (nth 3 org-stuck-projects))
21217 (re-list
21218 (delq nil
21219 (list
21220 (if todo todo-re)
21221 (if tags tags-re)
21222 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21223 gen-re)))))
21224 (setq org-agenda-skip-regexp
21225 (if re-list
21226 (mapconcat 'identity re-list "\\|")
21227 (error "No information how to identify unstuck projects")))
21228 (org-tags-view nil matcher)
21229 (with-current-buffer org-agenda-buffer-name
21230 (setq org-agenda-redo-command
21231 '(org-agenda-list-stuck-projects
21232 (or current-prefix-arg org-last-arg))))))
21234 ;;; Diary integration
21236 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21237 (defvar list-diary-entries-hook)
21239 (defun org-get-entries-from-diary (date)
21240 "Get the (Emacs Calendar) diary entries for DATE."
21241 (require 'diary-lib)
21242 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21243 (diary-display-hook '(fancy-diary-display))
21244 (pop-up-frames nil)
21245 (list-diary-entries-hook
21246 (cons 'org-diary-default-entry list-diary-entries-hook))
21247 (diary-file-name-prefix-function nil) ; turn this feature off
21248 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21249 entries
21250 (org-disable-agenda-to-diary t))
21251 (save-excursion
21252 (save-window-excursion
21253 (funcall (if (fboundp 'diary-list-entries)
21254 'diary-list-entries 'list-diary-entries)
21255 date 1)))
21256 (if (not (get-buffer fancy-diary-buffer))
21257 (setq entries nil)
21258 (with-current-buffer fancy-diary-buffer
21259 (setq buffer-read-only nil)
21260 (if (zerop (buffer-size))
21261 ;; No entries
21262 (setq entries nil)
21263 ;; Omit the date and other unnecessary stuff
21264 (org-agenda-cleanup-fancy-diary)
21265 ;; Add prefix to each line and extend the text properties
21266 (if (zerop (buffer-size))
21267 (setq entries nil)
21268 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21269 (set-buffer-modified-p nil)
21270 (kill-buffer fancy-diary-buffer)))
21271 (when entries
21272 (setq entries (org-split-string entries "\n"))
21273 (setq entries
21274 (mapcar
21275 (lambda (x)
21276 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21277 ;; Extend the text properties to the beginning of the line
21278 (org-add-props x (text-properties-at (1- (length x)) x)
21279 'type "diary" 'date date))
21280 entries)))))
21282 (defun org-agenda-cleanup-fancy-diary ()
21283 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21284 This gets rid of the date, the underline under the date, and
21285 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21286 date. It also removes lines that contain only whitespace."
21287 (goto-char (point-min))
21288 (if (looking-at ".*?:[ \t]*")
21289 (progn
21290 (replace-match "")
21291 (re-search-forward "\n=+$" nil t)
21292 (replace-match "")
21293 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21294 (re-search-forward "\n=+$" nil t)
21295 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21296 (goto-char (point-min))
21297 (while (re-search-forward "^ +\n" nil t)
21298 (replace-match ""))
21299 (goto-char (point-min))
21300 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21301 (replace-match "")))
21303 ;; Make sure entries from the diary have the right text properties.
21304 (eval-after-load "diary-lib"
21305 '(if (boundp 'diary-modify-entry-list-string-function)
21306 ;; We can rely on the hook, nothing to do
21308 ;; Hook not avaiable, must use advice to make this work
21309 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21310 "Make the position visible."
21311 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21312 (stringp string)
21313 buffer-file-name)
21314 (setq string (org-modify-diary-entry-string string))))))
21316 (defun org-modify-diary-entry-string (string)
21317 "Add text properties to string, allowing org-mode to act on it."
21318 (org-add-props string nil
21319 'mouse-face 'highlight
21320 'keymap org-agenda-keymap
21321 'help-echo (if buffer-file-name
21322 (format "mouse-2 or RET jump to diary file %s"
21323 (abbreviate-file-name buffer-file-name))
21325 'org-agenda-diary-link t
21326 'org-marker (org-agenda-new-marker (point-at-bol))))
21328 (defun org-diary-default-entry ()
21329 "Add a dummy entry to the diary.
21330 Needed to avoid empty dates which mess up holiday display."
21331 ;; Catch the error if dealing with the new add-to-diary-alist
21332 (when org-disable-agenda-to-diary
21333 (condition-case nil
21334 (add-to-diary-list original-date "Org-mode dummy" "")
21335 (error
21336 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21338 ;;;###autoload
21339 (defun org-diary (&rest args)
21340 "Return diary information from org-files.
21341 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21342 It accesses org files and extracts information from those files to be
21343 listed in the diary. The function accepts arguments specifying what
21344 items should be listed. The following arguments are allowed:
21346 :timestamp List the headlines of items containing a date stamp or
21347 date range matching the selected date. Deadlines will
21348 also be listed, on the expiration day.
21350 :sexp List entries resulting from diary-like sexps.
21352 :deadline List any deadlines past due, or due within
21353 `org-deadline-warning-days'. The listing occurs only
21354 in the diary for *today*, not at any other date. If
21355 an entry is marked DONE, it is no longer listed.
21357 :scheduled List all items which are scheduled for the given date.
21358 The diary for *today* also contains items which were
21359 scheduled earlier and are not yet marked DONE.
21361 :todo List all TODO items from the org-file. This may be a
21362 long list - so this is not turned on by default.
21363 Like deadlines, these entries only show up in the
21364 diary for *today*, not at any other date.
21366 The call in the diary file should look like this:
21368 &%%(org-diary) ~/path/to/some/orgfile.org
21370 Use a separate line for each org file to check. Or, if you omit the file name,
21371 all files listed in `org-agenda-files' will be checked automatically:
21373 &%%(org-diary)
21375 If you don't give any arguments (as in the example above), the default
21376 arguments (:deadline :scheduled :timestamp :sexp) are used.
21377 So the example above may also be written as
21379 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21381 The function expects the lisp variables `entry' and `date' to be provided
21382 by the caller, because this is how the calendar works. Don't use this
21383 function from a program - use `org-agenda-get-day-entries' instead."
21384 (when (> (- (time-to-seconds (current-time))
21385 org-agenda-last-marker-time)
21387 (org-agenda-reset-markers))
21388 (org-compile-prefix-format 'agenda)
21389 (org-set-sorting-strategy 'agenda)
21390 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21391 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21392 (list entry)
21393 (org-agenda-files t)))
21394 file rtn results)
21395 (org-prepare-agenda-buffers files)
21396 ;; If this is called during org-agenda, don't return any entries to
21397 ;; the calendar. Org Agenda will list these entries itself.
21398 (if org-disable-agenda-to-diary (setq files nil))
21399 (while (setq file (pop files))
21400 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21401 (setq results (append results rtn)))
21402 (if results
21403 (concat (org-finalize-agenda-entries results) "\n"))))
21405 ;;; Agenda entry finders
21407 (defun org-agenda-get-day-entries (file date &rest args)
21408 "Does the work for `org-diary' and `org-agenda'.
21409 FILE is the path to a file to be checked for entries. DATE is date like
21410 the one returned by `calendar-current-date'. ARGS are symbols indicating
21411 which kind of entries should be extracted. For details about these, see
21412 the documentation of `org-diary'."
21413 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21414 (let* ((org-startup-folded nil)
21415 (org-startup-align-all-tables nil)
21416 (buffer (if (file-exists-p file)
21417 (org-get-agenda-file-buffer file)
21418 (error "No such file %s" file)))
21419 arg results rtn)
21420 (if (not buffer)
21421 ;; If file does not exist, make sure an error message ends up in diary
21422 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21423 (with-current-buffer buffer
21424 (unless (org-mode-p)
21425 (error "Agenda file %s is not in `org-mode'" file))
21426 (let ((case-fold-search nil))
21427 (save-excursion
21428 (save-restriction
21429 (if org-agenda-restrict
21430 (narrow-to-region org-agenda-restrict-begin
21431 org-agenda-restrict-end)
21432 (widen))
21433 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21434 (while (setq arg (pop args))
21435 (cond
21436 ((and (eq arg :todo)
21437 (equal date (calendar-current-date)))
21438 (setq rtn (org-agenda-get-todos))
21439 (setq results (append results rtn)))
21440 ((eq arg :timestamp)
21441 (setq rtn (org-agenda-get-blocks))
21442 (setq results (append results rtn))
21443 (setq rtn (org-agenda-get-timestamps))
21444 (setq results (append results rtn)))
21445 ((eq arg :sexp)
21446 (setq rtn (org-agenda-get-sexps))
21447 (setq results (append results rtn)))
21448 ((eq arg :scheduled)
21449 (setq rtn (org-agenda-get-scheduled))
21450 (setq results (append results rtn)))
21451 ((eq arg :closed)
21452 (setq rtn (org-agenda-get-closed))
21453 (setq results (append results rtn)))
21454 ((eq arg :deadline)
21455 (setq rtn (org-agenda-get-deadlines))
21456 (setq results (append results rtn))))))))
21457 results))))
21459 (defun org-entry-is-todo-p ()
21460 (member (org-get-todo-state) org-not-done-keywords))
21462 (defun org-entry-is-done-p ()
21463 (member (org-get-todo-state) org-done-keywords))
21465 (defun org-get-todo-state ()
21466 (save-excursion
21467 (org-back-to-heading t)
21468 (and (looking-at org-todo-line-regexp)
21469 (match-end 2)
21470 (match-string 2))))
21472 (defun org-at-date-range-p (&optional inactive-ok)
21473 "Is the cursor inside a date range?"
21474 (interactive)
21475 (save-excursion
21476 (catch 'exit
21477 (let ((pos (point)))
21478 (skip-chars-backward "^[<\r\n")
21479 (skip-chars-backward "<[")
21480 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21481 (>= (match-end 0) pos)
21482 (throw 'exit t))
21483 (skip-chars-backward "^<[\r\n")
21484 (skip-chars-backward "<[")
21485 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21486 (>= (match-end 0) pos)
21487 (throw 'exit t)))
21488 nil)))
21490 (defun org-agenda-get-todos ()
21491 "Return the TODO information for agenda display."
21492 (let* ((props (list 'face nil
21493 'done-face 'org-done
21494 'org-not-done-regexp org-not-done-regexp
21495 'org-todo-regexp org-todo-regexp
21496 'mouse-face 'highlight
21497 'keymap org-agenda-keymap
21498 'help-echo
21499 (format "mouse-2 or RET jump to org file %s"
21500 (abbreviate-file-name buffer-file-name))))
21501 ;; FIXME: get rid of the \n at some point but watch out
21502 (regexp (concat "^\\*+[ \t]+\\("
21503 (if org-select-this-todo-keyword
21504 (if (equal org-select-this-todo-keyword "*")
21505 org-todo-regexp
21506 (concat "\\<\\("
21507 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21508 "\\)\\>"))
21509 org-not-done-regexp)
21510 "[^\n\r]*\\)"))
21511 marker priority category tags
21512 ee txt beg end)
21513 (goto-char (point-min))
21514 (while (re-search-forward regexp nil t)
21515 (catch :skip
21516 (save-match-data
21517 (beginning-of-line)
21518 (setq beg (point) end (progn (outline-next-heading) (point)))
21519 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21520 (re-search-forward org-ts-regexp end t))
21521 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21522 (re-search-forward org-scheduled-time-regexp end t))
21523 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21524 (re-search-forward org-deadline-time-regexp end t)
21525 (org-deadline-close (match-string 1))))
21526 (goto-char (1+ beg))
21527 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21528 (throw :skip nil)))
21529 (goto-char beg)
21530 (org-agenda-skip)
21531 (goto-char (match-beginning 1))
21532 (setq marker (org-agenda-new-marker (match-beginning 0))
21533 category (org-get-category)
21534 tags (org-get-tags-at (point))
21535 txt (org-format-agenda-item "" (match-string 1) category tags)
21536 priority (1+ (org-get-priority txt)))
21537 (org-add-props txt props
21538 'org-marker marker 'org-hd-marker marker
21539 'priority priority 'org-category category
21540 'type "todo")
21541 (push txt ee)
21542 (if org-agenda-todo-list-sublevels
21543 (goto-char (match-end 1))
21544 (org-end-of-subtree 'invisible))))
21545 (nreverse ee)))
21547 (defconst org-agenda-no-heading-message
21548 "No heading for this item in buffer or region.")
21550 (defun org-agenda-get-timestamps ()
21551 "Return the date stamp information for agenda display."
21552 (let* ((props (list 'face nil
21553 'org-not-done-regexp org-not-done-regexp
21554 'org-todo-regexp org-todo-regexp
21555 'mouse-face 'highlight
21556 'keymap org-agenda-keymap
21557 'help-echo
21558 (format "mouse-2 or RET jump to org file %s"
21559 (abbreviate-file-name buffer-file-name))))
21560 (d1 (calendar-absolute-from-gregorian date))
21561 (remove-re
21562 (concat
21563 (regexp-quote
21564 (format-time-string
21565 "<%Y-%m-%d"
21566 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21567 ".*?>"))
21568 (regexp
21569 (concat
21570 (regexp-quote
21571 (substring
21572 (format-time-string
21573 (car org-time-stamp-formats)
21574 (apply 'encode-time ; DATE bound by calendar
21575 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21576 0 11))
21577 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21578 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21579 marker hdmarker deadlinep scheduledp donep tmp priority category
21580 ee txt timestr tags b0 b3 e3 head)
21581 (goto-char (point-min))
21582 (while (re-search-forward regexp nil t)
21583 (setq b0 (match-beginning 0)
21584 b3 (match-beginning 3) e3 (match-end 3))
21585 (catch :skip
21586 (and (org-at-date-range-p) (throw :skip nil))
21587 (org-agenda-skip)
21588 (if (and (match-end 1)
21589 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21590 (throw :skip nil))
21591 (if (and e3
21592 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21593 (throw :skip nil))
21594 (setq marker (org-agenda-new-marker b0)
21595 category (org-get-category b0)
21596 tmp (buffer-substring (max (point-min)
21597 (- b0 org-ds-keyword-length))
21599 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21600 deadlinep (string-match org-deadline-regexp tmp)
21601 scheduledp (string-match org-scheduled-regexp tmp)
21602 donep (org-entry-is-done-p))
21603 (if (or scheduledp deadlinep) (throw :skip t))
21604 (if (string-match ">" timestr)
21605 ;; substring should only run to end of time stamp
21606 (setq timestr (substring timestr 0 (match-end 0))))
21607 (save-excursion
21608 (if (re-search-backward "^\\*+ " nil t)
21609 (progn
21610 (goto-char (match-beginning 0))
21611 (setq hdmarker (org-agenda-new-marker)
21612 tags (org-get-tags-at))
21613 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21614 (setq head (match-string 1))
21615 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21616 (setq txt (org-format-agenda-item
21617 nil head category tags timestr nil
21618 remove-re)))
21619 (setq txt org-agenda-no-heading-message))
21620 (setq priority (org-get-priority txt))
21621 (org-add-props txt props
21622 'org-marker marker 'org-hd-marker hdmarker)
21623 (org-add-props txt nil 'priority priority
21624 'org-category category 'date date
21625 'type "timestamp")
21626 (push txt ee))
21627 (outline-next-heading)))
21628 (nreverse ee)))
21630 (defun org-agenda-get-sexps ()
21631 "Return the sexp information for agenda display."
21632 (require 'diary-lib)
21633 (let* ((props (list 'face nil
21634 'mouse-face 'highlight
21635 'keymap org-agenda-keymap
21636 'help-echo
21637 (format "mouse-2 or RET jump to org file %s"
21638 (abbreviate-file-name buffer-file-name))))
21639 (regexp "^&?%%(")
21640 marker category ee txt tags entry result beg b sexp sexp-entry)
21641 (goto-char (point-min))
21642 (while (re-search-forward regexp nil t)
21643 (catch :skip
21644 (org-agenda-skip)
21645 (setq beg (match-beginning 0))
21646 (goto-char (1- (match-end 0)))
21647 (setq b (point))
21648 (forward-sexp 1)
21649 (setq sexp (buffer-substring b (point)))
21650 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21651 (org-trim (match-string 1))
21652 ""))
21653 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21654 (when result
21655 (setq marker (org-agenda-new-marker beg)
21656 category (org-get-category beg))
21658 (if (string-match "\\S-" result)
21659 (setq txt result)
21660 (setq txt "SEXP entry returned empty string"))
21662 (setq txt (org-format-agenda-item
21663 "" txt category tags 'time))
21664 (org-add-props txt props 'org-marker marker)
21665 (org-add-props txt nil
21666 'org-category category 'date date
21667 'type "sexp")
21668 (push txt ee))))
21669 (nreverse ee)))
21671 (defun org-agenda-get-closed ()
21672 "Return the logged TODO entries for agenda display."
21673 (let* ((props (list 'mouse-face 'highlight
21674 'org-not-done-regexp org-not-done-regexp
21675 'org-todo-regexp org-todo-regexp
21676 'keymap org-agenda-keymap
21677 'help-echo
21678 (format "mouse-2 or RET jump to org file %s"
21679 (abbreviate-file-name buffer-file-name))))
21680 (regexp (concat
21681 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21682 (regexp-quote
21683 (substring
21684 (format-time-string
21685 (car org-time-stamp-formats)
21686 (apply 'encode-time ; DATE bound by calendar
21687 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21688 1 11))))
21689 marker hdmarker priority category tags closedp
21690 ee txt timestr)
21691 (goto-char (point-min))
21692 (while (re-search-forward regexp nil t)
21693 (catch :skip
21694 (org-agenda-skip)
21695 (setq marker (org-agenda-new-marker (match-beginning 0))
21696 closedp (equal (match-string 1) org-closed-string)
21697 category (org-get-category (match-beginning 0))
21698 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21699 ;; donep (org-entry-is-done-p)
21701 (if (string-match "\\]" timestr)
21702 ;; substring should only run to end of time stamp
21703 (setq timestr (substring timestr 0 (match-end 0))))
21704 (save-excursion
21705 (if (re-search-backward "^\\*+ " nil t)
21706 (progn
21707 (goto-char (match-beginning 0))
21708 (setq hdmarker (org-agenda-new-marker)
21709 tags (org-get-tags-at))
21710 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21711 (setq txt (org-format-agenda-item
21712 (if closedp "Closed: " "Clocked: ")
21713 (match-string 1) category tags timestr)))
21714 (setq txt org-agenda-no-heading-message))
21715 (setq priority 100000)
21716 (org-add-props txt props
21717 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21718 'priority priority 'org-category category
21719 'type "closed" 'date date
21720 'undone-face 'org-warning 'done-face 'org-done)
21721 (push txt ee))
21722 (goto-char (point-at-eol))))
21723 (nreverse ee)))
21725 (defun org-agenda-get-deadlines ()
21726 "Return the deadline information for agenda display."
21727 (let* ((props (list 'mouse-face 'highlight
21728 'org-not-done-regexp org-not-done-regexp
21729 'org-todo-regexp org-todo-regexp
21730 'keymap org-agenda-keymap
21731 'help-echo
21732 (format "mouse-2 or RET jump to org file %s"
21733 (abbreviate-file-name buffer-file-name))))
21734 (regexp org-deadline-time-regexp)
21735 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21736 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21737 d2 diff dfrac wdays pos pos1 category tags
21738 ee txt head face s upcomingp donep timestr)
21739 (goto-char (point-min))
21740 (while (re-search-forward regexp nil t)
21741 (catch :skip
21742 (org-agenda-skip)
21743 (setq s (match-string 1)
21744 pos (1- (match-beginning 1))
21745 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21746 diff (- d2 d1)
21747 wdays (org-get-wdays s)
21748 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21749 upcomingp (and todayp (> diff 0)))
21750 ;; When to show a deadline in the calendar:
21751 ;; If the expiration is within wdays warning time.
21752 ;; Past-due deadlines are only shown on the current date
21753 (if (or (and (<= diff wdays)
21754 (and todayp (not org-agenda-only-exact-dates)))
21755 (= diff 0))
21756 (save-excursion
21757 (setq category (org-get-category))
21758 (if (re-search-backward "^\\*+[ \t]+" nil t)
21759 (progn
21760 (goto-char (match-end 0))
21761 (setq pos1 (match-beginning 0))
21762 (setq tags (org-get-tags-at pos1))
21763 (setq head (buffer-substring-no-properties
21764 (point)
21765 (progn (skip-chars-forward "^\r\n")
21766 (point))))
21767 (setq donep (string-match org-looking-at-done-regexp head))
21768 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21769 (setq timestr
21770 (concat (substring s (match-beginning 1)) " "))
21771 (setq timestr 'time))
21772 (if (and donep
21773 (or org-agenda-skip-deadline-if-done
21774 (not (= diff 0))))
21775 (setq txt nil)
21776 (setq txt (org-format-agenda-item
21777 (if (= diff 0)
21778 (car org-agenda-deadline-leaders)
21779 (format (nth 1 org-agenda-deadline-leaders)
21780 diff))
21781 head category tags timestr))))
21782 (setq txt org-agenda-no-heading-message))
21783 (when txt
21784 (setq face (org-agenda-deadline-face dfrac wdays))
21785 (org-add-props txt props
21786 'org-marker (org-agenda-new-marker pos)
21787 'org-hd-marker (org-agenda-new-marker pos1)
21788 'priority (+ (- diff)
21789 (org-get-priority txt))
21790 'org-category category
21791 'type (if upcomingp "upcoming-deadline" "deadline")
21792 'date (if upcomingp date d2)
21793 'face (if donep 'org-done face)
21794 'undone-face face 'done-face 'org-done)
21795 (push txt ee))))))
21796 (nreverse ee)))
21798 (defun org-agenda-deadline-face (fraction &optional wdays)
21799 "Return the face to displaying a deadline item.
21800 FRACTION is what fraction of the head-warning time has passed."
21801 (if (equal wdays 0) (setq fraction 1.))
21802 (let ((faces org-agenda-deadline-faces) f)
21803 (catch 'exit
21804 (while (setq f (pop faces))
21805 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21807 (defun org-agenda-get-scheduled ()
21808 "Return the scheduled information for agenda display."
21809 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21810 'org-todo-regexp org-todo-regexp
21811 'done-face 'org-done
21812 'mouse-face 'highlight
21813 'keymap org-agenda-keymap
21814 'help-echo
21815 (format "mouse-2 or RET jump to org file %s"
21816 (abbreviate-file-name buffer-file-name))))
21817 (regexp org-scheduled-time-regexp)
21818 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21819 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21820 d2 diff pos pos1 category tags
21821 ee txt head pastschedp donep face timestr s)
21822 (goto-char (point-min))
21823 (while (re-search-forward regexp nil t)
21824 (catch :skip
21825 (org-agenda-skip)
21826 (setq s (match-string 1)
21827 pos (1- (match-beginning 1))
21828 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21829 ;;; is this right?
21830 ;;; do we need to do this for deadleine too????
21831 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21832 diff (- d2 d1))
21833 (setq pastschedp (and todayp (< diff 0)))
21834 ;; When to show a scheduled item in the calendar:
21835 ;; If it is on or past the date.
21836 (if (or (and (< diff 0)
21837 (< (abs diff) org-scheduled-past-days)
21838 (and todayp (not org-agenda-only-exact-dates)))
21839 (= diff 0))
21840 (save-excursion
21841 (setq category (org-get-category))
21842 (if (re-search-backward "^\\*+[ \t]+" nil t)
21843 (progn
21844 (goto-char (match-end 0))
21845 (setq pos1 (match-beginning 0))
21846 (setq tags (org-get-tags-at))
21847 (setq head (buffer-substring-no-properties
21848 (point)
21849 (progn (skip-chars-forward "^\r\n") (point))))
21850 (setq donep (string-match org-looking-at-done-regexp head))
21851 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21852 (setq timestr
21853 (concat (substring s (match-beginning 1)) " "))
21854 (setq timestr 'time))
21855 (if (and donep
21856 (or org-agenda-skip-scheduled-if-done
21857 (not (= diff 0))))
21858 (setq txt nil)
21859 (setq txt (org-format-agenda-item
21860 (if (= diff 0)
21861 (car org-agenda-scheduled-leaders)
21862 (format (nth 1 org-agenda-scheduled-leaders)
21863 (- 1 diff)))
21864 head category tags timestr))))
21865 (setq txt org-agenda-no-heading-message))
21866 (when txt
21867 (setq face (if pastschedp
21868 'org-scheduled-previously
21869 'org-scheduled-today))
21870 (org-add-props txt props
21871 'undone-face face
21872 'face (if donep 'org-done face)
21873 'org-marker (org-agenda-new-marker pos)
21874 'org-hd-marker (org-agenda-new-marker pos1)
21875 'type (if pastschedp "past-scheduled" "scheduled")
21876 'date (if pastschedp d2 date)
21877 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21878 'org-category category)
21879 (push txt ee))))))
21880 (nreverse ee)))
21882 (defun org-agenda-get-blocks ()
21883 "Return the date-range information for agenda display."
21884 (let* ((props (list 'face nil
21885 'org-not-done-regexp org-not-done-regexp
21886 'org-todo-regexp org-todo-regexp
21887 'mouse-face 'highlight
21888 'keymap org-agenda-keymap
21889 'help-echo
21890 (format "mouse-2 or RET jump to org file %s"
21891 (abbreviate-file-name buffer-file-name))))
21892 (regexp org-tr-regexp)
21893 (d0 (calendar-absolute-from-gregorian date))
21894 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21895 donep head)
21896 (goto-char (point-min))
21897 (while (re-search-forward regexp nil t)
21898 (catch :skip
21899 (org-agenda-skip)
21900 (setq pos (point))
21901 (setq timestr (match-string 0)
21902 s1 (match-string 1)
21903 s2 (match-string 2)
21904 d1 (time-to-days (org-time-string-to-time s1))
21905 d2 (time-to-days (org-time-string-to-time s2)))
21906 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21907 ;; Only allow days between the limits, because the normal
21908 ;; date stamps will catch the limits.
21909 (save-excursion
21910 (setq marker (org-agenda-new-marker (point)))
21911 (setq category (org-get-category))
21912 (if (re-search-backward "^\\*+ " nil t)
21913 (progn
21914 (goto-char (match-beginning 0))
21915 (setq hdmarker (org-agenda-new-marker (point)))
21916 (setq tags (org-get-tags-at))
21917 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21918 (setq head (match-string 1))
21919 (and org-agenda-skip-timestamp-if-done
21920 (org-entry-is-done-p)
21921 (throw :skip t))
21922 (setq txt (org-format-agenda-item
21923 (format (if (= d1 d2) "" "(%d/%d): ")
21924 (1+ (- d0 d1)) (1+ (- d2 d1)))
21925 head category tags
21926 (if (= d0 d1) timestr))))
21927 (setq txt org-agenda-no-heading-message))
21928 (org-add-props txt props
21929 'org-marker marker 'org-hd-marker hdmarker
21930 'type "block" 'date date
21931 'priority (org-get-priority txt) 'org-category category)
21932 (push txt ee)))
21933 (goto-char pos)))
21934 ;; Sort the entries by expiration date.
21935 (nreverse ee)))
21937 ;;; Agenda presentation and sorting
21939 (defconst org-plain-time-of-day-regexp
21940 (concat
21941 "\\(\\<[012]?[0-9]"
21942 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21943 "\\(--?"
21944 "\\(\\<[012]?[0-9]"
21945 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21946 "\\)?")
21947 "Regular expression to match a plain time or time range.
21948 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21949 groups carry important information:
21950 0 the full match
21951 1 the first time, range or not
21952 8 the second time, if it is a range.")
21954 (defconst org-plain-time-extension-regexp
21955 (concat
21956 "\\(\\<[012]?[0-9]"
21957 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
21958 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
21959 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
21960 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
21961 groups carry important information:
21962 0 the full match
21963 7 hours of duration
21964 9 minutes of duration")
21966 (defconst org-stamp-time-of-day-regexp
21967 (concat
21968 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
21969 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
21970 "\\(--?"
21971 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
21972 "Regular expression to match a timestamp time or time range.
21973 After a match, the following groups carry important information:
21974 0 the full match
21975 1 date plus weekday, for backreferencing to make sure both times on same day
21976 2 the first time, range or not
21977 4 the second time, if it is a range.")
21979 (defvar org-prefix-has-time nil
21980 "A flag, set by `org-compile-prefix-format'.
21981 The flag is set if the currently compiled format contains a `%t'.")
21982 (defvar org-prefix-has-tag nil
21983 "A flag, set by `org-compile-prefix-format'.
21984 The flag is set if the currently compiled format contains a `%T'.")
21986 (defun org-format-agenda-item (extra txt &optional category tags dotime
21987 noprefix remove-re)
21988 "Format TXT to be inserted into the agenda buffer.
21989 In particular, it adds the prefix and corresponding text properties. EXTRA
21990 must be a string and replaces the `%s' specifier in the prefix format.
21991 CATEGORY (string, symbol or nil) may be used to overrule the default
21992 category taken from local variable or file name. It will replace the `%c'
21993 specifier in the format. DOTIME, when non-nil, indicates that a
21994 time-of-day should be extracted from TXT for sorting of this entry, and for
21995 the `%t' specifier in the format. When DOTIME is a string, this string is
21996 searched for a time before TXT is. NOPREFIX is a flag and indicates that
21997 only the correctly processes TXT should be returned - this is used by
21998 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
21999 Any match of REMOVE-RE will be removed from TXT."
22000 (save-match-data
22001 ;; Diary entries sometimes have extra whitespace at the beginning
22002 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22003 (let* ((category (or category
22004 org-category
22005 (if buffer-file-name
22006 (file-name-sans-extension
22007 (file-name-nondirectory buffer-file-name))
22008 "")))
22009 (tag (if tags (nth (1- (length tags)) tags) ""))
22010 time ; time and tag are needed for the eval of the prefix format
22011 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22012 (time-of-day (and dotime (org-get-time-of-day ts)))
22013 stamp plain s0 s1 s2 rtn srp)
22014 (when (and dotime time-of-day org-prefix-has-time)
22015 ;; Extract starting and ending time and move them to prefix
22016 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22017 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22018 (setq s0 (match-string 0 ts)
22019 srp (and stamp (match-end 3))
22020 s1 (match-string (if plain 1 2) ts)
22021 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22023 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22024 ;; them, we might want to remove them there to avoid duplication.
22025 ;; The user can turn this off with a variable.
22026 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22027 (string-match (concat (regexp-quote s0) " *") txt)
22028 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22029 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22030 (= (match-beginning 0) 0)
22032 (setq txt (replace-match "" nil nil txt))))
22033 ;; Normalize the time(s) to 24 hour
22034 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22035 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22037 (when (and s1 (not s2) org-agenda-default-appointment-duration
22038 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22039 (let ((m (+ (string-to-number (match-string 2 s1))
22040 (* 60 (string-to-number (match-string 1 s1)))
22041 org-agenda-default-appointment-duration))
22043 (setq h (/ m 60) m (- m (* h 60)))
22044 (setq s2 (format "%02d:%02d" h m))))
22046 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22047 txt)
22048 ;; Tags are in the string
22049 (if (or (eq org-agenda-remove-tags t)
22050 (and org-agenda-remove-tags
22051 org-prefix-has-tag))
22052 (setq txt (replace-match "" t t txt))
22053 (setq txt (replace-match
22054 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22055 (match-string 2 txt))
22056 t t txt))))
22058 (when remove-re
22059 (while (string-match remove-re txt)
22060 (setq txt (replace-match "" t t txt))))
22062 ;; Create the final string
22063 (if noprefix
22064 (setq rtn txt)
22065 ;; Prepare the variables needed in the eval of the compiled format
22066 (setq time (cond (s2 (concat s1 "-" s2))
22067 (s1 (concat s1 "......"))
22068 (t ""))
22069 extra (or extra "")
22070 category (if (symbolp category) (symbol-name category) category))
22071 ;; Evaluate the compiled format
22072 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22074 ;; And finally add the text properties
22075 (org-add-props rtn nil
22076 'org-category (downcase category) 'tags tags
22077 'org-highest-priority org-highest-priority
22078 'org-lowest-priority org-lowest-priority
22079 'prefix-length (- (length rtn) (length txt))
22080 'time-of-day time-of-day
22081 'txt txt
22082 'time time
22083 'extra extra
22084 'dotime dotime))))
22086 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22087 (defvar org-agenda-sorting-strategy-selected nil)
22089 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22090 (catch 'exit
22091 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22092 ((and todayp (member 'today (car org-agenda-time-grid))))
22093 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22094 ((member 'weekly (car org-agenda-time-grid)))
22095 (t (throw 'exit list)))
22096 (let* ((have (delq nil (mapcar
22097 (lambda (x) (get-text-property 1 'time-of-day x))
22098 list)))
22099 (string (nth 1 org-agenda-time-grid))
22100 (gridtimes (nth 2 org-agenda-time-grid))
22101 (req (car org-agenda-time-grid))
22102 (remove (member 'remove-match req))
22103 new time)
22104 (if (and (member 'require-timed req) (not have))
22105 ;; don't show empty grid
22106 (throw 'exit list))
22107 (while (setq time (pop gridtimes))
22108 (unless (and remove (member time have))
22109 (setq time (int-to-string time))
22110 (push (org-format-agenda-item
22111 nil string "" nil
22112 (concat (substring time 0 -2) ":" (substring time -2)))
22113 new)
22114 (put-text-property
22115 1 (length (car new)) 'face 'org-time-grid (car new))))
22116 (if (member 'time-up org-agenda-sorting-strategy-selected)
22117 (append new list)
22118 (append list new)))))
22120 (defun org-compile-prefix-format (key)
22121 "Compile the prefix format into a Lisp form that can be evaluated.
22122 The resulting form is returned and stored in the variable
22123 `org-prefix-format-compiled'."
22124 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22125 (let ((s (cond
22126 ((stringp org-agenda-prefix-format)
22127 org-agenda-prefix-format)
22128 ((assq key org-agenda-prefix-format)
22129 (cdr (assq key org-agenda-prefix-format)))
22130 (t " %-12:c%?-12t% s")))
22131 (start 0)
22132 varform vars var e c f opt)
22133 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22134 s start)
22135 (setq var (cdr (assoc (match-string 4 s)
22136 '(("c" . category) ("t" . time) ("s" . extra)
22137 ("T" . tag))))
22138 c (or (match-string 3 s) "")
22139 opt (match-beginning 1)
22140 start (1+ (match-beginning 0)))
22141 (if (equal var 'time) (setq org-prefix-has-time t))
22142 (if (equal var 'tag) (setq org-prefix-has-tag t))
22143 (setq f (concat "%" (match-string 2 s) "s"))
22144 (if opt
22145 (setq varform
22146 `(if (equal "" ,var)
22148 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22149 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22150 (setq s (replace-match "%s" t nil s))
22151 (push varform vars))
22152 (setq vars (nreverse vars))
22153 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22155 (defun org-set-sorting-strategy (key)
22156 (if (symbolp (car org-agenda-sorting-strategy))
22157 ;; the old format
22158 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22159 (setq org-agenda-sorting-strategy-selected
22160 (or (cdr (assq key org-agenda-sorting-strategy))
22161 (cdr (assq 'agenda org-agenda-sorting-strategy))
22162 '(time-up category-keep priority-down)))))
22164 (defun org-get-time-of-day (s &optional string mod24)
22165 "Check string S for a time of day.
22166 If found, return it as a military time number between 0 and 2400.
22167 If not found, return nil.
22168 The optional STRING argument forces conversion into a 5 character wide string
22169 HH:MM."
22170 (save-match-data
22171 (when
22172 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22173 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22174 (let* ((h (string-to-number (match-string 1 s)))
22175 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22176 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22177 (am-p (equal ampm "am"))
22178 (h1 (cond ((not ampm) h)
22179 ((= h 12) (if am-p 0 12))
22180 (t (+ h (if am-p 0 12)))))
22181 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22182 (mod h1 24) h1))
22183 (t0 (+ (* 100 h2) m))
22184 (t1 (concat (if (>= h1 24) "+" " ")
22185 (if (< t0 100) "0" "")
22186 (if (< t0 10) "0" "")
22187 (int-to-string t0))))
22188 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22190 (defun org-finalize-agenda-entries (list &optional nosort)
22191 "Sort and concatenate the agenda items."
22192 (setq list (mapcar 'org-agenda-highlight-todo list))
22193 (if nosort
22194 list
22195 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22197 (defun org-agenda-highlight-todo (x)
22198 (let (re pl)
22199 (if (eq x 'line)
22200 (save-excursion
22201 (beginning-of-line 1)
22202 (setq re (get-text-property (point) 'org-todo-regexp))
22203 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22204 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22205 (add-text-properties (match-beginning 0) (match-end 0)
22206 (list 'face (org-get-todo-face 0)))
22207 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22208 (delete-region (match-beginning 1) (1- (match-end 0)))
22209 (goto-char (match-beginning 1))
22210 (insert (format org-agenda-todo-keyword-format s)))))
22211 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22212 pl (get-text-property 0 'prefix-length x))
22213 (when (and re
22214 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22215 x (or pl 0)) pl))
22216 (add-text-properties
22217 (or (match-end 1) (match-end 0)) (match-end 0)
22218 (list 'face (org-get-todo-face (match-string 2 x)))
22220 (setq x (concat (substring x 0 (match-end 1))
22221 (format org-agenda-todo-keyword-format
22222 (match-string 2 x))
22224 (substring x (match-end 3)))))
22225 x)))
22227 (defsubst org-cmp-priority (a b)
22228 "Compare the priorities of string A and B."
22229 (let ((pa (or (get-text-property 1 'priority a) 0))
22230 (pb (or (get-text-property 1 'priority b) 0)))
22231 (cond ((> pa pb) +1)
22232 ((< pa pb) -1)
22233 (t nil))))
22235 (defsubst org-cmp-category (a b)
22236 "Compare the string values of categories of strings A and B."
22237 (let ((ca (or (get-text-property 1 'org-category a) ""))
22238 (cb (or (get-text-property 1 'org-category b) "")))
22239 (cond ((string-lessp ca cb) -1)
22240 ((string-lessp cb ca) +1)
22241 (t nil))))
22243 (defsubst org-cmp-tag (a b)
22244 "Compare the string values of categories of strings A and B."
22245 (let ((ta (car (last (get-text-property 1 'tags a))))
22246 (tb (car (last (get-text-property 1 'tags b)))))
22247 (cond ((not ta) +1)
22248 ((not tb) -1)
22249 ((string-lessp ta tb) -1)
22250 ((string-lessp tb ta) +1)
22251 (t nil))))
22253 (defsubst org-cmp-time (a b)
22254 "Compare the time-of-day values of strings A and B."
22255 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22256 (ta (or (get-text-property 1 'time-of-day a) def))
22257 (tb (or (get-text-property 1 'time-of-day b) def)))
22258 (cond ((< ta tb) -1)
22259 ((< tb ta) +1)
22260 (t nil))))
22262 (defun org-entries-lessp (a b)
22263 "Predicate for sorting agenda entries."
22264 ;; The following variables will be used when the form is evaluated.
22265 ;; So even though the compiler complains, keep them.
22266 (let* ((time-up (org-cmp-time a b))
22267 (time-down (if time-up (- time-up) nil))
22268 (priority-up (org-cmp-priority a b))
22269 (priority-down (if priority-up (- priority-up) nil))
22270 (category-up (org-cmp-category a b))
22271 (category-down (if category-up (- category-up) nil))
22272 (category-keep (if category-up +1 nil))
22273 (tag-up (org-cmp-tag a b))
22274 (tag-down (if tag-up (- tag-up) nil)))
22275 (cdr (assoc
22276 (eval (cons 'or org-agenda-sorting-strategy-selected))
22277 '((-1 . t) (1 . nil) (nil . nil))))))
22279 ;;; Agenda restriction lock
22281 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22282 "Overlay to mark the headline to which arenda commands are restricted.")
22283 (org-overlay-put org-agenda-restriction-lock-overlay
22284 'face 'org-agenda-restriction-lock)
22285 (org-overlay-put org-agenda-restriction-lock-overlay
22286 'help-echo "Agendas are currently limited to this subtree.")
22287 (org-detach-overlay org-agenda-restriction-lock-overlay)
22288 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22289 "Overlay marking the agenda restriction line in speedbar.")
22290 (org-overlay-put org-speedbar-restriction-lock-overlay
22291 'face 'org-agenda-restriction-lock)
22292 (org-overlay-put org-speedbar-restriction-lock-overlay
22293 'help-echo "Agendas are currently limited to this item.")
22294 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22296 (defun org-agenda-set-restriction-lock (&optional type)
22297 "Set restriction lock for agenda, to current subtree or file.
22298 Restriction will be the file if TYPE is `file', or if type is the
22299 universal prefix '(4), or if the cursor is before the first headline
22300 in the file. Otherwise, restriction will be to the current subtree."
22301 (interactive "P")
22302 (and (equal type '(4)) (setq type 'file))
22303 (setq type (cond
22304 (type type)
22305 ((org-at-heading-p) 'subtree)
22306 ((condition-case nil (org-back-to-heading t) (error nil))
22307 'subtree)
22308 (t 'file)))
22309 (if (eq type 'subtree)
22310 (progn
22311 (setq org-agenda-restrict t)
22312 (setq org-agenda-overriding-restriction 'subtree)
22313 (put 'org-agenda-files 'org-restrict
22314 (list (buffer-file-name (buffer-base-buffer))))
22315 (org-back-to-heading t)
22316 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22317 (move-marker org-agenda-restrict-begin (point))
22318 (move-marker org-agenda-restrict-end
22319 (save-excursion (org-end-of-subtree t)))
22320 (message "Locking agenda restriction to subtree"))
22321 (put 'org-agenda-files 'org-restrict
22322 (list (buffer-file-name (buffer-base-buffer))))
22323 (setq org-agenda-restrict nil)
22324 (setq org-agenda-overriding-restriction 'file)
22325 (move-marker org-agenda-restrict-begin nil)
22326 (move-marker org-agenda-restrict-end nil)
22327 (message "Locking agenda restriction to file"))
22328 (setq current-prefix-arg nil)
22329 (org-agenda-maybe-redo))
22331 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22332 "Remove the agenda restriction lock."
22333 (interactive "P")
22334 (org-detach-overlay org-agenda-restriction-lock-overlay)
22335 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22336 (setq org-agenda-overriding-restriction nil)
22337 (setq org-agenda-restrict nil)
22338 (put 'org-agenda-files 'org-restrict nil)
22339 (move-marker org-agenda-restrict-begin nil)
22340 (move-marker org-agenda-restrict-end nil)
22341 (setq current-prefix-arg nil)
22342 (message "Agenda restriction lock removed")
22343 (or noupdate (org-agenda-maybe-redo)))
22345 (defun org-agenda-maybe-redo ()
22346 "If there is any window showing the agenda view, update it."
22347 (let ((w (get-buffer-window org-agenda-buffer-name t))
22348 (w0 (selected-window)))
22349 (when w
22350 (select-window w)
22351 (org-agenda-redo)
22352 (select-window w0)
22353 (if org-agenda-overriding-restriction
22354 (message "Agenda view shifted to new %s restriction"
22355 org-agenda-overriding-restriction)
22356 (message "Agenda restriction lock removed")))))
22358 ;;; Agenda commands
22360 (defun org-agenda-check-type (error &rest types)
22361 "Check if agenda buffer is of allowed type.
22362 If ERROR is non-nil, throw an error, otherwise just return nil."
22363 (if (memq org-agenda-type types)
22365 (if error
22366 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22367 nil)))
22369 (defun org-agenda-quit ()
22370 "Exit agenda by removing the window or the buffer."
22371 (interactive)
22372 (let ((buf (current-buffer)))
22373 (if (not (one-window-p)) (delete-window))
22374 (kill-buffer buf)
22375 (org-agenda-reset-markers)
22376 (org-columns-remove-overlays))
22377 ;; Maybe restore the pre-agenda window configuration.
22378 (and org-agenda-restore-windows-after-quit
22379 (not (eq org-agenda-window-setup 'other-frame))
22380 org-pre-agenda-window-conf
22381 (set-window-configuration org-pre-agenda-window-conf)))
22383 (defun org-agenda-exit ()
22384 "Exit agenda by removing the window or the buffer.
22385 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22386 Org-mode buffers visited directly by the user will not be touched."
22387 (interactive)
22388 (org-release-buffers org-agenda-new-buffers)
22389 (setq org-agenda-new-buffers nil)
22390 (org-agenda-quit))
22392 (defun org-agenda-execute (arg)
22393 "Execute another agenda command, keeping same window.\\<global-map>
22394 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22395 (interactive "P")
22396 (let ((org-agenda-window-setup 'current-window))
22397 (org-agenda arg)))
22399 (defun org-save-all-org-buffers ()
22400 "Save all Org-mode buffers without user confirmation."
22401 (interactive)
22402 (message "Saving all Org-mode buffers...")
22403 (save-some-buffers t 'org-mode-p)
22404 (message "Saving all Org-mode buffers... done"))
22406 (defun org-agenda-redo ()
22407 "Rebuild Agenda.
22408 When this is the global TODO list, a prefix argument will be interpreted."
22409 (interactive)
22410 (let* ((org-agenda-keep-modes t)
22411 (line (org-current-line))
22412 (window-line (- line (org-current-line (window-start))))
22413 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22414 (message "Rebuilding agenda buffer...")
22415 (org-let lprops '(eval org-agenda-redo-command))
22416 (setq org-agenda-undo-list nil
22417 org-agenda-pending-undo-list nil)
22418 (message "Rebuilding agenda buffer...done")
22419 (goto-line line)
22420 (recenter window-line)))
22422 (defun org-agenda-manipulate-query-add ()
22423 "Manipulate the query by adding a search term with positive selection.
22424 Positive selection means, the term must be matched for selection of an entry."
22425 (interactive)
22426 (org-agenda-manipulate-query ?\[))
22427 (defun org-agenda-manipulate-query-subtract ()
22428 "Manipulate the query by adding a search term with negative selection.
22429 Negative selection means, term must not be matched for selection of an entry."
22430 (interactive)
22431 (org-agenda-manipulate-query ?\]))
22432 (defun org-agenda-manipulate-query-add-re ()
22433 "Manipulate the query by adding a search regexp with positive selection.
22434 Positive selection means, the regexp must match for selection of an entry."
22435 (interactive)
22436 (org-agenda-manipulate-query ?\{))
22437 (defun org-agenda-manipulate-query-subtract-re ()
22438 "Manipulate the query by adding a search regexp with negative selection.
22439 Negative selection means, regexp must not match for selection of an entry."
22440 (interactive)
22441 (org-agenda-manipulate-query ?\}))
22442 (defun org-agenda-manipulate-query (char)
22443 (cond
22444 ((eq org-agenda-type 'search)
22445 (org-add-to-string
22446 'org-agenda-query-string
22447 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22448 (?\{ . " +{}") (?\} . " -{}")))))
22449 (setq org-agenda-redo-command
22450 (list 'org-search-view
22451 org-todo-only
22452 org-agenda-query-string
22453 (+ (length org-agenda-query-string)
22454 (if (member char '(?\{ ?\})) 0 1))))
22455 (set-register org-agenda-query-register org-agenda-query-string)
22456 (org-agenda-redo))
22457 (t (error "Canot manipulate query for %s-type agenda buffers"
22458 org-agenda-type))))
22460 (defun org-add-to-string (var string)
22461 (set var (concat (symbol-value var) string)))
22463 (defun org-agenda-goto-date (date)
22464 "Jump to DATE in agenda."
22465 (interactive (list (org-read-date)))
22466 (org-agenda-list nil date))
22468 (defun org-agenda-goto-today ()
22469 "Go to today."
22470 (interactive)
22471 (org-agenda-check-type t 'timeline 'agenda)
22472 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22473 (cond
22474 (tdpos (goto-char tdpos))
22475 ((eq org-agenda-type 'agenda)
22476 (let* ((sd (time-to-days
22477 (time-subtract (current-time)
22478 (list 0 (* 3600 org-extend-today-until) 0))))
22479 (comp (org-agenda-compute-time-span sd org-agenda-span))
22480 (org-agenda-overriding-arguments org-agenda-last-arguments))
22481 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22482 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22483 (org-agenda-redo)
22484 (org-agenda-find-same-or-today-or-agenda)))
22485 (t (error "Cannot find today")))))
22487 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22488 (goto-char
22489 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22490 (text-property-any (point-min) (point-max) 'org-today t)
22491 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22492 (point-min))))
22494 (defun org-agenda-later (arg)
22495 "Go forward in time by thee current span.
22496 With prefix ARG, go forward that many times the current span."
22497 (interactive "p")
22498 (org-agenda-check-type t 'agenda)
22499 (let* ((span org-agenda-span)
22500 (sd org-starting-day)
22501 (greg (calendar-gregorian-from-absolute sd))
22502 (cnt (get-text-property (point) 'org-day-cnt))
22503 greg2 nd)
22504 (cond
22505 ((eq span 'day)
22506 (setq sd (+ arg sd) nd 1))
22507 ((eq span 'week)
22508 (setq sd (+ (* 7 arg) sd) nd 7))
22509 ((eq span 'month)
22510 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22511 sd (calendar-absolute-from-gregorian greg2))
22512 (setcar greg2 (1+ (car greg2)))
22513 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22514 ((eq span 'year)
22515 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22516 sd (calendar-absolute-from-gregorian greg2))
22517 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22518 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22519 (let ((org-agenda-overriding-arguments
22520 (list (car org-agenda-last-arguments) sd nd t)))
22521 (org-agenda-redo)
22522 (org-agenda-find-same-or-today-or-agenda cnt))))
22524 (defun org-agenda-earlier (arg)
22525 "Go backward in time by the current span.
22526 With prefix ARG, go backward that many times the current span."
22527 (interactive "p")
22528 (org-agenda-later (- arg)))
22530 (defun org-agenda-day-view ()
22531 "Switch to daily view for agenda."
22532 (interactive)
22533 (setq org-agenda-ndays 1)
22534 (org-agenda-change-time-span 'day))
22535 (defun org-agenda-week-view ()
22536 "Switch to daily view for agenda."
22537 (interactive)
22538 (setq org-agenda-ndays 7)
22539 (org-agenda-change-time-span 'week))
22540 (defun org-agenda-month-view ()
22541 "Switch to daily view for agenda."
22542 (interactive)
22543 (org-agenda-change-time-span 'month))
22544 (defun org-agenda-year-view ()
22545 "Switch to daily view for agenda."
22546 (interactive)
22547 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22548 (org-agenda-change-time-span 'year)
22549 (error "Abort")))
22551 (defun org-agenda-change-time-span (span)
22552 "Change the agenda view to SPAN.
22553 SPAN may be `day', `week', `month', `year'."
22554 (org-agenda-check-type t 'agenda)
22555 (if (equal org-agenda-span span)
22556 (error "Viewing span is already \"%s\"" span))
22557 (let* ((sd (or (get-text-property (point) 'day)
22558 org-starting-day))
22559 (computed (org-agenda-compute-time-span sd span))
22560 (org-agenda-overriding-arguments
22561 (list (car org-agenda-last-arguments)
22562 (car computed) (cdr computed) t)))
22563 (org-agenda-redo)
22564 (org-agenda-find-same-or-today-or-agenda))
22565 (org-agenda-set-mode-name)
22566 (message "Switched to %s view" span))
22568 (defun org-agenda-compute-time-span (sd span)
22569 "Compute starting date and number of days for agenda.
22570 SPAN may be `day', `week', `month', `year'. The return value
22571 is a cons cell with the starting date and the number of days,
22572 so that the date SD will be in that range."
22573 (let* ((greg (calendar-gregorian-from-absolute sd))
22575 (cond
22576 ((eq span 'day)
22577 (setq nd 1))
22578 ((eq span 'week)
22579 (let* ((nt (calendar-day-of-week
22580 (calendar-gregorian-from-absolute sd)))
22581 (d (if org-agenda-start-on-weekday
22582 (- nt org-agenda-start-on-weekday)
22583 0)))
22584 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22585 (setq nd 7)))
22586 ((eq span 'month)
22587 (setq sd (calendar-absolute-from-gregorian
22588 (list (car greg) 1 (nth 2 greg)))
22589 nd (- (calendar-absolute-from-gregorian
22590 (list (1+ (car greg)) 1 (nth 2 greg)))
22591 sd)))
22592 ((eq span 'year)
22593 (setq sd (calendar-absolute-from-gregorian
22594 (list 1 1 (nth 2 greg)))
22595 nd (- (calendar-absolute-from-gregorian
22596 (list 1 1 (1+ (nth 2 greg))))
22597 sd))))
22598 (cons sd nd)))
22600 ;; FIXME: does not work if user makes date format that starts with a blank
22601 (defun org-agenda-next-date-line (&optional arg)
22602 "Jump to the next line indicating a date in agenda buffer."
22603 (interactive "p")
22604 (org-agenda-check-type t 'agenda 'timeline)
22605 (beginning-of-line 1)
22606 (if (looking-at "^\\S-") (forward-char 1))
22607 (if (not (re-search-forward "^\\S-" nil t arg))
22608 (progn
22609 (backward-char 1)
22610 (error "No next date after this line in this buffer")))
22611 (goto-char (match-beginning 0)))
22613 (defun org-agenda-previous-date-line (&optional arg)
22614 "Jump to the previous line indicating a date in agenda buffer."
22615 (interactive "p")
22616 (org-agenda-check-type t 'agenda 'timeline)
22617 (beginning-of-line 1)
22618 (if (not (re-search-backward "^\\S-" nil t arg))
22619 (error "No previous date before this line in this buffer")))
22621 ;; Initialize the highlight
22622 (defvar org-hl (org-make-overlay 1 1))
22623 (org-overlay-put org-hl 'face 'highlight)
22625 (defun org-highlight (begin end &optional buffer)
22626 "Highlight a region with overlay."
22627 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22628 org-hl begin end (or buffer (current-buffer))))
22630 (defun org-unhighlight ()
22631 "Detach overlay INDEX."
22632 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22634 ;; FIXME this is currently not used.
22635 (defun org-highlight-until-next-command (beg end &optional buffer)
22636 (org-highlight beg end buffer)
22637 (add-hook 'pre-command-hook 'org-unhighlight-once))
22638 (defun org-unhighlight-once ()
22639 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22640 (org-unhighlight))
22642 (defun org-agenda-follow-mode ()
22643 "Toggle follow mode in an agenda buffer."
22644 (interactive)
22645 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22646 (org-agenda-set-mode-name)
22647 (message "Follow mode is %s"
22648 (if org-agenda-follow-mode "on" "off")))
22650 (defun org-agenda-log-mode ()
22651 "Toggle log mode in an agenda buffer."
22652 (interactive)
22653 (org-agenda-check-type t 'agenda 'timeline)
22654 (setq org-agenda-show-log (not org-agenda-show-log))
22655 (org-agenda-set-mode-name)
22656 (org-agenda-redo)
22657 (message "Log mode is %s"
22658 (if org-agenda-show-log "on" "off")))
22660 (defun org-agenda-toggle-diary ()
22661 "Toggle diary inclusion in an agenda buffer."
22662 (interactive)
22663 (org-agenda-check-type t 'agenda)
22664 (setq org-agenda-include-diary (not org-agenda-include-diary))
22665 (org-agenda-redo)
22666 (org-agenda-set-mode-name)
22667 (message "Diary inclusion turned %s"
22668 (if org-agenda-include-diary "on" "off")))
22670 (defun org-agenda-toggle-time-grid ()
22671 "Toggle time grid in an agenda buffer."
22672 (interactive)
22673 (org-agenda-check-type t 'agenda)
22674 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22675 (org-agenda-redo)
22676 (org-agenda-set-mode-name)
22677 (message "Time-grid turned %s"
22678 (if org-agenda-use-time-grid "on" "off")))
22680 (defun org-agenda-set-mode-name ()
22681 "Set the mode name to indicate all the small mode settings."
22682 (setq mode-name
22683 (concat "Org-Agenda"
22684 (if (equal org-agenda-ndays 1) " Day" "")
22685 (if (equal org-agenda-ndays 7) " Week" "")
22686 (if org-agenda-follow-mode " Follow" "")
22687 (if org-agenda-include-diary " Diary" "")
22688 (if org-agenda-use-time-grid " Grid" "")
22689 (if org-agenda-show-log " Log" "")))
22690 (force-mode-line-update))
22692 (defun org-agenda-post-command-hook ()
22693 (and (eolp) (not (bolp)) (backward-char 1))
22694 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22695 (if (and org-agenda-follow-mode
22696 (get-text-property (point) 'org-marker))
22697 (org-agenda-show)))
22699 (defun org-agenda-show-priority ()
22700 "Show the priority of the current item.
22701 This priority is composed of the main priority given with the [#A] cookies,
22702 and by additional input from the age of a schedules or deadline entry."
22703 (interactive)
22704 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22705 (message "Priority is %d" (if pri pri -1000))))
22707 (defun org-agenda-show-tags ()
22708 "Show the tags applicable to the current item."
22709 (interactive)
22710 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22711 (if tags
22712 (message "Tags are :%s:"
22713 (org-no-properties (mapconcat 'identity tags ":")))
22714 (message "No tags associated with this line"))))
22716 (defun org-agenda-goto (&optional highlight)
22717 "Go to the Org-mode file which contains the item at point."
22718 (interactive)
22719 (let* ((marker (or (get-text-property (point) 'org-marker)
22720 (org-agenda-error)))
22721 (buffer (marker-buffer marker))
22722 (pos (marker-position marker)))
22723 (switch-to-buffer-other-window buffer)
22724 (widen)
22725 (goto-char pos)
22726 (when (org-mode-p)
22727 (org-show-context 'agenda)
22728 (save-excursion
22729 (and (outline-next-heading)
22730 (org-flag-heading nil)))) ; show the next heading
22731 (recenter (/ (window-height) 2))
22732 (run-hooks 'org-agenda-after-show-hook)
22733 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22735 (defvar org-agenda-after-show-hook nil
22736 "Normal hook run after an item has been shown from the agenda.
22737 Point is in the buffer where the item originated.")
22739 (defun org-agenda-kill ()
22740 "Kill the entry or subtree belonging to the current agenda entry."
22741 (interactive)
22742 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22743 (let* ((marker (or (get-text-property (point) 'org-marker)
22744 (org-agenda-error)))
22745 (buffer (marker-buffer marker))
22746 (pos (marker-position marker))
22747 (type (get-text-property (point) 'type))
22748 dbeg dend (n 0) conf)
22749 (org-with-remote-undo buffer
22750 (with-current-buffer buffer
22751 (save-excursion
22752 (goto-char pos)
22753 (if (and (org-mode-p) (not (member type '("sexp"))))
22754 (setq dbeg (progn (org-back-to-heading t) (point))
22755 dend (org-end-of-subtree t t))
22756 (setq dbeg (point-at-bol)
22757 dend (min (point-max) (1+ (point-at-eol)))))
22758 (goto-char dbeg)
22759 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22760 (setq conf (or (eq t org-agenda-confirm-kill)
22761 (and (numberp org-agenda-confirm-kill)
22762 (> n org-agenda-confirm-kill))))
22763 (and conf
22764 (not (y-or-n-p
22765 (format "Delete entry with %d lines in buffer \"%s\"? "
22766 n (buffer-name buffer))))
22767 (error "Abort"))
22768 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22769 (with-current-buffer buffer (delete-region dbeg dend))
22770 (message "Agenda item and source killed"))))
22772 (defun org-agenda-archive ()
22773 "Kill the entry or subtree belonging to the current agenda entry."
22774 (interactive)
22775 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22776 (let* ((marker (or (get-text-property (point) 'org-marker)
22777 (org-agenda-error)))
22778 (buffer (marker-buffer marker))
22779 (pos (marker-position marker)))
22780 (org-with-remote-undo buffer
22781 (with-current-buffer buffer
22782 (if (org-mode-p)
22783 (save-excursion
22784 (goto-char pos)
22785 (org-remove-subtree-entries-from-agenda)
22786 (org-back-to-heading t)
22787 (org-archive-subtree))
22788 (error "Archiving works only in Org-mode files"))))))
22790 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22791 "Remove all lines in the agenda that correspond to a given subtree.
22792 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22793 If this information is not given, the function uses the tree at point."
22794 (let ((buf (or buf (current-buffer))) m p)
22795 (save-excursion
22796 (unless (and beg end)
22797 (org-back-to-heading t)
22798 (setq beg (point))
22799 (org-end-of-subtree t)
22800 (setq end (point)))
22801 (set-buffer (get-buffer org-agenda-buffer-name))
22802 (save-excursion
22803 (goto-char (point-max))
22804 (beginning-of-line 1)
22805 (while (not (bobp))
22806 (when (and (setq m (get-text-property (point) 'org-marker))
22807 (equal buf (marker-buffer m))
22808 (setq p (marker-position m))
22809 (>= p beg)
22810 (<= p end))
22811 (let ((inhibit-read-only t))
22812 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22813 (beginning-of-line 0))))))
22815 (defun org-agenda-open-link ()
22816 "Follow the link in the current line, if any."
22817 (interactive)
22818 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22819 (save-excursion
22820 (save-restriction
22821 (narrow-to-region (point-at-bol) (point-at-eol))
22822 (org-open-at-point))))
22824 (defun org-agenda-copy-local-variable (var)
22825 "Get a variable from a referenced buffer and install it here."
22826 (let ((m (get-text-property (point) 'org-marker)))
22827 (when (and m (buffer-live-p (marker-buffer m)))
22828 (org-set-local var (with-current-buffer (marker-buffer m)
22829 (symbol-value var))))))
22831 (defun org-agenda-switch-to (&optional delete-other-windows)
22832 "Go to the Org-mode file which contains the item at point."
22833 (interactive)
22834 (let* ((marker (or (get-text-property (point) 'org-marker)
22835 (org-agenda-error)))
22836 (buffer (marker-buffer marker))
22837 (pos (marker-position marker)))
22838 (switch-to-buffer buffer)
22839 (and delete-other-windows (delete-other-windows))
22840 (widen)
22841 (goto-char pos)
22842 (when (org-mode-p)
22843 (org-show-context 'agenda)
22844 (save-excursion
22845 (and (outline-next-heading)
22846 (org-flag-heading nil)))))) ; show the next heading
22848 (defun org-agenda-goto-mouse (ev)
22849 "Go to the Org-mode file which contains the item at the mouse click."
22850 (interactive "e")
22851 (mouse-set-point ev)
22852 (org-agenda-goto))
22854 (defun org-agenda-show ()
22855 "Display the Org-mode file which contains the item at point."
22856 (interactive)
22857 (let ((win (selected-window)))
22858 (org-agenda-goto t)
22859 (select-window win)))
22861 (defun org-agenda-recenter (arg)
22862 "Display the Org-mode file which contains the item at point and recenter."
22863 (interactive "P")
22864 (let ((win (selected-window)))
22865 (org-agenda-goto t)
22866 (recenter arg)
22867 (select-window win)))
22869 (defun org-agenda-show-mouse (ev)
22870 "Display the Org-mode file which contains the item at the mouse click."
22871 (interactive "e")
22872 (mouse-set-point ev)
22873 (org-agenda-show))
22875 (defun org-agenda-check-no-diary ()
22876 "Check if the entry is a diary link and abort if yes."
22877 (if (get-text-property (point) 'org-agenda-diary-link)
22878 (org-agenda-error)))
22880 (defun org-agenda-error ()
22881 (error "Command not allowed in this line"))
22883 (defun org-agenda-tree-to-indirect-buffer ()
22884 "Show the subtree corresponding to the current entry in an indirect buffer.
22885 This calls the command `org-tree-to-indirect-buffer' from the original
22886 Org-mode buffer.
22887 With numerical prefix arg ARG, go up to this level and then take that tree.
22888 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22889 dedicated frame)."
22890 (interactive)
22891 (org-agenda-check-no-diary)
22892 (let* ((marker (or (get-text-property (point) 'org-marker)
22893 (org-agenda-error)))
22894 (buffer (marker-buffer marker))
22895 (pos (marker-position marker)))
22896 (with-current-buffer buffer
22897 (save-excursion
22898 (goto-char pos)
22899 (call-interactively 'org-tree-to-indirect-buffer)))))
22901 (defvar org-last-heading-marker (make-marker)
22902 "Marker pointing to the headline that last changed its TODO state
22903 by a remote command from the agenda.")
22905 (defun org-agenda-todo-nextset ()
22906 "Switch TODO entry to next sequence."
22907 (interactive)
22908 (org-agenda-todo 'nextset))
22910 (defun org-agenda-todo-previousset ()
22911 "Switch TODO entry to previous sequence."
22912 (interactive)
22913 (org-agenda-todo 'previousset))
22915 (defun org-agenda-todo (&optional arg)
22916 "Cycle TODO state of line at point, also in Org-mode file.
22917 This changes the line at point, all other lines in the agenda referring to
22918 the same tree node, and the headline of the tree node in the Org-mode file."
22919 (interactive "P")
22920 (org-agenda-check-no-diary)
22921 (let* ((col (current-column))
22922 (marker (or (get-text-property (point) 'org-marker)
22923 (org-agenda-error)))
22924 (buffer (marker-buffer marker))
22925 (pos (marker-position marker))
22926 (hdmarker (get-text-property (point) 'org-hd-marker))
22927 (inhibit-read-only t)
22928 newhead)
22929 (org-with-remote-undo buffer
22930 (with-current-buffer buffer
22931 (widen)
22932 (goto-char pos)
22933 (org-show-context 'agenda)
22934 (save-excursion
22935 (and (outline-next-heading)
22936 (org-flag-heading nil))) ; show the next heading
22937 (org-todo arg)
22938 (and (bolp) (forward-char 1))
22939 (setq newhead (org-get-heading))
22940 (save-excursion
22941 (org-back-to-heading)
22942 (move-marker org-last-heading-marker (point))))
22943 (beginning-of-line 1)
22944 (save-excursion
22945 (org-agenda-change-all-lines newhead hdmarker 'fixface))
22946 (move-to-column col))))
22948 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
22949 "Change all lines in the agenda buffer which match HDMARKER.
22950 The new content of the line will be NEWHEAD (as modified by
22951 `org-format-agenda-item'). HDMARKER is checked with
22952 `equal' against all `org-hd-marker' text properties in the file.
22953 If FIXFACE is non-nil, the face of each item is modified acording to
22954 the new TODO state."
22955 (let* ((inhibit-read-only t)
22956 props m pl undone-face done-face finish new dotime cat tags)
22957 (save-excursion
22958 (goto-char (point-max))
22959 (beginning-of-line 1)
22960 (while (not finish)
22961 (setq finish (bobp))
22962 (when (and (setq m (get-text-property (point) 'org-hd-marker))
22963 (equal m hdmarker))
22964 (setq props (text-properties-at (point))
22965 dotime (get-text-property (point) 'dotime)
22966 cat (get-text-property (point) 'org-category)
22967 tags (get-text-property (point) 'tags)
22968 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
22969 pl (get-text-property (point) 'prefix-length)
22970 undone-face (get-text-property (point) 'undone-face)
22971 done-face (get-text-property (point) 'done-face))
22972 (move-to-column pl)
22973 (cond
22974 ((equal new "")
22975 (beginning-of-line 1)
22976 (and (looking-at ".*\n?") (replace-match "")))
22977 ((looking-at ".*")
22978 (replace-match new t t)
22979 (beginning-of-line 1)
22980 (add-text-properties (point-at-bol) (point-at-eol) props)
22981 (when fixface
22982 (add-text-properties
22983 (point-at-bol) (point-at-eol)
22984 (list 'face
22985 (if org-last-todo-state-is-todo
22986 undone-face done-face))))
22987 (org-agenda-highlight-todo 'line)
22988 (beginning-of-line 1))
22989 (t (error "Line update did not work"))))
22990 (beginning-of-line 0)))
22991 (org-finalize-agenda)))
22993 (defun org-agenda-align-tags (&optional line)
22994 "Align all tags in agenda items to `org-agenda-tags-column'."
22995 (let ((inhibit-read-only t) l c)
22996 (save-excursion
22997 (goto-char (if line (point-at-bol) (point-min)))
22998 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22999 (if line (point-at-eol) nil) t)
23000 (add-text-properties
23001 (match-beginning 2) (match-end 2)
23002 (list 'face (delq nil (list 'org-tag (get-text-property
23003 (match-beginning 2) 'face)))))
23004 (setq l (- (match-end 2) (match-beginning 2))
23005 c (if (< org-agenda-tags-column 0)
23006 (- (abs org-agenda-tags-column) l)
23007 org-agenda-tags-column))
23008 (delete-region (match-beginning 1) (match-end 1))
23009 (goto-char (match-beginning 1))
23010 (insert (org-add-props
23011 (make-string (max 1 (- c (current-column))) ?\ )
23012 (text-properties-at (point))))))))
23014 (defun org-agenda-priority-up ()
23015 "Increase the priority of line at point, also in Org-mode file."
23016 (interactive)
23017 (org-agenda-priority 'up))
23019 (defun org-agenda-priority-down ()
23020 "Decrease the priority of line at point, also in Org-mode file."
23021 (interactive)
23022 (org-agenda-priority 'down))
23024 (defun org-agenda-priority (&optional force-direction)
23025 "Set the priority of line at point, also in Org-mode file.
23026 This changes the line at point, all other lines in the agenda referring to
23027 the same tree node, and the headline of the tree node in the Org-mode file."
23028 (interactive)
23029 (org-agenda-check-no-diary)
23030 (let* ((marker (or (get-text-property (point) 'org-marker)
23031 (org-agenda-error)))
23032 (hdmarker (get-text-property (point) 'org-hd-marker))
23033 (buffer (marker-buffer hdmarker))
23034 (pos (marker-position hdmarker))
23035 (inhibit-read-only t)
23036 newhead)
23037 (org-with-remote-undo buffer
23038 (with-current-buffer buffer
23039 (widen)
23040 (goto-char pos)
23041 (org-show-context 'agenda)
23042 (save-excursion
23043 (and (outline-next-heading)
23044 (org-flag-heading nil))) ; show the next heading
23045 (funcall 'org-priority force-direction)
23046 (end-of-line 1)
23047 (setq newhead (org-get-heading)))
23048 (org-agenda-change-all-lines newhead hdmarker)
23049 (beginning-of-line 1))))
23051 (defun org-get-tags-at (&optional pos)
23052 "Get a list of all headline tags applicable at POS.
23053 POS defaults to point. If tags are inherited, the list contains
23054 the targets in the same sequence as the headlines appear, i.e.
23055 the tags of the current headline come last."
23056 (interactive)
23057 (let (tags lastpos)
23058 (save-excursion
23059 (save-restriction
23060 (widen)
23061 (goto-char (or pos (point)))
23062 (save-match-data
23063 (condition-case nil
23064 (progn
23065 (org-back-to-heading t)
23066 (while (not (equal lastpos (point)))
23067 (setq lastpos (point))
23068 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23069 (setq tags (append (org-split-string
23070 (org-match-string-no-properties 1) ":")
23071 tags)))
23072 (or org-use-tag-inheritance (error ""))
23073 (org-up-heading-all 1)))
23074 (error nil))))
23075 tags)))
23077 ;; FIXME: should fix the tags property of the agenda line.
23078 (defun org-agenda-set-tags ()
23079 "Set tags for the current headline."
23080 (interactive)
23081 (org-agenda-check-no-diary)
23082 (if (and (org-region-active-p) (interactive-p))
23083 (call-interactively 'org-change-tag-in-region)
23084 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23085 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23086 (org-agenda-error)))
23087 (buffer (marker-buffer hdmarker))
23088 (pos (marker-position hdmarker))
23089 (inhibit-read-only t)
23090 newhead)
23091 (org-with-remote-undo buffer
23092 (with-current-buffer buffer
23093 (widen)
23094 (goto-char pos)
23095 (save-excursion
23096 (org-show-context 'agenda))
23097 (save-excursion
23098 (and (outline-next-heading)
23099 (org-flag-heading nil))) ; show the next heading
23100 (goto-char pos)
23101 (call-interactively 'org-set-tags)
23102 (end-of-line 1)
23103 (setq newhead (org-get-heading)))
23104 (org-agenda-change-all-lines newhead hdmarker)
23105 (beginning-of-line 1)))))
23107 (defun org-agenda-toggle-archive-tag ()
23108 "Toggle the archive tag for the current entry."
23109 (interactive)
23110 (org-agenda-check-no-diary)
23111 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23112 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23113 (org-agenda-error)))
23114 (buffer (marker-buffer hdmarker))
23115 (pos (marker-position hdmarker))
23116 (inhibit-read-only t)
23117 newhead)
23118 (org-with-remote-undo buffer
23119 (with-current-buffer buffer
23120 (widen)
23121 (goto-char pos)
23122 (org-show-context 'agenda)
23123 (save-excursion
23124 (and (outline-next-heading)
23125 (org-flag-heading nil))) ; show the next heading
23126 (call-interactively 'org-toggle-archive-tag)
23127 (end-of-line 1)
23128 (setq newhead (org-get-heading)))
23129 (org-agenda-change-all-lines newhead hdmarker)
23130 (beginning-of-line 1))))
23132 (defun org-agenda-date-later (arg &optional what)
23133 "Change the date of this item to one day later."
23134 (interactive "p")
23135 (org-agenda-check-type t 'agenda 'timeline)
23136 (org-agenda-check-no-diary)
23137 (let* ((marker (or (get-text-property (point) 'org-marker)
23138 (org-agenda-error)))
23139 (buffer (marker-buffer marker))
23140 (pos (marker-position marker)))
23141 (org-with-remote-undo buffer
23142 (with-current-buffer buffer
23143 (widen)
23144 (goto-char pos)
23145 (if (not (org-at-timestamp-p))
23146 (error "Cannot find time stamp"))
23147 (org-timestamp-change arg (or what 'day)))
23148 (org-agenda-show-new-time marker org-last-changed-timestamp))
23149 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23151 (defun org-agenda-date-earlier (arg &optional what)
23152 "Change the date of this item to one day earlier."
23153 (interactive "p")
23154 (org-agenda-date-later (- arg) what))
23156 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23157 "Show new date stamp via text properties."
23158 ;; We use text properties to make this undoable
23159 (let ((inhibit-read-only t))
23160 (setq stamp (concat " " prefix " => " stamp))
23161 (save-excursion
23162 (goto-char (point-max))
23163 (while (not (bobp))
23164 (when (equal marker (get-text-property (point) 'org-marker))
23165 (move-to-column (- (window-width) (length stamp)) t)
23166 (if (featurep 'xemacs)
23167 ;; Use `duplicable' property to trigger undo recording
23168 (let ((ex (make-extent nil nil))
23169 (gl (make-glyph stamp)))
23170 (set-glyph-face gl 'secondary-selection)
23171 (set-extent-properties
23172 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23173 (insert-extent ex (1- (point)) (point-at-eol)))
23174 (add-text-properties
23175 (1- (point)) (point-at-eol)
23176 (list 'display (org-add-props stamp nil
23177 'face 'secondary-selection))))
23178 (beginning-of-line 1))
23179 (beginning-of-line 0)))))
23181 (defun org-agenda-date-prompt (arg)
23182 "Change the date of this item. Date is prompted for, with default today.
23183 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23184 be used to request time specification in the time stamp."
23185 (interactive "P")
23186 (org-agenda-check-type t 'agenda 'timeline)
23187 (org-agenda-check-no-diary)
23188 (let* ((marker (or (get-text-property (point) 'org-marker)
23189 (org-agenda-error)))
23190 (buffer (marker-buffer marker))
23191 (pos (marker-position marker)))
23192 (org-with-remote-undo buffer
23193 (with-current-buffer buffer
23194 (widen)
23195 (goto-char pos)
23196 (if (not (org-at-timestamp-p))
23197 (error "Cannot find time stamp"))
23198 (org-time-stamp arg)
23199 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23201 (defun org-agenda-schedule (arg)
23202 "Schedule the item at point."
23203 (interactive "P")
23204 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23205 (org-agenda-check-no-diary)
23206 (let* ((marker (or (get-text-property (point) 'org-marker)
23207 (org-agenda-error)))
23208 (type (marker-insertion-type marker))
23209 (buffer (marker-buffer marker))
23210 (pos (marker-position marker))
23211 (org-insert-labeled-timestamps-at-point nil)
23213 (when type (message "%s" type) (sit-for 3))
23214 (set-marker-insertion-type marker t)
23215 (org-with-remote-undo buffer
23216 (with-current-buffer buffer
23217 (widen)
23218 (goto-char pos)
23219 (setq ts (org-schedule arg)))
23220 (org-agenda-show-new-time marker ts "S"))
23221 (message "Item scheduled for %s" ts)))
23223 (defun org-agenda-deadline (arg)
23224 "Schedule the item at point."
23225 (interactive "P")
23226 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags 'search)
23227 (org-agenda-check-no-diary)
23228 (let* ((marker (or (get-text-property (point) 'org-marker)
23229 (org-agenda-error)))
23230 (buffer (marker-buffer marker))
23231 (pos (marker-position marker))
23232 (org-insert-labeled-timestamps-at-point nil)
23234 (org-with-remote-undo buffer
23235 (with-current-buffer buffer
23236 (widen)
23237 (goto-char pos)
23238 (setq ts (org-deadline arg)))
23239 (org-agenda-show-new-time marker ts "S"))
23240 (message "Deadline for this item set to %s" ts)))
23242 (defun org-get-heading (&optional no-tags)
23243 "Return the heading of the current entry, without the stars."
23244 (save-excursion
23245 (org-back-to-heading t)
23246 (if (looking-at
23247 (if no-tags
23248 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23249 "\\*+[ \t]+\\([^\r\n]*\\)"))
23250 (match-string 1) "")))
23252 (defun org-agenda-clock-in (&optional arg)
23253 "Start the clock on the currently selected item."
23254 (interactive "P")
23255 (org-agenda-check-no-diary)
23256 (let* ((marker (or (get-text-property (point) 'org-marker)
23257 (org-agenda-error)))
23258 (pos (marker-position marker)))
23259 (org-with-remote-undo (marker-buffer marker)
23260 (with-current-buffer (marker-buffer marker)
23261 (widen)
23262 (goto-char pos)
23263 (org-clock-in)))))
23265 (defun org-agenda-clock-out (&optional arg)
23266 "Stop the currently running clock."
23267 (interactive "P")
23268 (unless (marker-buffer org-clock-marker)
23269 (error "No running clock"))
23270 (org-with-remote-undo (marker-buffer org-clock-marker)
23271 (org-clock-out)))
23273 (defun org-agenda-clock-cancel (&optional arg)
23274 "Cancel the currently running clock."
23275 (interactive "P")
23276 (unless (marker-buffer org-clock-marker)
23277 (error "No running clock"))
23278 (org-with-remote-undo (marker-buffer org-clock-marker)
23279 (org-clock-cancel)))
23281 (defun org-agenda-diary-entry ()
23282 "Make a diary entry, like the `i' command from the calendar.
23283 All the standard commands work: block, weekly etc."
23284 (interactive)
23285 (org-agenda-check-type t 'agenda 'timeline)
23286 (require 'diary-lib)
23287 (let* ((char (progn
23288 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23289 (read-char-exclusive)))
23290 (cmd (cdr (assoc char
23291 '((?d . insert-diary-entry)
23292 (?w . insert-weekly-diary-entry)
23293 (?m . insert-monthly-diary-entry)
23294 (?y . insert-yearly-diary-entry)
23295 (?a . insert-anniversary-diary-entry)
23296 (?b . insert-block-diary-entry)
23297 (?c . insert-cyclic-diary-entry)))))
23298 (oldf (symbol-function 'calendar-cursor-to-date))
23299 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23300 (point (point))
23301 (mark (or (mark t) (point))))
23302 (unless cmd
23303 (error "No command associated with <%c>" char))
23304 (unless (and (get-text-property point 'day)
23305 (or (not (equal ?b char))
23306 (get-text-property mark 'day)))
23307 (error "Don't know which date to use for diary entry"))
23308 ;; We implement this by hacking the `calendar-cursor-to-date' function
23309 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23310 (let ((calendar-mark-ring
23311 (list (calendar-gregorian-from-absolute
23312 (or (get-text-property mark 'day)
23313 (get-text-property point 'day))))))
23314 (unwind-protect
23315 (progn
23316 (fset 'calendar-cursor-to-date
23317 (lambda (&optional error)
23318 (calendar-gregorian-from-absolute
23319 (get-text-property point 'day))))
23320 (call-interactively cmd))
23321 (fset 'calendar-cursor-to-date oldf)))))
23324 (defun org-agenda-execute-calendar-command (cmd)
23325 "Execute a calendar command from the agenda, with the date associated to
23326 the cursor position."
23327 (org-agenda-check-type t 'agenda 'timeline)
23328 (require 'diary-lib)
23329 (unless (get-text-property (point) 'day)
23330 (error "Don't know which date to use for calendar command"))
23331 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23332 (point (point))
23333 (date (calendar-gregorian-from-absolute
23334 (get-text-property point 'day)))
23335 ;; the following 3 vars are needed in the calendar
23336 (displayed-day (extract-calendar-day date))
23337 (displayed-month (extract-calendar-month date))
23338 (displayed-year (extract-calendar-year date)))
23339 (unwind-protect
23340 (progn
23341 (fset 'calendar-cursor-to-date
23342 (lambda (&optional error)
23343 (calendar-gregorian-from-absolute
23344 (get-text-property point 'day))))
23345 (call-interactively cmd))
23346 (fset 'calendar-cursor-to-date oldf))))
23348 (defun org-agenda-phases-of-moon ()
23349 "Display the phases of the moon for the 3 months around the cursor date."
23350 (interactive)
23351 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23353 (defun org-agenda-holidays ()
23354 "Display the holidays for the 3 months around the cursor date."
23355 (interactive)
23356 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23358 (defvar calendar-longitude)
23359 (defvar calendar-latitude)
23360 (defvar calendar-location-name)
23362 (defun org-agenda-sunrise-sunset (arg)
23363 "Display sunrise and sunset for the cursor date.
23364 Latitude and longitude can be specified with the variables
23365 `calendar-latitude' and `calendar-longitude'. When called with prefix
23366 argument, latitude and longitude will be prompted for."
23367 (interactive "P")
23368 (require 'solar)
23369 (let ((calendar-longitude (if arg nil calendar-longitude))
23370 (calendar-latitude (if arg nil calendar-latitude))
23371 (calendar-location-name
23372 (if arg "the given coordinates" calendar-location-name)))
23373 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23375 (defun org-agenda-goto-calendar ()
23376 "Open the Emacs calendar with the date at the cursor."
23377 (interactive)
23378 (org-agenda-check-type t 'agenda 'timeline)
23379 (let* ((day (or (get-text-property (point) 'day)
23380 (error "Don't know which date to open in calendar")))
23381 (date (calendar-gregorian-from-absolute day))
23382 (calendar-move-hook nil)
23383 (view-calendar-holidays-initially nil)
23384 (view-diary-entries-initially nil))
23385 (calendar)
23386 (calendar-goto-date date)))
23388 (defun org-calendar-goto-agenda ()
23389 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23390 This is a command that has to be installed in `calendar-mode-map'."
23391 (interactive)
23392 (org-agenda-list nil (calendar-absolute-from-gregorian
23393 (calendar-cursor-to-date))
23394 nil))
23396 (defun org-agenda-convert-date ()
23397 (interactive)
23398 (org-agenda-check-type t 'agenda 'timeline)
23399 (let ((day (get-text-property (point) 'day))
23400 date s)
23401 (unless day
23402 (error "Don't know which date to convert"))
23403 (setq date (calendar-gregorian-from-absolute day))
23404 (setq s (concat
23405 "Gregorian: " (calendar-date-string date) "\n"
23406 "ISO: " (calendar-iso-date-string date) "\n"
23407 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23408 "Julian: " (calendar-julian-date-string date) "\n"
23409 "Astron. JD: " (calendar-astro-date-string date)
23410 " (Julian date number at noon UTC)\n"
23411 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23412 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23413 "French: " (calendar-french-date-string date) "\n"
23414 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23415 "Mayan: " (calendar-mayan-date-string date) "\n"
23416 "Coptic: " (calendar-coptic-date-string date) "\n"
23417 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23418 "Persian: " (calendar-persian-date-string date) "\n"
23419 "Chinese: " (calendar-chinese-date-string date) "\n"))
23420 (with-output-to-temp-buffer "*Dates*"
23421 (princ s))
23422 (if (fboundp 'fit-window-to-buffer)
23423 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23426 ;;;; Embedded LaTeX
23428 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23429 "Keymap for the minor `org-cdlatex-mode'.")
23431 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23432 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23433 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23434 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23435 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23437 (defvar org-cdlatex-texmathp-advice-is-done nil
23438 "Flag remembering if we have applied the advice to texmathp already.")
23440 (define-minor-mode org-cdlatex-mode
23441 "Toggle the minor `org-cdlatex-mode'.
23442 This mode supports entering LaTeX environment and math in LaTeX fragments
23443 in Org-mode.
23444 \\{org-cdlatex-mode-map}"
23445 nil " OCDL" nil
23446 (when org-cdlatex-mode (require 'cdlatex))
23447 (unless org-cdlatex-texmathp-advice-is-done
23448 (setq org-cdlatex-texmathp-advice-is-done t)
23449 (defadvice texmathp (around org-math-always-on activate)
23450 "Always return t in org-mode buffers.
23451 This is because we want to insert math symbols without dollars even outside
23452 the LaTeX math segments. If Orgmode thinks that point is actually inside
23453 en embedded LaTeX fragement, let texmathp do its job.
23454 \\[org-cdlatex-mode-map]"
23455 (interactive)
23456 (let (p)
23457 (cond
23458 ((not (org-mode-p)) ad-do-it)
23459 ((eq this-command 'cdlatex-math-symbol)
23460 (setq ad-return-value t
23461 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23463 (let ((p (org-inside-LaTeX-fragment-p)))
23464 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23465 (setq ad-return-value t
23466 texmathp-why '("Org-mode embedded math" . 0))
23467 (if p ad-do-it)))))))))
23469 (defun turn-on-org-cdlatex ()
23470 "Unconditionally turn on `org-cdlatex-mode'."
23471 (org-cdlatex-mode 1))
23473 (defun org-inside-LaTeX-fragment-p ()
23474 "Test if point is inside a LaTeX fragment.
23475 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23476 sequence appearing also before point.
23477 Even though the matchers for math are configurable, this function assumes
23478 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23479 delimiters are skipped when they have been removed by customization.
23480 The return value is nil, or a cons cell with the delimiter and
23481 and the position of this delimiter.
23483 This function does a reasonably good job, but can locally be fooled by
23484 for example currency specifications. For example it will assume being in
23485 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23486 fragments that are properly closed, but during editing, we have to live
23487 with the uncertainty caused by missing closing delimiters. This function
23488 looks only before point, not after."
23489 (catch 'exit
23490 (let ((pos (point))
23491 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23492 (lim (progn
23493 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23494 (point)))
23495 dd-on str (start 0) m re)
23496 (goto-char pos)
23497 (when dodollar
23498 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23499 re (nth 1 (assoc "$" org-latex-regexps)))
23500 (while (string-match re str start)
23501 (cond
23502 ((= (match-end 0) (length str))
23503 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23504 ((= (match-end 0) (- (length str) 5))
23505 (throw 'exit nil))
23506 (t (setq start (match-end 0))))))
23507 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23508 (goto-char pos)
23509 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23510 (and (match-beginning 2) (throw 'exit nil))
23511 ;; count $$
23512 (while (re-search-backward "\\$\\$" lim t)
23513 (setq dd-on (not dd-on)))
23514 (goto-char pos)
23515 (if dd-on (cons "$$" m))))))
23518 (defun org-try-cdlatex-tab ()
23519 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23520 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23521 - inside a LaTeX fragment, or
23522 - after the first word in a line, where an abbreviation expansion could
23523 insert a LaTeX environment."
23524 (when org-cdlatex-mode
23525 (cond
23526 ((save-excursion
23527 (skip-chars-backward "a-zA-Z0-9*")
23528 (skip-chars-backward " \t")
23529 (bolp))
23530 (cdlatex-tab) t)
23531 ((org-inside-LaTeX-fragment-p)
23532 (cdlatex-tab) t)
23533 (t nil))))
23535 (defun org-cdlatex-underscore-caret (&optional arg)
23536 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23537 Revert to the normal definition outside of these fragments."
23538 (interactive "P")
23539 (if (org-inside-LaTeX-fragment-p)
23540 (call-interactively 'cdlatex-sub-superscript)
23541 (let (org-cdlatex-mode)
23542 (call-interactively (key-binding (vector last-input-event))))))
23544 (defun org-cdlatex-math-modify (&optional arg)
23545 "Execute `cdlatex-math-modify' in LaTeX fragments.
23546 Revert to the normal definition outside of these fragments."
23547 (interactive "P")
23548 (if (org-inside-LaTeX-fragment-p)
23549 (call-interactively 'cdlatex-math-modify)
23550 (let (org-cdlatex-mode)
23551 (call-interactively (key-binding (vector last-input-event))))))
23553 (defvar org-latex-fragment-image-overlays nil
23554 "List of overlays carrying the images of latex fragments.")
23555 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23557 (defun org-remove-latex-fragment-image-overlays ()
23558 "Remove all overlays with LaTeX fragment images in current buffer."
23559 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23560 (setq org-latex-fragment-image-overlays nil))
23562 (defun org-preview-latex-fragment (&optional subtree)
23563 "Preview the LaTeX fragment at point, or all locally or globally.
23564 If the cursor is in a LaTeX fragment, create the image and overlay
23565 it over the source code. If there is no fragment at point, display
23566 all fragments in the current text, from one headline to the next. With
23567 prefix SUBTREE, display all fragments in the current subtree. With a
23568 double prefix `C-u C-u', or when the cursor is before the first headline,
23569 display all fragments in the buffer.
23570 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23571 (interactive "P")
23572 (org-remove-latex-fragment-image-overlays)
23573 (save-excursion
23574 (save-restriction
23575 (let (beg end at msg)
23576 (cond
23577 ((or (equal subtree '(16))
23578 (not (save-excursion
23579 (re-search-backward (concat "^" outline-regexp) nil t))))
23580 (setq beg (point-min) end (point-max)
23581 msg "Creating images for buffer...%s"))
23582 ((equal subtree '(4))
23583 (org-back-to-heading)
23584 (setq beg (point) end (org-end-of-subtree t)
23585 msg "Creating images for subtree...%s"))
23587 (if (setq at (org-inside-LaTeX-fragment-p))
23588 (goto-char (max (point-min) (- (cdr at) 2)))
23589 (org-back-to-heading))
23590 (setq beg (point) end (progn (outline-next-heading) (point))
23591 msg (if at "Creating image...%s"
23592 "Creating images for entry...%s"))))
23593 (message msg "")
23594 (narrow-to-region beg end)
23595 (goto-char beg)
23596 (org-format-latex
23597 (concat "ltxpng/" (file-name-sans-extension
23598 (file-name-nondirectory
23599 buffer-file-name)))
23600 default-directory 'overlays msg at 'forbuffer)
23601 (message msg "done. Use `C-c C-c' to remove images.")))))
23603 (defvar org-latex-regexps
23604 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23605 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23606 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23607 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23608 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23609 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23610 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23611 "Regular expressions for matching embedded LaTeX.")
23613 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23614 "Replace LaTeX fragments with links to an image, and produce images."
23615 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23616 (let* ((prefixnodir (file-name-nondirectory prefix))
23617 (absprefix (expand-file-name prefix dir))
23618 (todir (file-name-directory absprefix))
23619 (opt org-format-latex-options)
23620 (matchers (plist-get opt :matchers))
23621 (re-list org-latex-regexps)
23622 (cnt 0) txt link beg end re e checkdir
23623 m n block linkfile movefile ov)
23624 ;; Check if there are old images files with this prefix, and remove them
23625 (when (file-directory-p todir)
23626 (mapc 'delete-file
23627 (directory-files
23628 todir 'full
23629 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23630 ;; Check the different regular expressions
23631 (while (setq e (pop re-list))
23632 (setq m (car e) re (nth 1 e) n (nth 2 e)
23633 block (if (nth 3 e) "\n\n" ""))
23634 (when (member m matchers)
23635 (goto-char (point-min))
23636 (while (re-search-forward re nil t)
23637 (when (or (not at) (equal (cdr at) (match-beginning n)))
23638 (setq txt (match-string n)
23639 beg (match-beginning n) end (match-end n)
23640 cnt (1+ cnt)
23641 linkfile (format "%s_%04d.png" prefix cnt)
23642 movefile (format "%s_%04d.png" absprefix cnt)
23643 link (concat block "[[file:" linkfile "]]" block))
23644 (if msg (message msg cnt))
23645 (goto-char beg)
23646 (unless checkdir ; make sure the directory exists
23647 (setq checkdir t)
23648 (or (file-directory-p todir) (make-directory todir)))
23649 (org-create-formula-image
23650 txt movefile opt forbuffer)
23651 (if overlays
23652 (progn
23653 (setq ov (org-make-overlay beg end))
23654 (if (featurep 'xemacs)
23655 (progn
23656 (org-overlay-put ov 'invisible t)
23657 (org-overlay-put
23658 ov 'end-glyph
23659 (make-glyph (vector 'png :file movefile))))
23660 (org-overlay-put
23661 ov 'display
23662 (list 'image :type 'png :file movefile :ascent 'center)))
23663 (push ov org-latex-fragment-image-overlays)
23664 (goto-char end))
23665 (delete-region beg end)
23666 (insert link))))))))
23668 ;; This function borrows from Ganesh Swami's latex2png.el
23669 (defun org-create-formula-image (string tofile options buffer)
23670 (let* ((tmpdir (if (featurep 'xemacs)
23671 (temp-directory)
23672 temporary-file-directory))
23673 (texfilebase (make-temp-name
23674 (expand-file-name "orgtex" tmpdir)))
23675 (texfile (concat texfilebase ".tex"))
23676 (dvifile (concat texfilebase ".dvi"))
23677 (pngfile (concat texfilebase ".png"))
23678 (fnh (face-attribute 'default :height nil))
23679 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23680 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23681 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23682 "Black"))
23683 (bg (or (plist-get options (if buffer :background :html-background))
23684 "Transparent")))
23685 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23686 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23687 (with-temp-file texfile
23688 (insert org-format-latex-header
23689 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23690 (let ((dir default-directory))
23691 (condition-case nil
23692 (progn
23693 (cd tmpdir)
23694 (call-process "latex" nil nil nil texfile))
23695 (error nil))
23696 (cd dir))
23697 (if (not (file-exists-p dvifile))
23698 (progn (message "Failed to create dvi file from %s" texfile) nil)
23699 (call-process "dvipng" nil nil nil
23700 "-E" "-fg" fg "-bg" bg
23701 "-D" dpi
23702 ;;"-x" scale "-y" scale
23703 "-T" "tight"
23704 "-o" pngfile
23705 dvifile)
23706 (if (not (file-exists-p pngfile))
23707 (progn (message "Failed to create png file from %s" texfile) nil)
23708 ;; Use the requested file name and clean up
23709 (copy-file pngfile tofile 'replace)
23710 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23711 (delete-file (concat texfilebase e)))
23712 pngfile))))
23714 (defun org-dvipng-color (attr)
23715 "Return an rgb color specification for dvipng."
23716 (apply 'format "rgb %s %s %s"
23717 (mapcar 'org-normalize-color
23718 (color-values (face-attribute 'default attr nil)))))
23720 (defun org-normalize-color (value)
23721 "Return string to be used as color value for an RGB component."
23722 (format "%g" (/ value 65535.0)))
23724 ;;;; Exporting
23726 ;;; Variables, constants, and parameter plists
23728 (defconst org-level-max 20)
23730 (defvar org-export-html-preamble nil
23731 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23732 (defvar org-export-html-postamble nil
23733 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23734 (defvar org-export-html-auto-preamble t
23735 "Should default preamble be inserted? Set by publishing functions.")
23736 (defvar org-export-html-auto-postamble t
23737 "Should default postamble be inserted? Set by publishing functions.")
23738 (defvar org-current-export-file nil) ; dynamically scoped parameter
23739 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23742 (defconst org-export-plist-vars
23743 '((:language . org-export-default-language)
23744 (:customtime . org-display-custom-times)
23745 (:headline-levels . org-export-headline-levels)
23746 (:section-numbers . org-export-with-section-numbers)
23747 (:table-of-contents . org-export-with-toc)
23748 (:preserve-breaks . org-export-preserve-breaks)
23749 (:archived-trees . org-export-with-archived-trees)
23750 (:emphasize . org-export-with-emphasize)
23751 (:sub-superscript . org-export-with-sub-superscripts)
23752 (:special-strings . org-export-with-special-strings)
23753 (:footnotes . org-export-with-footnotes)
23754 (:drawers . org-export-with-drawers)
23755 (:tags . org-export-with-tags)
23756 (:TeX-macros . org-export-with-TeX-macros)
23757 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23758 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23759 (:fixed-width . org-export-with-fixed-width)
23760 (:timestamps . org-export-with-timestamps)
23761 (:author-info . org-export-author-info)
23762 (:time-stamp-file . org-export-time-stamp-file)
23763 (:tables . org-export-with-tables)
23764 (:table-auto-headline . org-export-highlight-first-table-line)
23765 (:style . org-export-html-style)
23766 (:agenda-style . org-agenda-export-html-style)
23767 (:convert-org-links . org-export-html-link-org-files-as-html)
23768 (:inline-images . org-export-html-inline-images)
23769 (:html-extension . org-export-html-extension)
23770 (:html-table-tag . org-export-html-table-tag)
23771 (:expand-quoted-html . org-export-html-expand)
23772 (:timestamp . org-export-html-with-timestamp)
23773 (:publishing-directory . org-export-publishing-directory)
23774 (:preamble . org-export-html-preamble)
23775 (:postamble . org-export-html-postamble)
23776 (:auto-preamble . org-export-html-auto-preamble)
23777 (:auto-postamble . org-export-html-auto-postamble)
23778 (:author . user-full-name)
23779 (:email . user-mail-address)))
23781 (defun org-default-export-plist ()
23782 "Return the property list with default settings for the export variables."
23783 (let ((l org-export-plist-vars) rtn e)
23784 (while (setq e (pop l))
23785 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23786 rtn))
23788 (defun org-infile-export-plist ()
23789 "Return the property list with file-local settings for export."
23790 (save-excursion
23791 (save-restriction
23792 (widen)
23793 (goto-char 0)
23794 (let ((re (org-make-options-regexp
23795 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23796 p key val text options)
23797 (while (re-search-forward re nil t)
23798 (setq key (org-match-string-no-properties 1)
23799 val (org-match-string-no-properties 2))
23800 (cond
23801 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23802 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23803 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23804 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23805 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23806 ((string-equal key "TEXT")
23807 (setq text (if text (concat text "\n" val) val)))
23808 ((string-equal key "OPTIONS") (setq options val))))
23809 (setq p (plist-put p :text text))
23810 (when options
23811 (let ((op '(("H" . :headline-levels)
23812 ("num" . :section-numbers)
23813 ("toc" . :table-of-contents)
23814 ("\\n" . :preserve-breaks)
23815 ("@" . :expand-quoted-html)
23816 (":" . :fixed-width)
23817 ("|" . :tables)
23818 ("^" . :sub-superscript)
23819 ("-" . :special-strings)
23820 ("f" . :footnotes)
23821 ("d" . :drawers)
23822 ("tags" . :tags)
23823 ("*" . :emphasize)
23824 ("TeX" . :TeX-macros)
23825 ("LaTeX" . :LaTeX-fragments)
23826 ("skip" . :skip-before-1st-heading)
23827 ("author" . :author-info)
23828 ("timestamp" . :time-stamp-file)))
23830 (while (setq o (pop op))
23831 (if (string-match (concat (regexp-quote (car o))
23832 ":\\([^ \t\n\r;,.]*\\)")
23833 options)
23834 (setq p (plist-put p (cdr o)
23835 (car (read-from-string
23836 (match-string 1 options)))))))))
23837 p))))
23839 (defun org-export-directory (type plist)
23840 (let* ((val (plist-get plist :publishing-directory))
23841 (dir (if (listp val)
23842 (or (cdr (assoc type val)) ".")
23843 val)))
23844 dir))
23846 (defun org-skip-comments (lines)
23847 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23848 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23849 (re2 "^\\(\\*+\\)[ \t\n\r]")
23850 (case-fold-search nil)
23851 rtn line level)
23852 (while (setq line (pop lines))
23853 (cond
23854 ((and (string-match re1 line)
23855 (setq level (- (match-end 1) (match-beginning 1))))
23856 ;; Beginning of a COMMENT subtree. Skip it.
23857 (while (and (setq line (pop lines))
23858 (or (not (string-match re2 line))
23859 (> (- (match-end 1) (match-beginning 1)) level))))
23860 (setq lines (cons line lines)))
23861 ((string-match "^#" line)
23862 ;; an ordinary comment line
23864 ((and org-export-table-remove-special-lines
23865 (string-match "^[ \t]*|" line)
23866 (or (string-match "^[ \t]*| *[!_^] *|" line)
23867 (and (string-match "| *<[0-9]+> *|" line)
23868 (not (string-match "| *[^ <|]" line)))))
23869 ;; a special table line that should be removed
23871 (t (setq rtn (cons line rtn)))))
23872 (nreverse rtn)))
23874 (defun org-export (&optional arg)
23875 (interactive)
23876 (let ((help "[t] insert the export option template
23877 \[v] limit export to visible part of outline tree
23879 \[a] export as ASCII
23881 \[h] export as HTML
23882 \[H] export as HTML to temporary buffer
23883 \[R] export region as HTML
23884 \[b] export as HTML and browse immediately
23885 \[x] export as XOXO
23887 \[l] export as LaTeX
23888 \[L] export as LaTeX to temporary buffer
23890 \[i] export current file as iCalendar file
23891 \[I] export all agenda files as iCalendar files
23892 \[c] export agenda files into combined iCalendar file
23894 \[F] publish current file
23895 \[P] publish current project
23896 \[X] publish... (project will be prompted for)
23897 \[A] publish all projects")
23898 (cmds
23899 '((?t . org-insert-export-options-template)
23900 (?v . org-export-visible)
23901 (?a . org-export-as-ascii)
23902 (?h . org-export-as-html)
23903 (?b . org-export-as-html-and-open)
23904 (?H . org-export-as-html-to-buffer)
23905 (?R . org-export-region-as-html)
23906 (?x . org-export-as-xoxo)
23907 (?l . org-export-as-latex)
23908 (?L . org-export-as-latex-to-buffer)
23909 (?i . org-export-icalendar-this-file)
23910 (?I . org-export-icalendar-all-agenda-files)
23911 (?c . org-export-icalendar-combine-agenda-files)
23912 (?F . org-publish-current-file)
23913 (?P . org-publish-current-project)
23914 (?X . org-publish)
23915 (?A . org-publish-all)))
23916 r1 r2 ass)
23917 (save-window-excursion
23918 (delete-other-windows)
23919 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23920 (princ help))
23921 (message "Select command: ")
23922 (setq r1 (read-char-exclusive)))
23923 (setq r2 (if (< r1 27) (+ r1 96) r1))
23924 (if (setq ass (assq r2 cmds))
23925 (call-interactively (cdr ass))
23926 (error "No command associated with key %c" r1))))
23928 (defconst org-html-entities
23929 '(("nbsp")
23930 ("iexcl")
23931 ("cent")
23932 ("pound")
23933 ("curren")
23934 ("yen")
23935 ("brvbar")
23936 ("vert" . "&#124;")
23937 ("sect")
23938 ("uml")
23939 ("copy")
23940 ("ordf")
23941 ("laquo")
23942 ("not")
23943 ("shy")
23944 ("reg")
23945 ("macr")
23946 ("deg")
23947 ("plusmn")
23948 ("sup2")
23949 ("sup3")
23950 ("acute")
23951 ("micro")
23952 ("para")
23953 ("middot")
23954 ("odot"."o")
23955 ("star"."*")
23956 ("cedil")
23957 ("sup1")
23958 ("ordm")
23959 ("raquo")
23960 ("frac14")
23961 ("frac12")
23962 ("frac34")
23963 ("iquest")
23964 ("Agrave")
23965 ("Aacute")
23966 ("Acirc")
23967 ("Atilde")
23968 ("Auml")
23969 ("Aring") ("AA"."&Aring;")
23970 ("AElig")
23971 ("Ccedil")
23972 ("Egrave")
23973 ("Eacute")
23974 ("Ecirc")
23975 ("Euml")
23976 ("Igrave")
23977 ("Iacute")
23978 ("Icirc")
23979 ("Iuml")
23980 ("ETH")
23981 ("Ntilde")
23982 ("Ograve")
23983 ("Oacute")
23984 ("Ocirc")
23985 ("Otilde")
23986 ("Ouml")
23987 ("times")
23988 ("Oslash")
23989 ("Ugrave")
23990 ("Uacute")
23991 ("Ucirc")
23992 ("Uuml")
23993 ("Yacute")
23994 ("THORN")
23995 ("szlig")
23996 ("agrave")
23997 ("aacute")
23998 ("acirc")
23999 ("atilde")
24000 ("auml")
24001 ("aring")
24002 ("aelig")
24003 ("ccedil")
24004 ("egrave")
24005 ("eacute")
24006 ("ecirc")
24007 ("euml")
24008 ("igrave")
24009 ("iacute")
24010 ("icirc")
24011 ("iuml")
24012 ("eth")
24013 ("ntilde")
24014 ("ograve")
24015 ("oacute")
24016 ("ocirc")
24017 ("otilde")
24018 ("ouml")
24019 ("divide")
24020 ("oslash")
24021 ("ugrave")
24022 ("uacute")
24023 ("ucirc")
24024 ("uuml")
24025 ("yacute")
24026 ("thorn")
24027 ("yuml")
24028 ("fnof")
24029 ("Alpha")
24030 ("Beta")
24031 ("Gamma")
24032 ("Delta")
24033 ("Epsilon")
24034 ("Zeta")
24035 ("Eta")
24036 ("Theta")
24037 ("Iota")
24038 ("Kappa")
24039 ("Lambda")
24040 ("Mu")
24041 ("Nu")
24042 ("Xi")
24043 ("Omicron")
24044 ("Pi")
24045 ("Rho")
24046 ("Sigma")
24047 ("Tau")
24048 ("Upsilon")
24049 ("Phi")
24050 ("Chi")
24051 ("Psi")
24052 ("Omega")
24053 ("alpha")
24054 ("beta")
24055 ("gamma")
24056 ("delta")
24057 ("epsilon")
24058 ("varepsilon"."&epsilon;")
24059 ("zeta")
24060 ("eta")
24061 ("theta")
24062 ("iota")
24063 ("kappa")
24064 ("lambda")
24065 ("mu")
24066 ("nu")
24067 ("xi")
24068 ("omicron")
24069 ("pi")
24070 ("rho")
24071 ("sigmaf") ("varsigma"."&sigmaf;")
24072 ("sigma")
24073 ("tau")
24074 ("upsilon")
24075 ("phi")
24076 ("chi")
24077 ("psi")
24078 ("omega")
24079 ("thetasym") ("vartheta"."&thetasym;")
24080 ("upsih")
24081 ("piv")
24082 ("bull") ("bullet"."&bull;")
24083 ("hellip") ("dots"."&hellip;")
24084 ("prime")
24085 ("Prime")
24086 ("oline")
24087 ("frasl")
24088 ("weierp")
24089 ("image")
24090 ("real")
24091 ("trade")
24092 ("alefsym")
24093 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24094 ("uarr") ("uparrow"."&uarr;")
24095 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24096 ("darr")("downarrow"."&darr;")
24097 ("harr") ("leftrightarrow"."&harr;")
24098 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24099 ("lArr") ("Leftarrow"."&lArr;")
24100 ("uArr") ("Uparrow"."&uArr;")
24101 ("rArr") ("Rightarrow"."&rArr;")
24102 ("dArr") ("Downarrow"."&dArr;")
24103 ("hArr") ("Leftrightarrow"."&hArr;")
24104 ("forall")
24105 ("part") ("partial"."&part;")
24106 ("exist") ("exists"."&exist;")
24107 ("empty") ("emptyset"."&empty;")
24108 ("nabla")
24109 ("isin") ("in"."&isin;")
24110 ("notin")
24111 ("ni")
24112 ("prod")
24113 ("sum")
24114 ("minus")
24115 ("lowast") ("ast"."&lowast;")
24116 ("radic")
24117 ("prop") ("proptp"."&prop;")
24118 ("infin") ("infty"."&infin;")
24119 ("ang") ("angle"."&ang;")
24120 ("and") ("wedge"."&and;")
24121 ("or") ("vee"."&or;")
24122 ("cap")
24123 ("cup")
24124 ("int")
24125 ("there4")
24126 ("sim")
24127 ("cong") ("simeq"."&cong;")
24128 ("asymp")("approx"."&asymp;")
24129 ("ne") ("neq"."&ne;")
24130 ("equiv")
24131 ("le")
24132 ("ge")
24133 ("sub") ("subset"."&sub;")
24134 ("sup") ("supset"."&sup;")
24135 ("nsub")
24136 ("sube")
24137 ("supe")
24138 ("oplus")
24139 ("otimes")
24140 ("perp")
24141 ("sdot") ("cdot"."&sdot;")
24142 ("lceil")
24143 ("rceil")
24144 ("lfloor")
24145 ("rfloor")
24146 ("lang")
24147 ("rang")
24148 ("loz") ("Diamond"."&loz;")
24149 ("spades") ("spadesuit"."&spades;")
24150 ("clubs") ("clubsuit"."&clubs;")
24151 ("hearts") ("diamondsuit"."&hearts;")
24152 ("diams") ("diamondsuit"."&diams;")
24153 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24154 ("quot")
24155 ("amp")
24156 ("lt")
24157 ("gt")
24158 ("OElig")
24159 ("oelig")
24160 ("Scaron")
24161 ("scaron")
24162 ("Yuml")
24163 ("circ")
24164 ("tilde")
24165 ("ensp")
24166 ("emsp")
24167 ("thinsp")
24168 ("zwnj")
24169 ("zwj")
24170 ("lrm")
24171 ("rlm")
24172 ("ndash")
24173 ("mdash")
24174 ("lsquo")
24175 ("rsquo")
24176 ("sbquo")
24177 ("ldquo")
24178 ("rdquo")
24179 ("bdquo")
24180 ("dagger")
24181 ("Dagger")
24182 ("permil")
24183 ("lsaquo")
24184 ("rsaquo")
24185 ("euro")
24187 ("arccos"."arccos")
24188 ("arcsin"."arcsin")
24189 ("arctan"."arctan")
24190 ("arg"."arg")
24191 ("cos"."cos")
24192 ("cosh"."cosh")
24193 ("cot"."cot")
24194 ("coth"."coth")
24195 ("csc"."csc")
24196 ("deg"."deg")
24197 ("det"."det")
24198 ("dim"."dim")
24199 ("exp"."exp")
24200 ("gcd"."gcd")
24201 ("hom"."hom")
24202 ("inf"."inf")
24203 ("ker"."ker")
24204 ("lg"."lg")
24205 ("lim"."lim")
24206 ("liminf"."liminf")
24207 ("limsup"."limsup")
24208 ("ln"."ln")
24209 ("log"."log")
24210 ("max"."max")
24211 ("min"."min")
24212 ("Pr"."Pr")
24213 ("sec"."sec")
24214 ("sin"."sin")
24215 ("sinh"."sinh")
24216 ("sup"."sup")
24217 ("tan"."tan")
24218 ("tanh"."tanh")
24220 "Entities for TeX->HTML translation.
24221 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24222 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24223 In that case, \"\\ent\" will be translated to \"&other;\".
24224 The list contains HTML entities for Latin-1, Greek and other symbols.
24225 It is supplemented by a number of commonly used TeX macros with appropriate
24226 translations. There is currently no way for users to extend this.")
24228 ;;; General functions for all backends
24230 (defun org-cleaned-string-for-export (string &rest parameters)
24231 "Cleanup a buffer STRING so that links can be created safely."
24232 (interactive)
24233 (let* ((re-radio (and org-target-link-regexp
24234 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24235 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24236 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24237 (re-archive (concat ":" org-archive-tag ":"))
24238 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24239 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24240 (htmlp (plist-get parameters :for-html))
24241 (asciip (plist-get parameters :for-ascii))
24242 (latexp (plist-get parameters :for-LaTeX))
24243 (commentsp (plist-get parameters :comments))
24244 (archived-trees (plist-get parameters :archived-trees))
24245 (inhibit-read-only t)
24246 (drawers org-drawers)
24247 (exp-drawers (plist-get parameters :drawers))
24248 (outline-regexp "\\*+ ")
24249 a b xx
24250 rtn p)
24251 (with-current-buffer (get-buffer-create " org-mode-tmp")
24252 (erase-buffer)
24253 (insert string)
24254 ;; Remove license-to-kill stuff
24255 (while (setq p (text-property-any (point-min) (point-max)
24256 :org-license-to-kill t))
24257 (delete-region p (next-single-property-change p :org-license-to-kill)))
24259 (let ((org-inhibit-startup t)) (org-mode))
24260 (untabify (point-min) (point-max))
24262 ;; Get rid of drawers
24263 (unless (eq t exp-drawers)
24264 (goto-char (point-min))
24265 (let ((re (concat "^[ \t]*:\\("
24266 (mapconcat
24267 'identity
24268 (org-delete-all exp-drawers
24269 (copy-sequence drawers))
24270 "\\|")
24271 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24272 (while (re-search-forward re nil t)
24273 (replace-match ""))))
24275 ;; Get the correct stuff before the first headline
24276 (when (plist-get parameters :skip-before-1st-heading)
24277 (goto-char (point-min))
24278 (when (re-search-forward "^\\*+[ \t]" nil t)
24279 (delete-region (point-min) (match-beginning 0))
24280 (goto-char (point-min))
24281 (insert "\n")))
24282 (when (plist-get parameters :add-text)
24283 (goto-char (point-min))
24284 (insert (plist-get parameters :add-text) "\n"))
24286 ;; Get rid of archived trees
24287 (when (not (eq archived-trees t))
24288 (goto-char (point-min))
24289 (while (re-search-forward re-archive nil t)
24290 (if (not (org-on-heading-p t))
24291 (org-end-of-subtree t)
24292 (beginning-of-line 1)
24293 (setq a (if archived-trees
24294 (1+ (point-at-eol)) (point))
24295 b (org-end-of-subtree t))
24296 (if (> b a) (delete-region a b)))))
24298 ;; Find targets in comments and move them out of comments,
24299 ;; but mark them as targets that should be invisible
24300 (goto-char (point-min))
24301 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24302 (replace-match "\\1(INVISIBLE)"))
24304 ;; Protect backend specific stuff, throw away the others.
24305 (let ((formatters
24306 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24307 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24308 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24309 fmt)
24310 (goto-char (point-min))
24311 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24312 (goto-char (match-end 0))
24313 (while (not (looking-at "#\\+END_EXAMPLE"))
24314 (insert ": ")
24315 (beginning-of-line 2)))
24316 (goto-char (point-min))
24317 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24318 (add-text-properties (match-beginning 0) (match-end 0)
24319 '(org-protected t)))
24320 (while formatters
24321 (setq fmt (pop formatters))
24322 (when (car fmt)
24323 (goto-char (point-min))
24324 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24325 ":[ \t]*\\(.*\\)") nil t)
24326 (replace-match "\\1" t)
24327 (add-text-properties
24328 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24329 '(org-protected t))))
24330 (goto-char (point-min))
24331 (while (re-search-forward
24332 (concat "^#\\+"
24333 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24334 (cadddr fmt) "\\>.*\n?") nil t)
24335 (if (car fmt)
24336 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24337 '(org-protected t))
24338 (delete-region (match-beginning 0) (match-end 0))))))
24340 ;; Protect quoted subtrees
24341 (goto-char (point-min))
24342 (while (re-search-forward re-quote nil t)
24343 (goto-char (match-beginning 0))
24344 (end-of-line 1)
24345 (add-text-properties (point) (org-end-of-subtree t)
24346 '(org-protected t)))
24348 ;; Protect verbatim elements
24349 (goto-char (point-min))
24350 (while (re-search-forward org-verbatim-re nil t)
24351 (add-text-properties (match-beginning 4) (match-end 4)
24352 '(org-protected t))
24353 (goto-char (1+ (match-end 4))))
24355 ;; Remove subtrees that are commented
24356 (goto-char (point-min))
24357 (while (re-search-forward re-commented nil t)
24358 (goto-char (match-beginning 0))
24359 (delete-region (point) (org-end-of-subtree t)))
24361 ;; Remove special table lines
24362 (when org-export-table-remove-special-lines
24363 (goto-char (point-min))
24364 (while (re-search-forward "^[ \t]*|" nil t)
24365 (beginning-of-line 1)
24366 (if (or (looking-at "[ \t]*| *[!_^] *|")
24367 (and (looking-at ".*?| *<[0-9]+> *|")
24368 (not (looking-at ".*?| *[^ <|]"))))
24369 (delete-region (max (point-min) (1- (point-at-bol)))
24370 (point-at-eol))
24371 (end-of-line 1))))
24373 ;; Specific LaTeX stuff
24374 (when latexp
24375 (require 'org-export-latex nil)
24376 (org-export-latex-cleaned-string))
24378 (when asciip
24379 (org-export-ascii-clean-string))
24381 ;; Specific HTML stuff
24382 (when htmlp
24383 ;; Convert LaTeX fragments to images
24384 (when (plist-get parameters :LaTeX-fragments)
24385 (org-format-latex
24386 (concat "ltxpng/" (file-name-sans-extension
24387 (file-name-nondirectory
24388 org-current-export-file)))
24389 org-current-export-dir nil "Creating LaTeX image %s"))
24390 (message "Exporting..."))
24392 ;; Remove or replace comments
24393 (goto-char (point-min))
24394 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24395 (if commentsp
24396 (progn (add-text-properties
24397 (match-beginning 0) (match-end 0) '(org-protected t))
24398 (replace-match (format commentsp (match-string 1)) t t))
24399 (replace-match "")))
24401 ;; Find matches for radio targets and turn them into internal links
24402 (goto-char (point-min))
24403 (when re-radio
24404 (while (re-search-forward re-radio nil t)
24405 (org-if-unprotected
24406 (replace-match "\\1[[\\2]]"))))
24408 ;; Find all links that contain a newline and put them into a single line
24409 (goto-char (point-min))
24410 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24411 (org-if-unprotected
24412 (replace-match "\\1 \\3")
24413 (goto-char (match-beginning 0))))
24416 ;; Normalize links: Convert angle and plain links into bracket links
24417 ;; Expand link abbreviations
24418 (goto-char (point-min))
24419 (while (re-search-forward re-plain-link nil t)
24420 (goto-char (1- (match-end 0)))
24421 (org-if-unprotected
24422 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24423 ":" (match-string 3) "]]")))
24424 ;; added 'org-link face to links
24425 (put-text-property 0 (length s) 'face 'org-link s)
24426 (replace-match s t t))))
24427 (goto-char (point-min))
24428 (while (re-search-forward re-angle-link nil t)
24429 (goto-char (1- (match-end 0)))
24430 (org-if-unprotected
24431 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24432 ":" (match-string 3) "]]")))
24433 (put-text-property 0 (length s) 'face 'org-link s)
24434 (replace-match s t t))))
24435 (goto-char (point-min))
24436 (while (re-search-forward org-bracket-link-regexp nil t)
24437 (org-if-unprotected
24438 (let* ((s (concat "[[" (setq xx (save-match-data
24439 (org-link-expand-abbrev (match-string 1))))
24441 (if (match-end 3)
24442 (match-string 2)
24443 (concat "[" xx "]"))
24444 "]")))
24445 (put-text-property 0 (length s) 'face 'org-link s)
24446 (replace-match s t t))))
24448 ;; Find multiline emphasis and put them into single line
24449 (when (plist-get parameters :emph-multiline)
24450 (goto-char (point-min))
24451 (while (re-search-forward org-emph-re nil t)
24452 (if (not (= (char-after (match-beginning 3))
24453 (char-after (match-beginning 4))))
24454 (org-if-unprotected
24455 (subst-char-in-region (match-beginning 0) (match-end 0)
24456 ?\n ?\ t)
24457 (goto-char (1- (match-end 0))))
24458 (goto-char (1+ (match-beginning 0))))))
24460 (setq rtn (buffer-string)))
24461 (kill-buffer " org-mode-tmp")
24462 rtn))
24464 (defun org-export-grab-title-from-buffer ()
24465 "Get a title for the current document, from looking at the buffer."
24466 (let ((inhibit-read-only t))
24467 (save-excursion
24468 (goto-char (point-min))
24469 (let ((end (save-excursion (outline-next-heading) (point))))
24470 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24471 ;; Mark the line so that it will not be exported as normal text.
24472 (org-unmodified
24473 (add-text-properties (match-beginning 0) (match-end 0)
24474 (list :org-license-to-kill t)))
24475 ;; Return the title string
24476 (org-trim (match-string 0)))))))
24478 (defun org-export-get-title-from-subtree ()
24479 "Return subtree title and exclude it from export."
24480 (let (title (m (mark)))
24481 (save-excursion
24482 (goto-char (region-beginning))
24483 (when (and (org-at-heading-p)
24484 (>= (org-end-of-subtree t t) (region-end)))
24485 ;; This is a subtree, we take the title from the first heading
24486 (goto-char (region-beginning))
24487 (looking-at org-todo-line-regexp)
24488 (setq title (match-string 3))
24489 (org-unmodified
24490 (add-text-properties (point) (1+ (point-at-eol))
24491 (list :org-license-to-kill t)))))
24492 title))
24494 (defun org-solidify-link-text (s &optional alist)
24495 "Take link text and make a safe target out of it."
24496 (save-match-data
24497 (let* ((rtn
24498 (mapconcat
24499 'identity
24500 (org-split-string s "[ \t\r\n]+") "--"))
24501 (a (assoc rtn alist)))
24502 (or (cdr a) rtn))))
24504 (defun org-get-min-level (lines)
24505 "Get the minimum level in LINES."
24506 (let ((re "^\\(\\*+\\) ") l min)
24507 (catch 'exit
24508 (while (setq l (pop lines))
24509 (if (string-match re l)
24510 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24511 1)))
24513 ;; Variable holding the vector with section numbers
24514 (defvar org-section-numbers (make-vector org-level-max 0))
24516 (defun org-init-section-numbers ()
24517 "Initialize the vector for the section numbers."
24518 (let* ((level -1)
24519 (numbers (nreverse (org-split-string "" "\\.")))
24520 (depth (1- (length org-section-numbers)))
24521 (i depth) number-string)
24522 (while (>= i 0)
24523 (if (> i level)
24524 (aset org-section-numbers i 0)
24525 (setq number-string (or (car numbers) "0"))
24526 (if (string-match "\\`[A-Z]\\'" number-string)
24527 (aset org-section-numbers i
24528 (- (string-to-char number-string) ?A -1))
24529 (aset org-section-numbers i (string-to-number number-string)))
24530 (pop numbers))
24531 (setq i (1- i)))))
24533 (defun org-section-number (&optional level)
24534 "Return a string with the current section number.
24535 When LEVEL is non-nil, increase section numbers on that level."
24536 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24537 (when level
24538 (when (> level -1)
24539 (aset org-section-numbers
24540 level (1+ (aref org-section-numbers level))))
24541 (setq idx (1+ level))
24542 (while (<= idx depth)
24543 (if (not (= idx 1))
24544 (aset org-section-numbers idx 0))
24545 (setq idx (1+ idx))))
24546 (setq idx 0)
24547 (while (<= idx depth)
24548 (setq n (aref org-section-numbers idx))
24549 (setq string (concat string (if (not (string= string "")) "." "")
24550 (int-to-string n)))
24551 (setq idx (1+ idx)))
24552 (save-match-data
24553 (if (string-match "\\`\\([@0]\\.\\)+" string)
24554 (setq string (replace-match "" t nil string)))
24555 (if (string-match "\\(\\.0\\)+\\'" string)
24556 (setq string (replace-match "" t nil string))))
24557 string))
24559 ;;; ASCII export
24561 (defvar org-last-level nil) ; dynamically scoped variable
24562 (defvar org-min-level nil) ; dynamically scoped variable
24563 (defvar org-levels-open nil) ; dynamically scoped parameter
24564 (defvar org-ascii-current-indentation nil) ; For communication
24566 (defun org-export-as-ascii (arg)
24567 "Export the outline as a pretty ASCII file.
24568 If there is an active region, export only the region.
24569 The prefix ARG specifies how many levels of the outline should become
24570 underlined headlines. The default is 3."
24571 (interactive "P")
24572 (setq-default org-todo-line-regexp org-todo-line-regexp)
24573 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24574 (org-infile-export-plist)))
24575 (region-p (org-region-active-p))
24576 (subtree-p
24577 (when region-p
24578 (save-excursion
24579 (goto-char (region-beginning))
24580 (and (org-at-heading-p)
24581 (>= (org-end-of-subtree t t) (region-end))))))
24582 (custom-times org-display-custom-times)
24583 (org-ascii-current-indentation '(0 . 0))
24584 (level 0) line txt
24585 (umax nil)
24586 (umax-toc nil)
24587 (case-fold-search nil)
24588 (filename (concat (file-name-as-directory
24589 (org-export-directory :ascii opt-plist))
24590 (file-name-sans-extension
24591 (or (and subtree-p
24592 (org-entry-get (region-beginning)
24593 "EXPORT_FILE_NAME" t))
24594 (file-name-nondirectory buffer-file-name)))
24595 ".txt"))
24596 (filename (if (equal (file-truename filename)
24597 (file-truename buffer-file-name))
24598 (concat filename ".txt")
24599 filename))
24600 (buffer (find-file-noselect filename))
24601 (org-levels-open (make-vector org-level-max nil))
24602 (odd org-odd-levels-only)
24603 (date (plist-get opt-plist :date))
24604 (author (plist-get opt-plist :author))
24605 (title (or (and subtree-p (org-export-get-title-from-subtree))
24606 (plist-get opt-plist :title)
24607 (and (not
24608 (plist-get opt-plist :skip-before-1st-heading))
24609 (org-export-grab-title-from-buffer))
24610 (file-name-sans-extension
24611 (file-name-nondirectory buffer-file-name))))
24612 (email (plist-get opt-plist :email))
24613 (language (plist-get opt-plist :language))
24614 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24615 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24616 (todo nil)
24617 (lang-words nil)
24618 (region
24619 (buffer-substring
24620 (if (org-region-active-p) (region-beginning) (point-min))
24621 (if (org-region-active-p) (region-end) (point-max))))
24622 (lines (org-split-string
24623 (org-cleaned-string-for-export
24624 region
24625 :for-ascii t
24626 :skip-before-1st-heading
24627 (plist-get opt-plist :skip-before-1st-heading)
24628 :drawers (plist-get opt-plist :drawers)
24629 :verbatim-multiline t
24630 :archived-trees
24631 (plist-get opt-plist :archived-trees)
24632 :add-text (plist-get opt-plist :text))
24633 "\n"))
24634 thetoc have-headings first-heading-pos
24635 table-open table-buffer)
24637 (let ((inhibit-read-only t))
24638 (org-unmodified
24639 (remove-text-properties (point-min) (point-max)
24640 '(:org-license-to-kill t))))
24642 (setq org-min-level (org-get-min-level lines))
24643 (setq org-last-level org-min-level)
24644 (org-init-section-numbers)
24646 (find-file-noselect filename)
24648 (setq lang-words (or (assoc language org-export-language-setup)
24649 (assoc "en" org-export-language-setup)))
24650 (switch-to-buffer-other-window buffer)
24651 (erase-buffer)
24652 (fundamental-mode)
24653 ;; create local variables for all options, to make sure all called
24654 ;; functions get the correct information
24655 (mapc (lambda (x)
24656 (set (make-local-variable (cdr x))
24657 (plist-get opt-plist (car x))))
24658 org-export-plist-vars)
24659 (org-set-local 'org-odd-levels-only odd)
24660 (setq umax (if arg (prefix-numeric-value arg)
24661 org-export-headline-levels))
24662 (setq umax-toc (if (integerp org-export-with-toc)
24663 (min org-export-with-toc umax)
24664 umax))
24666 ;; File header
24667 (if title (org-insert-centered title ?=))
24668 (insert "\n")
24669 (if (and (or author email)
24670 org-export-author-info)
24671 (insert (concat (nth 1 lang-words) ": " (or author "")
24672 (if email (concat " <" email ">") "")
24673 "\n")))
24675 (cond
24676 ((and date (string-match "%" date))
24677 (setq date (format-time-string date (current-time))))
24678 (date)
24679 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24681 (if (and date org-export-time-stamp-file)
24682 (insert (concat (nth 2 lang-words) ": " date"\n")))
24684 (insert "\n\n")
24686 (if org-export-with-toc
24687 (progn
24688 (push (concat (nth 3 lang-words) "\n") thetoc)
24689 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24690 (mapc '(lambda (line)
24691 (if (string-match org-todo-line-regexp
24692 line)
24693 ;; This is a headline
24694 (progn
24695 (setq have-headings t)
24696 (setq level (- (match-end 1) (match-beginning 1))
24697 level (org-tr-level level)
24698 txt (match-string 3 line)
24699 todo
24700 (or (and org-export-mark-todo-in-toc
24701 (match-beginning 2)
24702 (not (member (match-string 2 line)
24703 org-done-keywords)))
24704 ; TODO, not DONE
24705 (and org-export-mark-todo-in-toc
24706 (= level umax-toc)
24707 (org-search-todo-below
24708 line lines level))))
24709 (setq txt (org-html-expand-for-ascii txt))
24711 (while (string-match org-bracket-link-regexp txt)
24712 (setq txt
24713 (replace-match
24714 (match-string (if (match-end 2) 3 1) txt)
24715 t t txt)))
24717 (if (and (memq org-export-with-tags '(not-in-toc nil))
24718 (string-match
24719 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24720 txt))
24721 (setq txt (replace-match "" t t txt)))
24722 (if (string-match quote-re0 txt)
24723 (setq txt (replace-match "" t t txt)))
24725 (if org-export-with-section-numbers
24726 (setq txt (concat (org-section-number level)
24727 " " txt)))
24728 (if (<= level umax-toc)
24729 (progn
24730 (push
24731 (concat
24732 (make-string
24733 (* (max 0 (- level org-min-level)) 4) ?\ )
24734 (format (if todo "%s (*)\n" "%s\n") txt))
24735 thetoc)
24736 (setq org-last-level level))
24737 ))))
24738 lines)
24739 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24741 (org-init-section-numbers)
24742 (while (setq line (pop lines))
24743 ;; Remove the quoted HTML tags.
24744 (setq line (org-html-expand-for-ascii line))
24745 ;; Remove targets
24746 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24747 (setq line (replace-match "" t t line)))
24748 ;; Replace internal links
24749 (while (string-match org-bracket-link-regexp line)
24750 (setq line (replace-match
24751 (if (match-end 3) "[\\3]" "[\\1]")
24752 t nil line)))
24753 (when custom-times
24754 (setq line (org-translate-time line)))
24755 (cond
24756 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24757 ;; a Headline
24758 (setq first-heading-pos (or first-heading-pos (point)))
24759 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24760 txt (match-string 2 line))
24761 (org-ascii-level-start level txt umax lines))
24763 ((and org-export-with-tables
24764 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24765 (if (not table-open)
24766 ;; New table starts
24767 (setq table-open t table-buffer nil))
24768 ;; Accumulate lines
24769 (setq table-buffer (cons line table-buffer))
24770 (when (or (not lines)
24771 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24772 (car lines))))
24773 (setq table-open nil
24774 table-buffer (nreverse table-buffer))
24775 (insert (mapconcat
24776 (lambda (x)
24777 (org-fix-indentation x org-ascii-current-indentation))
24778 (org-format-table-ascii table-buffer)
24779 "\n") "\n")))
24781 (setq line (org-fix-indentation line org-ascii-current-indentation))
24782 (if (and org-export-with-fixed-width
24783 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24784 (setq line (replace-match "\\1" nil nil line)))
24785 (insert line "\n"))))
24787 (normal-mode)
24789 ;; insert the table of contents
24790 (when thetoc
24791 (goto-char (point-min))
24792 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24793 (progn
24794 (goto-char (match-beginning 0))
24795 (replace-match ""))
24796 (goto-char first-heading-pos))
24797 (mapc 'insert thetoc)
24798 (or (looking-at "[ \t]*\n[ \t]*\n")
24799 (insert "\n\n")))
24801 ;; Convert whitespace place holders
24802 (goto-char (point-min))
24803 (let (beg end)
24804 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24805 (setq end (next-single-property-change beg 'org-whitespace))
24806 (goto-char beg)
24807 (delete-region beg end)
24808 (insert (make-string (- end beg) ?\ ))))
24810 (save-buffer)
24811 ;; remove display and invisible chars
24812 (let (beg end)
24813 (goto-char (point-min))
24814 (while (setq beg (next-single-property-change (point) 'display))
24815 (setq end (next-single-property-change beg 'display))
24816 (delete-region beg end)
24817 (goto-char beg)
24818 (insert "=>"))
24819 (goto-char (point-min))
24820 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24821 (setq end (next-single-property-change beg 'org-cwidth))
24822 (delete-region beg end)
24823 (goto-char beg)))
24824 (goto-char (point-min))))
24826 (defun org-export-ascii-clean-string ()
24827 "Do extra work for ASCII export"
24828 (goto-char (point-min))
24829 (while (re-search-forward org-verbatim-re nil t)
24830 (goto-char (match-end 2))
24831 (backward-delete-char 1) (insert "'")
24832 (goto-char (match-beginning 2))
24833 (delete-char 1) (insert "`")
24834 (goto-char (match-end 2))))
24836 (defun org-search-todo-below (line lines level)
24837 "Search the subtree below LINE for any TODO entries."
24838 (let ((rest (cdr (memq line lines)))
24839 (re org-todo-line-regexp)
24840 line lv todo)
24841 (catch 'exit
24842 (while (setq line (pop rest))
24843 (if (string-match re line)
24844 (progn
24845 (setq lv (- (match-end 1) (match-beginning 1))
24846 todo (and (match-beginning 2)
24847 (not (member (match-string 2 line)
24848 org-done-keywords))))
24849 ; TODO, not DONE
24850 (if (<= lv level) (throw 'exit nil))
24851 (if todo (throw 'exit t))))))))
24853 (defun org-html-expand-for-ascii (line)
24854 "Handle quoted HTML for ASCII export."
24855 (if org-export-html-expand
24856 (while (string-match "@<[^<>\n]*>" line)
24857 ;; We just remove the tags for now.
24858 (setq line (replace-match "" nil nil line))))
24859 line)
24861 (defun org-insert-centered (s &optional underline)
24862 "Insert the string S centered and underline it with character UNDERLINE."
24863 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24864 (insert (make-string ind ?\ ) s "\n")
24865 (if underline
24866 (insert (make-string ind ?\ )
24867 (make-string (string-width s) underline)
24868 "\n"))))
24870 (defun org-ascii-level-start (level title umax &optional lines)
24871 "Insert a new level in ASCII export."
24872 (let (char (n (- level umax 1)) (ind 0))
24873 (if (> level umax)
24874 (progn
24875 (insert (make-string (* 2 n) ?\ )
24876 (char-to-string (nth (% n (length org-export-ascii-bullets))
24877 org-export-ascii-bullets))
24878 " " title "\n")
24879 ;; find the indentation of the next non-empty line
24880 (catch 'stop
24881 (while lines
24882 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24883 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24884 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24885 (pop lines)))
24886 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24887 (if (or (not (equal (char-before) ?\n))
24888 (not (equal (char-before (1- (point))) ?\n)))
24889 (insert "\n"))
24890 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24891 (unless org-export-with-tags
24892 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24893 (setq title (replace-match "" t t title))))
24894 (if org-export-with-section-numbers
24895 (setq title (concat (org-section-number level) " " title)))
24896 (insert title "\n" (make-string (string-width title) char) "\n")
24897 (setq org-ascii-current-indentation '(0 . 0)))))
24899 (defun org-export-visible (type arg)
24900 "Create a copy of the visible part of the current buffer, and export it.
24901 The copy is created in a temporary buffer and removed after use.
24902 TYPE is the final key (as a string) that also select the export command in
24903 the `C-c C-e' export dispatcher.
24904 As a special case, if the you type SPC at the prompt, the temporary
24905 org-mode file will not be removed but presented to you so that you can
24906 continue to use it. The prefix arg ARG is passed through to the exporting
24907 command."
24908 (interactive
24909 (list (progn
24910 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24911 (read-char-exclusive))
24912 current-prefix-arg))
24913 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24914 (error "Invalid export key"))
24915 (let* ((binding (cdr (assoc type
24916 '((?a . org-export-as-ascii)
24917 (?\C-a . org-export-as-ascii)
24918 (?b . org-export-as-html-and-open)
24919 (?\C-b . org-export-as-html-and-open)
24920 (?h . org-export-as-html)
24921 (?H . org-export-as-html-to-buffer)
24922 (?R . org-export-region-as-html)
24923 (?x . org-export-as-xoxo)))))
24924 (keepp (equal type ?\ ))
24925 (file buffer-file-name)
24926 (buffer (get-buffer-create "*Org Export Visible*"))
24927 s e)
24928 ;; Need to hack the drawers here.
24929 (save-excursion
24930 (goto-char (point-min))
24931 (while (re-search-forward org-drawer-regexp nil t)
24932 (goto-char (match-beginning 1))
24933 (or (org-invisible-p) (org-flag-drawer nil))))
24934 (with-current-buffer buffer (erase-buffer))
24935 (save-excursion
24936 (setq s (goto-char (point-min)))
24937 (while (not (= (point) (point-max)))
24938 (goto-char (org-find-invisible))
24939 (append-to-buffer buffer s (point))
24940 (setq s (goto-char (org-find-visible))))
24941 (org-cycle-hide-drawers 'all)
24942 (goto-char (point-min))
24943 (unless keepp
24944 ;; Copy all comment lines to the end, to make sure #+ settings are
24945 ;; still available for the second export step. Kind of a hack, but
24946 ;; does do the trick.
24947 (if (looking-at "#[^\r\n]*")
24948 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
24949 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
24950 (append-to-buffer buffer (1+ (match-beginning 0))
24951 (min (point-max) (1+ (match-end 0))))))
24952 (set-buffer buffer)
24953 (let ((buffer-file-name file)
24954 (org-inhibit-startup t))
24955 (org-mode)
24956 (show-all)
24957 (unless keepp (funcall binding arg))))
24958 (if (not keepp)
24959 (kill-buffer buffer)
24960 (switch-to-buffer-other-window buffer)
24961 (goto-char (point-min)))))
24963 (defun org-find-visible ()
24964 (let ((s (point)))
24965 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24966 (get-char-property s 'invisible)))
24968 (defun org-find-invisible ()
24969 (let ((s (point)))
24970 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
24971 (not (get-char-property s 'invisible))))
24974 ;;; HTML export
24976 (defun org-get-current-options ()
24977 "Return a string with current options as keyword options.
24978 Does include HTML export options as well as TODO and CATEGORY stuff."
24979 (format
24980 "#+TITLE: %s
24981 #+AUTHOR: %s
24982 #+EMAIL: %s
24983 #+LANGUAGE: %s
24984 #+TEXT: Some descriptive text to be emitted. Several lines OK.
24985 #+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
24986 #+CATEGORY: %s
24987 #+SEQ_TODO: %s
24988 #+TYP_TODO: %s
24989 #+PRIORITIES: %c %c %c
24990 #+DRAWERS: %s
24991 #+STARTUP: %s %s %s %s %s
24992 #+TAGS: %s
24993 #+ARCHIVE: %s
24994 #+LINK: %s
24996 (buffer-name) (user-full-name) user-mail-address org-export-default-language
24997 org-export-headline-levels
24998 org-export-with-section-numbers
24999 org-export-with-toc
25000 org-export-preserve-breaks
25001 org-export-html-expand
25002 org-export-with-fixed-width
25003 org-export-with-tables
25004 org-export-with-sub-superscripts
25005 org-export-with-special-strings
25006 org-export-with-footnotes
25007 org-export-with-emphasize
25008 org-export-with-TeX-macros
25009 org-export-with-LaTeX-fragments
25010 org-export-skip-text-before-1st-heading
25011 org-export-with-drawers
25012 org-export-with-tags
25013 (file-name-nondirectory buffer-file-name)
25014 "TODO FEEDBACK VERIFY DONE"
25015 "Me Jason Marie DONE"
25016 org-highest-priority org-lowest-priority org-default-priority
25017 (mapconcat 'identity org-drawers " ")
25018 (cdr (assoc org-startup-folded
25019 '((nil . "showall") (t . "overview") (content . "content"))))
25020 (if org-odd-levels-only "odd" "oddeven")
25021 (if org-hide-leading-stars "hidestars" "showstars")
25022 (if org-startup-align-all-tables "align" "noalign")
25023 (cond ((eq org-log-done t) "logdone")
25024 ((equal org-log-done 'note) "lognotedone")
25025 ((not org-log-done) "nologdone"))
25026 (or (mapconcat (lambda (x)
25027 (cond
25028 ((equal '(:startgroup) x) "{")
25029 ((equal '(:endgroup) x) "}")
25030 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25031 (t (car x))))
25032 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25033 org-archive-location
25034 "org file:~/org/%s.org"
25037 (defun org-insert-export-options-template ()
25038 "Insert into the buffer a template with information for exporting."
25039 (interactive)
25040 (if (not (bolp)) (newline))
25041 (let ((s (org-get-current-options)))
25042 (and (string-match "#\\+CATEGORY" s)
25043 (setq s (substring s 0 (match-beginning 0))))
25044 (insert s)))
25046 (defun org-toggle-fixed-width-section (arg)
25047 "Toggle the fixed-width export.
25048 If there is no active region, the QUOTE keyword at the current headline is
25049 inserted or removed. When present, it causes the text between this headline
25050 and the next to be exported as fixed-width text, and unmodified.
25051 If there is an active region, this command adds or removes a colon as the
25052 first character of this line. If the first character of a line is a colon,
25053 this line is also exported in fixed-width font."
25054 (interactive "P")
25055 (let* ((cc 0)
25056 (regionp (org-region-active-p))
25057 (beg (if regionp (region-beginning) (point)))
25058 (end (if regionp (region-end)))
25059 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25060 (case-fold-search nil)
25061 (re "[ \t]*\\(:\\)")
25062 off)
25063 (if regionp
25064 (save-excursion
25065 (goto-char beg)
25066 (setq cc (current-column))
25067 (beginning-of-line 1)
25068 (setq off (looking-at re))
25069 (while (> nlines 0)
25070 (setq nlines (1- nlines))
25071 (beginning-of-line 1)
25072 (cond
25073 (arg
25074 (move-to-column cc t)
25075 (insert ":\n")
25076 (forward-line -1))
25077 ((and off (looking-at re))
25078 (replace-match "" t t nil 1))
25079 ((not off) (move-to-column cc t) (insert ":")))
25080 (forward-line 1)))
25081 (save-excursion
25082 (org-back-to-heading)
25083 (if (looking-at (concat outline-regexp
25084 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25085 (replace-match "" t t nil 1)
25086 (if (looking-at outline-regexp)
25087 (progn
25088 (goto-char (match-end 0))
25089 (insert org-quote-string " "))))))))
25091 (defun org-export-as-html-and-open (arg)
25092 "Export the outline as HTML and immediately open it with a browser.
25093 If there is an active region, export only the region.
25094 The prefix ARG specifies how many levels of the outline should become
25095 headlines. The default is 3. Lower levels will become bulleted lists."
25096 (interactive "P")
25097 (org-export-as-html arg 'hidden)
25098 (org-open-file buffer-file-name))
25100 (defun org-export-as-html-batch ()
25101 "Call `org-export-as-html', may be used in batch processing as
25102 emacs --batch
25103 --load=$HOME/lib/emacs/org.el
25104 --eval \"(setq org-export-headline-levels 2)\"
25105 --visit=MyFile --funcall org-export-as-html-batch"
25106 (org-export-as-html org-export-headline-levels 'hidden))
25108 (defun org-export-as-html-to-buffer (arg)
25109 "Call `org-exort-as-html` with output to a temporary buffer.
25110 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25111 (interactive "P")
25112 (org-export-as-html arg nil nil "*Org HTML Export*")
25113 (switch-to-buffer-other-window "*Org HTML Export*"))
25115 (defun org-replace-region-by-html (beg end)
25116 "Assume the current region has org-mode syntax, and convert it to HTML.
25117 This can be used in any buffer. For example, you could write an
25118 itemized list in org-mode syntax in an HTML buffer and then use this
25119 command to convert it."
25120 (interactive "r")
25121 (let (reg html buf pop-up-frames)
25122 (save-window-excursion
25123 (if (org-mode-p)
25124 (setq html (org-export-region-as-html
25125 beg end t 'string))
25126 (setq reg (buffer-substring beg end)
25127 buf (get-buffer-create "*Org tmp*"))
25128 (with-current-buffer buf
25129 (erase-buffer)
25130 (insert reg)
25131 (org-mode)
25132 (setq html (org-export-region-as-html
25133 (point-min) (point-max) t 'string)))
25134 (kill-buffer buf)))
25135 (delete-region beg end)
25136 (insert html)))
25138 (defun org-export-region-as-html (beg end &optional body-only buffer)
25139 "Convert region from BEG to END in org-mode buffer to HTML.
25140 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25141 contents, and only produce the region of converted text, useful for
25142 cut-and-paste operations.
25143 If BUFFER is a buffer or a string, use/create that buffer as a target
25144 of the converted HTML. If BUFFER is the symbol `string', return the
25145 produced HTML as a string and leave not buffer behind. For example,
25146 a Lisp program could call this function in the following way:
25148 (setq html (org-export-region-as-html beg end t 'string))
25150 When called interactively, the output buffer is selected, and shown
25151 in a window. A non-interactive call will only retunr the buffer."
25152 (interactive "r\nP")
25153 (when (interactive-p)
25154 (setq buffer "*Org HTML Export*"))
25155 (let ((transient-mark-mode t) (zmacs-regions t)
25156 rtn)
25157 (goto-char end)
25158 (set-mark (point)) ;; to activate the region
25159 (goto-char beg)
25160 (setq rtn (org-export-as-html
25161 nil nil nil
25162 buffer body-only))
25163 (if (fboundp 'deactivate-mark) (deactivate-mark))
25164 (if (and (interactive-p) (bufferp rtn))
25165 (switch-to-buffer-other-window rtn)
25166 rtn)))
25168 (defvar html-table-tag nil) ; dynamically scoped into this.
25169 (defun org-export-as-html (arg &optional hidden ext-plist
25170 to-buffer body-only pub-dir)
25171 "Export the outline as a pretty HTML file.
25172 If there is an active region, export only the region. The prefix
25173 ARG specifies how many levels of the outline should become
25174 headlines. The default is 3. Lower levels will become bulleted
25175 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25176 EXT-PLIST is a property list with external parameters overriding
25177 org-mode's default settings, but still inferior to file-local
25178 settings. When TO-BUFFER is non-nil, create a buffer with that
25179 name and export to that buffer. If TO-BUFFER is the symbol
25180 `string', don't leave any buffer behind but just return the
25181 resulting HTML as a string. When BODY-ONLY is set, don't produce
25182 the file header and footer, simply return the content of
25183 <body>...</body>, without even the body tags themselves. When
25184 PUB-DIR is set, use this as the publishing directory."
25185 (interactive "P")
25187 ;; Make sure we have a file name when we need it.
25188 (when (and (not (or to-buffer body-only))
25189 (not buffer-file-name))
25190 (if (buffer-base-buffer)
25191 (org-set-local 'buffer-file-name
25192 (with-current-buffer (buffer-base-buffer)
25193 buffer-file-name))
25194 (error "Need a file name to be able to export.")))
25196 (message "Exporting...")
25197 (setq-default org-todo-line-regexp org-todo-line-regexp)
25198 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25199 (setq-default org-done-keywords org-done-keywords)
25200 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25201 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25202 ext-plist
25203 (org-infile-export-plist)))
25205 (style (plist-get opt-plist :style))
25206 (html-extension (plist-get opt-plist :html-extension))
25207 (link-validate (plist-get opt-plist :link-validation-function))
25208 valid thetoc have-headings first-heading-pos
25209 (odd org-odd-levels-only)
25210 (region-p (org-region-active-p))
25211 (subtree-p
25212 (when region-p
25213 (save-excursion
25214 (goto-char (region-beginning))
25215 (and (org-at-heading-p)
25216 (>= (org-end-of-subtree t t) (region-end))))))
25217 ;; The following two are dynamically scoped into other
25218 ;; routines below.
25219 (org-current-export-dir
25220 (or pub-dir (org-export-directory :html opt-plist)))
25221 (org-current-export-file buffer-file-name)
25222 (level 0) (line "") (origline "") txt todo
25223 (umax nil)
25224 (umax-toc nil)
25225 (filename (if to-buffer nil
25226 (expand-file-name
25227 (concat
25228 (file-name-sans-extension
25229 (or (and subtree-p
25230 (org-entry-get (region-beginning)
25231 "EXPORT_FILE_NAME" t))
25232 (file-name-nondirectory buffer-file-name)))
25233 "." html-extension)
25234 (file-name-as-directory
25235 (or pub-dir (org-export-directory :html opt-plist))))))
25236 (current-dir (if buffer-file-name
25237 (file-name-directory buffer-file-name)
25238 default-directory))
25239 (buffer (if to-buffer
25240 (cond
25241 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25242 (t (get-buffer-create to-buffer)))
25243 (find-file-noselect filename)))
25244 (org-levels-open (make-vector org-level-max nil))
25245 (date (plist-get opt-plist :date))
25246 (author (plist-get opt-plist :author))
25247 (title (or (and subtree-p (org-export-get-title-from-subtree))
25248 (plist-get opt-plist :title)
25249 (and (not
25250 (plist-get opt-plist :skip-before-1st-heading))
25251 (org-export-grab-title-from-buffer))
25252 (and buffer-file-name
25253 (file-name-sans-extension
25254 (file-name-nondirectory buffer-file-name)))
25255 "UNTITLED"))
25256 (html-table-tag (plist-get opt-plist :html-table-tag))
25257 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25258 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25259 (inquote nil)
25260 (infixed nil)
25261 (in-local-list nil)
25262 (local-list-num nil)
25263 (local-list-indent nil)
25264 (llt org-plain-list-ordered-item-terminator)
25265 (email (plist-get opt-plist :email))
25266 (language (plist-get opt-plist :language))
25267 (lang-words nil)
25268 (target-alist nil) tg
25269 (head-count 0) cnt
25270 (start 0)
25271 (coding-system (and (boundp 'buffer-file-coding-system)
25272 buffer-file-coding-system))
25273 (coding-system-for-write (or org-export-html-coding-system
25274 coding-system))
25275 (save-buffer-coding-system (or org-export-html-coding-system
25276 coding-system))
25277 (charset (and coding-system-for-write
25278 (fboundp 'coding-system-get)
25279 (coding-system-get coding-system-for-write
25280 'mime-charset)))
25281 (region
25282 (buffer-substring
25283 (if region-p (region-beginning) (point-min))
25284 (if region-p (region-end) (point-max))))
25285 (lines
25286 (org-split-string
25287 (org-cleaned-string-for-export
25288 region
25289 :emph-multiline t
25290 :for-html t
25291 :skip-before-1st-heading
25292 (plist-get opt-plist :skip-before-1st-heading)
25293 :drawers (plist-get opt-plist :drawers)
25294 :archived-trees
25295 (plist-get opt-plist :archived-trees)
25296 :add-text
25297 (plist-get opt-plist :text)
25298 :LaTeX-fragments
25299 (plist-get opt-plist :LaTeX-fragments))
25300 "[\r\n]"))
25301 table-open type
25302 table-buffer table-orig-buffer
25303 ind start-is-num starter didclose
25304 rpl path desc descp desc1 desc2 link
25305 snumber fnc
25308 (let ((inhibit-read-only t))
25309 (org-unmodified
25310 (remove-text-properties (point-min) (point-max)
25311 '(:org-license-to-kill t))))
25313 (message "Exporting...")
25315 (setq org-min-level (org-get-min-level lines))
25316 (setq org-last-level org-min-level)
25317 (org-init-section-numbers)
25319 (cond
25320 ((and date (string-match "%" date))
25321 (setq date (format-time-string date (current-time))))
25322 (date)
25323 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25325 ;; Get the language-dependent settings
25326 (setq lang-words (or (assoc language org-export-language-setup)
25327 (assoc "en" org-export-language-setup)))
25329 ;; Switch to the output buffer
25330 (set-buffer buffer)
25331 (let ((inhibit-read-only t)) (erase-buffer))
25332 (fundamental-mode)
25334 (and (fboundp 'set-buffer-file-coding-system)
25335 (set-buffer-file-coding-system coding-system-for-write))
25337 (let ((case-fold-search nil)
25338 (org-odd-levels-only odd))
25339 ;; create local variables for all options, to make sure all called
25340 ;; functions get the correct information
25341 (mapc (lambda (x)
25342 (set (make-local-variable (cdr x))
25343 (plist-get opt-plist (car x))))
25344 org-export-plist-vars)
25345 (setq umax (if arg (prefix-numeric-value arg)
25346 org-export-headline-levels))
25347 (setq umax-toc (if (integerp org-export-with-toc)
25348 (min org-export-with-toc umax)
25349 umax))
25350 (unless body-only
25351 ;; File header
25352 (insert (format
25353 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25354 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25355 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25356 lang=\"%s\" xml:lang=\"%s\">
25357 <head>
25358 <title>%s</title>
25359 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25360 <meta name=\"generator\" content=\"Org-mode\"/>
25361 <meta name=\"generated\" content=\"%s\"/>
25362 <meta name=\"author\" content=\"%s\"/>
25364 </head><body>
25366 language language (org-html-expand title)
25367 (or charset "iso-8859-1") date author style))
25369 (insert (or (plist-get opt-plist :preamble) ""))
25371 (when (plist-get opt-plist :auto-preamble)
25372 (if title (insert (format org-export-html-title-format
25373 (org-html-expand title))))))
25375 (if (and org-export-with-toc (not body-only))
25376 (progn
25377 (push (format "<h%d>%s</h%d>\n"
25378 org-export-html-toplevel-hlevel
25379 (nth 3 lang-words)
25380 org-export-html-toplevel-hlevel)
25381 thetoc)
25382 (push "<div id=\"text-table-of-contents\">\n" thetoc)
25383 (push "<ul>\n<li>" thetoc)
25384 (setq lines
25385 (mapcar '(lambda (line)
25386 (if (string-match org-todo-line-regexp line)
25387 ;; This is a headline
25388 (progn
25389 (setq have-headings t)
25390 (setq level (- (match-end 1) (match-beginning 1))
25391 level (org-tr-level level)
25392 txt (save-match-data
25393 (org-html-expand
25394 (org-export-cleanup-toc-line
25395 (match-string 3 line))))
25396 todo
25397 (or (and org-export-mark-todo-in-toc
25398 (match-beginning 2)
25399 (not (member (match-string 2 line)
25400 org-done-keywords)))
25401 ; TODO, not DONE
25402 (and org-export-mark-todo-in-toc
25403 (= level umax-toc)
25404 (org-search-todo-below
25405 line lines level))))
25406 (if (string-match
25407 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25408 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25409 (if (string-match quote-re0 txt)
25410 (setq txt (replace-match "" t t txt)))
25411 (setq snumber (org-section-number level))
25412 (if org-export-with-section-numbers
25413 (setq txt (concat snumber " " txt)))
25414 (if (<= level (max umax umax-toc))
25415 (setq head-count (+ head-count 1)))
25416 (if (<= level umax-toc)
25417 (progn
25418 (if (> level org-last-level)
25419 (progn
25420 (setq cnt (- level org-last-level))
25421 (while (>= (setq cnt (1- cnt)) 0)
25422 (push "\n<ul>\n<li>" thetoc))
25423 (push "\n" thetoc)))
25424 (if (< level org-last-level)
25425 (progn
25426 (setq cnt (- org-last-level level))
25427 (while (>= (setq cnt (1- cnt)) 0)
25428 (push "</li>\n</ul>" thetoc))
25429 (push "\n" thetoc)))
25430 ;; Check for targets
25431 (while (string-match org-target-regexp line)
25432 (setq tg (match-string 1 line)
25433 line (replace-match
25434 (concat "@<span class=\"target\">" tg "@</span> ")
25435 t t line))
25436 (push (cons (org-solidify-link-text tg)
25437 (format "sec-%s" snumber))
25438 target-alist))
25439 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25440 (setq txt (replace-match "" t t txt)))
25441 (push
25442 (format
25443 (if todo
25444 "</li>\n<li><a href=\"#sec-%s\"><span class=\"todo\">%s</span></a>"
25445 "</li>\n<li><a href=\"#sec-%s\">%s</a>")
25446 snumber txt) thetoc)
25448 (setq org-last-level level))
25450 line)
25451 lines))
25452 (while (> org-last-level (1- org-min-level))
25453 (setq org-last-level (1- org-last-level))
25454 (push "</li>\n</ul>\n" thetoc))
25455 (push "</div>\n" thetoc)
25456 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25458 (setq head-count 0)
25459 (org-init-section-numbers)
25461 (while (setq line (pop lines) origline line)
25462 (catch 'nextline
25464 ;; end of quote section?
25465 (when (and inquote (string-match "^\\*+ " line))
25466 (insert "</pre>\n")
25467 (setq inquote nil))
25468 ;; inside a quote section?
25469 (when inquote
25470 (insert (org-html-protect line) "\n")
25471 (throw 'nextline nil))
25473 ;; verbatim lines
25474 (when (and org-export-with-fixed-width
25475 (string-match "^[ \t]*:\\(.*\\)" line))
25476 (when (not infixed)
25477 (setq infixed t)
25478 (insert "<pre>\n"))
25479 (insert (org-html-protect (match-string 1 line)) "\n")
25480 (when (and lines
25481 (not (string-match "^[ \t]*\\(:.*\\)"
25482 (car lines))))
25483 (setq infixed nil)
25484 (insert "</pre>\n"))
25485 (throw 'nextline nil))
25487 ;; Protected HTML
25488 (when (get-text-property 0 'org-protected line)
25489 (let (par)
25490 (when (re-search-backward
25491 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25492 (setq par (match-string 1))
25493 (replace-match "\\2\n"))
25494 (insert line "\n")
25495 (while (and lines
25496 (or (= (length (car lines)) 0)
25497 (get-text-property 0 'org-protected (car lines))))
25498 (insert (pop lines) "\n"))
25499 (and par (insert "<p>\n")))
25500 (throw 'nextline nil))
25502 ;; Horizontal line
25503 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25504 (insert "\n<hr/>\n")
25505 (throw 'nextline nil))
25507 ;; make targets to anchors
25508 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25509 (cond
25510 ((match-end 2)
25511 (setq line (replace-match
25512 (concat "@<a name=\""
25513 (org-solidify-link-text (match-string 1 line))
25514 "\">\\nbsp@</a>")
25515 t t line)))
25516 ((and org-export-with-toc (equal (string-to-char line) ?*))
25517 (setq line (replace-match
25518 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25519 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25520 t t line)))
25522 (setq line (replace-match
25523 (concat "@<a name=\""
25524 (org-solidify-link-text (match-string 1 line))
25525 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25526 t t line)))))
25528 (setq line (org-html-handle-time-stamps line))
25530 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25531 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25532 ;; Also handle sub_superscripts and checkboxes
25533 (or (string-match org-table-hline-regexp line)
25534 (setq line (org-html-expand line)))
25536 ;; Format the links
25537 (setq start 0)
25538 (while (string-match org-bracket-link-analytic-regexp line start)
25539 (setq start (match-beginning 0))
25540 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25541 (setq path (match-string 3 line))
25542 (setq desc1 (if (match-end 5) (match-string 5 line))
25543 desc2 (if (match-end 2) (concat type ":" path) path)
25544 descp (and desc1 (not (equal desc1 desc2)))
25545 desc (or desc1 desc2))
25546 ;; Make an image out of the description if that is so wanted
25547 (when (and descp (org-file-image-p desc))
25548 (save-match-data
25549 (if (string-match "^file:" desc)
25550 (setq desc (substring desc (match-end 0)))))
25551 (setq desc (concat "<img src=\"" desc "\"/>")))
25552 ;; FIXME: do we need to unescape here somewhere?
25553 (cond
25554 ((equal type "internal")
25555 (setq rpl
25556 (concat
25557 "<a href=\"#"
25558 (org-solidify-link-text
25559 (save-match-data (org-link-unescape path)) target-alist)
25560 "\">" desc "</a>")))
25561 ((member type '("http" "https"))
25562 ;; standard URL, just check if we need to inline an image
25563 (if (and (or (eq t org-export-html-inline-images)
25564 (and org-export-html-inline-images (not descp)))
25565 (org-file-image-p path))
25566 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25567 (setq link (concat type ":" path))
25568 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25569 ((member type '("ftp" "mailto" "news"))
25570 ;; standard URL
25571 (setq link (concat type ":" path))
25572 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25573 ((string= type "file")
25574 ;; FILE link
25575 (let* ((filename path)
25576 (abs-p (file-name-absolute-p filename))
25577 thefile file-is-image-p search)
25578 (save-match-data
25579 (if (string-match "::\\(.*\\)" filename)
25580 (setq search (match-string 1 filename)
25581 filename (replace-match "" t nil filename)))
25582 (setq valid
25583 (if (functionp link-validate)
25584 (funcall link-validate filename current-dir)
25586 (setq file-is-image-p (org-file-image-p filename))
25587 (setq thefile (if abs-p (expand-file-name filename) filename))
25588 (when (and org-export-html-link-org-files-as-html
25589 (string-match "\\.org$" thefile))
25590 (setq thefile (concat (substring thefile 0
25591 (match-beginning 0))
25592 "." html-extension))
25593 (if (and search
25594 ;; make sure this is can be used as target search
25595 (not (string-match "^[0-9]*$" search))
25596 (not (string-match "^\\*" search))
25597 (not (string-match "^/.*/$" search)))
25598 (setq thefile (concat thefile "#"
25599 (org-solidify-link-text
25600 (org-link-unescape search)))))
25601 (when (string-match "^file:" desc)
25602 (setq desc (replace-match "" t t desc))
25603 (if (string-match "\\.org$" desc)
25604 (setq desc (replace-match "" t t desc))))))
25605 (setq rpl (if (and file-is-image-p
25606 (or (eq t org-export-html-inline-images)
25607 (and org-export-html-inline-images
25608 (not descp))))
25609 (concat "<img src=\"" thefile "\"/>")
25610 (concat "<a href=\"" thefile "\">" desc "</a>")))
25611 (if (not valid) (setq rpl desc))))
25613 ((functionp (setq fnc (nth 2 (assoc type org-link-protocols))))
25614 (setq rpl
25615 (save-match-data
25616 (funcall fnc (org-link-unescape path) desc1 'html))))
25619 ;; just publish the path, as default
25620 (setq rpl (concat "<i>&lt;" type ":"
25621 (save-match-data (org-link-unescape path))
25622 "&gt;</i>"))))
25623 (setq line (replace-match rpl t t line)
25624 start (+ start (length rpl))))
25626 ;; TODO items
25627 (if (and (string-match org-todo-line-regexp line)
25628 (match-beginning 2))
25630 (setq line
25631 (concat (substring line 0 (match-beginning 2))
25632 "<span class=\""
25633 (if (member (match-string 2 line)
25634 org-done-keywords)
25635 "done" "todo")
25636 "\">" (match-string 2 line)
25637 "</span>" (substring line (match-end 2)))))
25639 ;; Does this contain a reference to a footnote?
25640 (when org-export-with-footnotes
25641 (setq start 0)
25642 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25643 (if (get-text-property (match-beginning 2) 'org-protected line)
25644 (setq start (match-end 2))
25645 (let ((n (match-string 2 line)))
25646 (setq line
25647 (replace-match
25648 (format
25649 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25650 (match-string 1 line) n n n)
25651 t t line))))))
25653 (cond
25654 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25655 ;; This is a headline
25656 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25657 txt (match-string 2 line))
25658 (if (string-match quote-re0 txt)
25659 (setq txt (replace-match "" t t txt)))
25660 (if (<= level (max umax umax-toc))
25661 (setq head-count (+ head-count 1)))
25662 (when in-local-list
25663 ;; Close any local lists before inserting a new header line
25664 (while local-list-num
25665 (org-close-li)
25666 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25667 (pop local-list-num))
25668 (setq local-list-indent nil
25669 in-local-list nil))
25670 (setq first-heading-pos (or first-heading-pos (point)))
25671 (org-html-level-start level txt umax
25672 (and org-export-with-toc (<= level umax))
25673 head-count)
25674 ;; QUOTES
25675 (when (string-match quote-re line)
25676 (insert "<pre>")
25677 (setq inquote t)))
25679 ((and org-export-with-tables
25680 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25681 (if (not table-open)
25682 ;; New table starts
25683 (setq table-open t table-buffer nil table-orig-buffer nil))
25684 ;; Accumulate lines
25685 (setq table-buffer (cons line table-buffer)
25686 table-orig-buffer (cons origline table-orig-buffer))
25687 (when (or (not lines)
25688 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25689 (car lines))))
25690 (setq table-open nil
25691 table-buffer (nreverse table-buffer)
25692 table-orig-buffer (nreverse table-orig-buffer))
25693 (org-close-par-maybe)
25694 (insert (org-format-table-html table-buffer table-orig-buffer))))
25696 ;; Normal lines
25697 (when (string-match
25698 (cond
25699 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25700 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25701 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25702 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25703 line)
25704 (setq ind (org-get-string-indentation line)
25705 start-is-num (match-beginning 4)
25706 starter (if (match-beginning 2)
25707 (substring (match-string 2 line) 0 -1))
25708 line (substring line (match-beginning 5)))
25709 (unless (string-match "[^ \t]" line)
25710 ;; empty line. Pretend indentation is large.
25711 (setq ind (if org-empty-line-terminates-plain-lists
25713 (1+ (or (car local-list-indent) 1)))))
25714 (setq didclose nil)
25715 (while (and in-local-list
25716 (or (and (= ind (car local-list-indent))
25717 (not starter))
25718 (< ind (car local-list-indent))))
25719 (setq didclose t)
25720 (org-close-li)
25721 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25722 (pop local-list-num) (pop local-list-indent)
25723 (setq in-local-list local-list-indent))
25724 (cond
25725 ((and starter
25726 (or (not in-local-list)
25727 (> ind (car local-list-indent))))
25728 ;; Start new (level of) list
25729 (org-close-par-maybe)
25730 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25731 (push start-is-num local-list-num)
25732 (push ind local-list-indent)
25733 (setq in-local-list t))
25734 (starter
25735 ;; continue current list
25736 (org-close-li)
25737 (insert "<li>\n"))
25738 (didclose
25739 ;; we did close a list, normal text follows: need <p>
25740 (org-open-par)))
25741 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25742 (setq line
25743 (replace-match
25744 (if (equal (match-string 1 line) "X")
25745 "<b>[X]</b>"
25746 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25747 t t line))))
25749 ;; Empty lines start a new paragraph. If hand-formatted lists
25750 ;; are not fully interpreted, lines starting with "-", "+", "*"
25751 ;; also start a new paragraph.
25752 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25754 ;; Is this the start of a footnote?
25755 (when org-export-with-footnotes
25756 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25757 (org-close-par-maybe)
25758 (let ((n (match-string 1 line)))
25759 (setq line (replace-match
25760 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25762 ;; Check if the line break needs to be conserved
25763 (cond
25764 ((string-match "\\\\\\\\[ \t]*$" line)
25765 (setq line (replace-match "<br/>" t t line)))
25766 (org-export-preserve-breaks
25767 (setq line (concat line "<br/>"))))
25769 (insert line "\n")))))
25771 ;; Properly close all local lists and other lists
25772 (when inquote (insert "</pre>\n"))
25773 (when in-local-list
25774 ;; Close any local lists before inserting a new header line
25775 (while local-list-num
25776 (org-close-li)
25777 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25778 (pop local-list-num))
25779 (setq local-list-indent nil
25780 in-local-list nil))
25781 (org-html-level-start 1 nil umax
25782 (and org-export-with-toc (<= level umax))
25783 head-count)
25784 ;; the </div> to lose the last text-... div.
25785 (insert "</div>\n")
25787 (unless body-only
25788 (when (plist-get opt-plist :auto-postamble)
25789 (insert "<div id=\"postamble\">")
25790 (when (and org-export-author-info author)
25791 (insert "<p class=\"author\"> "
25792 (nth 1 lang-words) ": " author "\n")
25793 (when email
25794 (if (listp (split-string email ",+ *"))
25795 (mapc (lambda(e)
25796 (insert "<a href=\"mailto:" e "\">&lt;"
25797 e "&gt;</a>\n"))
25798 (split-string email ",+ *"))
25799 (insert "<a href=\"mailto:" email "\">&lt;"
25800 email "&gt;</a>\n")))
25801 (insert "</p>\n"))
25802 (when (and date org-export-time-stamp-file)
25803 (insert "<p class=\"date\"> "
25804 (nth 2 lang-words) ": "
25805 date "</p>\n"))
25806 (insert "</div>"))
25808 (if org-export-html-with-timestamp
25809 (insert org-export-html-html-helper-timestamp))
25810 (insert (or (plist-get opt-plist :postamble) ""))
25811 (insert "</body>\n</html>\n"))
25813 (normal-mode)
25814 (if (eq major-mode default-major-mode) (html-mode))
25816 ;; insert the table of contents
25817 (goto-char (point-min))
25818 (when thetoc
25819 (if (or (re-search-forward
25820 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25821 (re-search-forward
25822 "\\[TABLE-OF-CONTENTS\\]" nil t))
25823 (progn
25824 (goto-char (match-beginning 0))
25825 (replace-match ""))
25826 (goto-char first-heading-pos)
25827 (when (looking-at "\\s-*</p>")
25828 (goto-char (match-end 0))
25829 (insert "\n")))
25830 (insert "<div id=\"table-of-contents\">\n")
25831 (mapc 'insert thetoc)
25832 (insert "</div>\n"))
25833 ;; remove empty paragraphs and lists
25834 (goto-char (point-min))
25835 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25836 (replace-match ""))
25837 (goto-char (point-min))
25838 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25839 (replace-match ""))
25840 (goto-char (point-min))
25841 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25842 (replace-match ""))
25843 ;; Convert whitespace place holders
25844 (goto-char (point-min))
25845 (let (beg end n)
25846 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25847 (setq n (get-text-property beg 'org-whitespace)
25848 end (next-single-property-change beg 'org-whitespace))
25849 (goto-char beg)
25850 (delete-region beg end)
25851 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25852 (make-string n ?x)))))
25853 (or to-buffer (save-buffer))
25854 (goto-char (point-min))
25855 (message "Exporting... done")
25856 (if (eq to-buffer 'string)
25857 (prog1 (buffer-substring (point-min) (point-max))
25858 (kill-buffer (current-buffer)))
25859 (current-buffer)))))
25861 (defvar org-table-colgroup-info nil)
25862 (defun org-format-table-ascii (lines)
25863 "Format a table for ascii export."
25864 (if (stringp lines)
25865 (setq lines (org-split-string lines "\n")))
25866 (if (not (string-match "^[ \t]*|" (car lines)))
25867 ;; Table made by table.el - test for spanning
25868 lines
25870 ;; A normal org table
25871 ;; Get rid of hlines at beginning and end
25872 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25873 (setq lines (nreverse lines))
25874 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25875 (setq lines (nreverse lines))
25876 (when org-export-table-remove-special-lines
25877 ;; Check if the table has a marking column. If yes remove the
25878 ;; column and the special lines
25879 (setq lines (org-table-clean-before-export lines)))
25880 ;; Get rid of the vertical lines except for grouping
25881 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25882 rtn line vl1 start)
25883 (while (setq line (pop lines))
25884 (if (string-match org-table-hline-regexp line)
25885 (and (string-match "|\\(.*\\)|" line)
25886 (setq line (replace-match " \\1" t nil line)))
25887 (setq start 0 vl1 vl)
25888 (while (string-match "|" line start)
25889 (setq start (match-end 0))
25890 (or (pop vl1) (setq line (replace-match " " t t line)))))
25891 (push line rtn))
25892 (nreverse rtn))))
25894 (defun org-colgroup-info-to-vline-list (info)
25895 (let (vl new last)
25896 (while info
25897 (setq last new new (pop info))
25898 (if (or (memq last '(:end :startend))
25899 (memq new '(:start :startend)))
25900 (push t vl)
25901 (push nil vl)))
25902 (setq vl (nreverse vl))
25903 (and vl (setcar vl nil))
25904 vl))
25906 (defun org-format-table-html (lines olines)
25907 "Find out which HTML converter to use and return the HTML code."
25908 (if (stringp lines)
25909 (setq lines (org-split-string lines "\n")))
25910 (if (string-match "^[ \t]*|" (car lines))
25911 ;; A normal org table
25912 (org-format-org-table-html lines)
25913 ;; Table made by table.el - test for spanning
25914 (let* ((hlines (delq nil (mapcar
25915 (lambda (x)
25916 (if (string-match "^[ \t]*\\+-" x) x
25917 nil))
25918 lines)))
25919 (first (car hlines))
25920 (ll (and (string-match "\\S-+" first)
25921 (match-string 0 first)))
25922 (re (concat "^[ \t]*" (regexp-quote ll)))
25923 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25924 hlines))))
25925 (if (and (not spanning)
25926 (not org-export-prefer-native-exporter-for-tables))
25927 ;; We can use my own converter with HTML conversions
25928 (org-format-table-table-html lines)
25929 ;; Need to use the code generator in table.el, with the original text.
25930 (org-format-table-table-html-using-table-generate-source olines)))))
25932 (defun org-format-org-table-html (lines &optional splice)
25933 "Format a table into HTML."
25934 ;; Get rid of hlines at beginning and end
25935 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25936 (setq lines (nreverse lines))
25937 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25938 (setq lines (nreverse lines))
25939 (when org-export-table-remove-special-lines
25940 ;; Check if the table has a marking column. If yes remove the
25941 ;; column and the special lines
25942 (setq lines (org-table-clean-before-export lines)))
25944 (let ((head (and org-export-highlight-first-table-line
25945 (delq nil (mapcar
25946 (lambda (x) (string-match "^[ \t]*|-" x))
25947 (cdr lines)))))
25948 (nlines 0) fnum i
25949 tbopen line fields html gr colgropen)
25950 (if splice (setq head nil))
25951 (unless splice (push (if head "<thead>" "<tbody>") html))
25952 (setq tbopen t)
25953 (while (setq line (pop lines))
25954 (catch 'next-line
25955 (if (string-match "^[ \t]*|-" line)
25956 (progn
25957 (unless splice
25958 (push (if head "</thead>" "</tbody>") html)
25959 (if lines (push "<tbody>" html) (setq tbopen nil)))
25960 (setq head nil) ;; head ends here, first time around
25961 ;; ignore this line
25962 (throw 'next-line t)))
25963 ;; Break the line into fields
25964 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
25965 (unless fnum (setq fnum (make-vector (length fields) 0)))
25966 (setq nlines (1+ nlines) i -1)
25967 (push (concat "<tr>"
25968 (mapconcat
25969 (lambda (x)
25970 (setq i (1+ i))
25971 (if (and (< i nlines)
25972 (string-match org-table-number-regexp x))
25973 (incf (aref fnum i)))
25974 (if head
25975 (concat (car org-export-table-header-tags) x
25976 (cdr org-export-table-header-tags))
25977 (concat (car org-export-table-data-tags) x
25978 (cdr org-export-table-data-tags))))
25979 fields "")
25980 "</tr>")
25981 html)))
25982 (unless splice (if tbopen (push "</tbody>" html)))
25983 (unless splice (push "</table>\n" html))
25984 (setq html (nreverse html))
25985 (unless splice
25986 ;; Put in col tags with the alignment (unfortuntely often ignored...)
25987 (push (mapconcat
25988 (lambda (x)
25989 (setq gr (pop org-table-colgroup-info))
25990 (format "%s<col align=\"%s\"></col>%s"
25991 (if (memq gr '(:start :startend))
25992 (prog1
25993 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
25994 (setq colgropen t))
25996 (if (> (/ (float x) nlines) org-table-number-fraction)
25997 "right" "left")
25998 (if (memq gr '(:end :startend))
25999 (progn (setq colgropen nil) "</colgroup>")
26000 "")))
26001 fnum "")
26002 html)
26003 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26004 (push html-table-tag html))
26005 (concat (mapconcat 'identity html "\n") "\n")))
26007 (defun org-table-clean-before-export (lines)
26008 "Check if the table has a marking column.
26009 If yes remove the column and the special lines."
26010 (setq org-table-colgroup-info nil)
26011 (if (memq nil
26012 (mapcar
26013 (lambda (x) (or (string-match "^[ \t]*|-" x)
26014 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26015 lines))
26016 (progn
26017 (setq org-table-clean-did-remove-column nil)
26018 (delq nil
26019 (mapcar
26020 (lambda (x)
26021 (cond
26022 ((string-match "^[ \t]*| */ *|" x)
26023 (setq org-table-colgroup-info
26024 (mapcar (lambda (x)
26025 (cond ((member x '("<" "&lt;")) :start)
26026 ((member x '(">" "&gt;")) :end)
26027 ((member x '("<>" "&lt;&gt;")) :startend)
26028 (t nil)))
26029 (org-split-string x "[ \t]*|[ \t]*")))
26030 nil)
26031 (t x)))
26032 lines)))
26033 (setq org-table-clean-did-remove-column t)
26034 (delq nil
26035 (mapcar
26036 (lambda (x)
26037 (cond
26038 ((string-match "^[ \t]*| */ *|" x)
26039 (setq org-table-colgroup-info
26040 (mapcar (lambda (x)
26041 (cond ((member x '("<" "&lt;")) :start)
26042 ((member x '(">" "&gt;")) :end)
26043 ((member x '("<>" "&lt;&gt;")) :startend)
26044 (t nil)))
26045 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26046 nil)
26047 ((string-match "^[ \t]*| *[!_^/] *|" x)
26048 nil) ; ignore this line
26049 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26050 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26051 ;; remove the first column
26052 (replace-match "\\1|" t nil x))))
26053 lines))))
26055 (defun org-format-table-table-html (lines)
26056 "Format a table generated by table.el into HTML.
26057 This conversion does *not* use `table-generate-source' from table.el.
26058 This has the advantage that Org-mode's HTML conversions can be used.
26059 But it has the disadvantage, that no cell- or row-spanning is allowed."
26060 (let (line field-buffer
26061 (head org-export-highlight-first-table-line)
26062 fields html empty)
26063 (setq html (concat html-table-tag "\n"))
26064 (while (setq line (pop lines))
26065 (setq empty "&nbsp;")
26066 (catch 'next-line
26067 (if (string-match "^[ \t]*\\+-" line)
26068 (progn
26069 (if field-buffer
26070 (progn
26071 (setq
26072 html
26073 (concat
26074 html
26075 "<tr>"
26076 (mapconcat
26077 (lambda (x)
26078 (if (equal x "") (setq x empty))
26079 (if head
26080 (concat (car org-export-table-header-tags) x
26081 (cdr org-export-table-header-tags))
26082 (concat (car org-export-table-data-tags) x
26083 (cdr org-export-table-data-tags))))
26084 field-buffer "\n")
26085 "</tr>\n"))
26086 (setq head nil)
26087 (setq field-buffer nil)))
26088 ;; Ignore this line
26089 (throw 'next-line t)))
26090 ;; Break the line into fields and store the fields
26091 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26092 (if field-buffer
26093 (setq field-buffer (mapcar
26094 (lambda (x)
26095 (concat x "<br/>" (pop fields)))
26096 field-buffer))
26097 (setq field-buffer fields))))
26098 (setq html (concat html "</table>\n"))
26099 html))
26101 (defun org-format-table-table-html-using-table-generate-source (lines)
26102 "Format a table into html, using `table-generate-source' from table.el.
26103 This has the advantage that cell- or row-spanning is allowed.
26104 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26105 (require 'table)
26106 (with-current-buffer (get-buffer-create " org-tmp1 ")
26107 (erase-buffer)
26108 (insert (mapconcat 'identity lines "\n"))
26109 (goto-char (point-min))
26110 (if (not (re-search-forward "|[^+]" nil t))
26111 (error "Error processing table"))
26112 (table-recognize-table)
26113 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26114 (table-generate-source 'html " org-tmp2 ")
26115 (set-buffer " org-tmp2 ")
26116 (buffer-substring (point-min) (point-max))))
26118 (defun org-html-handle-time-stamps (s)
26119 "Format time stamps in string S, or remove them."
26120 (catch 'exit
26121 (let (r b)
26122 (while (string-match org-maybe-keyword-time-regexp s)
26123 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26124 ;; never export CLOCK
26125 (throw 'exit ""))
26126 (or b (setq b (substring s 0 (match-beginning 0))))
26127 (if (not org-export-with-timestamps)
26128 (setq r (concat r (substring s 0 (match-beginning 0)))
26129 s (substring s (match-end 0)))
26130 (setq r (concat
26131 r (substring s 0 (match-beginning 0))
26132 (if (match-end 1)
26133 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26134 (match-string 1 s)))
26135 (format " @<span class=\"timestamp\">%s@</span>"
26136 (substring
26137 (org-translate-time (match-string 3 s)) 1 -1)))
26138 s (substring s (match-end 0)))))
26139 ;; Line break if line started and ended with time stamp stuff
26140 (if (not r)
26142 (setq r (concat r s))
26143 (unless (string-match "\\S-" (concat b s))
26144 (setq r (concat r "@<br/>")))
26145 r))))
26147 (defun org-html-protect (s)
26148 ;; convert & to &amp;, < to &lt; and > to &gt;
26149 (let ((start 0))
26150 (while (string-match "&" s start)
26151 (setq s (replace-match "&amp;" t t s)
26152 start (1+ (match-beginning 0))))
26153 (while (string-match "<" s)
26154 (setq s (replace-match "&lt;" t t s)))
26155 (while (string-match ">" s)
26156 (setq s (replace-match "&gt;" t t s))))
26159 (defun org-export-cleanup-toc-line (s)
26160 "Remove tags and time staps from lines going into the toc."
26161 (when (memq org-export-with-tags '(not-in-toc nil))
26162 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26163 (setq s (replace-match "" t t s))))
26164 (when org-export-remove-timestamps-from-toc
26165 (while (string-match org-maybe-keyword-time-regexp s)
26166 (setq s (replace-match "" t t s))))
26167 (while (string-match org-bracket-link-regexp s)
26168 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26169 t t s)))
26172 (defun org-html-expand (string)
26173 "Prepare STRING for HTML export. Applies all active conversions.
26174 If there are links in the string, don't modify these."
26175 (let* ((re (concat org-bracket-link-regexp "\\|"
26176 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26177 m s l res)
26178 (while (setq m (string-match re string))
26179 (setq s (substring string 0 m)
26180 l (match-string 0 string)
26181 string (substring string (match-end 0)))
26182 (push (org-html-do-expand s) res)
26183 (push l res))
26184 (push (org-html-do-expand string) res)
26185 (apply 'concat (nreverse res))))
26187 (defun org-html-do-expand (s)
26188 "Apply all active conversions to translate special ASCII to HTML."
26189 (setq s (org-html-protect s))
26190 (if org-export-html-expand
26191 (let ((start 0))
26192 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26193 (setq s (replace-match "<\\1>" t nil s)))))
26194 (if org-export-with-emphasize
26195 (setq s (org-export-html-convert-emphasize s)))
26196 (if org-export-with-special-strings
26197 (setq s (org-export-html-convert-special-strings s)))
26198 (if org-export-with-sub-superscripts
26199 (setq s (org-export-html-convert-sub-super s)))
26200 (if org-export-with-TeX-macros
26201 (let ((start 0) wd ass)
26202 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26203 (if (get-text-property (match-beginning 0) 'org-protected s)
26204 (setq start (match-end 0))
26205 (setq wd (match-string 1 s))
26206 (if (setq ass (assoc wd org-html-entities))
26207 (setq s (replace-match (or (cdr ass)
26208 (concat "&" (car ass) ";"))
26209 t t s))
26210 (setq start (+ start (length wd))))))))
26213 (defun org-create-multibrace-regexp (left right n)
26214 "Create a regular expression which will match a balanced sexp.
26215 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26216 as single character strings.
26217 The regexp returned will match the entire expression including the
26218 delimiters. It will also define a single group which contains the
26219 match except for the outermost delimiters. The maximum depth of
26220 stacked delimiters is N. Escaping delimiters is not possible."
26221 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26222 (or "\\|")
26223 (re nothing)
26224 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26225 (while (> n 1)
26226 (setq n (1- n)
26227 re (concat re or next)
26228 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26229 (concat left "\\(" re "\\)" right)))
26231 (defvar org-match-substring-regexp
26232 (concat
26233 "\\([^\\]\\)\\([_^]\\)\\("
26234 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26235 "\\|"
26236 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26237 "\\|"
26238 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26239 "The regular expression matching a sub- or superscript.")
26241 (defvar org-match-substring-with-braces-regexp
26242 (concat
26243 "\\([^\\]\\)\\([_^]\\)\\("
26244 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26245 "\\)")
26246 "The regular expression matching a sub- or superscript, forcing braces.")
26248 (defconst org-export-html-special-string-regexps
26249 '(("\\\\-" . "&shy;")
26250 ("---\\([^-]\\)" . "&mdash;\\1")
26251 ("--\\([^-]\\)" . "&ndash;\\1")
26252 ("\\.\\.\\." . "&hellip;"))
26253 "Regular expressions for special string conversion.")
26255 (defun org-export-html-convert-special-strings (string)
26256 "Convert special characters in STRING to HTML."
26257 (let ((all org-export-html-special-string-regexps)
26258 e a re rpl start)
26259 (while (setq a (pop all))
26260 (setq re (car a) rpl (cdr a) start 0)
26261 (while (string-match re string start)
26262 (if (get-text-property (match-beginning 0) 'org-protected string)
26263 (setq start (match-end 0))
26264 (setq string (replace-match rpl t nil string)))))
26265 string))
26267 (defun org-export-html-convert-sub-super (string)
26268 "Convert sub- and superscripts in STRING to HTML."
26269 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26270 (while (string-match org-match-substring-regexp string s)
26271 (cond
26272 ((and requireb (match-end 8)) (setq s (match-end 2)))
26273 ((get-text-property (match-beginning 2) 'org-protected string)
26274 (setq s (match-end 2)))
26276 (setq s (match-end 1)
26277 key (if (string= (match-string 2 string) "_") "sub" "sup")
26278 c (or (match-string 8 string)
26279 (match-string 6 string)
26280 (match-string 5 string))
26281 string (replace-match
26282 (concat (match-string 1 string)
26283 "<" key ">" c "</" key ">")
26284 t t string)))))
26285 (while (string-match "\\\\\\([_^]\\)" string)
26286 (setq string (replace-match (match-string 1 string) t t string)))
26287 string))
26289 (defun org-export-html-convert-emphasize (string)
26290 "Apply emphasis."
26291 (let ((s 0) rpl)
26292 (while (string-match org-emph-re string s)
26293 (if (not (equal
26294 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26295 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26296 (setq s (match-beginning 0)
26298 (concat
26299 (match-string 1 string)
26300 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26301 (match-string 4 string)
26302 (nth 3 (assoc (match-string 3 string)
26303 org-emphasis-alist))
26304 (match-string 5 string))
26305 string (replace-match rpl t t string)
26306 s (+ s (- (length rpl) 2)))
26307 (setq s (1+ s))))
26308 string))
26310 (defvar org-par-open nil)
26311 (defun org-open-par ()
26312 "Insert <p>, but first close previous paragraph if any."
26313 (org-close-par-maybe)
26314 (insert "\n<p>")
26315 (setq org-par-open t))
26316 (defun org-close-par-maybe ()
26317 "Close paragraph if there is one open."
26318 (when org-par-open
26319 (insert "</p>")
26320 (setq org-par-open nil)))
26321 (defun org-close-li ()
26322 "Close <li> if necessary."
26323 (org-close-par-maybe)
26324 (insert "</li>\n"))
26326 (defvar body-only) ; dynamically scoped into this.
26327 (defun org-html-level-start (level title umax with-toc head-count)
26328 "Insert a new level in HTML export.
26329 When TITLE is nil, just close all open levels."
26330 (org-close-par-maybe)
26331 (let ((l org-level-max) snumber)
26332 (while (>= l level)
26333 (if (aref org-levels-open (1- l))
26334 (progn
26335 (org-html-level-close l umax)
26336 (aset org-levels-open (1- l) nil)))
26337 (setq l (1- l)))
26338 (when title
26339 ;; If title is nil, this means this function is called to close
26340 ;; all levels, so the rest is done only if title is given
26341 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26342 (setq title (replace-match
26343 (if org-export-with-tags
26344 (save-match-data
26345 (concat
26346 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26347 (mapconcat 'identity (org-split-string
26348 (match-string 1 title) ":")
26349 "&nbsp;")
26350 "</span>"))
26352 t t title)))
26353 (if (> level umax)
26354 (progn
26355 (if (aref org-levels-open (1- level))
26356 (progn
26357 (org-close-li)
26358 (insert "<li>" title "<br/>\n"))
26359 (aset org-levels-open (1- level) t)
26360 (org-close-par-maybe)
26361 (insert "<ul>\n<li>" title "<br/>\n")))
26362 (aset org-levels-open (1- level) t)
26363 (setq snumber (org-section-number level))
26364 (if (and org-export-with-section-numbers (not body-only))
26365 (setq title (concat snumber " " title)))
26366 (setq level (+ level org-export-html-toplevel-hlevel -1))
26367 (unless (= head-count 1) (insert "\n</div>\n"))
26368 (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"
26369 snumber level level snumber title level snumber))
26370 (org-open-par)))))
26372 (defun org-html-level-close (level max-outline-level)
26373 "Terminate one level in HTML export."
26374 (if (<= level max-outline-level)
26375 (insert "</div>\n")
26376 (org-close-li)
26377 (insert "</ul>\n")))
26379 ;;; iCalendar export
26381 ;;;###autoload
26382 (defun org-export-icalendar-this-file ()
26383 "Export current file as an iCalendar file.
26384 The iCalendar file will be located in the same directory as the Org-mode
26385 file, but with extension `.ics'."
26386 (interactive)
26387 (org-export-icalendar nil buffer-file-name))
26389 ;;;###autoload
26390 (defun org-export-icalendar-all-agenda-files ()
26391 "Export all files in `org-agenda-files' to iCalendar .ics files.
26392 Each iCalendar file will be located in the same directory as the Org-mode
26393 file, but with extension `.ics'."
26394 (interactive)
26395 (apply 'org-export-icalendar nil (org-agenda-files t)))
26397 ;;;###autoload
26398 (defun org-export-icalendar-combine-agenda-files ()
26399 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26400 The file is stored under the name `org-combined-agenda-icalendar-file'."
26401 (interactive)
26402 (apply 'org-export-icalendar t (org-agenda-files t)))
26404 (defun org-export-icalendar (combine &rest files)
26405 "Create iCalendar files for all elements of FILES.
26406 If COMBINE is non-nil, combine all calendar entries into a single large
26407 file and store it under the name `org-combined-agenda-icalendar-file'."
26408 (save-excursion
26409 (org-prepare-agenda-buffers files)
26410 (let* ((dir (org-export-directory
26411 :ical (list :publishing-directory
26412 org-export-publishing-directory)))
26413 file ical-file ical-buffer category started org-agenda-new-buffers)
26414 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26415 (when combine
26416 (setq ical-file
26417 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26418 org-combined-agenda-icalendar-file
26419 (expand-file-name org-combined-agenda-icalendar-file dir))
26420 ical-buffer (org-get-agenda-file-buffer ical-file))
26421 (set-buffer ical-buffer) (erase-buffer))
26422 (while (setq file (pop files))
26423 (catch 'nextfile
26424 (org-check-agenda-file file)
26425 (set-buffer (org-get-agenda-file-buffer file))
26426 (unless combine
26427 (setq ical-file (concat (file-name-as-directory dir)
26428 (file-name-sans-extension
26429 (file-name-nondirectory buffer-file-name))
26430 ".ics"))
26431 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26432 (with-current-buffer ical-buffer (erase-buffer)))
26433 (setq category (or org-category
26434 (file-name-sans-extension
26435 (file-name-nondirectory buffer-file-name))))
26436 (if (symbolp category) (setq category (symbol-name category)))
26437 (let ((standard-output ical-buffer))
26438 (if combine
26439 (and (not started) (setq started t)
26440 (org-start-icalendar-file org-icalendar-combined-name))
26441 (org-start-icalendar-file category))
26442 (org-print-icalendar-entries combine)
26443 (when (or (and combine (not files)) (not combine))
26444 (org-finish-icalendar-file)
26445 (set-buffer ical-buffer)
26446 (save-buffer)
26447 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26448 (org-release-buffers org-agenda-new-buffers))))
26450 (defvar org-after-save-iCalendar-file-hook nil
26451 "Hook run after an iCalendar file has been saved.
26452 The iCalendar buffer is still current when this hook is run.
26453 A good way to use this is to tell a desktop calenndar application to re-read
26454 the iCalendar file.")
26456 (defun org-print-icalendar-entries (&optional combine)
26457 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26458 When COMBINE is non nil, add the category to each line."
26459 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26460 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26461 (dts (org-ical-ts-to-string
26462 (format-time-string (cdr org-time-stamp-formats) (current-time))
26463 "DTSTART"))
26464 hd ts ts2 state status (inc t) pos b sexp rrule
26465 scheduledp deadlinep tmp pri category entry location summary desc
26466 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26467 (org-refresh-category-properties)
26468 (save-excursion
26469 (goto-char (point-min))
26470 (while (re-search-forward re1 nil t)
26471 (catch :skip
26472 (org-agenda-skip)
26473 (when (boundp 'org-icalendar-verify-function)
26474 (unless (funcall org-icalendar-verify-function)
26475 (outline-next-heading)
26476 (backward-char 1)
26477 (throw :skip nil)))
26478 (setq pos (match-beginning 0)
26479 ts (match-string 0)
26480 inc t
26481 hd (org-get-heading)
26482 summary (org-icalendar-cleanup-string
26483 (org-entry-get nil "SUMMARY"))
26484 desc (org-icalendar-cleanup-string
26485 (or (org-entry-get nil "DESCRIPTION")
26486 (and org-icalendar-include-body (org-get-entry)))
26487 t org-icalendar-include-body)
26488 location (org-icalendar-cleanup-string
26489 (org-entry-get nil "LOCATION"))
26490 category (org-get-category))
26491 (if (looking-at re2)
26492 (progn
26493 (goto-char (match-end 0))
26494 (setq ts2 (match-string 1) inc nil))
26495 (setq tmp (buffer-substring (max (point-min)
26496 (- pos org-ds-keyword-length))
26497 pos)
26498 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26499 (progn
26500 (setq inc nil)
26501 (replace-match "\\1" t nil ts))
26503 deadlinep (string-match org-deadline-regexp tmp)
26504 scheduledp (string-match org-scheduled-regexp tmp)
26505 ;; donep (org-entry-is-done-p)
26507 (if (or (string-match org-tr-regexp hd)
26508 (string-match org-ts-regexp hd))
26509 (setq hd (replace-match "" t t hd)))
26510 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26511 (setq rrule
26512 (concat "\nRRULE:FREQ="
26513 (cdr (assoc
26514 (match-string 2 ts)
26515 '(("d" . "DAILY")("w" . "WEEKLY")
26516 ("m" . "MONTHLY")("y" . "YEARLY"))))
26517 ";INTERVAL=" (match-string 1 ts)))
26518 (setq rrule ""))
26519 (setq summary (or summary hd))
26520 (if (string-match org-bracket-link-regexp summary)
26521 (setq summary
26522 (replace-match (if (match-end 3)
26523 (match-string 3 summary)
26524 (match-string 1 summary))
26525 t t summary)))
26526 (if deadlinep (setq summary (concat "DL: " summary)))
26527 (if scheduledp (setq summary (concat "S: " summary)))
26528 (if (string-match "\\`<%%" ts)
26529 (with-current-buffer sexp-buffer
26530 (insert (substring ts 1 -1) " " summary "\n"))
26531 (princ (format "BEGIN:VEVENT
26533 %s%s
26534 SUMMARY:%s%s%s
26535 CATEGORIES:%s
26536 END:VEVENT\n"
26537 (org-ical-ts-to-string ts "DTSTART")
26538 (org-ical-ts-to-string ts2 "DTEND" inc)
26539 rrule summary
26540 (if (and desc (string-match "\\S-" desc))
26541 (concat "\nDESCRIPTION: " desc) "")
26542 (if (and location (string-match "\\S-" location))
26543 (concat "\nLOCATION: " location) "")
26544 category)))))
26546 (when (and org-icalendar-include-sexps
26547 (condition-case nil (require 'icalendar) (error nil))
26548 (fboundp 'icalendar-export-region))
26549 ;; Get all the literal sexps
26550 (goto-char (point-min))
26551 (while (re-search-forward "^&?%%(" nil t)
26552 (catch :skip
26553 (org-agenda-skip)
26554 (setq b (match-beginning 0))
26555 (goto-char (1- (match-end 0)))
26556 (forward-sexp 1)
26557 (end-of-line 1)
26558 (setq sexp (buffer-substring b (point)))
26559 (with-current-buffer sexp-buffer
26560 (insert sexp "\n"))
26561 (princ (org-diary-to-ical-string sexp-buffer)))))
26563 (when org-icalendar-include-todo
26564 (goto-char (point-min))
26565 (while (re-search-forward org-todo-line-regexp nil t)
26566 (catch :skip
26567 (org-agenda-skip)
26568 (when (boundp 'org-icalendar-verify-function)
26569 (unless (funcall org-icalendar-verify-function)
26570 (outline-next-heading)
26571 (backward-char 1)
26572 (throw :skip nil)))
26573 (setq state (match-string 2))
26574 (setq status (if (member state org-done-keywords)
26575 "COMPLETED" "NEEDS-ACTION"))
26576 (when (and state
26577 (or (not (member state org-done-keywords))
26578 (eq org-icalendar-include-todo 'all))
26579 (not (member org-archive-tag (org-get-tags-at)))
26581 (setq hd (match-string 3)
26582 summary (org-icalendar-cleanup-string
26583 (org-entry-get nil "SUMMARY"))
26584 desc (org-icalendar-cleanup-string
26585 (or (org-entry-get nil "DESCRIPTION")
26586 (and org-icalendar-include-body (org-get-entry)))
26587 t org-icalendar-include-body)
26588 location (org-icalendar-cleanup-string
26589 (org-entry-get nil "LOCATION")))
26590 (if (string-match org-bracket-link-regexp hd)
26591 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26592 (match-string 1 hd))
26593 t t hd)))
26594 (if (string-match org-priority-regexp hd)
26595 (setq pri (string-to-char (match-string 2 hd))
26596 hd (concat (substring hd 0 (match-beginning 1))
26597 (substring hd (match-end 1))))
26598 (setq pri org-default-priority))
26599 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26600 (- org-lowest-priority org-highest-priority))))))
26602 (princ (format "BEGIN:VTODO
26604 SUMMARY:%s%s%s
26605 CATEGORIES:%s
26606 SEQUENCE:1
26607 PRIORITY:%d
26608 STATUS:%s
26609 END:VTODO\n"
26611 (or summary hd)
26612 (if (and location (string-match "\\S-" location))
26613 (concat "\nLOCATION: " location) "")
26614 (if (and desc (string-match "\\S-" desc))
26615 (concat "\nDESCRIPTION: " desc) "")
26616 category pri status)))))))))
26618 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26619 "Take out stuff and quote what needs to be quoted.
26620 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26621 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26622 characters."
26623 (if (not s)
26625 (when is-body
26626 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26627 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26628 (while (string-match re s) (setq s (replace-match "" t t s)))
26629 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26630 (let ((start 0))
26631 (while (string-match "\\([,;\\]\\)" s start)
26632 (setq start (+ (match-beginning 0) 2)
26633 s (replace-match "\\\\\\1" nil nil s))))
26634 (when is-body
26635 (while (string-match "[ \t]*\n[ \t]*" s)
26636 (setq s (replace-match "\\n" t t s))))
26637 (setq s (org-trim s))
26638 (if is-body
26639 (if maxlength
26640 (if (and (numberp maxlength)
26641 (> (length s) maxlength))
26642 (setq s (substring s 0 maxlength)))))
26645 (defun org-get-entry ()
26646 "Clean-up description string."
26647 (save-excursion
26648 (org-back-to-heading t)
26649 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26651 (defun org-start-icalendar-file (name)
26652 "Start an iCalendar file by inserting the header."
26653 (let ((user user-full-name)
26654 (name (or name "unknown"))
26655 (timezone (cadr (current-time-zone))))
26656 (princ
26657 (format "BEGIN:VCALENDAR
26658 VERSION:2.0
26659 X-WR-CALNAME:%s
26660 PRODID:-//%s//Emacs with Org-mode//EN
26661 X-WR-TIMEZONE:%s
26662 CALSCALE:GREGORIAN\n" name user timezone))))
26664 (defun org-finish-icalendar-file ()
26665 "Finish an iCalendar file by inserting the END statement."
26666 (princ "END:VCALENDAR\n"))
26668 (defun org-ical-ts-to-string (s keyword &optional inc)
26669 "Take a time string S and convert it to iCalendar format.
26670 KEYWORD is added in front, to make a complete line like DTSTART....
26671 When INC is non-nil, increase the hour by two (if time string contains
26672 a time), or the day by one (if it does not contain a time)."
26673 (let ((t1 (org-parse-time-string s 'nodefault))
26674 t2 fmt have-time time)
26675 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26676 (setq t2 t1 have-time t)
26677 (setq t2 (org-parse-time-string s)))
26678 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26679 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26680 (when inc
26681 (if have-time
26682 (if org-agenda-default-appointment-duration
26683 (setq mi (+ org-agenda-default-appointment-duration mi))
26684 (setq h (+ 2 h)))
26685 (setq d (1+ d))))
26686 (setq time (encode-time s mi h d m y)))
26687 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26688 (concat keyword (format-time-string fmt time))))
26690 ;;; XOXO export
26692 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26693 (with-current-buffer buffer
26694 (apply 'insert output)))
26695 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26697 (defun org-export-as-xoxo (&optional buffer)
26698 "Export the org buffer as XOXO.
26699 The XOXO buffer is named *xoxo-<source buffer name>*"
26700 (interactive (list (current-buffer)))
26701 ;; A quickie abstraction
26703 ;; Output everything as XOXO
26704 (with-current-buffer (get-buffer buffer)
26705 (let* ((pos (point))
26706 (opt-plist (org-combine-plists (org-default-export-plist)
26707 (org-infile-export-plist)))
26708 (filename (concat (file-name-as-directory
26709 (org-export-directory :xoxo opt-plist))
26710 (file-name-sans-extension
26711 (file-name-nondirectory buffer-file-name))
26712 ".html"))
26713 (out (find-file-noselect filename))
26714 (last-level 1)
26715 (hanging-li nil))
26716 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26717 ;; Check the output buffer is empty.
26718 (with-current-buffer out (erase-buffer))
26719 ;; Kick off the output
26720 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26721 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26722 (let* ((hd (match-string-no-properties 1))
26723 (level (length hd))
26724 (text (concat
26725 (match-string-no-properties 2)
26726 (save-excursion
26727 (goto-char (match-end 0))
26728 (let ((str ""))
26729 (catch 'loop
26730 (while 't
26731 (forward-line)
26732 (if (looking-at "^[ \t]\\(.*\\)")
26733 (setq str (concat str (match-string-no-properties 1)))
26734 (throw 'loop str)))))))))
26736 ;; Handle level rendering
26737 (cond
26738 ((> level last-level)
26739 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26741 ((< level last-level)
26742 (dotimes (- (- last-level level) 1)
26743 (if hanging-li
26744 (org-export-as-xoxo-insert-into out "</li>\n"))
26745 (org-export-as-xoxo-insert-into out "</ol>\n"))
26746 (when hanging-li
26747 (org-export-as-xoxo-insert-into out "</li>\n")
26748 (setq hanging-li nil)))
26750 ((equal level last-level)
26751 (if hanging-li
26752 (org-export-as-xoxo-insert-into out "</li>\n")))
26755 (setq last-level level)
26757 ;; And output the new li
26758 (setq hanging-li 't)
26759 (if (equal ?+ (elt text 0))
26760 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26761 (org-export-as-xoxo-insert-into out "<li>" text))))
26763 ;; Finally finish off the ol
26764 (dotimes (- last-level 1)
26765 (if hanging-li
26766 (org-export-as-xoxo-insert-into out "</li>\n"))
26767 (org-export-as-xoxo-insert-into out "</ol>\n"))
26769 (goto-char pos)
26770 ;; Finish the buffer off and clean it up.
26771 (switch-to-buffer-other-window out)
26772 (indent-region (point-min) (point-max) nil)
26773 (save-buffer)
26774 (goto-char (point-min))
26778 ;;;; Key bindings
26780 ;; Make `C-c C-x' a prefix key
26781 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26783 ;; TAB key with modifiers
26784 (org-defkey org-mode-map "\C-i" 'org-cycle)
26785 (org-defkey org-mode-map [(tab)] 'org-cycle)
26786 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26787 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26788 (org-defkey org-mode-map "\M-\t" 'org-complete)
26789 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26790 ;; The following line is necessary under Suse GNU/Linux
26791 (unless (featurep 'xemacs)
26792 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26793 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26794 (define-key org-mode-map [backtab] 'org-shifttab)
26796 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26797 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26798 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26800 ;; Cursor keys with modifiers
26801 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26802 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26803 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26804 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26806 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26807 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26808 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26809 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26811 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26812 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26813 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26814 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26816 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26817 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26819 ;;; Extra keys for tty access.
26820 ;; We only set them when really needed because otherwise the
26821 ;; menus don't show the simple keys
26823 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26824 (not window-system))
26825 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26826 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26827 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26828 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26829 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26830 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26831 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26832 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26833 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26834 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26835 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26836 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26837 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26838 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26839 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26840 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26841 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26842 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26843 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26844 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26845 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26846 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26848 ;; All the other keys
26850 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26851 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26852 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26853 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26854 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26855 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26856 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26857 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26858 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26859 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26860 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26861 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26862 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26863 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26864 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26865 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26866 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26867 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26868 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26869 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26870 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26871 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26872 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26873 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26874 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26875 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26876 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26877 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26878 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26879 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26880 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26881 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26882 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26883 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26884 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26885 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26886 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26887 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26888 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26889 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
26890 (org-defkey org-mode-map "\C-c^" 'org-sort)
26891 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26892 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26893 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26894 (org-defkey org-mode-map "\C-m" 'org-return)
26895 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26896 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26897 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26898 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26899 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26900 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26901 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26902 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26903 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26904 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26905 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26906 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26907 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26908 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26909 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26910 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26912 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26913 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26914 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26915 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26917 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26918 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26919 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26920 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26921 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26922 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26923 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26924 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26925 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26926 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26927 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26928 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26930 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26932 (when (featurep 'xemacs)
26933 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26935 (defsubst org-table-p () (org-at-table-p))
26937 (defun org-self-insert-command (N)
26938 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26939 If the cursor is in a table looking at whitespace, the whitespace is
26940 overwritten, and the table is not marked as requiring realignment."
26941 (interactive "p")
26942 (if (and (org-table-p)
26943 (progn
26944 ;; check if we blank the field, and if that triggers align
26945 (and org-table-auto-blank-field
26946 (member last-command
26947 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26948 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26949 ;; got extra space, this field does not determine column width
26950 (let (org-table-may-need-update) (org-table-blank-field))
26951 ;; no extra space, this field may determine column width
26952 (org-table-blank-field)))
26954 (eq N 1)
26955 (looking-at "[^|\n]* |"))
26956 (let (org-table-may-need-update)
26957 (goto-char (1- (match-end 0)))
26958 (delete-backward-char 1)
26959 (goto-char (match-beginning 0))
26960 (self-insert-command N))
26961 (setq org-table-may-need-update t)
26962 (self-insert-command N)
26963 (org-fix-tags-on-the-fly)))
26965 (defun org-fix-tags-on-the-fly ()
26966 (when (and (equal (char-after (point-at-bol)) ?*)
26967 (org-on-heading-p))
26968 (org-align-tags-here org-tags-column)))
26970 (defun org-delete-backward-char (N)
26971 "Like `delete-backward-char', insert whitespace at field end in tables.
26972 When deleting backwards, in tables this function will insert whitespace in
26973 front of the next \"|\" separator, to keep the table aligned. The table will
26974 still be marked for re-alignment if the field did fill the entire column,
26975 because, in this case the deletion might narrow the column."
26976 (interactive "p")
26977 (if (and (org-table-p)
26978 (eq N 1)
26979 (string-match "|" (buffer-substring (point-at-bol) (point)))
26980 (looking-at ".*?|"))
26981 (let ((pos (point))
26982 (noalign (looking-at "[^|\n\r]* |"))
26983 (c org-table-may-need-update))
26984 (backward-delete-char N)
26985 (skip-chars-forward "^|")
26986 (insert " ")
26987 (goto-char (1- pos))
26988 ;; noalign: if there were two spaces at the end, this field
26989 ;; does not determine the width of the column.
26990 (if noalign (setq org-table-may-need-update c)))
26991 (backward-delete-char N)
26992 (org-fix-tags-on-the-fly)))
26994 (defun org-delete-char (N)
26995 "Like `delete-char', but insert whitespace at field end in tables.
26996 When deleting characters, in tables this function will insert whitespace in
26997 front of the next \"|\" separator, to keep the table aligned. The table will
26998 still be marked for re-alignment if the field did fill the entire column,
26999 because, in this case the deletion might narrow the column."
27000 (interactive "p")
27001 (if (and (org-table-p)
27002 (not (bolp))
27003 (not (= (char-after) ?|))
27004 (eq N 1))
27005 (if (looking-at ".*?|")
27006 (let ((pos (point))
27007 (noalign (looking-at "[^|\n\r]* |"))
27008 (c org-table-may-need-update))
27009 (replace-match (concat
27010 (substring (match-string 0) 1 -1)
27011 " |"))
27012 (goto-char pos)
27013 ;; noalign: if there were two spaces at the end, this field
27014 ;; does not determine the width of the column.
27015 (if noalign (setq org-table-may-need-update c)))
27016 (delete-char N))
27017 (delete-char N)
27018 (org-fix-tags-on-the-fly)))
27020 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27021 (put 'org-self-insert-command 'delete-selection t)
27022 (put 'orgtbl-self-insert-command 'delete-selection t)
27023 (put 'org-delete-char 'delete-selection 'supersede)
27024 (put 'org-delete-backward-char 'delete-selection 'supersede)
27026 ;; Make `flyspell-mode' delay after some commands
27027 (put 'org-self-insert-command 'flyspell-delayed t)
27028 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27029 (put 'org-delete-char 'flyspell-delayed t)
27030 (put 'org-delete-backward-char 'flyspell-delayed t)
27032 ;; Make pabbrev-mode expand after org-mode commands
27033 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27034 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27036 ;; How to do this: Measure non-white length of current string
27037 ;; If equal to column width, we should realign.
27039 (defun org-remap (map &rest commands)
27040 "In MAP, remap the functions given in COMMANDS.
27041 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27042 (let (new old)
27043 (while commands
27044 (setq old (pop commands) new (pop commands))
27045 (if (fboundp 'command-remapping)
27046 (org-defkey map (vector 'remap old) new)
27047 (substitute-key-definition old new map global-map)))))
27049 (when (eq org-enable-table-editor 'optimized)
27050 ;; If the user wants maximum table support, we need to hijack
27051 ;; some standard editing functions
27052 (org-remap org-mode-map
27053 'self-insert-command 'org-self-insert-command
27054 'delete-char 'org-delete-char
27055 'delete-backward-char 'org-delete-backward-char)
27056 (org-defkey org-mode-map "|" 'org-force-self-insert))
27058 (defun org-shiftcursor-error ()
27059 "Throw an error because Shift-Cursor command was applied in wrong context."
27060 (error "This command is active in special context like tables, headlines or timestamps"))
27062 (defun org-shifttab (&optional arg)
27063 "Global visibility cycling or move to previous table field.
27064 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27065 on context.
27066 See the individual commands for more information."
27067 (interactive "P")
27068 (cond
27069 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27070 (arg (message "Content view to level: ")
27071 (org-content (prefix-numeric-value arg))
27072 (setq org-cycle-global-status 'overview))
27073 (t (call-interactively 'org-global-cycle))))
27075 (defun org-shiftmetaleft ()
27076 "Promote subtree or delete table column.
27077 Calls `org-promote-subtree', `org-outdent-item',
27078 or `org-table-delete-column', depending on context.
27079 See the individual commands for more information."
27080 (interactive)
27081 (cond
27082 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27083 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27084 ((org-at-item-p) (call-interactively 'org-outdent-item))
27085 (t (org-shiftcursor-error))))
27087 (defun org-shiftmetaright ()
27088 "Demote subtree or insert table column.
27089 Calls `org-demote-subtree', `org-indent-item',
27090 or `org-table-insert-column', depending on context.
27091 See the individual commands for more information."
27092 (interactive)
27093 (cond
27094 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27095 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27096 ((org-at-item-p) (call-interactively 'org-indent-item))
27097 (t (org-shiftcursor-error))))
27099 (defun org-shiftmetaup (&optional arg)
27100 "Move subtree up or kill table row.
27101 Calls `org-move-subtree-up' or `org-table-kill-row' or
27102 `org-move-item-up' depending on context. See the individual commands
27103 for more information."
27104 (interactive "P")
27105 (cond
27106 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27107 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27108 ((org-at-item-p) (call-interactively 'org-move-item-up))
27109 (t (org-shiftcursor-error))))
27110 (defun org-shiftmetadown (&optional arg)
27111 "Move subtree down or insert table row.
27112 Calls `org-move-subtree-down' or `org-table-insert-row' or
27113 `org-move-item-down', depending on context. See the individual
27114 commands for more information."
27115 (interactive "P")
27116 (cond
27117 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27118 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27119 ((org-at-item-p) (call-interactively 'org-move-item-down))
27120 (t (org-shiftcursor-error))))
27122 (defun org-metaleft (&optional arg)
27123 "Promote heading or move table column to left.
27124 Calls `org-do-promote' or `org-table-move-column', depending on context.
27125 With no specific context, calls the Emacs default `backward-word'.
27126 See the individual commands for more information."
27127 (interactive "P")
27128 (cond
27129 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27130 ((or (org-on-heading-p) (org-region-active-p))
27131 (call-interactively 'org-do-promote))
27132 ((org-at-item-p) (call-interactively 'org-outdent-item))
27133 (t (call-interactively 'backward-word))))
27135 (defun org-metaright (&optional arg)
27136 "Demote subtree or move table column to right.
27137 Calls `org-do-demote' or `org-table-move-column', depending on context.
27138 With no specific context, calls the Emacs default `forward-word'.
27139 See the individual commands for more information."
27140 (interactive "P")
27141 (cond
27142 ((org-at-table-p) (call-interactively 'org-table-move-column))
27143 ((or (org-on-heading-p) (org-region-active-p))
27144 (call-interactively 'org-do-demote))
27145 ((org-at-item-p) (call-interactively 'org-indent-item))
27146 (t (call-interactively 'forward-word))))
27148 (defun org-metaup (&optional arg)
27149 "Move subtree up or move table row up.
27150 Calls `org-move-subtree-up' or `org-table-move-row' or
27151 `org-move-item-up', depending on context. See the individual commands
27152 for more information."
27153 (interactive "P")
27154 (cond
27155 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27156 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27157 ((org-at-item-p) (call-interactively 'org-move-item-up))
27158 (t (transpose-lines 1) (beginning-of-line -1))))
27160 (defun org-metadown (&optional arg)
27161 "Move subtree down or move table row down.
27162 Calls `org-move-subtree-down' or `org-table-move-row' or
27163 `org-move-item-down', depending on context. See the individual
27164 commands for more information."
27165 (interactive "P")
27166 (cond
27167 ((org-at-table-p) (call-interactively 'org-table-move-row))
27168 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27169 ((org-at-item-p) (call-interactively 'org-move-item-down))
27170 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27172 (defun org-shiftup (&optional arg)
27173 "Increase item in timestamp or increase priority of current headline.
27174 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27175 depending on context. See the individual commands for more information."
27176 (interactive "P")
27177 (cond
27178 ((org-at-timestamp-p t)
27179 (call-interactively (if org-edit-timestamp-down-means-later
27180 'org-timestamp-down 'org-timestamp-up)))
27181 ((org-on-heading-p) (call-interactively 'org-priority-up))
27182 ((org-at-item-p) (call-interactively 'org-previous-item))
27183 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27185 (defun org-shiftdown (&optional arg)
27186 "Decrease item in timestamp or decrease priority of current headline.
27187 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27188 depending on context. See the individual commands for more information."
27189 (interactive "P")
27190 (cond
27191 ((org-at-timestamp-p t)
27192 (call-interactively (if org-edit-timestamp-down-means-later
27193 'org-timestamp-up 'org-timestamp-down)))
27194 ((org-on-heading-p) (call-interactively 'org-priority-down))
27195 (t (call-interactively 'org-next-item))))
27197 (defun org-shiftright ()
27198 "Next TODO keyword or timestamp one day later, depending on context."
27199 (interactive)
27200 (cond
27201 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27202 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27203 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27204 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27205 (t (org-shiftcursor-error))))
27207 (defun org-shiftleft ()
27208 "Previous TODO keyword or timestamp one day earlier, depending on context."
27209 (interactive)
27210 (cond
27211 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27212 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27213 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27214 ((org-at-property-p)
27215 (call-interactively 'org-property-previous-allowed-value))
27216 (t (org-shiftcursor-error))))
27218 (defun org-shiftcontrolright ()
27219 "Switch to next TODO set."
27220 (interactive)
27221 (cond
27222 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27223 (t (org-shiftcursor-error))))
27225 (defun org-shiftcontrolleft ()
27226 "Switch to previous TODO set."
27227 (interactive)
27228 (cond
27229 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27230 (t (org-shiftcursor-error))))
27232 (defun org-ctrl-c-ret ()
27233 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27234 (interactive)
27235 (cond
27236 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27237 (t (call-interactively 'org-insert-heading))))
27239 (defun org-copy-special ()
27240 "Copy region in table or copy current subtree.
27241 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27242 See the individual commands for more information."
27243 (interactive)
27244 (call-interactively
27245 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27247 (defun org-cut-special ()
27248 "Cut region in table or cut current subtree.
27249 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27250 See the individual commands for more information."
27251 (interactive)
27252 (call-interactively
27253 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27255 (defun org-paste-special (arg)
27256 "Paste rectangular region into table, or past subtree relative to level.
27257 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27258 See the individual commands for more information."
27259 (interactive "P")
27260 (if (org-at-table-p)
27261 (org-table-paste-rectangle)
27262 (org-paste-subtree arg)))
27264 (defun org-ctrl-c-ctrl-c (&optional arg)
27265 "Set tags in headline, or update according to changed information at point.
27267 This command does many different things, depending on context:
27269 - If the cursor is in a headline, prompt for tags and insert them
27270 into the current line, aligned to `org-tags-column'. When called
27271 with prefix arg, realign all tags in the current buffer.
27273 - If the cursor is in one of the special #+KEYWORD lines, this
27274 triggers scanning the buffer for these lines and updating the
27275 information.
27277 - If the cursor is inside a table, realign the table. This command
27278 works even if the automatic table editor has been turned off.
27280 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27281 the entire table.
27283 - If the cursor is a the beginning of a dynamic block, update it.
27285 - If the cursor is inside a table created by the table.el package,
27286 activate that table.
27288 - If the current buffer is a remember buffer, close note and file it.
27289 with a prefix argument, file it without further interaction to the default
27290 location.
27292 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27293 links in this buffer.
27295 - If the cursor is on a numbered item in a plain list, renumber the
27296 ordered list.
27298 - If the cursor is on a checkbox, toggle it."
27299 (interactive "P")
27300 (let ((org-enable-table-editor t))
27301 (cond
27302 ((or org-clock-overlays
27303 org-occur-highlights
27304 org-latex-fragment-image-overlays)
27305 (org-remove-clock-overlays)
27306 (org-remove-occur-highlights)
27307 (org-remove-latex-fragment-image-overlays)
27308 (message "Temporary highlights/overlays removed from current buffer"))
27309 ((and (local-variable-p 'org-finish-function (current-buffer))
27310 (fboundp org-finish-function))
27311 (funcall org-finish-function))
27312 ((org-at-property-p)
27313 (call-interactively 'org-property-action))
27314 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27315 ((org-on-heading-p) (call-interactively 'org-set-tags))
27316 ((org-at-table.el-p)
27317 (require 'table)
27318 (beginning-of-line 1)
27319 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27320 (call-interactively 'table-recognize-table))
27321 ((org-at-table-p)
27322 (org-table-maybe-eval-formula)
27323 (if arg
27324 (call-interactively 'org-table-recalculate)
27325 (org-table-maybe-recalculate-line))
27326 (call-interactively 'org-table-align))
27327 ((org-at-item-checkbox-p)
27328 (call-interactively 'org-toggle-checkbox))
27329 ((org-at-item-p)
27330 (call-interactively 'org-maybe-renumber-ordered-list))
27331 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27332 ;; Dynamic block
27333 (beginning-of-line 1)
27334 (org-update-dblock))
27335 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27336 (cond
27337 ((equal (match-string 1) "TBLFM")
27338 ;; Recalculate the table before this line
27339 (save-excursion
27340 (beginning-of-line 1)
27341 (skip-chars-backward " \r\n\t")
27342 (if (org-at-table-p)
27343 (org-call-with-arg 'org-table-recalculate t))))
27345 (call-interactively 'org-mode-restart))))
27346 (t (error "C-c C-c can do nothing useful at this location.")))))
27348 (defun org-mode-restart ()
27349 "Restart Org-mode, to scan again for special lines.
27350 Also updates the keyword regular expressions."
27351 (interactive)
27352 (let ((org-inhibit-startup t)) (org-mode))
27353 (message "Org-mode restarted to refresh keyword and special line setup"))
27355 (defun org-kill-note-or-show-branches ()
27356 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27357 (interactive)
27358 (if (not org-finish-function)
27359 (call-interactively 'show-branches)
27360 (let ((org-note-abort t))
27361 (funcall org-finish-function))))
27363 (defun org-return (&optional indent)
27364 "Goto next table row or insert a newline.
27365 Calls `org-table-next-row' or `newline', depending on context.
27366 See the individual commands for more information."
27367 (interactive)
27368 (cond
27369 ((bobp) (if indent (newline-and-indent) (newline)))
27370 ((and (org-at-heading-p)
27371 (looking-at
27372 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27373 (org-show-entry)
27374 (end-of-line 1)
27375 (newline))
27376 ((org-at-table-p)
27377 (org-table-justify-field-maybe)
27378 (call-interactively 'org-table-next-row))
27379 (t (if indent (newline-and-indent) (newline)))))
27381 (defun org-return-indent ()
27382 "Goto next table row or insert a newline and indent.
27383 Calls `org-table-next-row' or `newline-and-indent', depending on
27384 context. See the individual commands for more information."
27385 (interactive)
27386 (org-return t))
27388 (defun org-ctrl-c-star ()
27389 "Compute table, or change heading status of lines.
27390 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27391 depending on context. This will also turn a plain list item or a normal
27392 line into a subheading."
27393 (interactive)
27394 (cond
27395 ((org-at-table-p)
27396 (call-interactively 'org-table-recalculate))
27397 ((org-region-active-p)
27398 ;; Convert all lines in region to list items
27399 (call-interactively 'org-toggle-region-headings))
27400 ((org-on-heading-p)
27401 (org-toggle-region-headings (point-at-bol)
27402 (min (1+ (point-at-eol)) (point-max))))
27403 ((org-at-item-p)
27404 ;; Convert to heading
27405 (let ((level (save-match-data
27406 (save-excursion
27407 (condition-case nil
27408 (progn
27409 (org-back-to-heading t)
27410 (funcall outline-level))
27411 (error 0))))))
27412 (replace-match
27413 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27414 (t (org-toggle-region-headings (point-at-bol)
27415 (min (1+ (point-at-eol)) (point-max))))))
27417 (defun org-ctrl-c-minus ()
27418 "Insert separator line in table or modify bullet status of line.
27419 Also turns a plain line or a region of lines into list items.
27420 Calls `org-table-insert-hline', `org-toggle-region-items', or
27421 `org-cycle-list-bullet', depending on context."
27422 (interactive)
27423 (cond
27424 ((org-at-table-p)
27425 (call-interactively 'org-table-insert-hline))
27426 ((org-on-heading-p)
27427 ;; Convert to item
27428 (save-excursion
27429 (beginning-of-line 1)
27430 (if (looking-at "\\*+ ")
27431 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27432 ((org-region-active-p)
27433 ;; Convert all lines in region to list items
27434 (call-interactively 'org-toggle-region-items))
27435 ((org-in-item-p)
27436 (call-interactively 'org-cycle-list-bullet))
27437 (t (org-toggle-region-items (point-at-bol)
27438 (min (1+ (point-at-eol)) (point-max))))))
27440 (defun org-toggle-region-items (beg end)
27441 "Convert all lines in region to list items.
27442 If the first line is already an item, convert all list items in the region
27443 to normal lines."
27444 (interactive "r")
27445 (let (l2 l)
27446 (save-excursion
27447 (goto-char end)
27448 (setq l2 (org-current-line))
27449 (goto-char beg)
27450 (beginning-of-line 1)
27451 (setq l (1- (org-current-line)))
27452 (if (org-at-item-p)
27453 ;; We already have items, de-itemize
27454 (while (< (setq l (1+ l)) l2)
27455 (when (org-at-item-p)
27456 (goto-char (match-beginning 2))
27457 (delete-region (match-beginning 2) (match-end 2))
27458 (and (looking-at "[ \t]+") (replace-match "")))
27459 (beginning-of-line 2))
27460 (while (< (setq l (1+ l)) l2)
27461 (unless (org-at-item-p)
27462 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27463 (replace-match "\\1- \\2")))
27464 (beginning-of-line 2))))))
27466 (defun org-toggle-region-headings (beg end)
27467 "Convert all lines in region to list items.
27468 If the first line is already an item, convert all list items in the region
27469 to normal lines."
27470 (interactive "r")
27471 (let (l2 l)
27472 (save-excursion
27473 (goto-char end)
27474 (setq l2 (org-current-line))
27475 (goto-char beg)
27476 (beginning-of-line 1)
27477 (setq l (1- (org-current-line)))
27478 (if (org-on-heading-p)
27479 ;; We already have headlines, de-star them
27480 (while (< (setq l (1+ l)) l2)
27481 (when (org-on-heading-p t)
27482 (and (looking-at outline-regexp) (replace-match "")))
27483 (beginning-of-line 2))
27484 (let* ((stars (save-excursion
27485 (re-search-backward org-complex-heading-regexp nil t)
27486 (or (match-string 1) "*")))
27487 (add-stars (if org-odd-levels-only "**" "*"))
27488 (rpl (concat stars add-stars " \\2")))
27489 (while (< (setq l (1+ l)) l2)
27490 (unless (org-on-heading-p)
27491 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27492 (replace-match rpl)))
27493 (beginning-of-line 2)))))))
27495 (defun org-meta-return (&optional arg)
27496 "Insert a new heading or wrap a region in a table.
27497 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27498 See the individual commands for more information."
27499 (interactive "P")
27500 (cond
27501 ((org-at-table-p)
27502 (call-interactively 'org-table-wrap-region))
27503 (t (call-interactively 'org-insert-heading))))
27505 ;;; Menu entries
27507 ;; Define the Org-mode menus
27508 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27509 '("Tbl"
27510 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27511 ["Next Field" org-cycle (org-at-table-p)]
27512 ["Previous Field" org-shifttab (org-at-table-p)]
27513 ["Next Row" org-return (org-at-table-p)]
27514 "--"
27515 ["Blank Field" org-table-blank-field (org-at-table-p)]
27516 ["Edit Field" org-table-edit-field (org-at-table-p)]
27517 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27518 "--"
27519 ("Column"
27520 ["Move Column Left" org-metaleft (org-at-table-p)]
27521 ["Move Column Right" org-metaright (org-at-table-p)]
27522 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27523 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27524 ("Row"
27525 ["Move Row Up" org-metaup (org-at-table-p)]
27526 ["Move Row Down" org-metadown (org-at-table-p)]
27527 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27528 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27529 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27530 "--"
27531 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27532 ("Rectangle"
27533 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27534 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27535 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27536 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27537 "--"
27538 ("Calculate"
27539 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27540 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27541 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27542 "--"
27543 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27544 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27545 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27546 "--"
27547 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27548 "--"
27549 ["Sum Column/Rectangle" org-table-sum
27550 (or (org-at-table-p) (org-region-active-p))]
27551 ["Which Column?" org-table-current-column (org-at-table-p)])
27552 ["Debug Formulas"
27553 org-table-toggle-formula-debugger
27554 :style toggle :selected org-table-formula-debug]
27555 ["Show Col/Row Numbers"
27556 org-table-toggle-coordinate-overlays
27557 :style toggle :selected org-table-overlay-coordinates]
27558 "--"
27559 ["Create" org-table-create (and (not (org-at-table-p))
27560 org-enable-table-editor)]
27561 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27562 ["Import from File" org-table-import (not (org-at-table-p))]
27563 ["Export to File" org-table-export (org-at-table-p)]
27564 "--"
27565 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27567 (easy-menu-define org-org-menu org-mode-map "Org menu"
27568 '("Org"
27569 ("Show/Hide"
27570 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27571 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27572 ["Sparse Tree" org-occur t]
27573 ["Reveal Context" org-reveal t]
27574 ["Show All" show-all t]
27575 "--"
27576 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27577 "--"
27578 ["New Heading" org-insert-heading t]
27579 ("Navigate Headings"
27580 ["Up" outline-up-heading t]
27581 ["Next" outline-next-visible-heading t]
27582 ["Previous" outline-previous-visible-heading t]
27583 ["Next Same Level" outline-forward-same-level t]
27584 ["Previous Same Level" outline-backward-same-level t]
27585 "--"
27586 ["Jump" org-goto t])
27587 ("Edit Structure"
27588 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27589 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27590 "--"
27591 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27592 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27593 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27594 "--"
27595 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27596 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27597 ["Demote Heading" org-metaright (not (org-at-table-p))]
27598 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27599 "--"
27600 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27601 "--"
27602 ["Convert to odd levels" org-convert-to-odd-levels t]
27603 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27604 ("Editing"
27605 ["Emphasis..." org-emphasize t])
27606 ("Archive"
27607 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27608 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27609 ; :active t :keys "C-u C-c C-x C-a"]
27610 ["Sparse trees open ARCHIVE trees"
27611 (setq org-sparse-tree-open-archived-trees
27612 (not org-sparse-tree-open-archived-trees))
27613 :style toggle :selected org-sparse-tree-open-archived-trees]
27614 ["Cycling opens ARCHIVE trees"
27615 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27616 :style toggle :selected org-cycle-open-archived-trees]
27617 ["Agenda includes ARCHIVE trees"
27618 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27619 :style toggle :selected (not org-agenda-skip-archived-trees)]
27620 "--"
27621 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27622 ; ["Check and Move Children" (org-archive-subtree '(4))
27623 ; :active t :keys "C-u C-c C-x C-s"]
27625 "--"
27626 ("TODO Lists"
27627 ["TODO/DONE/-" org-todo t]
27628 ("Select keyword"
27629 ["Next keyword" org-shiftright (org-on-heading-p)]
27630 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27631 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27632 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27633 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27634 ["Show TODO Tree" org-show-todo-tree t]
27635 ["Global TODO list" org-todo-list t]
27636 "--"
27637 ["Set Priority" org-priority t]
27638 ["Priority Up" org-shiftup t]
27639 ["Priority Down" org-shiftdown t])
27640 ("TAGS and Properties"
27641 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27642 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27643 "--"
27644 ["Set property" 'org-set-property t]
27645 ["Column view of properties" org-columns t]
27646 ["Insert Column View DBlock" org-insert-columns-dblock t])
27647 ("Dates and Scheduling"
27648 ["Timestamp" org-time-stamp t]
27649 ["Timestamp (inactive)" org-time-stamp-inactive t]
27650 ("Change Date"
27651 ["1 Day Later" org-shiftright t]
27652 ["1 Day Earlier" org-shiftleft t]
27653 ["1 ... Later" org-shiftup t]
27654 ["1 ... Earlier" org-shiftdown t])
27655 ["Compute Time Range" org-evaluate-time-range t]
27656 ["Schedule Item" org-schedule t]
27657 ["Deadline" org-deadline t]
27658 "--"
27659 ["Custom time format" org-toggle-time-stamp-overlays
27660 :style radio :selected org-display-custom-times]
27661 "--"
27662 ["Goto Calendar" org-goto-calendar t]
27663 ["Date from Calendar" org-date-from-calendar t])
27664 ("Logging work"
27665 ["Clock in" org-clock-in t]
27666 ["Clock out" org-clock-out t]
27667 ["Clock cancel" org-clock-cancel t]
27668 ["Goto running clock" org-clock-goto t]
27669 ["Display times" org-clock-display t]
27670 ["Create clock table" org-clock-report t]
27671 "--"
27672 ["Record DONE time"
27673 (progn (setq org-log-done (not org-log-done))
27674 (message "Switching to %s will %s record a timestamp"
27675 (car org-done-keywords)
27676 (if org-log-done "automatically" "not")))
27677 :style toggle :selected org-log-done])
27678 "--"
27679 ["Agenda Command..." org-agenda t]
27680 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27681 ("File List for Agenda")
27682 ("Special views current file"
27683 ["TODO Tree" org-show-todo-tree t]
27684 ["Check Deadlines" org-check-deadlines t]
27685 ["Timeline" org-timeline t]
27686 ["Tags Tree" org-tags-sparse-tree t])
27687 "--"
27688 ("Hyperlinks"
27689 ["Store Link (Global)" org-store-link t]
27690 ["Insert Link" org-insert-link t]
27691 ["Follow Link" org-open-at-point t]
27692 "--"
27693 ["Next link" org-next-link t]
27694 ["Previous link" org-previous-link t]
27695 "--"
27696 ["Descriptive Links"
27697 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27698 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27699 ["Literal Links"
27700 (progn
27701 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27702 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27703 "--"
27704 ["Export/Publish..." org-export t]
27705 ("LaTeX"
27706 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27707 :selected org-cdlatex-mode]
27708 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27709 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27710 ["Modify math symbol" org-cdlatex-math-modify
27711 (org-inside-LaTeX-fragment-p)]
27712 ["Export LaTeX fragments as images"
27713 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27714 :style toggle :selected org-export-with-LaTeX-fragments])
27715 "--"
27716 ("Documentation"
27717 ["Show Version" org-version t]
27718 ["Info Documentation" org-info t])
27719 ("Customize"
27720 ["Browse Org Group" org-customize t]
27721 "--"
27722 ["Expand This Menu" org-create-customize-menu
27723 (fboundp 'customize-menu-create)])
27724 "--"
27725 ["Refresh setup" org-mode-restart t]
27728 (defun org-info (&optional node)
27729 "Read documentation for Org-mode in the info system.
27730 With optional NODE, go directly to that node."
27731 (interactive)
27732 (info (format "(org)%s" (or node ""))))
27734 (defun org-install-agenda-files-menu ()
27735 (let ((bl (buffer-list)))
27736 (save-excursion
27737 (while bl
27738 (set-buffer (pop bl))
27739 (if (org-mode-p) (setq bl nil)))
27740 (when (org-mode-p)
27741 (easy-menu-change
27742 '("Org") "File List for Agenda"
27743 (append
27744 (list
27745 ["Edit File List" (org-edit-agenda-file-list) t]
27746 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27747 ["Remove Current File from List" org-remove-file t]
27748 ["Cycle through agenda files" org-cycle-agenda-files t]
27749 ["Occur in all agenda files" org-occur-in-agenda-files t]
27750 "--")
27751 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27753 ;;;; Documentation
27755 (defun org-customize ()
27756 "Call the customize function with org as argument."
27757 (interactive)
27758 (customize-browse 'org))
27760 (defun org-create-customize-menu ()
27761 "Create a full customization menu for Org-mode, insert it into the menu."
27762 (interactive)
27763 (if (fboundp 'customize-menu-create)
27764 (progn
27765 (easy-menu-change
27766 '("Org") "Customize"
27767 `(["Browse Org group" org-customize t]
27768 "--"
27769 ,(customize-menu-create 'org)
27770 ["Set" Custom-set t]
27771 ["Save" Custom-save t]
27772 ["Reset to Current" Custom-reset-current t]
27773 ["Reset to Saved" Custom-reset-saved t]
27774 ["Reset to Standard Settings" Custom-reset-standard t]))
27775 (message "\"Org\"-menu now contains full customization menu"))
27776 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27778 ;;;; Miscellaneous stuff
27781 ;;; Generally useful functions
27783 (defun org-context ()
27784 "Return a list of contexts of the current cursor position.
27785 If several contexts apply, all are returned.
27786 Each context entry is a list with a symbol naming the context, and
27787 two positions indicating start and end of the context. Possible
27788 contexts are:
27790 :headline anywhere in a headline
27791 :headline-stars on the leading stars in a headline
27792 :todo-keyword on a TODO keyword (including DONE) in a headline
27793 :tags on the TAGS in a headline
27794 :priority on the priority cookie in a headline
27795 :item on the first line of a plain list item
27796 :item-bullet on the bullet/number of a plain list item
27797 :checkbox on the checkbox in a plain list item
27798 :table in an org-mode table
27799 :table-special on a special filed in a table
27800 :table-table in a table.el table
27801 :link on a hyperlink
27802 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27803 :target on a <<target>>
27804 :radio-target on a <<<radio-target>>>
27805 :latex-fragment on a LaTeX fragment
27806 :latex-preview on a LaTeX fragment with overlayed preview image
27808 This function expects the position to be visible because it uses font-lock
27809 faces as a help to recognize the following contexts: :table-special, :link,
27810 and :keyword."
27811 (let* ((f (get-text-property (point) 'face))
27812 (faces (if (listp f) f (list f)))
27813 (p (point)) clist o)
27814 ;; First the large context
27815 (cond
27816 ((org-on-heading-p t)
27817 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27818 (when (progn
27819 (beginning-of-line 1)
27820 (looking-at org-todo-line-tags-regexp))
27821 (push (org-point-in-group p 1 :headline-stars) clist)
27822 (push (org-point-in-group p 2 :todo-keyword) clist)
27823 (push (org-point-in-group p 4 :tags) clist))
27824 (goto-char p)
27825 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27826 (if (looking-at "\\[#[A-Z0-9]\\]")
27827 (push (org-point-in-group p 0 :priority) clist)))
27829 ((org-at-item-p)
27830 (push (org-point-in-group p 2 :item-bullet) clist)
27831 (push (list :item (point-at-bol)
27832 (save-excursion (org-end-of-item) (point)))
27833 clist)
27834 (and (org-at-item-checkbox-p)
27835 (push (org-point-in-group p 0 :checkbox) clist)))
27837 ((org-at-table-p)
27838 (push (list :table (org-table-begin) (org-table-end)) clist)
27839 (if (memq 'org-formula faces)
27840 (push (list :table-special
27841 (previous-single-property-change p 'face)
27842 (next-single-property-change p 'face)) clist)))
27843 ((org-at-table-p 'any)
27844 (push (list :table-table) clist)))
27845 (goto-char p)
27847 ;; Now the small context
27848 (cond
27849 ((org-at-timestamp-p)
27850 (push (org-point-in-group p 0 :timestamp) clist))
27851 ((memq 'org-link faces)
27852 (push (list :link
27853 (previous-single-property-change p 'face)
27854 (next-single-property-change p 'face)) clist))
27855 ((memq 'org-special-keyword faces)
27856 (push (list :keyword
27857 (previous-single-property-change p 'face)
27858 (next-single-property-change p 'face)) clist))
27859 ((org-on-target-p)
27860 (push (org-point-in-group p 0 :target) clist)
27861 (goto-char (1- (match-beginning 0)))
27862 (if (looking-at org-radio-target-regexp)
27863 (push (org-point-in-group p 0 :radio-target) clist))
27864 (goto-char p))
27865 ((setq o (car (delq nil
27866 (mapcar
27867 (lambda (x)
27868 (if (memq x org-latex-fragment-image-overlays) x))
27869 (org-overlays-at (point))))))
27870 (push (list :latex-fragment
27871 (org-overlay-start o) (org-overlay-end o)) clist)
27872 (push (list :latex-preview
27873 (org-overlay-start o) (org-overlay-end o)) clist))
27874 ((org-inside-LaTeX-fragment-p)
27875 ;; FIXME: positions wrong.
27876 (push (list :latex-fragment (point) (point)) clist)))
27878 (setq clist (nreverse (delq nil clist)))
27879 clist))
27881 ;; FIXME: Compare with at-regexp-p Do we need both?
27882 (defun org-in-regexp (re &optional nlines visually)
27883 "Check if point is inside a match of regexp.
27884 Normally only the current line is checked, but you can include NLINES extra
27885 lines both before and after point into the search.
27886 If VISUALLY is set, require that the cursor is not after the match but
27887 really on, so that the block visually is on the match."
27888 (catch 'exit
27889 (let ((pos (point))
27890 (eol (point-at-eol (+ 1 (or nlines 0))))
27891 (inc (if visually 1 0)))
27892 (save-excursion
27893 (beginning-of-line (- 1 (or nlines 0)))
27894 (while (re-search-forward re eol t)
27895 (if (and (<= (match-beginning 0) pos)
27896 (>= (+ inc (match-end 0)) pos))
27897 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27899 (defun org-at-regexp-p (regexp)
27900 "Is point inside a match of REGEXP in the current line?"
27901 (catch 'exit
27902 (save-excursion
27903 (let ((pos (point)) (end (point-at-eol)))
27904 (beginning-of-line 1)
27905 (while (re-search-forward regexp end t)
27906 (if (and (<= (match-beginning 0) pos)
27907 (>= (match-end 0) pos))
27908 (throw 'exit t)))
27909 nil))))
27911 (defun org-occur-in-agenda-files (regexp &optional nlines)
27912 "Call `multi-occur' with buffers for all agenda files."
27913 (interactive "sOrg-files matching: \np")
27914 (let* ((files (org-agenda-files))
27915 (tnames (mapcar 'file-truename files))
27916 (extra org-agenda-text-search-extra-files)
27918 (while (setq f (pop extra))
27919 (unless (member (file-truename f) tnames)
27920 (add-to-list 'files f 'append)
27921 (add-to-list 'tnames (file-truename f) 'append)))
27922 (multi-occur
27923 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27924 regexp)))
27926 (if (boundp 'occur-mode-find-occurrence-hook)
27927 ;; Emacs 23
27928 (add-hook 'occur-mode-find-occurrence-hook
27929 (lambda ()
27930 (when (org-mode-p)
27931 (org-reveal))))
27932 ;; Emacs 22
27933 (defadvice occur-mode-goto-occurrence
27934 (after org-occur-reveal activate)
27935 (and (org-mode-p) (org-reveal)))
27936 (defadvice occur-mode-goto-occurrence-other-window
27937 (after org-occur-reveal activate)
27938 (and (org-mode-p) (org-reveal)))
27939 (defadvice occur-mode-display-occurrence
27940 (after org-occur-reveal activate)
27941 (when (org-mode-p)
27942 (let ((pos (occur-mode-find-occurrence)))
27943 (with-current-buffer (marker-buffer pos)
27944 (save-excursion
27945 (goto-char pos)
27946 (org-reveal)))))))
27948 (defun org-uniquify (list)
27949 "Remove duplicate elements from LIST."
27950 (let (res)
27951 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27952 res))
27954 (defun org-delete-all (elts list)
27955 "Remove all elements in ELTS from LIST."
27956 (while elts
27957 (setq list (delete (pop elts) list)))
27958 list)
27960 (defun org-back-over-empty-lines ()
27961 "Move backwards over witespace, to the beginning of the first empty line.
27962 Returns the number o empty lines passed."
27963 (let ((pos (point)))
27964 (skip-chars-backward " \t\n\r")
27965 (beginning-of-line 2)
27966 (goto-char (min (point) pos))
27967 (count-lines (point) pos)))
27969 (defun org-skip-whitespace ()
27970 (skip-chars-forward " \t\n\r"))
27972 (defun org-point-in-group (point group &optional context)
27973 "Check if POINT is in match-group GROUP.
27974 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27975 match. If the match group does ot exist or point is not inside it,
27976 return nil."
27977 (and (match-beginning group)
27978 (>= point (match-beginning group))
27979 (<= point (match-end group))
27980 (if context
27981 (list context (match-beginning group) (match-end group))
27982 t)))
27984 (defun org-switch-to-buffer-other-window (&rest args)
27985 "Switch to buffer in a second window on the current frame.
27986 In particular, do not allow pop-up frames."
27987 (let (pop-up-frames special-display-buffer-names special-display-regexps
27988 special-display-function)
27989 (apply 'switch-to-buffer-other-window args)))
27991 (defun org-combine-plists (&rest plists)
27992 "Create a single property list from all plists in PLISTS.
27993 The process starts by copying the first list, and then setting properties
27994 from the other lists. Settings in the last list are the most significant
27995 ones and overrule settings in the other lists."
27996 (let ((rtn (copy-sequence (pop plists)))
27997 p v ls)
27998 (while plists
27999 (setq ls (pop plists))
28000 (while ls
28001 (setq p (pop ls) v (pop ls))
28002 (setq rtn (plist-put rtn p v))))
28003 rtn))
28005 (defun org-move-line-down (arg)
28006 "Move the current line down. With prefix argument, move it past ARG lines."
28007 (interactive "p")
28008 (let ((col (current-column))
28009 beg end pos)
28010 (beginning-of-line 1) (setq beg (point))
28011 (beginning-of-line 2) (setq end (point))
28012 (beginning-of-line (+ 1 arg))
28013 (setq pos (move-marker (make-marker) (point)))
28014 (insert (delete-and-extract-region beg end))
28015 (goto-char pos)
28016 (move-to-column col)))
28018 (defun org-move-line-up (arg)
28019 "Move the current line up. With prefix argument, move it past ARG lines."
28020 (interactive "p")
28021 (let ((col (current-column))
28022 beg end pos)
28023 (beginning-of-line 1) (setq beg (point))
28024 (beginning-of-line 2) (setq end (point))
28025 (beginning-of-line (- arg))
28026 (setq pos (move-marker (make-marker) (point)))
28027 (insert (delete-and-extract-region beg end))
28028 (goto-char pos)
28029 (move-to-column col)))
28031 (defun org-replace-escapes (string table)
28032 "Replace %-escapes in STRING with values in TABLE.
28033 TABLE is an association list with keys like \"%a\" and string values.
28034 The sequences in STRING may contain normal field width and padding information,
28035 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28036 so values can contain further %-escapes if they are define later in TABLE."
28037 (let ((case-fold-search nil)
28038 e re rpl)
28039 (while (setq e (pop table))
28040 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28041 (while (string-match re string)
28042 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28043 (cdr e)))
28044 (setq string (replace-match rpl t t string))))
28045 string))
28048 (defun org-sublist (list start end)
28049 "Return a section of LIST, from START to END.
28050 Counting starts at 1."
28051 (let (rtn (c start))
28052 (setq list (nthcdr (1- start) list))
28053 (while (and list (<= c end))
28054 (push (pop list) rtn)
28055 (setq c (1+ c)))
28056 (nreverse rtn)))
28058 (defun org-find-base-buffer-visiting (file)
28059 "Like `find-buffer-visiting' but alway return the base buffer and
28060 not an indirect buffer"
28061 (let ((buf (find-buffer-visiting file)))
28062 (if buf
28063 (or (buffer-base-buffer buf) buf)
28064 nil)))
28066 (defun org-image-file-name-regexp ()
28067 "Return regexp matching the file names of images."
28068 (if (fboundp 'image-file-name-regexp)
28069 (image-file-name-regexp)
28070 (let ((image-file-name-extensions
28071 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28072 "xbm" "xpm" "pbm" "pgm" "ppm")))
28073 (concat "\\."
28074 (regexp-opt (nconc (mapcar 'upcase
28075 image-file-name-extensions)
28076 image-file-name-extensions)
28078 "\\'"))))
28080 (defun org-file-image-p (file)
28081 "Return non-nil if FILE is an image."
28082 (save-match-data
28083 (string-match (org-image-file-name-regexp) file)))
28085 ;;; Paragraph filling stuff.
28086 ;; We want this to be just right, so use the full arsenal.
28088 (defun org-indent-line-function ()
28089 "Indent line like previous, but further if previous was headline or item."
28090 (interactive)
28091 (let* ((pos (point))
28092 (itemp (org-at-item-p))
28093 column bpos bcol tpos tcol bullet btype bullet-type)
28094 ;; Find the previous relevant line
28095 (beginning-of-line 1)
28096 (cond
28097 ((looking-at "#") (setq column 0))
28098 ((looking-at "\\*+ ") (setq column 0))
28100 (beginning-of-line 0)
28101 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28102 (beginning-of-line 0))
28103 (cond
28104 ((looking-at "\\*+[ \t]+")
28105 (goto-char (match-end 0))
28106 (setq column (current-column)))
28107 ((org-in-item-p)
28108 (org-beginning-of-item)
28109 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28110 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28111 (setq bpos (match-beginning 1) tpos (match-end 0)
28112 bcol (progn (goto-char bpos) (current-column))
28113 tcol (progn (goto-char tpos) (current-column))
28114 bullet (match-string 1)
28115 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28116 (if (not itemp)
28117 (setq column tcol)
28118 (goto-char pos)
28119 (beginning-of-line 1)
28120 (if (looking-at "\\S-")
28121 (progn
28122 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28123 (setq bullet (match-string 1)
28124 btype (if (string-match "[0-9]" bullet) "n" bullet))
28125 (setq column (if (equal btype bullet-type) bcol tcol)))
28126 (setq column (org-get-indentation)))))
28127 (t (setq column (org-get-indentation))))))
28128 (goto-char pos)
28129 (if (<= (current-column) (current-indentation))
28130 (indent-line-to column)
28131 (save-excursion (indent-line-to column)))
28132 (setq column (current-column))
28133 (beginning-of-line 1)
28134 (if (looking-at
28135 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28136 (replace-match (concat "\\1" (format org-property-format
28137 (match-string 2) (match-string 3)))
28138 t nil))
28139 (move-to-column column)))
28141 (defun org-set-autofill-regexps ()
28142 (interactive)
28143 ;; In the paragraph separator we include headlines, because filling
28144 ;; text in a line directly attached to a headline would otherwise
28145 ;; fill the headline as well.
28146 (org-set-local 'comment-start-skip "^#+[ \t]*")
28147 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28148 ;; The paragraph starter includes hand-formatted lists.
28149 (org-set-local 'paragraph-start
28150 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28151 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28152 ;; But only if the user has not turned off tables or fixed-width regions
28153 (org-set-local
28154 'auto-fill-inhibit-regexp
28155 (concat "\\*+ \\|#\\+"
28156 "\\|[ \t]*" org-keyword-time-regexp
28157 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28158 (concat
28159 "\\|[ \t]*["
28160 (if org-enable-table-editor "|" "")
28161 (if org-enable-fixed-width-editor ":" "")
28162 "]"))))
28163 ;; We use our own fill-paragraph function, to make sure that tables
28164 ;; and fixed-width regions are not wrapped. That function will pass
28165 ;; through to `fill-paragraph' when appropriate.
28166 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28167 ; Adaptive filling: To get full control, first make sure that
28168 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28169 (org-set-local 'adaptive-fill-regexp "\000")
28170 (org-set-local 'adaptive-fill-function
28171 'org-adaptive-fill-function)
28172 (org-set-local
28173 'align-mode-rules-list
28174 '((org-in-buffer-settings
28175 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28176 (modes . '(org-mode))))))
28178 (defun org-fill-paragraph (&optional justify)
28179 "Re-align a table, pass through to fill-paragraph if no table."
28180 (let ((table-p (org-at-table-p))
28181 (table.el-p (org-at-table.el-p)))
28182 (cond ((and (equal (char-after (point-at-bol)) ?*)
28183 (save-excursion (goto-char (point-at-bol))
28184 (looking-at outline-regexp)))
28185 t) ; skip headlines
28186 (table.el-p t) ; skip table.el tables
28187 (table-p (org-table-align) t) ; align org-mode tables
28188 (t nil)))) ; call paragraph-fill
28190 ;; For reference, this is the default value of adaptive-fill-regexp
28191 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28193 (defun org-adaptive-fill-function ()
28194 "Return a fill prefix for org-mode files.
28195 In particular, this makes sure hanging paragraphs for hand-formatted lists
28196 work correctly."
28197 (cond ((looking-at "#[ \t]+")
28198 (match-string 0))
28199 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28200 (save-excursion
28201 (goto-char (match-end 0))
28202 (make-string (current-column) ?\ )))
28203 (t nil)))
28205 ;;;; Functions extending outline functionality
28208 (defun org-beginning-of-line (&optional arg)
28209 "Go to the beginning of the current line. If that is invisible, continue
28210 to a visible line beginning. This makes the function of C-a more intuitive.
28211 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28212 first attempt, and only move to after the tags when the cursor is already
28213 beyond the end of the headline."
28214 (interactive "P")
28215 (let ((pos (point)))
28216 (beginning-of-line 1)
28217 (if (bobp)
28219 (backward-char 1)
28220 (if (org-invisible-p)
28221 (while (and (not (bobp)) (org-invisible-p))
28222 (backward-char 1)
28223 (beginning-of-line 1))
28224 (forward-char 1)))
28225 (when org-special-ctrl-a/e
28226 (cond
28227 ((and (looking-at org-todo-line-regexp)
28228 (= (char-after (match-end 1)) ?\ ))
28229 (goto-char
28230 (if (eq org-special-ctrl-a/e t)
28231 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28232 ((= pos (point)) (match-beginning 3))
28233 (t (point)))
28234 (cond ((> pos (point)) (point))
28235 ((not (eq last-command this-command)) (point))
28236 (t (match-beginning 3))))))
28237 ((org-at-item-p)
28238 (goto-char
28239 (if (eq org-special-ctrl-a/e t)
28240 (cond ((> pos (match-end 4)) (match-end 4))
28241 ((= pos (point)) (match-end 4))
28242 (t (point)))
28243 (cond ((> pos (point)) (point))
28244 ((not (eq last-command this-command)) (point))
28245 (t (match-end 4))))))))))
28247 (defun org-end-of-line (&optional arg)
28248 "Go to the end of the line.
28249 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28250 first attempt, and only move to after the tags when the cursor is already
28251 beyond the end of the headline."
28252 (interactive "P")
28253 (if (or (not org-special-ctrl-a/e)
28254 (not (org-on-heading-p)))
28255 (end-of-line arg)
28256 (let ((pos (point)))
28257 (beginning-of-line 1)
28258 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28259 (if (eq org-special-ctrl-a/e t)
28260 (if (or (< pos (match-beginning 1))
28261 (= pos (match-end 0)))
28262 (goto-char (match-beginning 1))
28263 (goto-char (match-end 0)))
28264 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28265 (goto-char (match-end 0))
28266 (goto-char (match-beginning 1))))
28267 (end-of-line arg)))))
28269 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28270 (define-key org-mode-map "\C-e" 'org-end-of-line)
28272 (defun org-kill-line (&optional arg)
28273 "Kill line, to tags or end of line."
28274 (interactive "P")
28275 (cond
28276 ((or (not org-special-ctrl-k)
28277 (bolp)
28278 (not (org-on-heading-p)))
28279 (call-interactively 'kill-line))
28280 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28281 (kill-region (point) (match-beginning 1))
28282 (org-set-tags nil t))
28283 (t (kill-region (point) (point-at-eol)))))
28285 (define-key org-mode-map "\C-k" 'org-kill-line)
28287 (defun org-invisible-p ()
28288 "Check if point is at a character currently not visible."
28289 ;; Early versions of noutline don't have `outline-invisible-p'.
28290 (if (fboundp 'outline-invisible-p)
28291 (outline-invisible-p)
28292 (get-char-property (point) 'invisible)))
28294 (defun org-invisible-p2 ()
28295 "Check if point is at a character currently not visible."
28296 (save-excursion
28297 (if (and (eolp) (not (bobp))) (backward-char 1))
28298 ;; Early versions of noutline don't have `outline-invisible-p'.
28299 (if (fboundp 'outline-invisible-p)
28300 (outline-invisible-p)
28301 (get-char-property (point) 'invisible))))
28303 (defalias 'org-back-to-heading 'outline-back-to-heading)
28304 (defalias 'org-on-heading-p 'outline-on-heading-p)
28305 (defalias 'org-at-heading-p 'outline-on-heading-p)
28306 (defun org-at-heading-or-item-p ()
28307 (or (org-on-heading-p) (org-at-item-p)))
28309 (defun org-on-target-p ()
28310 (or (org-in-regexp org-radio-target-regexp)
28311 (org-in-regexp org-target-regexp)))
28313 (defun org-up-heading-all (arg)
28314 "Move to the heading line of which the present line is a subheading.
28315 This function considers both visible and invisible heading lines.
28316 With argument, move up ARG levels."
28317 (if (fboundp 'outline-up-heading-all)
28318 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28319 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28321 (defun org-up-heading-safe ()
28322 "Move to the heading line of which the present line is a subheading.
28323 This version will not throw an error. It will return the level of the
28324 headline found, or nil if no higher level is found."
28325 (let ((pos (point)) start-level level
28326 (re (concat "^" outline-regexp)))
28327 (catch 'exit
28328 (outline-back-to-heading t)
28329 (setq start-level (funcall outline-level))
28330 (if (equal start-level 1) (throw 'exit nil))
28331 (while (re-search-backward re nil t)
28332 (setq level (funcall outline-level))
28333 (if (< level start-level) (throw 'exit level)))
28334 nil)))
28336 (defun org-first-sibling-p ()
28337 "Is this heading the first child of its parents?"
28338 (interactive)
28339 (let ((re (concat "^" outline-regexp))
28340 level l)
28341 (unless (org-at-heading-p t)
28342 (error "Not at a heading"))
28343 (setq level (funcall outline-level))
28344 (save-excursion
28345 (if (not (re-search-backward re nil t))
28347 (setq l (funcall outline-level))
28348 (< l level)))))
28350 (defun org-goto-sibling (&optional previous)
28351 "Goto the next sibling, even if it is invisible.
28352 When PREVIOUS is set, go to the previous sibling instead. Returns t
28353 when a sibling was found. When none is found, return nil and don't
28354 move point."
28355 (let ((fun (if previous 're-search-backward 're-search-forward))
28356 (pos (point))
28357 (re (concat "^" outline-regexp))
28358 level l)
28359 (when (condition-case nil (org-back-to-heading t) (error nil))
28360 (setq level (funcall outline-level))
28361 (catch 'exit
28362 (or previous (forward-char 1))
28363 (while (funcall fun re nil t)
28364 (setq l (funcall outline-level))
28365 (when (< l level) (goto-char pos) (throw 'exit nil))
28366 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28367 (goto-char pos)
28368 nil))))
28370 (defun org-show-siblings ()
28371 "Show all siblings of the current headline."
28372 (save-excursion
28373 (while (org-goto-sibling) (org-flag-heading nil)))
28374 (save-excursion
28375 (while (org-goto-sibling 'previous)
28376 (org-flag-heading nil))))
28378 (defun org-show-hidden-entry ()
28379 "Show an entry where even the heading is hidden."
28380 (save-excursion
28381 (org-show-entry)))
28383 (defun org-flag-heading (flag &optional entry)
28384 "Flag the current heading. FLAG non-nil means make invisible.
28385 When ENTRY is non-nil, show the entire entry."
28386 (save-excursion
28387 (org-back-to-heading t)
28388 ;; Check if we should show the entire entry
28389 (if entry
28390 (progn
28391 (org-show-entry)
28392 (save-excursion
28393 (and (outline-next-heading)
28394 (org-flag-heading nil))))
28395 (outline-flag-region (max (point-min) (1- (point)))
28396 (save-excursion (outline-end-of-heading) (point))
28397 flag))))
28399 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28400 ;; This is an exact copy of the original function, but it uses
28401 ;; `org-back-to-heading', to make it work also in invisible
28402 ;; trees. And is uses an invisible-OK argument.
28403 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28404 (org-back-to-heading invisible-OK)
28405 (let ((first t)
28406 (level (funcall outline-level)))
28407 (while (and (not (eobp))
28408 (or first (> (funcall outline-level) level)))
28409 (setq first nil)
28410 (outline-next-heading))
28411 (unless to-heading
28412 (if (memq (preceding-char) '(?\n ?\^M))
28413 (progn
28414 ;; Go to end of line before heading
28415 (forward-char -1)
28416 (if (memq (preceding-char) '(?\n ?\^M))
28417 ;; leave blank line before heading
28418 (forward-char -1))))))
28419 (point))
28421 (defun org-show-subtree ()
28422 "Show everything after this heading at deeper levels."
28423 (outline-flag-region
28424 (point)
28425 (save-excursion
28426 (outline-end-of-subtree) (outline-next-heading) (point))
28427 nil))
28429 (defun org-show-entry ()
28430 "Show the body directly following this heading.
28431 Show the heading too, if it is currently invisible."
28432 (interactive)
28433 (save-excursion
28434 (condition-case nil
28435 (progn
28436 (org-back-to-heading t)
28437 (outline-flag-region
28438 (max (point-min) (1- (point)))
28439 (save-excursion
28440 (re-search-forward
28441 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28442 (or (match-beginning 1) (point-max)))
28443 nil))
28444 (error nil))))
28446 (defun org-make-options-regexp (kwds)
28447 "Make a regular expression for keyword lines."
28448 (concat
28450 "#?[ \t]*\\+\\("
28451 (mapconcat 'regexp-quote kwds "\\|")
28452 "\\):[ \t]*"
28453 "\\(.+\\)"))
28455 ;; Make isearch reveal the necessary context
28456 (defun org-isearch-end ()
28457 "Reveal context after isearch exits."
28458 (when isearch-success ; only if search was successful
28459 (if (featurep 'xemacs)
28460 ;; Under XEmacs, the hook is run in the correct place,
28461 ;; we directly show the context.
28462 (org-show-context 'isearch)
28463 ;; In Emacs the hook runs *before* restoring the overlays.
28464 ;; So we have to use a one-time post-command-hook to do this.
28465 ;; (Emacs 22 has a special variable, see function `org-mode')
28466 (unless (and (boundp 'isearch-mode-end-hook-quit)
28467 isearch-mode-end-hook-quit)
28468 ;; Only when the isearch was not quitted.
28469 (org-add-hook 'post-command-hook 'org-isearch-post-command
28470 'append 'local)))))
28472 (defun org-isearch-post-command ()
28473 "Remove self from hook, and show context."
28474 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28475 (org-show-context 'isearch))
28478 ;;;; Integration with and fixes for other packages
28480 ;;; Imenu support
28482 (defvar org-imenu-markers nil
28483 "All markers currently used by Imenu.")
28484 (make-variable-buffer-local 'org-imenu-markers)
28486 (defun org-imenu-new-marker (&optional pos)
28487 "Return a new marker for use by Imenu, and remember the marker."
28488 (let ((m (make-marker)))
28489 (move-marker m (or pos (point)))
28490 (push m org-imenu-markers)
28493 (defun org-imenu-get-tree ()
28494 "Produce the index for Imenu."
28495 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28496 (setq org-imenu-markers nil)
28497 (let* ((n org-imenu-depth)
28498 (re (concat "^" outline-regexp))
28499 (subs (make-vector (1+ n) nil))
28500 (last-level 0)
28501 m tree level head)
28502 (save-excursion
28503 (save-restriction
28504 (widen)
28505 (goto-char (point-max))
28506 (while (re-search-backward re nil t)
28507 (setq level (org-reduced-level (funcall outline-level)))
28508 (when (<= level n)
28509 (looking-at org-complex-heading-regexp)
28510 (setq head (org-match-string-no-properties 4)
28511 m (org-imenu-new-marker))
28512 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28513 (if (>= level last-level)
28514 (push (cons head m) (aref subs level))
28515 (push (cons head (aref subs (1+ level))) (aref subs level))
28516 (loop for i from (1+ level) to n do (aset subs i nil)))
28517 (setq last-level level)))))
28518 (aref subs 1)))
28520 (eval-after-load "imenu"
28521 '(progn
28522 (add-hook 'imenu-after-jump-hook
28523 (lambda () (org-show-context 'org-goto)))))
28525 ;; Speedbar support
28527 (defun org-speedbar-set-agenda-restriction ()
28528 "Restrict future agenda commands to the location at point in speedbar.
28529 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28530 (interactive)
28531 (let (p m tp np dir txt w)
28532 (cond
28533 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28534 'org-imenu t))
28535 (setq m (get-text-property p 'org-imenu-marker))
28536 (save-excursion
28537 (save-restriction
28538 (set-buffer (marker-buffer m))
28539 (goto-char m)
28540 (org-agenda-set-restriction-lock 'subtree))))
28541 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28542 'speedbar-function 'speedbar-find-file))
28543 (setq tp (previous-single-property-change
28544 (1+ p) 'speedbar-function)
28545 np (next-single-property-change
28546 tp 'speedbar-function)
28547 dir (speedbar-line-directory)
28548 txt (buffer-substring-no-properties (or tp (point-min))
28549 (or np (point-max))))
28550 (save-excursion
28551 (save-restriction
28552 (set-buffer (find-file-noselect
28553 (let ((default-directory dir))
28554 (expand-file-name txt))))
28555 (unless (org-mode-p)
28556 (error "Cannot restrict to non-Org-mode file"))
28557 (org-agenda-set-restriction-lock 'file))))
28558 (t (error "Don't know how to restrict Org-mode's agenda")))
28559 (org-move-overlay org-speedbar-restriction-lock-overlay
28560 (point-at-bol) (point-at-eol))
28561 (setq current-prefix-arg nil)
28562 (org-agenda-maybe-redo)))
28564 (eval-after-load "speedbar"
28565 '(progn
28566 (speedbar-add-supported-extension ".org")
28567 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28568 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28569 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28570 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28571 (add-hook 'speedbar-visiting-tag-hook
28572 (lambda () (org-show-context 'org-goto)))))
28575 ;;; Fixes and Hacks
28577 ;; Make flyspell not check words in links, to not mess up our keymap
28578 (defun org-mode-flyspell-verify ()
28579 "Don't let flyspell put overlays at active buttons."
28580 (not (get-text-property (point) 'keymap)))
28582 ;; Make `bookmark-jump' show the jump location if it was hidden.
28583 (eval-after-load "bookmark"
28584 '(if (boundp 'bookmark-after-jump-hook)
28585 ;; We can use the hook
28586 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28587 ;; Hook not available, use advice
28588 (defadvice bookmark-jump (after org-make-visible activate)
28589 "Make the position visible."
28590 (org-bookmark-jump-unhide))))
28592 (defun org-bookmark-jump-unhide ()
28593 "Unhide the current position, to show the bookmark location."
28594 (and (org-mode-p)
28595 (or (org-invisible-p)
28596 (save-excursion (goto-char (max (point-min) (1- (point))))
28597 (org-invisible-p)))
28598 (org-show-context 'bookmark-jump)))
28600 ;; Make session.el ignore our circular variable
28601 (eval-after-load "session"
28602 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28604 ;;;; Experimental code
28606 (defun org-closed-in-range ()
28607 "Sparse tree of items closed in a certain time range.
28608 Still experimental, may disappear in the future."
28609 (interactive)
28610 ;; Get the time interval from the user.
28611 (let* ((time1 (time-to-seconds
28612 (org-read-date nil 'to-time nil "Starting date: ")))
28613 (time2 (time-to-seconds
28614 (org-read-date nil 'to-time nil "End date:")))
28615 ;; callback function
28616 (callback (lambda ()
28617 (let ((time
28618 (time-to-seconds
28619 (apply 'encode-time
28620 (org-parse-time-string
28621 (match-string 1))))))
28622 ;; check if time in interval
28623 (and (>= time time1) (<= time time2))))))
28624 ;; make tree, check each match with the callback
28625 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28628 ;;;; Finish up
28630 (provide 'org)
28632 (run-hooks 'org-load-hook)
28634 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28635 ;;; org.el ends here