Release 5.11b
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blob597c7b7109c1165da898a648fc5d466442020e28
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 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.11b
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 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.11"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 (defmacro org-unmodified (&rest body)
101 "Execute body without changing buffer-modified-p."
102 `(set-buffer-modified-p
103 (prog1 (buffer-modified-p) ,@body)))
105 (defmacro org-re (s)
106 "Replace posix classes in regular expression."
107 (if (featurep 'xemacs)
108 (let ((ss s))
109 (save-match-data
110 (while (string-match "\\[:alnum:\\]" ss)
111 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
112 (while (string-match "\\[:alpha:\\]" ss)
113 (setq ss (replace-match "a-zA-Z" t t ss)))
114 ss))
117 (defmacro org-preserve-lc (&rest body)
118 `(let ((_line (org-current-line))
119 (_col (current-column)))
120 (unwind-protect
121 (progn ,@body)
122 (goto-line _line)
123 (move-to-column _col))))
125 (defmacro org-without-partial-completion (&rest body)
126 `(let ((pc-mode (and (boundp 'partial-completion-mode)
127 partial-completion-mode)))
128 (unwind-protect
129 (progn
130 (if pc-mode (partial-completion-mode -1))
131 ,@body)
132 (if pc-mode (partial-completion-mode 1)))))
134 ;;; The custom variables
136 (defgroup org nil
137 "Outline-based notes management and organizer."
138 :tag "Org"
139 :group 'outlines
140 :group 'hypermedia
141 :group 'calendar)
143 ;; FIXME: Needs a separate group...
144 (defcustom org-completion-fallback-command 'hippie-expand
145 "The expansion command called by \\[org-complete] in normal context.
146 Normal means, no org-mode-specific context."
147 :group 'org
148 :type 'function)
150 (defgroup org-startup nil
151 "Options concerning startup of Org-mode."
152 :tag "Org Startup"
153 :group 'org)
155 (defcustom org-startup-folded t
156 "Non-nil means, entering Org-mode will switch to OVERVIEW.
157 This can also be configured on a per-file basis by adding one of
158 the following lines anywhere in the buffer:
160 #+STARTUP: fold
161 #+STARTUP: nofold
162 #+STARTUP: content"
163 :group 'org-startup
164 :type '(choice
165 (const :tag "nofold: show all" nil)
166 (const :tag "fold: overview" t)
167 (const :tag "content: all headlines" content)))
169 (defcustom org-startup-truncated t
170 "Non-nil means, entering Org-mode will set `truncate-lines'.
171 This is useful since some lines containing links can be very long and
172 uninteresting. Also tables look terrible when wrapped."
173 :group 'org-startup
174 :type 'boolean)
176 (defcustom org-startup-align-all-tables nil
177 "Non-nil means, align all tables when visiting a file.
178 This is useful when the column width in tables is forced with <N> cookies
179 in table fields. Such tables will look correct only after the first re-align.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182 #+STARTUP: align
183 #+STARTUP: noalign"
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-insert-mode-line-in-empty-file nil
188 "Non-nil means insert the first line setting Org-mode in empty files.
189 When the function `org-mode' is called interactively in an empty file, this
190 normally means that the file name does not automatically trigger Org-mode.
191 To ensure that the file will always be in Org-mode in the future, a
192 line enforcing Org-mode will be inserted into the buffer, if this option
193 has been set."
194 :group 'org-startup
195 :type 'boolean)
197 (defcustom org-replace-disputed-keys nil
198 "Non-nil means use alternative key bindings for some keys.
199 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
200 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
201 If you want to use Org-mode together with one of these other modes,
202 or more generally if you would like to move some Org-mode commands to
203 other keys, set this variable and configure the keys with the variable
204 `org-disputed-keys'.
206 This option is only relevant at load-time of Org-mode, and must be set
207 *before* org.el is loaded. Changing it requires a restart of Emacs to
208 become effective."
209 :group 'org-startup
210 :type 'boolean)
212 (if (fboundp 'defvaralias)
213 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
215 (defcustom org-disputed-keys
216 '(([(shift up)] . [(meta p)])
217 ([(shift down)] . [(meta n)])
218 ([(shift left)] . [(meta -)])
219 ([(shift right)] . [(meta +)])
220 ([(control shift right)] . [(meta shift +)])
221 ([(control shift left)] . [(meta shift -)]))
222 "Keys for which Org-mode and other modes compete.
223 This is an alist, cars are the default keys, second element specifies
224 the alternative to use when `org-replace-disputed-keys' is t.
226 Keys can be specified in any syntax supported by `define-key'.
227 The value of this option takes effect only at Org-mode's startup,
228 therefore you'll have to restart Emacs to apply it after changing."
229 :group 'org-startup
230 :type 'alist)
232 (defun org-key (key)
233 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
234 Or return the original if not disputed."
235 (if org-replace-disputed-keys
236 (let* ((nkey (key-description key))
237 (x (org-find-if (lambda (x)
238 (equal (key-description (car x)) nkey))
239 org-disputed-keys)))
240 (if x (cdr x) key))
241 key))
243 (defun org-find-if (predicate seq)
244 (catch 'exit
245 (while seq
246 (if (funcall predicate (car seq))
247 (throw 'exit (car seq))
248 (pop seq)))))
250 (defun org-defkey (keymap key def)
251 "Define a key, possibly translated, as returned by `org-key'."
252 (define-key keymap (org-key key) def))
254 (defcustom org-ellipsis nil
255 "The ellipsis to use in the Org-mode outline.
256 When nil, just use the standard three dots. When a string, use that instead,
257 When a face, use the standart 3 dots, but with the specified face.
258 The change affects only Org-mode (which will then use its own display table).
259 Changing this requires executing `M-x org-mode' in a buffer to become
260 effective."
261 :group 'org-startup
262 :type '(choice (const :tag "Default" nil)
263 (face :tag "Face" :value org-warning)
264 (string :tag "String" :value "...#")))
266 (defvar org-display-table nil
267 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
269 (defgroup org-keywords nil
270 "Keywords in Org-mode."
271 :tag "Org Keywords"
272 :group 'org)
274 (defcustom org-deadline-string "DEADLINE:"
275 "String to mark deadline entries.
276 A deadline is this string, followed by a time stamp. Should be a word,
277 terminated by a colon. You can insert a schedule keyword and
278 a timestamp with \\[org-deadline].
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type 'string)
283 (defcustom org-scheduled-string "SCHEDULED:"
284 "String to mark scheduled TODO entries.
285 A schedule is this string, followed by a time stamp. Should be a word,
286 terminated by a colon. You can insert a schedule keyword and
287 a timestamp with \\[org-schedule].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
292 (defcustom org-closed-string "CLOSED:"
293 "String used as the prefix for timestamps logging closing a TODO entry."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-clock-string "CLOCK:"
298 "String used as prefix for timestamps clocking work hours on an item."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-comment-string "COMMENT"
303 "Entries starting with this keyword will never be exported.
304 An entry can be toggled between COMMENT and normal with
305 \\[org-toggle-comment].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
310 (defcustom org-quote-string "QUOTE"
311 "Entries starting with this keyword will be exported in fixed-width font.
312 Quoting applies only to the text in the entry following the headline, and does
313 not extend beyond the next headline, even if that is lower level.
314 An entry can be toggled between QUOTE and normal with
315 \\[org-toggle-fixed-width-section]."
316 :group 'org-keywords
317 :type 'string)
319 (defconst org-repeat-re
320 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
321 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
322 "Regular expression for specifying repeated events.
323 After a match, group 1 contains the repeat expression.")
325 (defgroup org-structure nil
326 "Options concerning the general structure of Org-mode files."
327 :tag "Org Structure"
328 :group 'org)
330 (defgroup org-reveal-location nil
331 "Options about how to make context of a location visible."
332 :tag "Org Reveal Location"
333 :group 'org-structure)
335 (defcustom org-show-hierarchy-above '((default . t))
336 "Non-nil means, show full hierarchy when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the hierarchy of headings
339 above the exposed location is shown.
340 Turning this off for example for sparse trees makes them very compact.
341 Instead of t, this can also be an alist specifying this option for different
342 contexts. Valid contexts are
343 agenda when exposing an entry from the agenda
344 org-goto when using the command `org-goto' on key C-c C-j
345 occur-tree when using the command `org-occur' on key C-c /
346 tags-tree when constructing a sparse tree based on tags matches
347 link-search when exposing search matches associated with a link
348 mark-goto when exposing the jump goal of a mark
349 bookmark-jump when exposing a bookmark location
350 isearch when exiting from an incremental search
351 default default for all contexts not set explicitly"
352 :group 'org-reveal-location
353 :type '(choice
354 (const :tag "Always" t)
355 (const :tag "Never" nil)
356 (repeat :greedy t :tag "Individual contexts"
357 (cons
358 (choice :tag "Context"
359 (const agenda)
360 (const org-goto)
361 (const occur-tree)
362 (const tags-tree)
363 (const link-search)
364 (const mark-goto)
365 (const bookmark-jump)
366 (const isearch)
367 (const default))
368 (boolean)))))
370 (defcustom org-show-following-heading '((default . nil))
371 "Non-nil means, show following heading when revealing a location.
372 Org-mode often shows locations in an org-mode file which might have
373 been invisible before. When this is set, the heading following the
374 match is shown.
375 Turning this off for example for sparse trees makes them very compact,
376 but makes it harder to edit the location of the match. In such a case,
377 use the command \\[org-reveal] to show more context.
378 Instead of t, this can also be an alist specifying this option for different
379 contexts. See `org-show-hierarchy-above' for valid contexts."
380 :group 'org-reveal-location
381 :type '(choice
382 (const :tag "Always" t)
383 (const :tag "Never" nil)
384 (repeat :greedy t :tag "Individual contexts"
385 (cons
386 (choice :tag "Context"
387 (const agenda)
388 (const org-goto)
389 (const occur-tree)
390 (const tags-tree)
391 (const link-search)
392 (const mark-goto)
393 (const bookmark-jump)
394 (const isearch)
395 (const default))
396 (boolean)))))
398 (defcustom org-show-siblings '((default . nil) (isearch t))
399 "Non-nil means, show all sibling heading when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the sibling of the current entry
402 heading are all made visible. If `org-show-hierarchy-above' is t,
403 the same happens on each level of the hierarchy above the current entry.
405 By default this is on for the isearch context, off for all other contexts.
406 Turning this off for example for sparse trees makes them very compact,
407 but makes it harder to edit the location of the match. In such a case,
408 use the command \\[org-reveal] to show more context.
409 Instead of t, this can also be an alist specifying this option for different
410 contexts. See `org-show-hierarchy-above' for valid contexts."
411 :group 'org-reveal-location
412 :type '(choice
413 (const :tag "Always" t)
414 (const :tag "Never" nil)
415 (repeat :greedy t :tag "Individual contexts"
416 (cons
417 (choice :tag "Context"
418 (const agenda)
419 (const org-goto)
420 (const occur-tree)
421 (const tags-tree)
422 (const link-search)
423 (const mark-goto)
424 (const bookmark-jump)
425 (const isearch)
426 (const default))
427 (boolean)))))
429 (defgroup org-cycle nil
430 "Options concerning visibility cycling in Org-mode."
431 :tag "Org Cycle"
432 :group 'org-structure)
434 (defcustom org-drawers '("PROPERTIES" "CLOCK")
435 "Names of drawers. Drawers are not opened by cycling on the headline above.
436 Drawers only open with a TAB on the drawer line itself. A drawer looks like
437 this:
438 :DRAWERNAME:
439 .....
440 :END:
441 The drawer \"PROPERTIES\" is special for capturing properties through
442 the property API."
443 :group 'org-structure
444 :type '(repeat (string :tag "Drawer Name")))
446 (defcustom org-cycle-global-at-bob nil
447 "Cycle globally if cursor is at beginning of buffer and not at a headline.
448 This makes it possible to do global cycling without having to use S-TAB or
449 C-u TAB. For this special case to work, the first line of the buffer
450 must not be a headline - it may be empty ot some other text. When used in
451 this way, `org-cycle-hook' is disables temporarily, to make sure the
452 cursor stays at the beginning of the buffer.
453 When this option is nil, don't do anything special at the beginning
454 of the buffer."
455 :group 'org-cycle
456 :type 'boolean)
458 (defcustom org-cycle-emulate-tab t
459 "Where should `org-cycle' emulate TAB.
460 nil Never
461 white Only in completely white lines
462 whitestart Only at the beginning of lines, before the first non-white char.
463 t Everywhere except in headlines
464 exc-hl-bol Everywhere except at the start of a headline
465 If TAB is used in a place where it does not emulate TAB, the current subtree
466 visibility is cycled."
467 :group 'org-cycle
468 :type '(choice (const :tag "Never" nil)
469 (const :tag "Only in completely white lines" white)
470 (const :tag "Before first char in a line" whitestart)
471 (const :tag "Everywhere except in headlines" t)
472 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
475 (defcustom org-cycle-separator-lines 2
476 "Number of empty lines needed to keep an empty line between collapsed trees.
477 If you leave an empty line between the end of a subtree and the following
478 headline, this empty line is hidden when the subtree is folded.
479 Org-mode will leave (exactly) one empty line visible if the number of
480 empty lines is equal or larger to the number given in this variable.
481 So the default 2 means, at least 2 empty lines after the end of a subtree
482 are needed to produce free space between a collapsed subtree and the
483 following headline.
485 Special case: when 0, never leave empty lines in collapsed view."
486 :group 'org-cycle
487 :type 'integer)
489 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
490 org-cycle-hide-drawers
491 org-cycle-show-empty-lines
492 org-optimize-window-after-visibility-change)
493 "Hook that is run after `org-cycle' has changed the buffer visibility.
494 The function(s) in this hook must accept a single argument which indicates
495 the new state that was set by the most recent `org-cycle' command. The
496 argument is a symbol. After a global state change, it can have the values
497 `overview', `content', or `all'. After a local state change, it can have
498 the values `folded', `children', or `subtree'."
499 :group 'org-cycle
500 :type 'hook)
502 (defgroup org-edit-structure nil
503 "Options concerning structure editing in Org-mode."
504 :tag "Org Edit Structure"
505 :group 'org-structure)
507 (defcustom org-special-ctrl-a/e nil
508 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
509 When t, `C-a' will bring back the cursor to the beginning of the
510 headline text, i.e. after the stars and after a possible TODO keyword.
511 In an item, this will be the position after the bullet.
512 When the cursor is already at that position, another `C-a' will bring
513 it to the beginning of the line.
514 `C-e' will jump to the end of the headline, ignoring the presence of tags
515 in the headline. A second `C-e' will then jump to the true end of the
516 line, after any tags.
517 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
518 and only a directly following, identical keypress will bring the cursor
519 to the special positions."
520 :group 'org-edit-structure
521 :type '(choice
522 (const :tag "off" nil)
523 (const :tag "after bullet first" t)
524 (const :tag "border first" reversed)))
526 (if (fboundp 'defvaralias)
527 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
529 (defcustom org-odd-levels-only nil
530 "Non-nil means, skip even levels and only use odd levels for the outline.
531 This has the effect that two stars are being added/taken away in
532 promotion/demotion commands. It also influences how levels are
533 handled by the exporters.
534 Changing it requires restart of `font-lock-mode' to become effective
535 for fontification also in regions already fontified.
536 You may also set this on a per-file basis by adding one of the following
537 lines to the buffer:
539 #+STARTUP: odd
540 #+STARTUP: oddeven"
541 :group 'org-edit-structure
542 :group 'org-font-lock
543 :type 'boolean)
545 (defcustom org-adapt-indentation t
546 "Non-nil means, adapt indentation when promoting and demoting.
547 When this is set and the *entire* text in an entry is indented, the
548 indentation is increased by one space in a demotion command, and
549 decreased by one in a promotion command. If any line in the entry
550 body starts at column 0, indentation is not changed at all."
551 :group 'org-edit-structure
552 :type 'boolean)
554 (defcustom org-blank-before-new-entry '((heading . nil)
555 (plain-list-item . nil))
556 "Should `org-insert-heading' leave a blank line before new heading/item?
557 The value is an alist, with `heading' and `plain-list-item' as car,
558 and a boolean flag as cdr."
559 :group 'org-edit-structure
560 :type '(list
561 (cons (const heading) (boolean))
562 (cons (const plain-list-item) (boolean))))
564 (defcustom org-insert-heading-hook nil
565 "Hook being run after inserting a new heading."
566 :group 'org-edit-structure
567 :type 'boolean)
569 (defcustom org-enable-fixed-width-editor t
570 "Non-nil means, lines starting with \":\" are treated as fixed-width.
571 This currently only means, they are never auto-wrapped.
572 When nil, such lines will be treated like ordinary lines.
573 See also the QUOTE keyword."
574 :group 'org-edit-structure
575 :type 'boolean)
577 (defgroup org-sparse-trees nil
578 "Options concerning sparse trees in Org-mode."
579 :tag "Org Sparse Trees"
580 :group 'org-structure)
582 (defcustom org-highlight-sparse-tree-matches t
583 "Non-nil means, highlight all matches that define a sparse tree.
584 The highlights will automatically disappear the next time the buffer is
585 changed by an edit command."
586 :group 'org-sparse-trees
587 :type 'boolean)
589 (defcustom org-remove-highlights-with-change t
590 "Non-nil means, any change to the buffer will remove temporary highlights.
591 Such highlights are created by `org-occur' and `org-clock-display'.
592 When nil, `C-c C-c needs to be used to get rid of the highlights.
593 The highlights created by `org-preview-latex-fragment' always need
594 `C-c C-c' to be removed."
595 :group 'org-sparse-trees
596 :group 'org-time
597 :type 'boolean)
600 (defcustom org-occur-hook '(org-first-headline-recenter)
601 "Hook that is run after `org-occur' has constructed a sparse tree.
602 This can be used to recenter the window to show as much of the structure
603 as possible."
604 :group 'org-sparse-trees
605 :type 'hook)
607 (defgroup org-plain-lists nil
608 "Options concerning plain lists in Org-mode."
609 :tag "Org Plain lists"
610 :group 'org-structure)
612 (defcustom org-cycle-include-plain-lists nil
613 "Non-nil means, include plain lists into visibility cycling.
614 This means that during cycling, plain list items will *temporarily* be
615 interpreted as outline headlines with a level given by 1000+i where i is the
616 indentation of the bullet. In all other operations, plain list items are
617 not seen as headlines. For example, you cannot assign a TODO keyword to
618 such an item."
619 :group 'org-plain-lists
620 :type 'boolean)
622 (defcustom org-plain-list-ordered-item-terminator t
623 "The character that makes a line with leading number an ordered list item.
624 Valid values are ?. and ?\). To get both terminators, use t. While
625 ?. may look nicer, it creates the danger that a line with leading
626 number may be incorrectly interpreted as an item. ?\) therefore is
627 the safe choice."
628 :group 'org-plain-lists
629 :type '(choice (const :tag "dot like in \"2.\"" ?.)
630 (const :tag "paren like in \"2)\"" ?\))
631 (const :tab "both" t)))
633 (defcustom org-auto-renumber-ordered-lists t
634 "Non-nil means, automatically renumber ordered plain lists.
635 Renumbering happens when the sequence have been changed with
636 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
637 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
638 :group 'org-plain-lists
639 :type 'boolean)
641 (defcustom org-provide-checkbox-statistics t
642 "Non-nil means, update checkbox statistics after insert and toggle.
643 When this is set, checkbox statistics is updated each time you either insert
644 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
645 with \\[org-ctrl-c-ctrl-c\\]."
646 :group 'org-plain-lists
647 :type 'boolean)
649 (defgroup org-archive nil
650 "Options concerning archiving in Org-mode."
651 :tag "Org Archive"
652 :group 'org-structure)
654 (defcustom org-archive-tag "ARCHIVE"
655 "The tag that marks a subtree as archived.
656 An archived subtree does not open during visibility cycling, and does
657 not contribute to the agenda listings."
658 :group 'org-archive
659 :group 'org-keywords
660 :type 'string)
662 (defcustom org-agenda-skip-archived-trees t
663 "Non-nil means, the agenda will skip any items located in archived trees.
664 An archived tree is a tree marked with the tag ARCHIVE."
665 :group 'org-archive
666 :group 'org-agenda-skip
667 :type 'boolean)
669 (defcustom org-cycle-open-archived-trees nil
670 "Non-nil means, `org-cycle' will open archived trees.
671 An archived tree is a tree marked with the tag ARCHIVE.
672 When nil, archived trees will stay folded. You can still open them with
673 normal outline commands like `show-all', but not with the cycling commands."
674 :group 'org-archive
675 :group 'org-cycle
676 :type 'boolean)
678 (defcustom org-sparse-tree-open-archived-trees nil
679 "Non-nil means sparse tree construction shows matches in archived trees.
680 When nil, matches in these trees are highlighted, but the trees are kept in
681 collapsed state."
682 :group 'org-archive
683 :group 'org-sparse-trees
684 :type 'boolean)
686 (defcustom org-archive-location "%s_archive::"
687 "The location where subtrees should be archived.
688 This string consists of two parts, separated by a double-colon.
690 The first part is a file name - when omitted, archiving happens in the same
691 file. %s will be replaced by the current file name (without directory part).
692 Archiving to a different file is useful to keep archived entries from
693 contributing to the Org-mode Agenda.
695 The part after the double colon is a headline. The archived entries will be
696 filed under that headline. When omitted, the subtrees are simply filed away
697 at the end of the file, as top-level entries.
699 Here are a few examples:
700 \"%s_archive::\"
701 If the current file is Projects.org, archive in file
702 Projects.org_archive, as top-level trees. This is the default.
704 \"::* Archived Tasks\"
705 Archive in the current file, under the top-level headline
706 \"* Archived Tasks\".
708 \"~/org/archive.org::\"
709 Archive in file ~/org/archive.org (absolute path), as top-level trees.
711 \"basement::** Finished Tasks\"
712 Archive in file ./basement (relative path), as level 3 trees
713 below the level 2 heading \"** Finished Tasks\".
715 You may set this option on a per-file basis by adding to the buffer a
716 line like
718 #+ARCHIVE: basement::** Finished Tasks"
719 :group 'org-archive
720 :type 'string)
722 (defcustom org-archive-mark-done t
723 "Non-nil means, mark entries as DONE when they are moved to the archive file.
724 This can be a string to set the keyword to use. When t, Org-mode will
725 use the first keyword in its list that means done."
726 :group 'org-archive
727 :type '(choice
728 (const :tag "No" nil)
729 (const :tag "Yes" t)
730 (string :tag "Use this keyword")))
732 (defcustom org-archive-stamp-time t
733 "Non-nil means, add a time stamp to entries moved to an archive file.
734 This variable is obsolete and has no effect anymore, instead add ot remove
735 `time' from the variablle `org-archive-save-context-info'."
736 :group 'org-archive
737 :type 'boolean)
739 (defcustom org-archive-save-context-info '(time file category todo itags)
740 "Parts of context info that should be stored as properties when archiving.
741 When a subtree is moved to an archive file, it looses information given by
742 context, like inherited tags, the category, and possibly also the TODO
743 state (depending on the variable `org-archive-mark-done').
744 This variable can be a list of any of the following symbols:
746 time The time of archiving.
747 file The file where the entry originates.
748 itags The local tags, in the headline of the subtree.
749 ltags The tags the subtree inherits from further up the hierarchy.
750 todo The pre-archive TODO state.
751 category The category, taken from file name or #+CATEGORY lines.
753 For each symbol present in the list, a property will be created in
754 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
755 information."
756 :group 'org-archive
757 :type '(set :greedy t
758 (const :tag "Time" time)
759 (const :tag "File" file)
760 (const :tag "Category" category)
761 (const :tag "TODO state" todo)
762 (const :tag "TODO state" priority)
763 (const :tag "Inherited tags" itags)
764 (const :tag "Local tags" ltags)))
766 (defgroup org-table nil
767 "Options concerning tables in Org-mode."
768 :tag "Org Table"
769 :group 'org)
771 (defcustom org-enable-table-editor 'optimized
772 "Non-nil means, lines starting with \"|\" are handled by the table editor.
773 When nil, such lines will be treated like ordinary lines.
775 When equal to the symbol `optimized', the table editor will be optimized to
776 do the following:
777 - Automatic overwrite mode in front of whitespace in table fields.
778 This makes the structure of the table stay in tact as long as the edited
779 field does not exceed the column width.
780 - Minimize the number of realigns. Normally, the table is aligned each time
781 TAB or RET are pressed to move to another field. With optimization this
782 happens only if changes to a field might have changed the column width.
783 Optimization requires replacing the functions `self-insert-command',
784 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
785 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
786 very good at guessing when a re-align will be necessary, but you can always
787 force one with \\[org-ctrl-c-ctrl-c].
789 If you would like to use the optimized version in Org-mode, but the
790 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
792 This variable can be used to turn on and off the table editor during a session,
793 but in order to toggle optimization, a restart is required.
795 See also the variable `org-table-auto-blank-field'."
796 :group 'org-table
797 :type '(choice
798 (const :tag "off" nil)
799 (const :tag "on" t)
800 (const :tag "on, optimized" optimized)))
802 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
803 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
804 In the optimized version, the table editor takes over all simple keys that
805 normally just insert a character. In tables, the characters are inserted
806 in a way to minimize disturbing the table structure (i.e. in overwrite mode
807 for empty fields). Outside tables, the correct binding of the keys is
808 restored.
810 The default for this option is t if the optimized version is also used in
811 Org-mode. See the variable `org-enable-table-editor' for details. Changing
812 this variable requires a restart of Emacs to become effective."
813 :group 'org-table
814 :type 'boolean)
816 (defcustom orgtbl-radio-table-templates
817 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
818 % END RECEIVE ORGTBL %n
819 \\begin{comment}
820 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
821 | | |
822 \\end{comment}\n")
823 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
824 @c END RECEIVE ORGTBL %n
825 @ignore
826 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
827 | | |
828 @end ignore\n")
829 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
830 <!-- END RECEIVE ORGTBL %n -->
831 <!--
832 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
833 | | |
834 -->\n"))
835 "Templates for radio tables in different major modes.
836 All occurrences of %n in a template will be replaced with the name of the
837 table, obtained by prompting the user."
838 :group 'org-table
839 :type '(repeat
840 (list (symbol :tag "Major mode")
841 (string :tag "Format"))))
843 (defgroup org-table-settings nil
844 "Settings for tables in Org-mode."
845 :tag "Org Table Settings"
846 :group 'org-table)
848 (defcustom org-table-default-size "5x2"
849 "The default size for newly created tables, Columns x Rows."
850 :group 'org-table-settings
851 :type 'string)
853 (defcustom org-table-number-regexp
854 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
855 "Regular expression for recognizing numbers in table columns.
856 If a table column contains mostly numbers, it will be aligned to the
857 right. If not, it will be aligned to the left.
859 The default value of this option is a regular expression which allows
860 anything which looks remotely like a number as used in scientific
861 context. For example, all of the following will be considered a
862 number:
863 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
865 Other options offered by the customize interface are more restrictive."
866 :group 'org-table-settings
867 :type '(choice
868 (const :tag "Positive Integers"
869 "^[0-9]+$")
870 (const :tag "Integers"
871 "^[-+]?[0-9]+$")
872 (const :tag "Floating Point Numbers"
873 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
874 (const :tag "Floating Point Number or Integer"
875 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
876 (const :tag "Exponential, Floating point, Integer"
877 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
878 (const :tag "Very General Number-Like, including hex"
879 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
880 (string :tag "Regexp:")))
882 (defcustom org-table-number-fraction 0.5
883 "Fraction of numbers in a column required to make the column align right.
884 In a column all non-white fields are considered. If at least this
885 fraction of fields is matched by `org-table-number-fraction',
886 alignment to the right border applies."
887 :group 'org-table-settings
888 :type 'number)
890 (defgroup org-table-editing nil
891 "Bahavior of tables during editing in Org-mode."
892 :tag "Org Table Editing"
893 :group 'org-table)
895 (defcustom org-table-automatic-realign t
896 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
897 When nil, aligning is only done with \\[org-table-align], or after column
898 removal/insertion."
899 :group 'org-table-editing
900 :type 'boolean)
902 (defcustom org-table-auto-blank-field t
903 "Non-nil means, automatically blank table field when starting to type into it.
904 This only happens when typing immediately after a field motion
905 command (TAB, S-TAB or RET).
906 Only relevant when `org-enable-table-editor' is equal to `optimized'."
907 :group 'org-table-editing
908 :type 'boolean)
910 (defcustom org-table-tab-jumps-over-hlines t
911 "Non-nil means, tab in the last column of a table with jump over a hline.
912 If a horizontal separator line is following the current line,
913 `org-table-next-field' can either create a new row before that line, or jump
914 over the line. When this option is nil, a new line will be created before
915 this line."
916 :group 'org-table-editing
917 :type 'boolean)
919 (defcustom org-table-tab-recognizes-table.el t
920 "Non-nil means, TAB will automatically notice a table.el table.
921 When it sees such a table, it moves point into it and - if necessary -
922 calls `table-recognize-table'."
923 :group 'org-table-editing
924 :type 'boolean)
926 (defgroup org-table-calculation nil
927 "Options concerning tables in Org-mode."
928 :tag "Org Table Calculation"
929 :group 'org-table)
931 (defcustom org-table-use-standard-references t
932 "Should org-mode work with table refrences like B3 instead of @3$2?
933 Possible values are:
934 nil never use them
935 from accept as input, do not present for editing
936 t: accept as input and present for editing"
937 :group 'org-table-calculation
938 :type '(choice
939 (const :tag "Never, don't even check unser input for them" nil)
940 (const :tag "Always, both as user input, and when editing" t)
941 (const :tag "Convert user input, don't offer during editing" 'from)))
943 (defcustom org-table-copy-increment t
944 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
945 :group 'org-table-calculation
946 :type 'boolean)
948 (defcustom org-calc-default-modes
949 '(calc-internal-prec 12
950 calc-float-format (float 5)
951 calc-angle-mode deg
952 calc-prefer-frac nil
953 calc-symbolic-mode nil
954 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
955 calc-display-working-message t
957 "List with Calc mode settings for use in calc-eval for table formulas.
958 The list must contain alternating symbols (Calc modes variables and values).
959 Don't remove any of the default settings, just change the values. Org-mode
960 relies on the variables to be present in the list."
961 :group 'org-table-calculation
962 :type 'plist)
964 (defcustom org-table-formula-evaluate-inline t
965 "Non-nil means, TAB and RET evaluate a formula in current table field.
966 If the current field starts with an equal sign, it is assumed to be a formula
967 which should be evaluated as described in the manual and in the documentation
968 string of the command `org-table-eval-formula'. This feature requires the
969 Emacs calc package.
970 When this variable is nil, formula calculation is only available through
971 the command \\[org-table-eval-formula]."
972 :group 'org-table-calculation
973 :type 'boolean)
975 (defcustom org-table-formula-use-constants t
976 "Non-nil means, interpret constants in formulas in tables.
977 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
978 by the value given in `org-table-formula-constants', or by a value obtained
979 from the `constants.el' package."
980 :group 'org-table-calculation
981 :type 'boolean)
983 (defcustom org-table-formula-constants nil
984 "Alist with constant names and values, for use in table formulas.
985 The car of each element is a name of a constant, without the `$' before it.
986 The cdr is the value as a string. For example, if you'd like to use the
987 speed of light in a formula, you would configure
989 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
991 and then use it in an equation like `$1*$c'.
993 Constants can also be defined on a per-file basis using a line like
995 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
996 :group 'org-table-calculation
997 :type '(repeat
998 (cons (string :tag "name")
999 (string :tag "value"))))
1001 (defvar org-table-formula-constants-local nil
1002 "Local version of `org-table-formula-constants'.")
1003 (make-variable-buffer-local 'org-table-formula-constants-local)
1005 (defcustom org-table-allow-automatic-line-recalculation t
1006 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1007 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1008 :group 'org-table-calculation
1009 :type 'boolean)
1011 (defgroup org-link nil
1012 "Options concerning links in Org-mode."
1013 :tag "Org Link"
1014 :group 'org)
1016 (defvar org-link-abbrev-alist-local nil
1017 "Buffer-local version of `org-link-abbrev-alist', which see.
1018 The value of this is taken from the #+LINK lines.")
1019 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1021 (defcustom org-link-abbrev-alist nil
1022 "Alist of link abbreviations.
1023 The car of each element is a string, to be replaced at the start of a link.
1024 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1025 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1027 [[linkkey:tag][description]]
1029 If REPLACE is a string, the tag will simply be appended to create the link.
1030 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1031 also be a function that will be called with the tag as the only argument to
1032 create the link. See the manual for examples."
1033 :group 'org-link
1034 :type 'alist)
1036 (defcustom org-descriptive-links t
1037 "Non-nil means, hide link part and only show description of bracket links.
1038 Bracket links are like [[link][descritpion]]. This variable sets the initial
1039 state in new org-mode buffers. The setting can then be toggled on a
1040 per-buffer basis from the Org->Hyperlinks menu."
1041 :group 'org-link
1042 :type 'boolean)
1044 (defcustom org-link-file-path-type 'adaptive
1045 "How the path name in file links should be stored.
1046 Valid values are:
1048 relative relative to the current directory, i.e. the directory of the file
1049 into which the link is being inserted.
1050 absolute absolute path, if possible with ~ for home directory.
1051 noabbrev absolute path, no abbreviation of home directory.
1052 adaptive Use relative path for files in the current directory and sub-
1053 directories of it. For other files, use an absolute path."
1054 :group 'org-link
1055 :type '(choice
1056 (const relative)
1057 (const absolute)
1058 (const noabbrev)
1059 (const adaptive)))
1061 (defcustom org-activate-links '(bracket angle plain radio tag date)
1062 "Types of links that should be activated in Org-mode files.
1063 This is a list of symbols, each leading to the activation of a certain link
1064 type. In principle, it does not hurt to turn on most link types - there may
1065 be a small gain when turning off unused link types. The types are:
1067 bracket The recommended [[link][description]] or [[link]] links with hiding.
1068 angular Links in angular brackes that may contain whitespace like
1069 <bbdb:Carsten Dominik>.
1070 plain Plain links in normal text, no whitespace, like http://google.com.
1071 radio Text that is matched by a radio target, see manual for details.
1072 tag Tag settings in a headline (link to tag search).
1073 date Time stamps (link to calendar).
1075 Changing this variable requires a restart of Emacs to become effective."
1076 :group 'org-link
1077 :type '(set (const :tag "Double bracket links (new style)" bracket)
1078 (const :tag "Angular bracket links (old style)" angular)
1079 (const :tag "plain text links" plain)
1080 (const :tag "Radio target matches" radio)
1081 (const :tag "Tags" tag)
1082 (const :tag "Tags" target)
1083 (const :tag "Timestamps" date)))
1085 (defgroup org-link-store nil
1086 "Options concerning storing links in Org-mode"
1087 :tag "Org Store Link"
1088 :group 'org-link)
1090 (defcustom org-email-link-description-format "Email %c: %.30s"
1091 "Format of the description part of a link to an email or usenet message.
1092 The following %-excapes will be replaced by corresponding information:
1094 %F full \"From\" field
1095 %f name, taken from \"From\" field, address if no name
1096 %T full \"To\" field
1097 %t first name in \"To\" field, address if no name
1098 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1099 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1100 %s subject
1101 %m message-id.
1103 You may use normal field width specification between the % and the letter.
1104 This is for example useful to limit the length of the subject.
1106 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1107 :group 'org-link-store
1108 :type 'string)
1110 (defcustom org-from-is-user-regexp
1111 (let (r1 r2)
1112 (when (and user-mail-address (not (string= user-mail-address "")))
1113 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1114 (when (and user-full-name (not (string= user-full-name "")))
1115 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1116 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1117 "Regexp mached against the \"From:\" header of an email or usenet message.
1118 It should match if the message is from the user him/herself."
1119 :group 'org-link-store
1120 :type 'regexp)
1122 (defcustom org-context-in-file-links t
1123 "Non-nil means, file links from `org-store-link' contain context.
1124 A search string will be added to the file name with :: as separator and
1125 used to find the context when the link is activated by the command
1126 `org-open-at-point'.
1127 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1128 negates this setting for the duration of the command."
1129 :group 'org-link-store
1130 :type 'boolean)
1132 (defcustom org-keep-stored-link-after-insertion nil
1133 "Non-nil means, keep link in list for entire session.
1135 The command `org-store-link' adds a link pointing to the current
1136 location to an internal list. These links accumulate during a session.
1137 The command `org-insert-link' can be used to insert links into any
1138 Org-mode file (offering completion for all stored links). When this
1139 option is nil, every link which has been inserted once using \\[org-insert-link]
1140 will be removed from the list, to make completing the unused links
1141 more efficient."
1142 :group 'org-link-store
1143 :type 'boolean)
1145 (defcustom org-usenet-links-prefer-google nil
1146 "Non-nil means, `org-store-link' will create web links to Google groups.
1147 When nil, Gnus will be used for such links.
1148 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1149 negates this setting for the duration of the command."
1150 :group 'org-link-store
1151 :type 'boolean)
1153 (defgroup org-link-follow nil
1154 "Options concerning following links in Org-mode"
1155 :tag "Org Follow Link"
1156 :group 'org-link)
1158 (defcustom org-tab-follows-link nil
1159 "Non-nil means, on links TAB will follow the link.
1160 Needs to be set before org.el is loaded."
1161 :group 'org-link-follow
1162 :type 'boolean)
1164 (defcustom org-return-follows-link nil
1165 "Non-nil means, on links RET will follow the link.
1166 Needs to be set before org.el is loaded."
1167 :group 'org-link-follow
1168 :type 'boolean)
1170 (defcustom org-mouse-1-follows-link t
1171 "Non-nil means, mouse-1 on a link will follow the link.
1172 A longer mouse click will still set point. Does not wortk on XEmacs.
1173 Needs to be set before org.el is loaded."
1174 :group 'org-link-follow
1175 :type 'boolean)
1177 (defcustom org-mark-ring-length 4
1178 "Number of different positions to be recorded in the ring
1179 Changing this requires a restart of Emacs to work correctly."
1180 :group 'org-link-follow
1181 :type 'interger)
1183 (defcustom org-link-frame-setup
1184 '((vm . vm-visit-folder-other-frame)
1185 (gnus . gnus-other-frame)
1186 (file . find-file-other-window))
1187 "Setup the frame configuration for following links.
1188 When following a link with Emacs, it may often be useful to display
1189 this link in another window or frame. This variable can be used to
1190 set this up for the different types of links.
1191 For VM, use any of
1192 `vm-visit-folder'
1193 `vm-visit-folder-other-frame'
1194 For Gnus, use any of
1195 `gnus'
1196 `gnus-other-frame'
1197 For FILE, use any of
1198 `find-file'
1199 `find-file-other-window'
1200 `find-file-other-frame'
1201 For the calendar, use the variable `calendar-setup'.
1202 For BBDB, it is currently only possible to display the matches in
1203 another window."
1204 :group 'org-link-follow
1205 :type '(list
1206 (cons (const vm)
1207 (choice
1208 (const vm-visit-folder)
1209 (const vm-visit-folder-other-window)
1210 (const vm-visit-folder-other-frame)))
1211 (cons (const gnus)
1212 (choice
1213 (const gnus)
1214 (const gnus-other-frame)))
1215 (cons (const file)
1216 (choice
1217 (const find-file)
1218 (const find-file-other-window)
1219 (const find-file-other-frame)))))
1221 (defcustom org-display-internal-link-with-indirect-buffer nil
1222 "Non-nil means, use indirect buffer to display infile links.
1223 Activating internal links (from one location in a file to another location
1224 in the same file) normally just jumps to the location. When the link is
1225 activated with a C-u prefix (or with mouse-3), the link is displayed in
1226 another window. When this option is set, the other window actually displays
1227 an indirect buffer clone of the current buffer, to avoid any visibility
1228 changes to the current buffer."
1229 :group 'org-link-follow
1230 :type 'boolean)
1232 (defcustom org-open-non-existing-files nil
1233 "Non-nil means, `org-open-file' will open non-existing files.
1234 When nil, an error will be generated."
1235 :group 'org-link-follow
1236 :type 'boolean)
1238 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1239 "Function and arguments to call for following mailto links.
1240 This is a list with the first element being a lisp function, and the
1241 remaining elements being arguments to the function. In string arguments,
1242 %a will be replaced by the address, and %s will be replaced by the subject
1243 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1244 :group 'org-link-follow
1245 :type '(choice
1246 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1247 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1248 (const :tag "message-mail" (message-mail "%a" "%s"))
1249 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1251 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1252 "Non-nil means, ask for confirmation before executing shell links.
1253 Shell links can be dangerous, just thing about a link
1255 [[shell:rm -rf ~/*][Google Search]]
1257 This link would show up in your Org-mode document as \"Google Search\"
1258 but really it would remove your entire home directory.
1259 Therefore I *definitely* advise against setting this variable to nil.
1260 Just change it to `y-or-n-p' of you want to confirm with a single key press
1261 rather than having to type \"yes\"."
1262 :group 'org-link-follow
1263 :type '(choice
1264 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1265 (const :tag "with y-or-n (faster)" y-or-n-p)
1266 (const :tag "no confirmation (dangerous)" nil)))
1268 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1269 "Non-nil means, ask for confirmation before executing elisp links.
1270 Elisp links can be dangerous, just think about a link
1272 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1274 This link would show up in your Org-mode document as \"Google Search\"
1275 but really it would remove your entire home directory.
1276 Therefore I *definitely* advise against setting this variable to nil.
1277 Just change it to `y-or-n-p' of you want to confirm with a single key press
1278 rather than having to type \"yes\"."
1279 :group 'org-link-follow
1280 :type '(choice
1281 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1282 (const :tag "with y-or-n (faster)" y-or-n-p)
1283 (const :tag "no confirmation (dangerous)" nil)))
1285 (defconst org-file-apps-defaults-gnu
1286 '((remote . emacs)
1287 (t . mailcap))
1288 "Default file applications on a UNIX or GNU/Linux system.
1289 See `org-file-apps'.")
1291 (defconst org-file-apps-defaults-macosx
1292 '((remote . emacs)
1293 (t . "open %s")
1294 ("ps" . "gv %s")
1295 ("ps.gz" . "gv %s")
1296 ("eps" . "gv %s")
1297 ("eps.gz" . "gv %s")
1298 ("dvi" . "xdvi %s")
1299 ("fig" . "xfig %s"))
1300 "Default file applications on a MacOS X system.
1301 The system \"open\" is known as a default, but we use X11 applications
1302 for some files for which the OS does not have a good default.
1303 See `org-file-apps'.")
1305 (defconst org-file-apps-defaults-windowsnt
1306 (list
1307 '(remote . emacs)
1308 (cons t
1309 (list (if (featurep 'xemacs)
1310 'mswindows-shell-execute
1311 'w32-shell-execute)
1312 "open" 'file)))
1313 "Default file applications on a Windows NT system.
1314 The system \"open\" is used for most files.
1315 See `org-file-apps'.")
1317 (defcustom org-file-apps
1319 ("txt" . emacs)
1320 ("tex" . emacs)
1321 ("ltx" . emacs)
1322 ("org" . emacs)
1323 ("el" . emacs)
1324 ("bib" . emacs)
1326 "External applications for opening `file:path' items in a document.
1327 Org-mode uses system defaults for different file types, but
1328 you can use this variable to set the application for a given file
1329 extension. The entries in this list are cons cells where the car identifies
1330 files and the cdr the corresponding command. Possible values for the
1331 file identifier are
1332 \"ext\" A string identifying an extension
1333 `directory' Matches a directory
1334 `remote' Matches a remote file, accessible through tramp or efs.
1335 Remote files most likely should be visited through Emacs
1336 because external applications cannot handle such paths.
1337 t Default for all remaining files
1339 Possible values for the command are:
1340 `emacs' The file will be visited by the current Emacs process.
1341 `default' Use the default application for this file type.
1342 string A command to be executed by a shell; %s will be replaced
1343 by the path to the file.
1344 sexp A Lisp form which will be evaluated. The file path will
1345 be available in the Lisp variable `file'.
1346 For more examples, see the system specific constants
1347 `org-file-apps-defaults-macosx'
1348 `org-file-apps-defaults-windowsnt'
1349 `org-file-apps-defaults-gnu'."
1350 :group 'org-link-follow
1351 :type '(repeat
1352 (cons (choice :value ""
1353 (string :tag "Extension")
1354 (const :tag "Default for unrecognized files" t)
1355 (const :tag "Remote file" remote)
1356 (const :tag "Links to a directory" directory))
1357 (choice :value ""
1358 (const :tag "Visit with Emacs" emacs)
1359 (const :tag "Use system default" default)
1360 (string :tag "Command")
1361 (sexp :tag "Lisp form")))))
1363 (defcustom org-mhe-search-all-folders nil
1364 "Non-nil means, that the search for the mh-message will be extended to
1365 all folders if the message cannot be found in the folder given in the link.
1366 Searching all folders is very efficient with one of the search engines
1367 supported by MH-E, but will be slow with pick."
1368 :group 'org-link-follow
1369 :type 'boolean)
1371 (defgroup org-remember nil
1372 "Options concerning interaction with remember.el."
1373 :tag "Org Remember"
1374 :group 'org)
1376 (defcustom org-directory "~/org"
1377 "Directory with org files.
1378 This directory will be used as default to prompt for org files.
1379 Used by the hooks for remember.el."
1380 :group 'org-remember
1381 :type 'directory)
1383 (defcustom org-default-notes-file "~/.notes"
1384 "Default target for storing notes.
1385 Used by the hooks for remember.el. This can be a string, or nil to mean
1386 the value of `remember-data-file'.
1387 You can set this on a per-template basis with the variable
1388 `org-remember-templates'."
1389 :group 'org-remember
1390 :type '(choice
1391 (const :tag "Default from remember-data-file" nil)
1392 file))
1394 (defcustom org-remember-store-without-prompt t
1395 "Non-nil means, `C-c C-c' stores remember note without further promts.
1396 In this case, you need `C-u C-c C-c' to get the prompts for
1397 note file and headline.
1398 When this variable is nil, `C-c C-c' give you the prompts, and
1399 `C-u C-c C-c' trigger the fasttrack."
1400 :group 'org-remember
1401 :type 'boolean)
1403 (defcustom org-remember-default-headline ""
1404 "The headline that should be the default location in the notes file.
1405 When filing remember notes, the cursor will start at that position.
1406 You can set this on a per-template basis with the variable
1407 `org-remember-templates'."
1408 :group 'org-remember
1409 :type 'string)
1411 (defcustom org-remember-templates nil
1412 "Templates for the creation of remember buffers.
1413 When nil, just let remember make the buffer.
1414 When not nil, this is a list of 4-element lists. In each entry, the first
1415 element is a character, a unique key to select this template.
1416 The second element is the template. The third element is optional and can
1417 specify a destination file for remember items created with this template.
1418 The default file is given by `org-default-notes-file'. An optional forth
1419 element can specify the headline in that file that should be offered
1420 first when the user is asked to file the entry. The default headline is
1421 given in the variable `org-remember-default-headline'.
1423 The template specifies the structure of the remember buffer. It should have
1424 a first line starting with a star, to act as the org-mode headline.
1425 Furthermore, the following %-escapes will be replaced with content:
1427 %^{prompt} prompt the user for a string and replace this sequence with it.
1428 %t time stamp, date only
1429 %T time stamp with date and time
1430 %u, %U like the above, but inactive time stamps
1431 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1432 You may define a prompt like %^{Please specify birthday}t
1433 %n user name (taken from `user-full-name')
1434 %a annotation, normally the link created with org-store-link
1435 %i initial content, the region when remember is called with C-u.
1436 If %i is indented, the entire inserted text will be indented
1437 as well.
1439 %? After completing the template, position cursor here.
1441 Apart from these general escapes, you can access information specific to the
1442 link type that is created. For example, calling `remember' in emails or gnus
1443 will record the author and the subject of the message, which you can access
1444 with %:author and %:subject, respectively. Here is a complete list of what
1445 is recorded for each link type.
1447 Link type | Available information
1448 -------------------+------------------------------------------------------
1449 bbdb | %:type %:name %:company
1450 vm, wl, mh, rmail | %:type %:subject %:message-id
1451 | %:from %:fromname %:fromaddress
1452 | %:to %:toname %:toaddress
1453 | %:fromto (either \"to NAME\" or \"from NAME\")
1454 gnus | %:group, for messages also all email fields
1455 w3, w3m | %:type %:url
1456 info | %:type %:file %:node
1457 calendar | %:type %:date"
1458 :group 'org-remember
1459 :get (lambda (var) ; Make sure all entries have 4 elements
1460 (mapcar (lambda (x)
1461 (cond ((= (length x) 3) (append x '("")))
1462 ((= (length x) 2) (append x '("" "")))
1463 (t x)))
1464 (default-value var)))
1465 :type '(repeat
1466 :tag "enabled"
1467 (list :value (?a "\n" nil nil)
1468 (character :tag "Selection Key")
1469 (string :tag "Template")
1470 (file :tag "Destination file (optional)")
1471 (string :tag "Destination headline (optional)"))))
1473 (defcustom org-reverse-note-order nil
1474 "Non-nil means, store new notes at the beginning of a file or entry.
1475 When nil, new notes will be filed to the end of a file or entry."
1476 :group 'org-remember
1477 :type '(choice
1478 (const :tag "Reverse always" t)
1479 (const :tag "Reverse never" nil)
1480 (repeat :tag "By file name regexp"
1481 (cons regexp boolean))))
1483 (defgroup org-todo nil
1484 "Options concerning TODO items in Org-mode."
1485 :tag "Org TODO"
1486 :group 'org)
1488 (defgroup org-progress nil
1489 "Options concerning Progress logging in Org-mode."
1490 :tag "Org Progress"
1491 :group 'org-time)
1493 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1494 "List of TODO entry keyword sequences and their interpretation.
1495 \\<org-mode-map>This is a list of sequences.
1497 Each sequence starts with a symbol, either `sequence' or `type',
1498 indicating if the keywords should be interpreted as a sequence of
1499 action steps, or as different types of TODO items. The first
1500 keywords are states requiring action - these states will select a headline
1501 for inclusion into the global TODO list Org-mode produces. If one of
1502 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1503 signify that no further action is necessary. If \"|\" is not found,
1504 the last keyword is treated as the only DONE state of the sequence.
1506 The command \\[org-todo] cycles an entry through these states, and one
1507 additional state where no keyword is present. For details about this
1508 cycling, see the manual.
1510 TODO keywords and interpretation can also be set on a per-file basis with
1511 the special #+SEQ_TODO and #+TYP_TODO lines.
1513 For backward compatibility, this variable may also be just a list
1514 of keywords - in this case the interptetation (sequence or type) will be
1515 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1516 :group 'org-todo
1517 :group 'org-keywords
1518 :type '(choice
1519 (repeat :tag "Old syntax, just keywords"
1520 (string :tag "Keyword"))
1521 (repeat :tag "New syntax"
1522 (cons
1523 (choice
1524 :tag "Interpretation"
1525 (const :tag "Sequence (cycling hits every state)" sequence)
1526 (const :tag "Type (cycling directly to DONE)" type))
1527 (repeat
1528 (string :tag "Keyword"))))))
1530 (defvar org-todo-keywords-1 nil)
1531 (make-variable-buffer-local 'org-todo-keywords-1)
1532 (defvar org-todo-keywords-for-agenda nil)
1533 (defvar org-done-keywords-for-agenda nil)
1534 (defvar org-not-done-keywords nil)
1535 (make-variable-buffer-local 'org-not-done-keywords)
1536 (defvar org-done-keywords nil)
1537 (make-variable-buffer-local 'org-done-keywords)
1538 (defvar org-todo-heads nil)
1539 (make-variable-buffer-local 'org-todo-heads)
1540 (defvar org-todo-sets nil)
1541 (make-variable-buffer-local 'org-todo-sets)
1542 (defvar org-todo-log-states nil)
1543 (make-variable-buffer-local 'org-todo-log-states)
1544 (defvar org-todo-kwd-alist nil)
1545 (make-variable-buffer-local 'org-todo-kwd-alist)
1546 (defvar org-todo-key-alist nil)
1547 (make-variable-buffer-local 'org-todo-key-alist)
1548 (defvar org-todo-key-trigger nil)
1549 (make-variable-buffer-local 'org-todo-key-trigger)
1551 (defcustom org-todo-interpretation 'sequence
1552 "Controls how TODO keywords are interpreted.
1553 This variable is in principle obsolete and is only used for
1554 backward compatibility, if the interpretation of todo keywords is
1555 not given already in `org-todo-keywords'. See that variable for
1556 more information."
1557 :group 'org-todo
1558 :group 'org-keywords
1559 :type '(choice (const sequence)
1560 (const type)))
1562 (defcustom org-use-fast-todo-selection 'prefix
1563 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1564 This variable describes if and under what circumstances the cycling
1565 mechanism for TODO keywords will be replaced by a single-key, direct
1566 selection scheme.
1568 When nil, fast selection is never used.
1570 When the symbol `prefix', it will be used when `org-todo' is called with
1571 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1572 in an agenda buffer.
1574 When t, fast selection is used by default. In this case, the prefix
1575 argument forces cycling instead.
1577 In all cases, the special interface is only used if access keys have actually
1578 been assigned by the user, i.e. if keywords in the configuration are followed
1579 by a letter in parenthesis, like TODO(t)."
1580 :group 'org-todo
1581 :type '(choice
1582 (const :tag "Never" nil)
1583 (const :tag "By default" t)
1584 (const :tag "Only with C-u C-c C-t" prefix)))
1586 (defcustom org-after-todo-state-change-hook nil
1587 "Hook which is run after the state of a TODO item was changed.
1588 The new state (a string with a TODO keyword, or nil) is available in the
1589 Lisp variable `state'."
1590 :group 'org-todo
1591 :type 'hook)
1593 (defcustom org-log-done nil
1594 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1595 When the state of an entry is changed from nothing or a DONE state to
1596 a not-done TODO state, remove a previous closing date.
1598 This can also be a list of symbols indicating under which conditions
1599 the time stamp recording the action should be annotated with a short note.
1600 Valid members of this list are
1602 done Offer to record a note when marking entries done
1603 state Offer to record a note whenever changing the TODO state
1604 of an item. This is only relevant if TODO keywords are
1605 interpreted as sequence, see variable `org-todo-interpretation'.
1606 When `state' is set, this includes tracking `done'.
1607 clock-out Offer to record a note when clocking out of an item.
1609 A separate window will then pop up and allow you to type a note.
1610 After finishing with C-c C-c, the note will be added directly after the
1611 timestamp, as a plain list item. See also the variable
1612 `org-log-note-headings'.
1614 Logging can also be configured on a per-file basis by adding one of
1615 the following lines anywhere in the buffer:
1617 #+STARTUP: logdone
1618 #+STARTUP: nologging
1619 #+STARTUP: lognotedone
1620 #+STARTUP: lognotestate
1621 #+STARTUP: lognoteclock-out
1623 You can have local logging settings for a subtree by setting the LOGGING
1624 property to one or more of these keywords."
1625 :group 'org-todo
1626 :group 'org-progress
1627 :type '(choice
1628 (const :tag "off" nil)
1629 (const :tag "on" t)
1630 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1631 (const :tag "when item is marked DONE" done)
1632 (const :tag "when TODO state changes" state)
1633 (const :tag "when clocking out" clock-out))))
1635 (defcustom org-log-done-with-time t
1636 "Non-nil means, the CLOSED time stamp will contain date and time.
1637 When nil, only the date will be recorded."
1638 :group 'org-progress
1639 :type 'boolean)
1641 (defcustom org-log-note-headings
1642 '((done . "CLOSING NOTE %t")
1643 (state . "State %-12s %t")
1644 (clock-out . ""))
1645 "Headings for notes added when clocking out or closing TODO items.
1646 The value is an alist, with the car being a symbol indicating the note
1647 context, and the cdr is the heading to be used. The heading may also be the
1648 empty string.
1649 %t in the heading will be replaced by a time stamp.
1650 %s will be replaced by the new TODO state, in double quotes.
1651 %u will be replaced by the user name.
1652 %U will be replaced by the full user name."
1653 :group 'org-todo
1654 :group 'org-progress
1655 :type '(list :greedy t
1656 (cons (const :tag "Heading when closing an item" done) string)
1657 (cons (const :tag
1658 "Heading when changing todo state (todo sequence only)"
1659 state) string)
1660 (cons (const :tag "Heading when clocking out" clock-out) string)))
1662 (defcustom org-log-states-order-reversed t
1663 "Non-nil means, the latest state change note will be directly after heading.
1664 When nil, the notes will be orderer according to time."
1665 :group 'org-todo
1666 :group 'org-progress
1667 :type 'boolean)
1669 (defcustom org-log-repeat t
1670 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1671 When nil, no note will be taken.
1672 This option can also be set with on a per-file-basis with
1674 #+STARTUP: logrepeat
1675 #+STARTUP: nologrepeat
1677 You can have local logging settings for a subtree by setting the LOGGING
1678 property to one or more of these keywords."
1679 :group 'org-todo
1680 :group 'org-progress
1681 :type 'boolean)
1683 (defcustom org-clock-into-drawer 2
1684 "Should clocking info be wrapped into a drawer?
1685 When t, clocking info will always be inserted into a :CLOCK: drawer.
1686 If necessary, the drawer will be created.
1687 When nil, the drawer will not be created, but used when present.
1688 When an integer and the number of clocking entries in an item
1689 reaches or exceeds this number, a drawer will be created."
1690 :group 'org-todo
1691 :group 'org-progress
1692 :type '(choice
1693 (const :tag "Always" t)
1694 (const :tag "Only when drawer exists" nil)
1695 (integer :tag "When at least N clock entries")))
1697 (defcustom org-clock-out-when-done t
1698 "When t, the clock will be stopped when the relevant entry is marked DONE.
1699 Nil means, clock will keep running until stopped explicitly with
1700 `C-c C-x C-o', or until the clock is started in a different item."
1701 :group 'org-progress
1702 :type 'boolean)
1704 (defgroup org-priorities nil
1705 "Priorities in Org-mode."
1706 :tag "Org Priorities"
1707 :group 'org-todo)
1709 (defcustom org-highest-priority ?A
1710 "The highest priority of TODO items. A character like ?A, ?B etc.
1711 Must have a smaller ASCII number than `org-lowest-priority'."
1712 :group 'org-priorities
1713 :type 'character)
1715 (defcustom org-lowest-priority ?C
1716 "The lowest priority of TODO items. A character like ?A, ?B etc.
1717 Must have a larger ASCII number than `org-highest-priority'."
1718 :group 'org-priorities
1719 :type 'character)
1721 (defcustom org-default-priority ?B
1722 "The default priority of TODO items.
1723 This is the priority an item get if no explicit priority is given."
1724 :group 'org-priorities
1725 :type 'character)
1727 (defcustom org-priority-start-cycle-with-default t
1728 "Non-nil means, start with default priority when starting to cycle.
1729 When this is nil, the first step in the cycle will be (depending on the
1730 command used) one higher or lower that the default priority."
1731 :group 'org-priorities
1732 :type 'boolean)
1734 (defgroup org-time nil
1735 "Options concerning time stamps and deadlines in Org-mode."
1736 :tag "Org Time"
1737 :group 'org)
1739 (defcustom org-insert-labeled-timestamps-at-point nil
1740 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1741 When nil, these labeled time stamps are forces into the second line of an
1742 entry, just after the headline. When scheduling from the global TODO list,
1743 the time stamp will always be forced into the second line."
1744 :group 'org-time
1745 :type 'boolean)
1747 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1748 "Formats for `format-time-string' which are used for time stamps.
1749 It is not recommended to change this constant.")
1751 (defcustom org-time-stamp-rounding-minutes 0
1752 "Number of minutes to round time stamps to upon insertion.
1753 When zero, insert the time unmodified. Useful rounding numbers
1754 should be factors of 60, so for example 5, 10, 15.
1755 When this is not zero, you can still force an exact time-stamp by using
1756 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1757 :group 'org-time
1758 :type 'integer)
1760 (defcustom org-display-custom-times nil
1761 "Non-nil means, overlay custom formats over all time stamps.
1762 The formats are defined through the variable `org-time-stamp-custom-formats'.
1763 To turn this on on a per-file basis, insert anywhere in the file:
1764 #+STARTUP: customtime"
1765 :group 'org-time
1766 :set 'set-default
1767 :type 'sexp)
1768 (make-variable-buffer-local 'org-display-custom-times)
1770 (defcustom org-time-stamp-custom-formats
1771 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1772 "Custom formats for time stamps. See `format-time-string' for the syntax.
1773 These are overlayed over the default ISO format if the variable
1774 `org-display-custom-times' is set. Time like %H:%M should be at the
1775 end of the second format."
1776 :group 'org-time
1777 :type 'sexp)
1779 (defun org-time-stamp-format (&optional long inactive)
1780 "Get the right format for a time string."
1781 (let ((f (if long (cdr org-time-stamp-formats)
1782 (car org-time-stamp-formats))))
1783 (if inactive
1784 (concat "[" (substring f 1 -1) "]")
1785 f)))
1787 (defcustom org-deadline-warning-days 14
1788 "No. of days before expiration during which a deadline becomes active.
1789 This variable governs the display in sparse trees and in the agenda.
1790 When negative, it means use this number (the absolute value of it)
1791 even if a deadline has a different individual lead time specified."
1792 :group 'org-time
1793 :type 'number)
1795 (defcustom org-popup-calendar-for-date-prompt t
1796 "Non-nil means, pop up a calendar when prompting for a date.
1797 In the calendar, the date can be selected with mouse-1. However, the
1798 minibuffer will also be active, and you can simply enter the date as well.
1799 When nil, only the minibuffer will be available."
1800 :group 'org-time
1801 :type 'boolean)
1803 (defcustom org-edit-timestamp-down-means-later nil
1804 "Non-nil means, S-down will increase the time in a time stamp.
1805 When nil, S-up will increase."
1806 :group 'org-time
1807 :type 'boolean)
1809 (defcustom org-calendar-follow-timestamp-change t
1810 "Non-nil means, make the calendar window follow timestamp changes.
1811 When a timestamp is modified and the calendar window is visible, it will be
1812 moved to the new date."
1813 :group 'org-time
1814 :type 'boolean)
1816 (defgroup org-tags nil
1817 "Options concerning tags in Org-mode."
1818 :tag "Org Tags"
1819 :group 'org)
1821 (defcustom org-tag-alist nil
1822 "List of tags allowed in Org-mode files.
1823 When this list is nil, Org-mode will base TAG input on what is already in the
1824 buffer.
1825 The value of this variable is an alist, the car of each entry must be a
1826 keyword as a string, the cdr may be a character that is used to select
1827 that tag through the fast-tag-selection interface.
1828 See the manual for details."
1829 :group 'org-tags
1830 :type '(repeat
1831 (choice
1832 (cons (string :tag "Tag name")
1833 (character :tag "Access char"))
1834 (const :tag "Start radio group" (:startgroup))
1835 (const :tag "End radio group" (:endgroup)))))
1837 (defcustom org-use-fast-tag-selection 'auto
1838 "Non-nil means, use fast tag selection scheme.
1839 This is a special interface to select and deselect tags with single keys.
1840 When nil, fast selection is never used.
1841 When the symbol `auto', fast selection is used if and only if selection
1842 characters for tags have been configured, either through the variable
1843 `org-tag-alist' or through a #+TAGS line in the buffer.
1844 When t, fast selection is always used and selection keys are assigned
1845 automatically if necessary."
1846 :group 'org-tags
1847 :type '(choice
1848 (const :tag "Always" t)
1849 (const :tag "Never" nil)
1850 (const :tag "When selection characters are configured" 'auto)))
1852 (defcustom org-fast-tag-selection-single-key nil
1853 "Non-nil means, fast tag selection exits after first change.
1854 When nil, you have to press RET to exit it.
1855 During fast tag selection, you can toggle this flag with `C-c'.
1856 This variable can also have the value `expert'. In this case, the window
1857 displaying the tags menu is not even shown, until you press C-c again."
1858 :group 'org-tags
1859 :type '(choice
1860 (const :tag "No" nil)
1861 (const :tag "Yes" t)
1862 (const :tag "Expert" expert)))
1864 (defvar org-fast-tag-selection-include-todo nil
1865 "Non-nil means, fast tags selection interface will also offer TODO states.
1866 This is an undocumented feature, you should not rely on it.")
1868 (defcustom org-tags-column -80
1869 "The column to which tags should be indented in a headline.
1870 If this number is positive, it specifies the column. If it is negative,
1871 it means that the tags should be flushright to that column. For example,
1872 -80 works well for a normal 80 character screen."
1873 :group 'org-tags
1874 :type 'integer)
1876 (defcustom org-auto-align-tags t
1877 "Non-nil means, realign tags after pro/demotion of TODO state change.
1878 These operations change the length of a headline and therefore shift
1879 the tags around. With this options turned on, after each such operation
1880 the tags are again aligned to `org-tags-column'."
1881 :group 'org-tags
1882 :type 'boolean)
1884 (defcustom org-use-tag-inheritance t
1885 "Non-nil means, tags in levels apply also for sublevels.
1886 When nil, only the tags directly given in a specific line apply there.
1887 If you turn off this option, you very likely want to turn on the
1888 companion option `org-tags-match-list-sublevels'."
1889 :group 'org-tags
1890 :type 'boolean)
1892 (defcustom org-tags-match-list-sublevels nil
1893 "Non-nil means list also sublevels of headlines matching tag search.
1894 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1895 the sublevels of a headline matching a tag search often also match
1896 the same search. Listing all of them can create very long lists.
1897 Setting this variable to nil causes subtrees of a match to be skipped.
1898 This option is off by default, because inheritance in on. If you turn
1899 inheritance off, you very likely want to turn this option on.
1901 As a special case, if the tag search is restricted to TODO items, the
1902 value of this variable is ignored and sublevels are always checked, to
1903 make sure all corresponding TODO items find their way into the list."
1904 :group 'org-tags
1905 :type 'boolean)
1907 (defvar org-tags-history nil
1908 "History of minibuffer reads for tags.")
1909 (defvar org-last-tags-completion-table nil
1910 "The last used completion table for tags.")
1911 (defvar org-after-tags-change-hook nil
1912 "Hook that is run after the tags in a line have changed.")
1914 (defgroup org-properties nil
1915 "Options concerning properties in Org-mode."
1916 :tag "Org Properties"
1917 :group 'org)
1919 (defcustom org-property-format "%-10s %s"
1920 "How property key/value pairs should be formatted by `indent-line'.
1921 When `indent-line' hits a property definition, it will format the line
1922 according to this format, mainly to make sure that the values are
1923 lined-up with respect to each other."
1924 :group 'org-properties
1925 :type 'string)
1927 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1928 "The default column format, if no other format has been defined.
1929 This variable can be set on the per-file basis by inserting a line
1931 #+COLUMNS: %25ITEM ....."
1932 :group 'org-properties
1933 :type 'string)
1935 (defcustom org-global-properties nil
1936 "List of property/value pairs that can be inherited by any entry.
1937 You can set buffer-local values for this by adding lines like
1939 #+PROPERTY: NAME VALUE"
1940 :group 'org-properties
1941 :type '(repeat
1942 (cons (string :tag "Property")
1943 (string :tag "Value"))))
1945 (defvar org-local-properties nil
1946 "List of property/value pairs that can be inherited by any entry.
1947 Valid for the current buffer.
1948 This variable is populated from #+PROPERTY lines.")
1950 (defgroup org-agenda nil
1951 "Options concerning agenda views in Org-mode."
1952 :tag "Org Agenda"
1953 :group 'org)
1955 (defvar org-category nil
1956 "Variable used by org files to set a category for agenda display.
1957 Such files should use a file variable to set it, for example
1959 # -*- mode: org; org-category: \"ELisp\"
1961 or contain a special line
1963 #+CATEGORY: ELisp
1965 If the file does not specify a category, then file's base name
1966 is used instead.")
1967 (make-variable-buffer-local 'org-category)
1969 (defcustom org-agenda-files nil
1970 "The files to be used for agenda display.
1971 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1972 \\[org-remove-file]. You can also use customize to edit the list.
1974 If the value of the variable is not a list but a single file name, then
1975 the list of agenda files is actually stored and maintained in that file, one
1976 agenda file per line."
1977 :group 'org-agenda
1978 :type '(choice
1979 (repeat :tag "List of files" file)
1980 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1982 (defcustom org-agenda-skip-unavailable-files nil
1983 "t means to just skip non-reachable files in `org-agenda-files'.
1984 Nil means to remove them, after a query, from the list."
1985 :group 'org-agenda
1986 :type 'boolean)
1988 (defcustom org-agenda-confirm-kill 1
1989 "When set, remote killing from the agenda buffer needs confirmation.
1990 When t, a confirmation is always needed. When a number N, confirmation is
1991 only needed when the text to be killed contains more than N non-white lines."
1992 :group 'org-agenda
1993 :type '(choice
1994 (const :tag "Never" nil)
1995 (const :tag "Always" t)
1996 (number :tag "When more than N lines")))
1998 (defcustom org-calendar-to-agenda-key [?c]
1999 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2000 The command `org-calendar-goto-agenda' will be bound to this key. The
2001 default is the character `c' because then `c' can be used to switch back and
2002 forth between agenda and calendar."
2003 :group 'org-agenda
2004 :type 'sexp)
2006 (defcustom org-agenda-compact-blocks nil
2007 "Non-nil means, make the block agenda more compact.
2008 This is done by leaving out unnecessary lines."
2009 :group 'org-agenda
2010 :type nil)
2012 (defgroup org-agenda-export nil
2013 "Options concerning exporting agenda views in Org-mode."
2014 :tag "Org Agenda Export"
2015 :group 'org-agenda)
2017 (defcustom org-agenda-with-colors t
2018 "Non-nil means, use colors in agenda views."
2019 :group 'org-agenda-export
2020 :type 'boolean)
2022 (defcustom org-agenda-exporter-settings nil
2023 "Alist of variable/value pairs that should be active during agenda export.
2024 This is a good place to set uptions for ps-print and for htmlize."
2025 :group 'org-agenda-export
2026 :type '(repeat
2027 (list
2028 (variable)
2029 (sexp :tag "Value"))))
2031 (defcustom org-agenda-export-html-style ""
2032 "The style specification for exported HTML Agenda files.
2033 If this variable contains a string, it will replace the default <style>
2034 section as produced by `htmlize'.
2035 Since there are different ways of setting style information, this variable
2036 needs to contain the full HTML structure to provide a style, including the
2037 surrounding HTML tags. The style specifications should include definitions
2038 the fonts used by the agenda, here is an example:
2040 <style type=\"text/css\">
2041 p { font-weight: normal; color: gray; }
2042 .org-agenda-structure {
2043 font-size: 110%;
2044 color: #003399;
2045 font-weight: 600;
2047 .org-todo {
2048 color: #cc6666;Week-agenda:
2049 font-weight: bold;
2051 .org-done {
2052 color: #339933;
2054 .title { text-align: center; }
2055 .todo, .deadline { color: red; }
2056 .done { color: green; }
2057 </style>
2059 or, if you want to keep the style in a file,
2061 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2063 As the value of this option simply gets inserted into the HTML <head> header,
2064 you can \"misuse\" it to also add other text to the header. However,
2065 <style>...</style> is required, if not present the variable will be ignored."
2066 :group 'org-agenda-export
2067 :group 'org-export-html
2068 :type 'string)
2070 (defgroup org-agenda-custom-commands nil
2071 "Options concerning agenda views in Org-mode."
2072 :tag "Org Agenda Custom Commands"
2073 :group 'org-agenda)
2075 (defcustom org-agenda-custom-commands nil
2076 "Custom commands for the agenda.
2077 These commands will be offered on the splash screen displayed by the
2078 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2080 (key type match options files)
2082 key The key (a single char as a string) to be associated with the command.
2083 type The command type, any of the following symbols:
2084 todo Entries with a specific TODO keyword, in all agenda files.
2085 tags Tags match in all agenda files.
2086 tags-todo Tags match in all agenda files, TODO entries only.
2087 todo-tree Sparse tree of specific TODO keyword in *current* file.
2088 tags-tree Sparse tree with all tags matches in *current* file.
2089 occur-tree Occur sparse tree for *current* file.
2090 match What to search for:
2091 - a single keyword for TODO keyword searches
2092 - a tags match expression for tags searches
2093 - a regular expression for occur searches
2094 options A list of option settings, similar to that in a let form, so like
2095 this: ((opt1 val1) (opt2 val2) ...)
2096 files A list of files file to write the produced agenda buffer to
2097 with the command `org-store-agenda-views'.
2098 If a file name ends in \".html\", an HTML version of the buffer
2099 is written out. If it ends in \".ps\", a postscript version is
2100 produced. Otherwide, only the plain text is written to the file.
2102 You can also define a set of commands, to create a composite agenda buffer.
2103 In this case, an entry looks like this:
2105 (key desc (cmd1 cmd2 ...) general-options file)
2107 where
2109 desc A description string to be displayed in the dispatcher menu.
2110 cmd An agenda command, similar to the above. However, tree commands
2111 are no allowed, but instead you can get agenda and global todo list.
2112 So valid commands for a set are:
2113 (agenda)
2114 (alltodo)
2115 (stuck)
2116 (todo \"match\" options files)
2117 (tags \"match\" options files)
2118 (tags-todo \"match\" options files)
2120 Each command can carry a list of options, and another set of options can be
2121 given for the whole set of commands. Individual command options take
2122 precedence over the general options."
2123 :group 'org-agenda-custom-commands
2124 :type '(repeat
2125 (choice :value ("a" tags "" nil)
2126 (list :tag "Single command"
2127 (string :tag "Key")
2128 (choice
2129 (const :tag "Agenda" agenda)
2130 (const :tag "TODO list" alltodo)
2131 (const :tag "Stuck projects" stuck)
2132 (const :tag "Tags search (all agenda files)" tags)
2133 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2134 (const :tag "TODO keyword search (all agenda files)" todo)
2135 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2136 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2137 (const :tag "Occur tree (current buffer)" occur-tree)
2138 (symbol :tag "Other, user-defined function"))
2139 (string :tag "Match")
2140 (repeat :tag "Local options"
2141 (list (variable :tag "Option") (sexp :tag "Value")))
2142 (option (repeat :tag "Export" (file :tag "Export to"))))
2143 (list :tag "Command series, all agenda files"
2144 (string :tag "Key")
2145 (string :tag "Description")
2146 (repeat
2147 (choice
2148 (const :tag "Agenda" (agenda))
2149 (const :tag "TODO list" (alltodo))
2150 (const :tag "Stuck projects" (stuck))
2151 (list :tag "Tags search"
2152 (const :format "" tags)
2153 (string :tag "Match")
2154 (repeat :tag "Local options"
2155 (list (variable :tag "Option")
2156 (sexp :tag "Value"))))
2158 (list :tag "Tags search, TODO entries only"
2159 (const :format "" tags-todo)
2160 (string :tag "Match")
2161 (repeat :tag "Local options"
2162 (list (variable :tag "Option")
2163 (sexp :tag "Value"))))
2165 (list :tag "TODO keyword search"
2166 (const :format "" todo)
2167 (string :tag "Match")
2168 (repeat :tag "Local options"
2169 (list (variable :tag "Option")
2170 (sexp :tag "Value"))))
2172 (list :tag "Other, user-defined function"
2173 (symbol :tag "function")
2174 (string :tag "Match")
2175 (repeat :tag "Local options"
2176 (list (variable :tag "Option")
2177 (sexp :tag "Value"))))))
2179 (repeat :tag "General options"
2180 (list (variable :tag "Option")
2181 (sexp :tag "Value")))
2182 (option (repeat :tag "Export" (file :tag "Export to")))))))
2184 (defcustom org-stuck-projects
2185 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2186 "How to identify stuck projects.
2187 This is a list of four items:
2188 1. A tags/todo matcher string that is used to identify a project.
2189 The entire tree below a headline matched by this is considered one project.
2190 2. A list of TODO keywords identifying non-stuck projects.
2191 If the project subtree contains any headline with one of these todo
2192 keywords, the project is considered to be not stuck. If you specify
2193 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2194 3. A list of tags identifying non-stuck projects.
2195 If the project subtree contains any headline with one of these tags,
2196 the project is considered to be not stuck. If you specify \"*\" as
2197 a tag, any tag will mark the project unstuck.
2198 4. An arbitrary regular expression matching non-stuck projects.
2200 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2201 or `C-c a #' to produce the list."
2202 :group 'org-agenda-custom-commands
2203 :type '(list
2204 (string :tag "Tags/TODO match to identify a project")
2205 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2206 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2207 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2210 (defgroup org-agenda-skip nil
2211 "Options concerning skipping parts of agenda files."
2212 :tag "Org Agenda Skip"
2213 :group 'org-agenda)
2215 (defcustom org-agenda-todo-list-sublevels t
2216 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2217 When nil, the sublevels of a TODO entry are not checked, resulting in
2218 potentially much shorter TODO lists."
2219 :group 'org-agenda-skip
2220 :group 'org-todo
2221 :type 'boolean)
2223 (defcustom org-agenda-todo-ignore-scheduled nil
2224 "Non-nil means, don't show scheduled entries in the global todo list.
2225 The idea behind this is that by scheduling it, you have already taken care
2226 of this item."
2227 :group 'org-agenda-skip
2228 :group 'org-todo
2229 :type 'boolean)
2231 (defcustom org-agenda-todo-ignore-deadlines nil
2232 "Non-nil means, don't show near deadline entries in the global todo list.
2233 Near means closer than `org-deadline-warning-days' days.
2234 The idea behind this is that such items will appear in the agenda anyway."
2235 :group 'org-agenda-skip
2236 :group 'org-todo
2237 :type 'boolean)
2239 (defcustom org-agenda-skip-scheduled-if-done nil
2240 "Non-nil means don't show scheduled items in agenda when they are done.
2241 This is relevant for the daily/weekly agenda, not for the TODO list. And
2242 it applies only to the actual date of the scheduling. Warnings about
2243 an item with a past scheduling dates are always turned off when the item
2244 is DONE."
2245 :group 'org-agenda-skip
2246 :type 'boolean)
2248 (defcustom org-agenda-skip-deadline-if-done nil
2249 "Non-nil means don't show deadines when the corresponding item is done.
2250 When nil, the deadline is still shown and should give you a happy feeling.
2251 This is relevant for the daily/weekly agenda. And it applied only to the
2252 actualy date of the deadline. Warnings about approching and past-due
2253 deadlines are always turned off when the item is DONE."
2254 :group 'org-agenda-skip
2255 :type 'boolean)
2257 (defcustom org-timeline-show-empty-dates 3
2258 "Non-nil means, `org-timeline' also shows dates without an entry.
2259 When nil, only the days which actually have entries are shown.
2260 When t, all days between the first and the last date are shown.
2261 When an integer, show also empty dates, but if there is a gap of more than
2262 N days, just insert a special line indicating the size of the gap."
2263 :group 'org-agenda-skip
2264 :type '(choice
2265 (const :tag "None" nil)
2266 (const :tag "All" t)
2267 (number :tag "at most")))
2270 (defgroup org-agenda-startup nil
2271 "Options concerning initial settings in the Agenda in Org Mode."
2272 :tag "Org Agenda Startup"
2273 :group 'org-agenda)
2275 (defcustom org-finalize-agenda-hook nil
2276 "Hook run just before displaying an agenda buffer."
2277 :group 'org-agenda-startup
2278 :type 'hook)
2280 (defcustom org-agenda-mouse-1-follows-link nil
2281 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2282 A longer mouse click will still set point. Does not wortk on XEmacs.
2283 Needs to be set before org.el is loaded."
2284 :group 'org-agenda-startup
2285 :type 'boolean)
2287 (defcustom org-agenda-start-with-follow-mode nil
2288 "The initial value of follow-mode in a newly created agenda window."
2289 :group 'org-agenda-startup
2290 :type 'boolean)
2292 (defgroup org-agenda-windows nil
2293 "Options concerning the windows used by the Agenda in Org Mode."
2294 :tag "Org Agenda Windows"
2295 :group 'org-agenda)
2297 (defcustom org-agenda-window-setup 'reorganize-frame
2298 "How the agenda buffer should be displayed.
2299 Possible values for this option are:
2301 current-window Show agenda in the current window, keeping all other windows.
2302 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2303 other-window Use `switch-to-buffer-other-window' to display agenda.
2304 reorganize-frame Show only two windows on the current frame, the current
2305 window and the agenda.
2306 See also the variable `org-agenda-restore-windows-after-quit'."
2307 :group 'org-agenda-windows
2308 :type '(choice
2309 (const current-window)
2310 (const other-frame)
2311 (const other-window)
2312 (const reorganize-frame)))
2314 (defcustom org-agenda-restore-windows-after-quit nil
2315 "Non-nil means, restore window configuration open exiting agenda.
2316 Before the window configuration is changed for displaying the agenda,
2317 the current status is recorded. When the agenda is exited with
2318 `q' or `x' and this option is set, the old state is restored. If
2319 `org-agenda-window-setup' is `other-frame', the value of this
2320 option will be ignored.."
2321 :group 'org-agenda-windows
2322 :type 'boolean)
2324 (defcustom org-indirect-buffer-display 'other-window
2325 "How should indirect tree buffers be displayed?
2326 This applies to indirect buffers created with the commands
2327 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2328 Valid values are:
2329 current-window Display in the current window
2330 other-window Just display in another window.
2331 dedicated-frame Create one new frame, and re-use it each time.
2332 new-frame Make a new frame each time."
2333 :group 'org-structure
2334 :group 'org-agenda-windows
2335 :type '(choice
2336 (const :tag "In current window" current-window)
2337 (const :tag "In current frame, other window" other-window)
2338 (const :tag "Each time a new frame" new-frame)
2339 (const :tag "One dedicated frame" dedicated-frame)))
2341 (defgroup org-agenda-daily/weekly nil
2342 "Options concerning the daily/weekly agenda."
2343 :tag "Org Agenda Daily/Weekly"
2344 :group 'org-agenda)
2346 (defcustom org-agenda-ndays 7
2347 "Number of days to include in overview display.
2348 Should be 1 or 7."
2349 :group 'org-agenda-daily/weekly
2350 :type 'number)
2352 (defcustom org-agenda-start-on-weekday 1
2353 "Non-nil means, start the overview always on the specified weekday.
2354 0 denotes Sunday, 1 denotes Monday etc.
2355 When nil, always start on the current day."
2356 :group 'org-agenda-daily/weekly
2357 :type '(choice (const :tag "Today" nil)
2358 (number :tag "Weekday No.")))
2360 (defcustom org-agenda-show-all-dates t
2361 "Non-nil means, `org-agenda' shows every day in the selected range.
2362 When nil, only the days which actually have entries are shown."
2363 :group 'org-agenda-daily/weekly
2364 :type 'boolean)
2366 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2367 "Format string for displaying dates in the agenda.
2368 Used by the daily/weekly agenda and by the timeline. This should be
2369 a format string understood by `format-time-string', or a function returning
2370 the formatted date as a string. The function must take a single argument,
2371 a calendar-style date list like (month day year)."
2372 :group 'org-agenda-daily/weekly
2373 :type '(choice
2374 (string :tag "Format string")
2375 (function :tag "Function")))
2377 (defun org-agenda-format-date-aligned (date)
2378 "Format a date string for display in the daily/weekly agenda, or timeline.
2379 This function makes sure that dates are aligned for easy reading."
2380 (format "%-9s %2d %s %4d"
2381 (calendar-day-name date)
2382 (extract-calendar-day date)
2383 (calendar-month-name (extract-calendar-month date))
2384 (extract-calendar-year date)))
2386 (defcustom org-agenda-include-diary nil
2387 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2388 :group 'org-agenda-daily/weekly
2389 :type 'boolean)
2391 (defcustom org-agenda-include-all-todo nil
2392 "Set means weekly/daily agenda will always contain all TODO entries.
2393 The TODO entries will be listed at the top of the agenda, before
2394 the entries for specific days."
2395 :group 'org-agenda-daily/weekly
2396 :type 'boolean)
2398 (defcustom org-agenda-repeating-timestamp-show-all t
2399 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2400 When nil, only one occurence is shown, either today or the
2401 nearest into the future."
2402 :group 'org-agenda-daily/weekly
2403 :type 'boolean)
2405 (defgroup org-agenda-time-grid nil
2406 "Options concerning the time grid in the Org-mode Agenda."
2407 :tag "Org Agenda Time Grid"
2408 :group 'org-agenda)
2410 (defcustom org-agenda-use-time-grid t
2411 "Non-nil means, show a time grid in the agenda schedule.
2412 A time grid is a set of lines for specific times (like every two hours between
2413 8:00 and 20:00). The items scheduled for a day at specific times are
2414 sorted in between these lines.
2415 For details about when the grid will be shown, and what it will look like, see
2416 the variable `org-agenda-time-grid'."
2417 :group 'org-agenda-time-grid
2418 :type 'boolean)
2420 (defcustom org-agenda-time-grid
2421 '((daily today require-timed)
2422 "----------------"
2423 (800 1000 1200 1400 1600 1800 2000))
2425 "The settings for time grid for agenda display.
2426 This is a list of three items. The first item is again a list. It contains
2427 symbols specifying conditions when the grid should be displayed:
2429 daily if the agenda shows a single day
2430 weekly if the agenda shows an entire week
2431 today show grid on current date, independent of daily/weekly display
2432 require-timed show grid only if at least one item has a time specification
2434 The second item is a string which will be places behing the grid time.
2436 The third item is a list of integers, indicating the times that should have
2437 a grid line."
2438 :group 'org-agenda-time-grid
2439 :type
2440 '(list
2441 (set :greedy t :tag "Grid Display Options"
2442 (const :tag "Show grid in single day agenda display" daily)
2443 (const :tag "Show grid in weekly agenda display" weekly)
2444 (const :tag "Always show grid for today" today)
2445 (const :tag "Show grid only if any timed entries are present"
2446 require-timed)
2447 (const :tag "Skip grid times already present in an entry"
2448 remove-match))
2449 (string :tag "Grid String")
2450 (repeat :tag "Grid Times" (integer :tag "Time"))))
2452 (defgroup org-agenda-sorting nil
2453 "Options concerning sorting in the Org-mode Agenda."
2454 :tag "Org Agenda Sorting"
2455 :group 'org-agenda)
2457 (let ((sorting-choice
2458 '(choice
2459 (const time-up) (const time-down)
2460 (const category-keep) (const category-up) (const category-down)
2461 (const tag-down) (const tag-up)
2462 (const priority-up) (const priority-down))))
2464 (defcustom org-agenda-sorting-strategy
2465 '((agenda time-up category-keep priority-down)
2466 (todo category-keep priority-down)
2467 (tags category-keep priority-down))
2468 "Sorting structure for the agenda items of a single day.
2469 This is a list of symbols which will be used in sequence to determine
2470 if an entry should be listed before another entry. The following
2471 symbols are recognized:
2473 time-up Put entries with time-of-day indications first, early first
2474 time-down Put entries with time-of-day indications first, late first
2475 category-keep Keep the default order of categories, corresponding to the
2476 sequence in `org-agenda-files'.
2477 category-up Sort alphabetically by category, A-Z.
2478 category-down Sort alphabetically by category, Z-A.
2479 tag-up Sort alphabetically by last tag, A-Z.
2480 tag-down Sort alphabetically by last tag, Z-A.
2481 priority-up Sort numerically by priority, high priority last.
2482 priority-down Sort numerically by priority, high priority first.
2484 The different possibilities will be tried in sequence, and testing stops
2485 if one comparison returns a \"not-equal\". For example, the default
2486 '(time-up category-keep priority-down)
2487 means: Pull out all entries having a specified time of day and sort them,
2488 in order to make a time schedule for the current day the first thing in the
2489 agenda listing for the day. Of the entries without a time indication, keep
2490 the grouped in categories, don't sort the categories, but keep them in
2491 the sequence given in `org-agenda-files'. Within each category sort by
2492 priority.
2494 Leaving out `category-keep' would mean that items will be sorted across
2495 categories by priority."
2496 :group 'org-agenda-sorting
2497 :type `(choice
2498 (repeat :tag "General" ,sorting-choice)
2499 (list :tag "Individually"
2500 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2501 (repeat ,sorting-choice))
2502 (cons (const :tag "Strategy for TODO lists" todo)
2503 (repeat ,sorting-choice))
2504 (cons (const :tag "Strategy for Tags matches" tags)
2505 (repeat ,sorting-choice))))))
2507 (defcustom org-sort-agenda-notime-is-late t
2508 "Non-nil means, items without time are considered late.
2509 This is only relevant for sorting. When t, items which have no explicit
2510 time like 15:30 will be considered as 99:01, i.e. later than any items which
2511 do have a time. When nil, the default time is before 0:00. You can use this
2512 option to decide if the schedule for today should come before or after timeless
2513 agenda entries."
2514 :group 'org-agenda-sorting
2515 :type 'boolean)
2517 (defgroup org-agenda-line-format nil
2518 "Options concerning the entry prefix in the Org-mode agenda display."
2519 :tag "Org Agenda Line Format"
2520 :group 'org-agenda)
2522 (defcustom org-agenda-prefix-format
2523 '((agenda . " %-12:c%?-12t% s")
2524 (timeline . " % s")
2525 (todo . " %-12:c")
2526 (tags . " %-12:c"))
2527 "Format specifications for the prefix of items in the agenda views.
2528 An alist with four entries, for the different agenda types. The keys to the
2529 sublists are `agenda', `timeline', `todo', and `tags'. The values
2530 are format strings.
2531 This format works similar to a printf format, with the following meaning:
2533 %c the category of the item, \"Diary\" for entries from the diary, or
2534 as given by the CATEGORY keyword or derived from the file name.
2535 %T the *last* tag of the item. Last because inherited tags come
2536 first in the list.
2537 %t the time-of-day specification if one applies to the entry, in the
2538 format HH:MM
2539 %s Scheduling/Deadline information, a short string
2541 All specifiers work basically like the standard `%s' of printf, but may
2542 contain two additional characters: A question mark just after the `%' and
2543 a whitespace/punctuation character just before the final letter.
2545 If the first character after `%' is a question mark, the entire field
2546 will only be included if the corresponding value applies to the
2547 current entry. This is useful for fields which should have fixed
2548 width when present, but zero width when absent. For example,
2549 \"%?-12t\" will result in a 12 character time field if a time of the
2550 day is specified, but will completely disappear in entries which do
2551 not contain a time.
2553 If there is punctuation or whitespace character just before the final
2554 format letter, this character will be appended to the field value if
2555 the value is not empty. For example, the format \"%-12:c\" leads to
2556 \"Diary: \" if the category is \"Diary\". If the category were be
2557 empty, no additional colon would be interted.
2559 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2560 - Indent the line with two space characters
2561 - Give the category in a 12 chars wide field, padded with whitespace on
2562 the right (because of `-'). Append a colon if there is a category
2563 (because of `:').
2564 - If there is a time-of-day, put it into a 12 chars wide field. If no
2565 time, don't put in an empty field, just skip it (because of '?').
2566 - Finally, put the scheduling information and append a whitespace.
2568 As another example, if you don't want the time-of-day of entries in
2569 the prefix, you could use:
2571 (setq org-agenda-prefix-format \" %-11:c% s\")
2573 See also the variables `org-agenda-remove-times-when-in-prefix' and
2574 `org-agenda-remove-tags'."
2575 :type '(choice
2576 (string :tag "General format")
2577 (list :greedy t :tag "View dependent"
2578 (cons (const agenda) (string :tag "Format"))
2579 (cons (const timeline) (string :tag "Format"))
2580 (cons (const todo) (string :tag "Format"))
2581 (cons (const tags) (string :tag "Format"))))
2582 :group 'org-agenda-line-format)
2584 (defvar org-prefix-format-compiled nil
2585 "The compiled version of the most recently used prefix format.
2586 See the variable `org-agenda-prefix-format'.")
2588 (defcustom org-agenda-remove-times-when-in-prefix t
2589 "Non-nil means, remove duplicate time specifications in agenda items.
2590 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2591 time-of-day specification in a headline or diary entry is extracted and
2592 placed into the prefix. If this option is non-nil, the original specification
2593 \(a timestamp or -range, or just a plain time(range) specification like
2594 11:30-4pm) will be removed for agenda display. This makes the agenda less
2595 cluttered.
2596 The option can be t or nil. It may also be the symbol `beg', indicating
2597 that the time should only be removed what it is located at the beginning of
2598 the headline/diary entry."
2599 :group 'org-agenda-line-format
2600 :type '(choice
2601 (const :tag "Always" t)
2602 (const :tag "Never" nil)
2603 (const :tag "When at beginning of entry" beg)))
2606 (defcustom org-agenda-default-appointment-duration nil
2607 "Default duration for appointments that only have a starting time.
2608 When nil, no duration is specified in such cases.
2609 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2610 :group 'org-agenda-line-format
2611 :type '(choice
2612 (integer :tag "Minutes")
2613 (const :tag "No default duration")))
2616 (defcustom org-agenda-remove-tags nil
2617 "Non-nil means, remove the tags from the headline copy in the agenda.
2618 When this is the symbol `prefix', only remove tags when
2619 `org-agenda-prefix-format' contains a `%T' specifier."
2620 :group 'org-agenda-line-format
2621 :type '(choice
2622 (const :tag "Always" t)
2623 (const :tag "Never" nil)
2624 (const :tag "When prefix format contains %T" prefix)))
2626 (if (fboundp 'defvaralias)
2627 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2628 'org-agenda-remove-tags))
2630 (defcustom org-agenda-tags-column -80
2631 "Shift tags in agenda items to this column.
2632 If this number is positive, it specifies the column. If it is negative,
2633 it means that the tags should be flushright to that column. For example,
2634 -80 works well for a normal 80 character screen."
2635 :group 'org-agenda-line-format
2636 :type 'integer)
2638 (if (fboundp 'defvaralias)
2639 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2641 (defgroup org-latex nil
2642 "Options for embedding LaTeX code into Org-mode"
2643 :tag "Org LaTeX"
2644 :group 'org)
2646 (defcustom org-format-latex-options
2647 '(:foreground default :background default :scale 1.0
2648 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2649 :matchers ("begin" "$" "$$" "\\(" "\\["))
2650 "Options for creating images from LaTeX fragments.
2651 This is a property list with the following properties:
2652 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2653 `default' means use the forground of the default face.
2654 :background the background color, or \"Transparent\".
2655 `default' means use the background of the default face.
2656 :scale a scaling factor for the size of the images
2657 :html-foreground, :html-background, :html-scale
2658 The same numbers for HTML export.
2659 :matchers a list indicating which matchers should be used to
2660 find LaTeX fragments. Valid members of this list are:
2661 \"begin\" find environments
2662 \"$\" find math expressions surrounded by $...$
2663 \"$$\" find math expressions surrounded by $$....$$
2664 \"\\(\" find math expressions surrounded by \\(...\\)
2665 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2666 :group 'org-latex
2667 :type 'plist)
2669 (defcustom org-format-latex-header "\\documentclass{article}
2670 \\usepackage{fullpage} % do not remove
2671 \\usepackage{amssymb}
2672 \\usepackage[usenames]{color}
2673 \\usepackage{amsmath}
2674 \\usepackage{latexsym}
2675 \\usepackage[mathscr]{eucal}
2676 \\pagestyle{empty} % do not remove"
2677 "The document header used for processing LaTeX fragments."
2678 :group 'org-latex
2679 :type 'string)
2681 (defgroup org-export nil
2682 "Options for exporting org-listings."
2683 :tag "Org Export"
2684 :group 'org)
2686 (defgroup org-export-general nil
2687 "General options for exporting Org-mode files."
2688 :tag "Org Export General"
2689 :group 'org-export)
2691 (defcustom org-export-publishing-directory "."
2692 "Path to the location where exported files should be located.
2693 This path may be relative to the directory where the Org-mode file lives.
2694 The default is to put them into the same directory as the Org-mode file.
2695 The variable may also be an alist with export types `:html', `:ascii',
2696 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2697 If a directory path is relative, it is interpreted relative to the
2698 directory where the exported Org-mode files lives."
2699 :group 'org-export-general
2700 :type '(choice
2701 (directory)
2702 (repeat
2703 (cons
2704 (choice :tag "Type"
2705 (const :html) (const :LaTeX)
2706 (const :ascii) (const :ical) (const :xoxo))
2707 (directory)))))
2709 (defcustom org-export-language-setup
2710 '(("en" "Author" "Date" "Table of Contents")
2711 ("cs" "Autor" "Datum" "Obsah")
2712 ("da" "Ophavsmand" "Dato" "Indhold")
2713 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2714 ("es" "Autor" "Fecha" "\xcdndice")
2715 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2716 ("it" "Autore" "Data" "Indice")
2717 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2718 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2719 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2720 "Terms used in export text, translated to different languages.
2721 Use the variable `org-export-default-language' to set the language,
2722 or use the +OPTION lines for a per-file setting."
2723 :group 'org-export-general
2724 :type '(repeat
2725 (list
2726 (string :tag "HTML language tag")
2727 (string :tag "Author")
2728 (string :tag "Date")
2729 (string :tag "Table of Contents"))))
2731 (defcustom org-export-default-language "en"
2732 "The default language of HTML export, as a string.
2733 This should have an association in `org-export-language-setup'."
2734 :group 'org-export-general
2735 :type 'string)
2737 (defcustom org-export-skip-text-before-1st-heading t
2738 "Non-nil means, skip all text before the first headline when exporting.
2739 When nil, that text is exported as well."
2740 :group 'org-export-general
2741 :type 'boolean)
2743 (defcustom org-export-headline-levels 3
2744 "The last level which is still exported as a headline.
2745 Inferior levels will produce itemize lists when exported.
2746 Note that a numeric prefix argument to an exporter function overrides
2747 this setting.
2749 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2750 :group 'org-export-general
2751 :type 'number)
2753 (defcustom org-export-with-section-numbers t
2754 "Non-nil means, add section numbers to headlines when exporting.
2756 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2757 :group 'org-export-general
2758 :type 'boolean)
2760 (defcustom org-export-with-toc t
2761 "Non-nil means, create a table of contents in exported files.
2762 The TOC contains headlines with levels up to`org-export-headline-levels'.
2763 When an integer, include levels up to N in the toc, this may then be
2764 different from `org-export-headline-levels', but it will not be allowed
2765 to be larger than the number of headline levels.
2766 When nil, no table of contents is made.
2768 Headlines which contain any TODO items will be marked with \"(*)\" in
2769 ASCII export, and with red color in HTML output, if the option
2770 `org-export-mark-todo-in-toc' is set.
2772 In HTML output, the TOC will be clickable.
2774 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2775 or \"toc:3\"."
2776 :group 'org-export-general
2777 :type '(choice
2778 (const :tag "No Table of Contents" nil)
2779 (const :tag "Full Table of Contents" t)
2780 (integer :tag "TOC to level")))
2782 (defcustom org-export-mark-todo-in-toc nil
2783 "Non-nil means, mark TOC lines that contain any open TODO items."
2784 :group 'org-export-general
2785 :type 'boolean)
2787 (defcustom org-export-preserve-breaks nil
2788 "Non-nil means, preserve all line breaks when exporting.
2789 Normally, in HTML output paragraphs will be reformatted. In ASCII
2790 export, line breaks will always be preserved, regardless of this variable.
2792 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2793 :group 'org-export-general
2794 :type 'boolean)
2796 (defcustom org-export-with-archived-trees 'headline
2797 "Whether subtrees with the ARCHIVE tag should be exported.
2798 This can have three different values
2799 nil Do not export, pretend this tree is not present
2800 t Do export the entire tree
2801 headline Only export the headline, but skip the tree below it."
2802 :group 'org-export-general
2803 :group 'org-archive
2804 :type '(choice
2805 (const :tag "not at all" nil)
2806 (const :tag "headline only" 'headline)
2807 (const :tag "entirely" t)))
2809 (defcustom org-export-author-info t
2810 "Non-nil means, insert author name and email into the exported file.
2812 This option can also be set with the +OPTIONS line,
2813 e.g. \"author-info:nil\"."
2814 :group 'org-export-general
2815 :type 'boolean)
2817 (defcustom org-export-time-stamp-file t
2818 "Non-nil means, insert a time stamp into the exported file.
2819 The time stamp shows when the file was created.
2821 This option can also be set with the +OPTIONS line,
2822 e.g. \"timestamp:nil\"."
2823 :group 'org-export-general
2824 :type 'boolean)
2826 (defcustom org-export-with-timestamps t
2827 "If nil, do not export time stamps and associated keywords."
2828 :group 'org-export-general
2829 :type 'boolean)
2831 (defcustom org-export-remove-timestamps-from-toc t
2832 "If nil, remove timestamps from the table of contents entries."
2833 :group 'org-export-general
2834 :type 'boolean)
2836 (defcustom org-export-with-tags 'not-in-toc
2837 "If nil, do not export tags, just remove them from headlines.
2838 If this is the symbol `not-in-toc', tags will be removed from table of
2839 contents entries, but still be shown in the headlines of the document."
2840 :group 'org-export-general
2841 :type '(choice
2842 (const :tag "Off" nil)
2843 (const :tag "Not in TOC" not-in-toc)
2844 (const :tag "On" t)))
2846 (defcustom org-export-with-property-drawer nil
2847 "Non-nil means, export property drawers.
2848 When nil, these drawers are removed before export.
2850 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2851 :group 'org-export-general
2852 :type 'boolean)
2854 (defgroup org-export-translation nil
2855 "Options for translating special ascii sequences for the export backends."
2856 :tag "Org Export Translation"
2857 :group 'org-export)
2859 (defcustom org-export-with-emphasize t
2860 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2861 If the export target supports emphasizing text, the word will be
2862 typeset in bold, italic, or underlined, respectively. Works only for
2863 single words, but you can say: I *really* *mean* *this*.
2864 Not all export backends support this.
2866 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2867 :group 'org-export-translation
2868 :type 'boolean)
2870 (defcustom org-export-with-footnotes t
2871 "If nil, export [1] as a footnote marker.
2872 Lines starting with [1] will be formatted as footnotes.
2874 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2875 :group 'org-export-translation
2876 :type 'boolean)
2878 (defcustom org-export-with-sub-superscripts t
2879 "Non-nil means, interpret \"_\" and \"^\" for export.
2880 When this option is turned on, you can use TeX-like syntax for sub- and
2881 superscripts. Several characters after \"_\" or \"^\" will be
2882 considered as a single item - so grouping with {} is normally not
2883 needed. For example, the following things will be parsed as single
2884 sub- or superscripts.
2886 10^24 or 10^tau several digits will be considered 1 item.
2887 10^-12 or 10^-tau a leading sign with digits or a word
2888 x^2-y^3 will be read as x^2 - y^3, because items are
2889 terminated by almost any nonword/nondigit char.
2890 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2892 Still, ambiguity is possible - so when in doubt use {} to enclose the
2893 sub/superscript. If you set this variable to the symbol `{}',
2894 the braces are *required* in order to trigger interpretations as
2895 sub/superscript. This can be helpful in documents that need \"_\"
2896 frequently in plain text.
2898 Not all export backends support this, but HTML does.
2900 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2901 :group 'org-export-translation
2902 :type '(choice
2903 (const :tag "Always interpret" t)
2904 (const :tag "Only with braces" {})
2905 (const :tag "Never interpret" nil)))
2907 (defcustom org-export-with-TeX-macros t
2908 "Non-nil means, interpret simple TeX-like macros when exporting.
2909 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2910 No only real TeX macros will work here, but the standard HTML entities
2911 for math can be used as macro names as well. For a list of supported
2912 names in HTML export, see the constant `org-html-entities'.
2913 Not all export backends support this.
2915 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2916 :group 'org-export-translation
2917 :group 'org-export-latex
2918 :type 'boolean)
2920 (defcustom org-export-with-LaTeX-fragments nil
2921 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2922 When set, the exporter will find LaTeX environments if the \\begin line is
2923 the first non-white thing on a line. It will also find the math delimiters
2924 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2925 display math.
2927 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2928 :group 'org-export-translation
2929 :group 'org-export-latex
2930 :type 'boolean)
2932 (defcustom org-export-with-fixed-width t
2933 "Non-nil means, lines starting with \":\" will be in fixed width font.
2934 This can be used to have pre-formatted text, fragments of code etc. For
2935 example:
2936 : ;; Some Lisp examples
2937 : (while (defc cnt)
2938 : (ding))
2939 will be looking just like this in also HTML. See also the QUOTE keyword.
2940 Not all export backends support this.
2942 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2943 :group 'org-export-translation
2944 :type 'boolean)
2946 (defcustom org-match-sexp-depth 3
2947 "Number of stacked braces for sub/superscript matching.
2948 This has to be set before loading org.el to be effective."
2949 :group 'org-export-translation
2950 :type 'integer)
2952 (defgroup org-export-tables nil
2953 "Options for exporting tables in Org-mode."
2954 :tag "Org Export Tables"
2955 :group 'org-export)
2957 (defcustom org-export-with-tables t
2958 "If non-nil, lines starting with \"|\" define a table.
2959 For example:
2961 | Name | Address | Birthday |
2962 |-------------+----------+-----------|
2963 | Arthur Dent | England | 29.2.2100 |
2965 Not all export backends support this.
2967 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2968 :group 'org-export-tables
2969 :type 'boolean)
2971 (defcustom org-export-highlight-first-table-line t
2972 "Non-nil means, highlight the first table line.
2973 In HTML export, this means use <th> instead of <td>.
2974 In tables created with table.el, this applies to the first table line.
2975 In Org-mode tables, all lines before the first horizontal separator
2976 line will be formatted with <th> tags."
2977 :group 'org-export-tables
2978 :type 'boolean)
2980 (defcustom org-export-table-remove-special-lines t
2981 "Remove special lines and marking characters in calculating tables.
2982 This removes the special marking character column from tables that are set
2983 up for spreadsheet calculations. It also removes the entire lines
2984 marked with `!', `_', or `^'. The lines with `$' are kept, because
2985 the values of constants may be useful to have."
2986 :group 'org-export-tables
2987 :type 'boolean)
2989 (defcustom org-export-prefer-native-exporter-for-tables nil
2990 "Non-nil means, always export tables created with table.el natively.
2991 Natively means, use the HTML code generator in table.el.
2992 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2993 the table does not use row- or column-spanning). This has the
2994 advantage, that the automatic HTML conversions for math symbols and
2995 sub/superscripts can be applied. Org-mode's HTML generator is also
2996 much faster."
2997 :group 'org-export-tables
2998 :type 'boolean)
3000 (defgroup org-export-ascii nil
3001 "Options specific for ASCII export of Org-mode files."
3002 :tag "Org Export ASCII"
3003 :group 'org-export)
3005 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3006 "Characters for underlining headings in ASCII export.
3007 In the given sequence, these characters will be used for level 1, 2, ..."
3008 :group 'org-export-ascii
3009 :type '(repeat character))
3011 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3012 "Bullet characters for headlines converted to lists in ASCII export.
3013 The first character is is used for the first lest level generated in this
3014 way, and so on. If there are more levels than characters given here,
3015 the list will be repeated.
3016 Note that plain lists will keep the same bullets as the have in the
3017 Org-mode file."
3018 :group 'org-export-ascii
3019 :type '(repeat character))
3021 (defgroup org-export-xml nil
3022 "Options specific for XML export of Org-mode files."
3023 :tag "Org Export XML"
3024 :group 'org-export)
3026 (defgroup org-export-html nil
3027 "Options specific for HTML export of Org-mode files."
3028 :tag "Org Export HTML"
3029 :group 'org-export)
3031 (defcustom org-export-html-coding-system nil
3033 :group 'org-export-html
3034 :type 'coding-system)
3036 (defcustom org-export-html-extension "html"
3037 "The extension for exported HTML files."
3038 :group 'org-export-html
3039 :type 'string)
3041 (defcustom org-export-html-style
3042 "<style type=\"text/css\">
3043 html {
3044 font-family: Times, serif;
3045 font-size: 12pt;
3047 .title { text-align: center; }
3048 .todo { color: red; }
3049 .done { color: green; }
3050 .timestamp { color: grey }
3051 .timestamp-kwd { color: CadetBlue }
3052 .tag { background-color:lightblue; font-weight:normal }
3053 .target { background-color: lavender; }
3054 pre {
3055 border: 1pt solid #AEBDCC;
3056 background-color: #F3F5F7;
3057 padding: 5pt;
3058 font-family: courier, monospace;
3060 table { border-collapse: collapse; }
3061 td, th {
3062 vertical-align: top;
3063 <!--border: 1pt solid #ADB9CC;-->
3065 </style>"
3066 "The default style specification for exported HTML files.
3067 Since there are different ways of setting style information, this variable
3068 needs to contain the full HTML structure to provide a style, including the
3069 surrounding HTML tags. The style specifications should include definitions
3070 for new classes todo, done, title, and deadline. For example, legal values
3071 would be:
3073 <style type=\"text/css\">
3074 p { font-weight: normal; color: gray; }
3075 h1 { color: black; }
3076 .title { text-align: center; }
3077 .todo, .deadline { color: red; }
3078 .done { color: green; }
3079 </style>
3081 or, if you want to keep the style in a file,
3083 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3085 As the value of this option simply gets inserted into the HTML <head> header,
3086 you can \"misuse\" it to add arbitrary text to the header."
3087 :group 'org-export-html
3088 :type 'string)
3091 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3092 "Format for typesetting the document title in HTML export."
3093 :group 'org-export-html
3094 :type 'string)
3096 (defcustom org-export-html-toplevel-hlevel 2
3097 "The <H> level for level 1 headings in HTML export."
3098 :group 'org-export-html
3099 :type 'string)
3101 (defcustom org-export-html-link-org-files-as-html t
3102 "Non-nil means, make file links to `file.org' point to `file.html'.
3103 When org-mode is exporting an org-mode file to HTML, links to
3104 non-html files are directly put into a href tag in HTML.
3105 However, links to other Org-mode files (recognized by the
3106 extension `.org.) should become links to the corresponding html
3107 file, assuming that the linked org-mode file will also be
3108 converted to HTML.
3109 When nil, the links still point to the plain `.org' file."
3110 :group 'org-export-html
3111 :type 'boolean)
3113 (defcustom org-export-html-inline-images 'maybe
3114 "Non-nil means, inline images into exported HTML pages.
3115 This is done using an <img> tag. When nil, an anchor with href is used to
3116 link to the image. If this option is `maybe', then images in links with
3117 an empty description will be inlined, while images with a description will
3118 be linked only."
3119 :group 'org-export-html
3120 :type '(choice (const :tag "Never" nil)
3121 (const :tag "Always" t)
3122 (const :tag "When there is no description" maybe)))
3124 ;; FIXME: rename
3125 (defcustom org-export-html-expand t
3126 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3127 When nil, these tags will be exported as plain text and therefore
3128 not be interpreted by a browser.
3130 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3131 :group 'org-export-html
3132 :type 'boolean)
3134 (defcustom org-export-html-table-tag
3135 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3136 "The HTML tag that is used to start a table.
3137 This must be a <table> tag, but you may change the options like
3138 borders and spacing."
3139 :group 'org-export-html
3140 :type 'string)
3142 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3143 "The opening tag for table header fields.
3144 This is customizable so that alignment options can be specified."
3145 :group 'org-export-tables
3146 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3148 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3149 "The opening tag for table data fields.
3150 This is customizable so that alignment options can be specified."
3151 :group 'org-export-tables
3152 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3154 (defcustom org-export-html-with-timestamp nil
3155 "If non-nil, write `org-export-html-html-helper-timestamp'
3156 into the exported HTML text. Otherwise, the buffer will just be saved
3157 to a file."
3158 :group 'org-export-html
3159 :type 'boolean)
3161 (defcustom org-export-html-html-helper-timestamp
3162 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3163 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3164 :group 'org-export-html
3165 :type 'string)
3167 (defgroup org-export-icalendar nil
3168 "Options specific for iCalendar export of Org-mode files."
3169 :tag "Org Export iCalendar"
3170 :group 'org-export)
3172 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3173 "The file name for the iCalendar file covering all agenda files.
3174 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3175 The file name should be absolute, the file will be overwritten without warning."
3176 :group 'org-export-icalendar
3177 :type 'file)
3179 (defcustom org-icalendar-include-todo nil
3180 "Non-nil means, export to iCalendar files should also cover TODO items."
3181 :group 'org-export-icalendar
3182 :type '(choice
3183 (const :tag "None" nil)
3184 (const :tag "Unfinished" t)
3185 (const :tag "All" all)))
3187 (defcustom org-icalendar-include-sexps t
3188 "Non-nil means, export to iCalendar files should also cover sexp entries.
3189 These are entries like in the diary, but directly in an Org-mode file."
3190 :group 'org-export-icalendar
3191 :type 'boolean)
3193 (defcustom org-icalendar-include-body 100
3194 "Amount of text below headline to be included in iCalendar export.
3195 This is a number of characters that should maximally be included.
3196 Properties, scheduling and clocking lines will always be removed.
3197 The text will be inserted into the DESCRIPTION field."
3198 :group 'org-export-icalendar
3199 :type '(choice
3200 (const :tag "Nothing" nil)
3201 (const :tag "Everything" t)
3202 (integer :tag "Max characters")))
3204 (defcustom org-icalendar-combined-name "OrgMode"
3205 "Calendar name for the combined iCalendar representing all agenda files."
3206 :group 'org-export-icalendar
3207 :type 'string)
3209 (defgroup org-font-lock nil
3210 "Font-lock settings for highlighting in Org-mode."
3211 :tag "Org Font Lock"
3212 :group 'org)
3214 (defcustom org-level-color-stars-only nil
3215 "Non-nil means fontify only the stars in each headline.
3216 When nil, the entire headline is fontified.
3217 Changing it requires restart of `font-lock-mode' to become effective
3218 also in regions already fontified."
3219 :group 'org-font-lock
3220 :type 'boolean)
3222 (defcustom org-hide-leading-stars nil
3223 "Non-nil means, hide the first N-1 stars in a headline.
3224 This works by using the face `org-hide' for these stars. This
3225 face is white for a light background, and black for a dark
3226 background. You may have to customize the face `org-hide' to
3227 make this work.
3228 Changing it requires restart of `font-lock-mode' to become effective
3229 also in regions already fontified.
3230 You may also set this on a per-file basis by adding one of the following
3231 lines to the buffer:
3233 #+STARTUP: hidestars
3234 #+STARTUP: showstars"
3235 :group 'org-font-lock
3236 :type 'boolean)
3238 (defcustom org-fontify-done-headline nil
3239 "Non-nil means, change the face of a headline if it is marked DONE.
3240 Normally, only the TODO/DONE keyword indicates the state of a headline.
3241 When this is non-nil, the headline after the keyword is set to the
3242 `org-headline-done' as an additional indication."
3243 :group 'org-font-lock
3244 :type 'boolean)
3246 (defcustom org-fontify-emphasized-text t
3247 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3248 Changing this variable requires a restart of Emacs to take effect."
3249 :group 'org-font-lock
3250 :type 'boolean)
3252 (defvar org-emph-re nil
3253 "Regular expression for matching emphasis.")
3254 (defvar org-emphasis-regexp-components) ; defined just below
3255 (defvar org-emphasis-alist) ; defined just below
3256 (defun org-set-emph-re (var val)
3257 "Set variable and compute the emphasis regular expression."
3258 (set var val)
3259 (when (and (boundp 'org-emphasis-alist)
3260 (boundp 'org-emphasis-regexp-components)
3261 org-emphasis-alist org-emphasis-regexp-components)
3262 (let* ((e org-emphasis-regexp-components)
3263 (pre (car e))
3264 (post (nth 1 e))
3265 (border (nth 2 e))
3266 (body (nth 3 e))
3267 (nl (nth 4 e))
3268 (stacked (nth 5 e))
3269 (body1 (concat body "*?"))
3270 (markers (mapconcat 'car org-emphasis-alist "")))
3271 ;; make sure special characters appear at the right position in the class
3272 (if (string-match "\\^" markers)
3273 (setq markers (concat (replace-match "" t t markers) "^")))
3274 (if (string-match "-" markers)
3275 (setq markers (concat (replace-match "" t t markers) "-")))
3276 (if (> nl 0)
3277 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3278 (int-to-string nl) "\\}")))
3279 ;; Make the regexp
3280 (setq org-emph-re
3281 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3282 "\\("
3283 "\\([" markers "]\\)"
3284 "\\("
3285 "[^" border (if (and nil stacked) markers) "]"
3286 body1
3287 "[^" border (if (and nil stacked) markers) "]"
3288 "\\)"
3289 "\\3\\)"
3290 "\\([" post (if stacked markers) "]\\|$\\)")))))
3292 (defcustom org-emphasis-regexp-components
3293 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3294 "Components used to build the reqular expression for emphasis.
3295 This is a list with 6 entries. Terminology: In an emphasis string
3296 like \" *strong word* \", we call the initial space PREMATCH, the final
3297 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3298 and \"trong wor\" is the body. The different components in this variable
3299 specify what is allowed/forbidden in each part:
3301 pre Chars allowed as prematch. Beginning of line will be allowed too.
3302 post Chars allowed as postmatch. End of line will be allowed too.
3303 border The chars *forbidden* as border characters.
3304 body-regexp A regexp like \".\" to match a body character. Don't use
3305 non-shy groups here, and don't allow newline here.
3306 newline The maximum number of newlines allowed in an emphasis exp.
3307 stacked Non-nil means, allow stacked styles. This works only in HTML
3308 export. When this is set, all marker characters (as given in
3309 `org-emphasis-alist') will be allowed as pre/post, aiding
3310 inside-out matching.
3311 Use customize to modify this, or restart Emacs after changing it."
3312 :group 'org-font-lock
3313 :set 'org-set-emph-re
3314 :type '(list
3315 (sexp :tag "Allowed chars in pre ")
3316 (sexp :tag "Allowed chars in post ")
3317 (sexp :tag "Forbidden chars in border ")
3318 (sexp :tag "Regexp for body ")
3319 (integer :tag "number of newlines allowed")
3320 (boolean :tag "Stacking allowed ")))
3322 (defcustom org-emphasis-alist
3323 '(("*" bold "<b>" "</b>")
3324 ("/" italic "<i>" "</i>")
3325 ("_" underline "<u>" "</u>")
3326 ("=" org-code "<code>" "</code>")
3327 ("+" (:strike-through t) "<del>" "</del>")
3329 "Special syntax for emphasized text.
3330 Text starting and ending with a special character will be emphasized, for
3331 example *bold*, _underlined_ and /italic/. This variable sets the marker
3332 characters, the face to be used by font-lock for highlighting in Org-mode
3333 Emacs buffers, and the HTML tags to be used for this.
3334 Use customize to modify this, or restart Emacs after changing it."
3335 :group 'org-font-lock
3336 :set 'org-set-emph-re
3337 :type '(repeat
3338 (list
3339 (string :tag "Marker character")
3340 (choice
3341 (face :tag "Font-lock-face")
3342 (plist :tag "Face property list"))
3343 (string :tag "HTML start tag")
3344 (string :tag "HTML end tag"))))
3346 ;;; The faces
3348 (defgroup org-faces nil
3349 "Faces in Org-mode."
3350 :tag "Org Faces"
3351 :group 'org-font-lock)
3353 (defun org-compatible-face (inherits specs)
3354 "Make a compatible face specification.
3355 If INHERITS is an existing face and if the Emacs version supports it,
3356 just inherit the face. If not, use SPECS to define the face.
3357 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3358 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3359 to the top of the list. The `min-colors' attribute will be removed from
3360 any other entries, and any resulting duplicates will be removed entirely."
3361 (cond
3362 ((and inherits (facep inherits)
3363 (not (featurep 'xemacs)) (> emacs-major-version 22))
3364 ;; In Emacs 23, we use inheritance where possible.
3365 ;; We only do this in Emacs 23, because only there the outline
3366 ;; faces have been changed to the original org-mode-level-faces.
3367 (list (list t :inherit inherits)))
3368 ((or (featurep 'xemacs) (< emacs-major-version 22))
3369 ;; These do not understand the `min-colors' attribute.
3370 (let (r e a)
3371 (while (setq e (pop specs))
3372 (cond
3373 ((memq (car e) '(t default)) (push e r))
3374 ((setq a (member '(min-colors 8) (car e)))
3375 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3376 (cdr e)))))
3377 ((setq a (assq 'min-colors (car e)))
3378 (setq e (cons (delq a (car e)) (cdr e)))
3379 (or (assoc (car e) r) (push e r)))
3380 (t (or (assoc (car e) r) (push e r)))))
3381 (nreverse r)))
3382 (t specs)))
3384 (defface org-hide
3385 '((((background light)) (:foreground "white"))
3386 (((background dark)) (:foreground "black")))
3387 "Face used to hide leading stars in headlines.
3388 The forground color of this face should be equal to the background
3389 color of the frame."
3390 :group 'org-faces)
3392 (defface org-level-1 ;; font-lock-function-name-face
3393 (org-compatible-face
3394 'outline-1
3395 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3396 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3397 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3398 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3399 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3400 (t (:bold t))))
3401 "Face used for level 1 headlines."
3402 :group 'org-faces)
3404 (defface org-level-2 ;; font-lock-variable-name-face
3405 (org-compatible-face
3406 'outline-2
3407 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3408 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3409 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3410 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3411 (t (:bold t))))
3412 "Face used for level 2 headlines."
3413 :group 'org-faces)
3415 (defface org-level-3 ;; font-lock-keyword-face
3416 (org-compatible-face
3417 'outline-3
3418 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3419 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3420 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3421 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3422 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3423 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3424 (t (:bold t))))
3425 "Face used for level 3 headlines."
3426 :group 'org-faces)
3428 (defface org-level-4 ;; font-lock-comment-face
3429 (org-compatible-face
3430 'outline-4
3431 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3432 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3433 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3434 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3435 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3436 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3437 (t (:bold t))))
3438 "Face used for level 4 headlines."
3439 :group 'org-faces)
3441 (defface org-level-5 ;; font-lock-type-face
3442 (org-compatible-face
3443 'outline-5
3444 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3445 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3446 (((class color) (min-colors 8)) (:foreground "green"))))
3447 "Face used for level 5 headlines."
3448 :group 'org-faces)
3450 (defface org-level-6 ;; font-lock-constant-face
3451 (org-compatible-face
3452 'outline-6
3453 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3454 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3455 (((class color) (min-colors 8)) (:foreground "magenta"))))
3456 "Face used for level 6 headlines."
3457 :group 'org-faces)
3459 (defface org-level-7 ;; font-lock-builtin-face
3460 (org-compatible-face
3461 'outline-7
3462 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3463 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3464 (((class color) (min-colors 8)) (:foreground "blue"))))
3465 "Face used for level 7 headlines."
3466 :group 'org-faces)
3468 (defface org-level-8 ;; font-lock-string-face
3469 (org-compatible-face
3470 'outline-8
3471 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3472 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3473 (((class color) (min-colors 8)) (:foreground "green"))))
3474 "Face used for level 8 headlines."
3475 :group 'org-faces)
3477 (defface org-special-keyword ;; font-lock-string-face
3478 (org-compatible-face
3480 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3481 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3482 (t (:italic t))))
3483 "Face used for special keywords."
3484 :group 'org-faces)
3486 (defface org-drawer ;; font-lock-function-name-face
3487 (org-compatible-face
3489 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3490 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3491 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3492 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3493 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3494 (t (:bold t))))
3495 "Face used for drawers."
3496 :group 'org-faces)
3498 (defface org-property-value nil
3499 "Face used for the value of a property."
3500 :group 'org-faces)
3502 (defface org-column
3503 (org-compatible-face
3505 '((((class color) (min-colors 16) (background light))
3506 (:background "grey90"))
3507 (((class color) (min-colors 16) (background dark))
3508 (:background "grey30"))
3509 (((class color) (min-colors 8))
3510 (:background "cyan" :foreground "black"))
3511 (t (:inverse-video t))))
3512 "Face for column display of entry properties."
3513 :group 'org-faces)
3515 (when (fboundp 'set-face-attribute)
3516 ;; Make sure that a fixed-width face is used when we have a column table.
3517 (set-face-attribute 'org-column nil
3518 :height (face-attribute 'default :height)
3519 :family (face-attribute 'default :family)))
3521 (defface org-warning
3522 (org-compatible-face
3523 'font-lock-warning-face
3524 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3525 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3526 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3527 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3528 (t (:bold t))))
3529 "Face for deadlines and TODO keywords."
3530 :group 'org-faces)
3532 (defface org-archived ; similar to shadow
3533 (org-compatible-face
3534 'shadow
3535 '((((class color grayscale) (min-colors 88) (background light))
3536 (:foreground "grey50"))
3537 (((class color grayscale) (min-colors 88) (background dark))
3538 (:foreground "grey70"))
3539 (((class color) (min-colors 8) (background light))
3540 (:foreground "green"))
3541 (((class color) (min-colors 8) (background dark))
3542 (:foreground "yellow"))))
3543 "Face for headline with the ARCHIVE tag."
3544 :group 'org-faces)
3546 (defface org-link
3547 '((((class color) (background light)) (:foreground "Purple" :underline t))
3548 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3549 (t (:underline t)))
3550 "Face for links."
3551 :group 'org-faces)
3553 (defface org-target
3554 '((((class color) (background light)) (:underline t))
3555 (((class color) (background dark)) (:underline t))
3556 (t (:underline t)))
3557 "Face for links."
3558 :group 'org-faces)
3560 (defface org-date
3561 '((((class color) (background light)) (:foreground "Purple" :underline t))
3562 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3563 (t (:underline t)))
3564 "Face for links."
3565 :group 'org-faces)
3567 (defface org-sexp-date
3568 '((((class color) (background light)) (:foreground "Purple"))
3569 (((class color) (background dark)) (:foreground "Cyan"))
3570 (t (:underline t)))
3571 "Face for links."
3572 :group 'org-faces)
3574 (defface org-tag
3575 '((t (:bold t)))
3576 "Face for tags."
3577 :group 'org-faces)
3579 (defface org-todo ; font-lock-warning-face
3580 (org-compatible-face
3582 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3583 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3584 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3585 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3586 (t (:inverse-video t :bold t))))
3587 "Face for TODO keywords."
3588 :group 'org-faces)
3590 (defface org-done ;; font-lock-type-face
3591 (org-compatible-face
3593 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3594 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3595 (((class color) (min-colors 8)) (:foreground "green"))
3596 (t (:bold t))))
3597 "Face used for todo keywords that indicate DONE items."
3598 :group 'org-faces)
3600 (defface org-headline-done ;; font-lock-string-face
3601 (org-compatible-face
3603 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3604 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3605 (((class color) (min-colors 8) (background light)) (:bold nil))))
3606 "Face used to indicate that a headline is DONE.
3607 This face is only used if `org-fontify-done-headline' is set. If applies
3608 to the part of the headline after the DONE keyword."
3609 :group 'org-faces)
3611 (defcustom org-todo-keyword-faces nil
3612 "Faces for specific TODO keywords.
3613 This is a list of cons cells, with TODO keywords in the car
3614 and faces in the cdr. The face can be a symbol, or a property
3615 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3616 :group 'org-faces
3617 :group 'org-todo
3618 :type '(repeat
3619 (cons
3620 (string :tag "keyword")
3621 (sexp :tag "face"))))
3623 (defface org-table ;; font-lock-function-name-face
3624 (org-compatible-face
3626 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3627 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3628 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3629 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3630 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3631 (((class color) (min-colors 8) (background dark)))))
3632 "Face used for tables."
3633 :group 'org-faces)
3635 (defface org-formula
3636 (org-compatible-face
3638 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3639 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3640 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3641 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3642 (t (:bold t :italic t))))
3643 "Face for formulas."
3644 :group 'org-faces)
3646 (defface org-code
3647 (org-compatible-face
3649 '((((class color grayscale) (min-colors 88) (background light))
3650 (:foreground "grey50"))
3651 (((class color grayscale) (min-colors 88) (background dark))
3652 (:foreground "grey70"))
3653 (((class color) (min-colors 8) (background light))
3654 (:foreground "green"))
3655 (((class color) (min-colors 8) (background dark))
3656 (:foreground "yellow"))))
3657 "Face for fixed-with text like code snippets."
3658 :group 'org-faces
3659 :version "22.1")
3661 (defface org-agenda-structure ;; font-lock-function-name-face
3662 (org-compatible-face
3664 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3665 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3666 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3667 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3668 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3669 (t (:bold t))))
3670 "Face used in agenda for captions and dates."
3671 :group 'org-faces)
3673 (defface org-scheduled-today
3674 (org-compatible-face
3676 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3677 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3678 (((class color) (min-colors 8)) (:foreground "green"))
3679 (t (:bold t :italic t))))
3680 "Face for items scheduled for a certain day."
3681 :group 'org-faces)
3683 (defface org-scheduled-previously
3684 (org-compatible-face
3686 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3687 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3688 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3689 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3690 (t (:bold t))))
3691 "Face for items scheduled previously, and not yet done."
3692 :group 'org-faces)
3694 (defface org-upcoming-deadline
3695 (org-compatible-face
3697 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3698 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3699 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3700 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3701 (t (:bold t))))
3702 "Face for items scheduled previously, and not yet done."
3703 :group 'org-faces)
3705 (defcustom org-agenda-deadline-faces
3706 '((1.0 . org-warning)
3707 (0.5 . org-upcoming-deadline)
3708 (0.0 . default))
3709 "Faces for showing deadlines in the agenda.
3710 This is a list of cons cells. The cdr of each cess is a face to be used,
3711 and it can also just be a like like '(:foreground \"yellow\").
3712 Each car is a fraction of the head-warning time that must have passed for
3713 this the face in the cdr to be used for display. The numbers must be
3714 given in descending order. The head-warning time is normally taken
3715 from `org-deadline-warning-days', but can also be specified in the deadline
3716 timestamp itself, like this:
3718 DEADLINE: <2007-08-13 Mon -8d>
3720 You may use d for days, w for weeks, m for months and y for years. Months
3721 and years will only be treated in an approximate fashion (30.4 days for a
3722 month and 365.24 days for a year)."
3723 :group 'org-faces
3724 :group 'org-agenda-daily/weekly
3725 :type '(repeat
3726 (cons
3727 (number :tag "Fraction of head-warning time passed")
3728 (sexp :tag "Face"))))
3730 (defface org-time-grid ;; font-lock-variable-name-face
3731 (org-compatible-face
3733 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3734 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3735 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3736 "Face used for time grids."
3737 :group 'org-faces)
3739 (defconst org-level-faces
3740 '(org-level-1 org-level-2 org-level-3 org-level-4
3741 org-level-5 org-level-6 org-level-7 org-level-8
3744 (defcustom org-n-level-faces (length org-level-faces)
3745 "The number different faces to be used for headlines.
3746 Org-mode defines 8 different headline faces, so this can be at most 8.
3747 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3748 :type 'number
3749 :group 'org-faces)
3751 ;;; Variables for pre-computed regular expressions, all buffer local
3753 (defvar org-drawer-regexp nil
3754 "Matches first line of a hidden block.")
3755 (make-variable-buffer-local 'org-drawer-regexp)
3756 (defvar org-todo-regexp nil
3757 "Matches any of the TODO state keywords.")
3758 (make-variable-buffer-local 'org-todo-regexp)
3759 (defvar org-not-done-regexp nil
3760 "Matches any of the TODO state keywords except the last one.")
3761 (make-variable-buffer-local 'org-not-done-regexp)
3762 (defvar org-todo-line-regexp nil
3763 "Matches a headline and puts TODO state into group 2 if present.")
3764 (make-variable-buffer-local 'org-todo-line-regexp)
3765 (defvar org-todo-line-tags-regexp nil
3766 "Matches a headline and puts TODO state into group 2 if present.
3767 Also put tags into group 4 if tags are present.")
3768 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3769 (defvar org-nl-done-regexp nil
3770 "Matches newline followed by a headline with the DONE keyword.")
3771 (make-variable-buffer-local 'org-nl-done-regexp)
3772 (defvar org-looking-at-done-regexp nil
3773 "Matches the DONE keyword a point.")
3774 (make-variable-buffer-local 'org-looking-at-done-regexp)
3775 (defvar org-ds-keyword-length 12
3776 "Maximum length of the Deadline and SCHEDULED keywords.")
3777 (make-variable-buffer-local 'org-ds-keyword-length)
3778 (defvar org-deadline-regexp nil
3779 "Matches the DEADLINE keyword.")
3780 (make-variable-buffer-local 'org-deadline-regexp)
3781 (defvar org-deadline-time-regexp nil
3782 "Matches the DEADLINE keyword together with a time stamp.")
3783 (make-variable-buffer-local 'org-deadline-time-regexp)
3784 (defvar org-deadline-line-regexp nil
3785 "Matches the DEADLINE keyword and the rest of the line.")
3786 (make-variable-buffer-local 'org-deadline-line-regexp)
3787 (defvar org-scheduled-regexp nil
3788 "Matches the SCHEDULED keyword.")
3789 (make-variable-buffer-local 'org-scheduled-regexp)
3790 (defvar org-scheduled-time-regexp nil
3791 "Matches the SCHEDULED keyword together with a time stamp.")
3792 (make-variable-buffer-local 'org-scheduled-time-regexp)
3793 (defvar org-closed-time-regexp nil
3794 "Matches the CLOSED keyword together with a time stamp.")
3795 (make-variable-buffer-local 'org-closed-time-regexp)
3797 (defvar org-keyword-time-regexp nil
3798 "Matches any of the 4 keywords, together with the time stamp.")
3799 (make-variable-buffer-local 'org-keyword-time-regexp)
3800 (defvar org-keyword-time-not-clock-regexp nil
3801 "Matches any of the 3 keywords, together with the time stamp.")
3802 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3803 (defvar org-maybe-keyword-time-regexp nil
3804 "Matches a timestamp, possibly preceeded by a keyword.")
3805 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3806 (defvar org-planning-or-clock-line-re nil
3807 "Matches a line with planning or clock info.")
3808 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3810 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3811 rear-nonsticky t mouse-map t fontified t)
3812 "Properties to remove when a string without properties is wanted.")
3814 (defsubst org-match-string-no-properties (num &optional string)
3815 (if (featurep 'xemacs)
3816 (let ((s (match-string num string)))
3817 (remove-text-properties 0 (length s) org-rm-props s)
3819 (match-string-no-properties num string)))
3821 (defsubst org-no-properties (s)
3822 (if (fboundp 'set-text-properties)
3823 (set-text-properties 0 (length s) nil s)
3824 (remove-text-properties 0 (length s) org-rm-props s))
3827 (defsubst org-get-alist-option (option key)
3828 (cond ((eq key t) t)
3829 ((eq option t) t)
3830 ((assoc key option) (cdr (assoc key option)))
3831 (t (cdr (assq 'default option)))))
3833 (defsubst org-inhibit-invisibility ()
3834 "Modified `buffer-invisibility-spec' for Emacs 21.
3835 Some ops with invisible text do not work correctly on Emacs 21. For these
3836 we turn off invisibility temporarily. Use this in a `let' form."
3837 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3839 (defsubst org-set-local (var value)
3840 "Make VAR local in current buffer and set it to VALUE."
3841 (set (make-variable-buffer-local var) value))
3843 (defsubst org-mode-p ()
3844 "Check if the current buffer is in Org-mode."
3845 (eq major-mode 'org-mode))
3847 (defsubst org-last (list)
3848 "Return the last element of LIST."
3849 (car (last list)))
3851 (defun org-let (list &rest body)
3852 (eval (cons 'let (cons list body))))
3853 (put 'org-let 'lisp-indent-function 1)
3855 (defun org-let2 (list1 list2 &rest body)
3856 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3857 (put 'org-let2 'lisp-indent-function 2)
3858 (defconst org-startup-options
3859 '(("fold" org-startup-folded t)
3860 ("overview" org-startup-folded t)
3861 ("nofold" org-startup-folded nil)
3862 ("showall" org-startup-folded nil)
3863 ("content" org-startup-folded content)
3864 ("hidestars" org-hide-leading-stars t)
3865 ("showstars" org-hide-leading-stars nil)
3866 ("odd" org-odd-levels-only t)
3867 ("oddeven" org-odd-levels-only nil)
3868 ("align" org-startup-align-all-tables t)
3869 ("noalign" org-startup-align-all-tables nil)
3870 ("customtime" org-display-custom-times t)
3871 ("logging" org-log-done t)
3872 ("logdone" org-log-done t)
3873 ("nologging" org-log-done nil)
3874 ("lognotedone" org-log-done done push)
3875 ("lognotestate" org-log-done state push)
3876 ("lognoteclock-out" org-log-done clock-out push)
3877 ("logrepeat" org-log-repeat t)
3878 ("nologrepeat" org-log-repeat nil)
3879 ("constcgs" constants-unit-system cgs)
3880 ("constSI" constants-unit-system SI))
3881 "Variable associated with STARTUP options for org-mode.
3882 Each element is a list of three items: The startup options as written
3883 in the #+STARTUP line, the corresponding variable, and the value to
3884 set this variable to if the option is found. An optional forth element PUSH
3885 means to push this value onto the list in the variable.")
3887 (defun org-set-regexps-and-options ()
3888 "Precompute regular expressions for current buffer."
3889 (when (org-mode-p)
3890 (org-set-local 'org-todo-kwd-alist nil)
3891 (org-set-local 'org-todo-key-alist nil)
3892 (org-set-local 'org-todo-key-trigger nil)
3893 (org-set-local 'org-todo-keywords-1 nil)
3894 (org-set-local 'org-done-keywords nil)
3895 (org-set-local 'org-todo-heads nil)
3896 (org-set-local 'org-todo-sets nil)
3897 (org-set-local 'org-todo-log-states nil)
3898 (let ((re (org-make-options-regexp
3899 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3900 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3901 "CONSTANTS" "PROPERTY")))
3902 (splitre "[ \t]+")
3903 kwds kws0 kwsa key value cat arch tags const links hw dws
3904 tail sep kws1 prio props
3905 ex log note)
3906 (save-excursion
3907 (save-restriction
3908 (widen)
3909 (goto-char (point-min))
3910 (while (re-search-forward re nil t)
3911 (setq key (match-string 1) value (org-match-string-no-properties 2))
3912 (cond
3913 ((equal key "CATEGORY")
3914 (if (string-match "[ \t]+$" value)
3915 (setq value (replace-match "" t t value)))
3916 (setq cat (intern value)))
3917 ((member key '("SEQ_TODO" "TODO"))
3918 (push (cons 'sequence (org-split-string value splitre)) kwds))
3919 ((equal key "TYP_TODO")
3920 (push (cons 'type (org-split-string value splitre)) kwds))
3921 ((equal key "TAGS")
3922 (setq tags (append tags (org-split-string value splitre))))
3923 ((equal key "COLUMNS")
3924 (org-set-local 'org-columns-default-format value))
3925 ((equal key "LINK")
3926 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3927 (push (cons (match-string 1 value)
3928 (org-trim (match-string 2 value)))
3929 links)))
3930 ((equal key "PRIORITIES")
3931 (setq prio (org-split-string value " +")))
3932 ((equal key "PROPERTY")
3933 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3934 (push (cons (match-string 1 value) (match-string 2 value))
3935 props)))
3936 ((equal key "CONSTANTS")
3937 (setq const (append const (org-split-string value splitre))))
3938 ((equal key "STARTUP")
3939 (let ((opts (org-split-string value splitre))
3940 l var val)
3941 (while (setq l (pop opts))
3942 (when (setq l (assoc l org-startup-options))
3943 (setq var (nth 1 l) val (nth 2 l))
3944 (if (not (nth 3 l))
3945 (set (make-local-variable var) val)
3946 (if (not (listp (symbol-value var)))
3947 (set (make-local-variable var) nil))
3948 (set (make-local-variable var) (symbol-value var))
3949 (add-to-list var val))))))
3950 ((equal key "ARCHIVE")
3951 (string-match " *$" value)
3952 (setq arch (replace-match "" t t value))
3953 (remove-text-properties 0 (length arch)
3954 '(face t fontified t) arch)))
3956 (and cat (org-set-local 'org-category cat))
3957 (when prio
3958 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3959 (setq prio (mapcar 'string-to-char prio))
3960 (org-set-local 'org-highest-priority (nth 0 prio))
3961 (org-set-local 'org-lowest-priority (nth 1 prio))
3962 (org-set-local 'org-default-priority (nth 2 prio)))
3963 (and props (org-set-local 'org-local-properties (nreverse props)))
3964 (and arch (org-set-local 'org-archive-location arch))
3965 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3966 ;; Process the TODO keywords
3967 (unless kwds
3968 ;; Use the global values as if they had been given locally.
3969 (setq kwds (default-value 'org-todo-keywords))
3970 (if (stringp (car kwds))
3971 (setq kwds (list (cons org-todo-interpretation
3972 (default-value 'org-todo-keywords)))))
3973 (setq kwds (reverse kwds)))
3974 (setq kwds (nreverse kwds))
3975 (let (inter kws kw)
3976 (while (setq kws (pop kwds))
3977 (setq inter (pop kws) sep (member "|" kws)
3978 kws0 (delete "|" (copy-sequence kws))
3979 kwsa nil
3980 kws1 (mapcar
3981 (lambda (x)
3982 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
3983 (progn
3984 (setq kw (match-string 1 x)
3985 ex (and (match-end 2) (match-string 2 x))
3986 log (and ex (string-match "@" ex))
3987 key (and ex (substring ex 0 1)))
3988 (if (equal key "@") (setq key nil))
3989 (push (cons kw (and key (string-to-char key))) kwsa)
3990 (and log (push kw org-todo-log-states))
3992 (error "Invalid TODO keyword %s" x)))
3993 kws0)
3994 kwsa (if kwsa (append '((:startgroup))
3995 (nreverse kwsa)
3996 '((:endgroup))))
3997 hw (car kws1)
3998 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3999 tail (list inter hw (car dws) (org-last dws)))
4000 (add-to-list 'org-todo-heads hw 'append)
4001 (push kws1 org-todo-sets)
4002 (setq org-done-keywords (append org-done-keywords dws nil))
4003 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4004 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4005 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4006 (setq org-todo-sets (nreverse org-todo-sets)
4007 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4008 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4009 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4010 ;; Process the constants
4011 (when const
4012 (let (e cst)
4013 (while (setq e (pop const))
4014 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4015 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4016 (setq org-table-formula-constants-local cst)))
4018 ;; Process the tags.
4019 (when tags
4020 (let (e tgs)
4021 (while (setq e (pop tags))
4022 (cond
4023 ((equal e "{") (push '(:startgroup) tgs))
4024 ((equal e "}") (push '(:endgroup) tgs))
4025 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4026 (push (cons (match-string 1 e)
4027 (string-to-char (match-string 2 e)))
4028 tgs))
4029 (t (push (list e) tgs))))
4030 (org-set-local 'org-tag-alist nil)
4031 (while (setq e (pop tgs))
4032 (or (and (stringp (car e))
4033 (assoc (car e) org-tag-alist))
4034 (push e org-tag-alist))))))
4036 ;; Compute the regular expressions and other local variables
4037 (if (not org-done-keywords)
4038 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4039 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4040 (length org-scheduled-string)))
4041 org-drawer-regexp
4042 (concat "^[ \t]*:\\("
4043 (mapconcat 'regexp-quote org-drawers "\\|")
4044 "\\):[ \t]*$")
4045 org-not-done-keywords
4046 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4047 org-todo-regexp
4048 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4049 "\\|") "\\)\\>")
4050 org-not-done-regexp
4051 (concat "\\<\\("
4052 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4053 "\\)\\>")
4054 org-todo-line-regexp
4055 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4056 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4057 "\\)\\>\\)?[ \t]*\\(.*\\)")
4058 org-nl-done-regexp
4059 (concat "\n\\*+[ \t]+"
4060 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4061 "\\)" "\\>")
4062 org-todo-line-tags-regexp
4063 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4064 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4065 (org-re
4066 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4067 org-looking-at-done-regexp
4068 (concat "^" "\\(?:"
4069 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4070 "\\>")
4071 org-deadline-regexp (concat "\\<" org-deadline-string)
4072 org-deadline-time-regexp
4073 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4074 org-deadline-line-regexp
4075 (concat "\\<\\(" org-deadline-string "\\).*")
4076 org-scheduled-regexp
4077 (concat "\\<" org-scheduled-string)
4078 org-scheduled-time-regexp
4079 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4080 org-closed-time-regexp
4081 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4082 org-keyword-time-regexp
4083 (concat "\\<\\(" org-scheduled-string
4084 "\\|" org-deadline-string
4085 "\\|" org-closed-string
4086 "\\|" org-clock-string "\\)"
4087 " *[[<]\\([^]>]+\\)[]>]")
4088 org-keyword-time-not-clock-regexp
4089 (concat "\\<\\(" org-scheduled-string
4090 "\\|" org-deadline-string
4091 "\\|" org-closed-string
4092 "\\)"
4093 " *[[<]\\([^]>]+\\)[]>]")
4094 org-maybe-keyword-time-regexp
4095 (concat "\\(\\<\\(" org-scheduled-string
4096 "\\|" org-deadline-string
4097 "\\|" org-closed-string
4098 "\\|" org-clock-string "\\)\\)?"
4099 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4100 org-planning-or-clock-line-re
4101 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4102 "\\|" org-deadline-string
4103 "\\|" org-closed-string "\\|" org-clock-string
4104 "\\)\\>\\)")
4107 (org-set-font-lock-defaults)))
4109 (defun org-remove-keyword-keys (list)
4110 (mapcar (lambda (x)
4111 (if (string-match "(..?)$" x)
4112 (substring x 0 (match-beginning 0))
4114 list))
4116 ;;; Some variables ujsed in various places
4118 (defvar org-window-configuration nil
4119 "Used in various places to store a window configuration.")
4120 (defvar org-finish-function nil
4121 "Function to be called when `C-c C-c' is used.
4122 This is for getting out of special buffers like remember.")
4124 ;;; Foreign variables, to inform the compiler
4126 ;; XEmacs only
4127 (defvar outline-mode-menu-heading)
4128 (defvar outline-mode-menu-show)
4129 (defvar outline-mode-menu-hide)
4130 (defvar zmacs-regions) ; XEmacs regions
4131 ;; Emacs only
4132 (defvar mark-active)
4134 ;; Packages that org-mode interacts with
4135 (defvar calc-embedded-close-formula)
4136 (defvar calc-embedded-open-formula)
4137 (defvar font-lock-unfontify-region-function)
4138 (defvar org-goto-start-pos)
4139 (defvar vm-message-pointer)
4140 (defvar vm-folder-directory)
4141 (defvar wl-summary-buffer-elmo-folder)
4142 (defvar wl-summary-buffer-folder-name)
4143 (defvar gnus-other-frame-object)
4144 (defvar gnus-group-name)
4145 (defvar gnus-article-current)
4146 (defvar w3m-current-url)
4147 (defvar w3m-current-title)
4148 (defvar mh-progs)
4149 (defvar mh-current-folder)
4150 (defvar mh-show-folder-buffer)
4151 (defvar mh-index-folder)
4152 (defvar mh-searcher)
4153 (defvar calendar-mode-map)
4154 (defvar Info-current-file)
4155 (defvar Info-current-node)
4156 (defvar texmathp-why)
4157 (defvar remember-save-after-remembering)
4158 (defvar remember-data-file)
4159 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4160 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4161 (defvar org-latex-regexps)
4162 (defvar constants-unit-system)
4164 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4166 ;; FIXME: Occasionally check by commenting these, to make sure
4167 ;; no other functions uses these, forgetting to let-bind them.
4168 (defvar entry)
4169 (defvar state)
4170 (defvar last-state)
4171 (defvar date)
4172 (defvar description)
4175 ;; Defined somewhere in this file, but used before definition.
4176 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4177 (defvar org-agenda-buffer-name)
4178 (defvar org-agenda-undo-list)
4179 (defvar org-agenda-pending-undo-list)
4180 (defvar org-agenda-overriding-header)
4181 (defvar orgtbl-mode)
4182 (defvar org-html-entities)
4183 (defvar org-struct-menu)
4184 (defvar org-org-menu)
4185 (defvar org-tbl-menu)
4186 (defvar org-agenda-keymap)
4188 ;;;; Emacs/XEmacs compatibility
4190 ;; Overlay compatibility functions
4191 (defun org-make-overlay (beg end &optional buffer)
4192 (if (featurep 'xemacs)
4193 (make-extent beg end buffer)
4194 (make-overlay beg end buffer)))
4195 (defun org-delete-overlay (ovl)
4196 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4197 (defun org-detach-overlay (ovl)
4198 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4199 (defun org-move-overlay (ovl beg end &optional buffer)
4200 (if (featurep 'xemacs)
4201 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4202 (move-overlay ovl beg end buffer)))
4203 (defun org-overlay-put (ovl prop value)
4204 (if (featurep 'xemacs)
4205 (set-extent-property ovl prop value)
4206 (overlay-put ovl prop value)))
4207 (defun org-overlay-display (ovl text &optional face evap)
4208 "Make overlay OVL display TEXT with face FACE."
4209 (if (featurep 'xemacs)
4210 (let ((gl (make-glyph text)))
4211 (and face (set-glyph-face gl face))
4212 (set-extent-property ovl 'invisible t)
4213 (set-extent-property ovl 'end-glyph gl))
4214 (overlay-put ovl 'display text)
4215 (if face (overlay-put ovl 'face face))
4216 (if evap (overlay-put ovl 'evaporate t))))
4217 (defun org-overlay-before-string (ovl text &optional face evap)
4218 "Make overlay OVL display TEXT with face FACE."
4219 (if (featurep 'xemacs)
4220 (let ((gl (make-glyph text)))
4221 (and face (set-glyph-face gl face))
4222 (set-extent-property ovl 'begin-glyph gl))
4223 (if face (org-add-props text nil 'face face))
4224 (overlay-put ovl 'before-string text)
4225 (if evap (overlay-put ovl 'evaporate t))))
4226 (defun org-overlay-get (ovl prop)
4227 (if (featurep 'xemacs)
4228 (extent-property ovl prop)
4229 (overlay-get ovl prop)))
4230 (defun org-overlays-at (pos)
4231 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4232 (defun org-overlays-in (&optional start end)
4233 (if (featurep 'xemacs)
4234 (extent-list nil start end)
4235 (overlays-in start end)))
4236 (defun org-overlay-start (o)
4237 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4238 (defun org-overlay-end (o)
4239 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4240 (defun org-find-overlays (prop &optional pos delete)
4241 "Find all overlays specifying PROP at POS or point.
4242 If DELETE is non-nil, delete all those overlays."
4243 (let ((overlays (org-overlays-at (or pos (point))))
4244 ov found)
4245 (while (setq ov (pop overlays))
4246 (if (org-overlay-get ov prop)
4247 (if delete (org-delete-overlay ov) (push ov found))))
4248 found))
4250 ;; Region compatibility
4252 (defun org-add-hook (hook function &optional append local)
4253 "Add-hook, compatible with both Emacsen."
4254 (if (and local (featurep 'xemacs))
4255 (add-local-hook hook function append)
4256 (add-hook hook function append local)))
4258 (defvar org-ignore-region nil
4259 "To temporarily disable the active region.")
4261 (defun org-region-active-p ()
4262 "Is `transient-mark-mode' on and the region active?
4263 Works on both Emacs and XEmacs."
4264 (if org-ignore-region
4266 (if (featurep 'xemacs)
4267 (and zmacs-regions (region-active-p))
4268 (and transient-mark-mode mark-active))))
4270 ;; Invisibility compatibility
4272 (defun org-add-to-invisibility-spec (arg)
4273 "Add elements to `buffer-invisibility-spec'.
4274 See documentation for `buffer-invisibility-spec' for the kind of elements
4275 that can be added."
4276 (cond
4277 ((fboundp 'add-to-invisibility-spec)
4278 (add-to-invisibility-spec arg))
4279 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4280 (setq buffer-invisibility-spec (list arg)))
4282 (setq buffer-invisibility-spec
4283 (cons arg buffer-invisibility-spec)))))
4285 (defun org-remove-from-invisibility-spec (arg)
4286 "Remove elements from `buffer-invisibility-spec'."
4287 (if (fboundp 'remove-from-invisibility-spec)
4288 (remove-from-invisibility-spec arg)
4289 (if (consp buffer-invisibility-spec)
4290 (setq buffer-invisibility-spec
4291 (delete arg buffer-invisibility-spec)))))
4293 (defun org-in-invisibility-spec-p (arg)
4294 "Is ARG a member of `buffer-invisibility-spec'?"
4295 (if (consp buffer-invisibility-spec)
4296 (member arg buffer-invisibility-spec)
4297 nil))
4299 ;;;; Define the Org-mode
4301 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4302 (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."))
4305 ;; We use a before-change function to check if a table might need
4306 ;; an update.
4307 (defvar org-table-may-need-update t
4308 "Indicates that a table might need an update.
4309 This variable is set by `org-before-change-function'.
4310 `org-table-align' sets it back to nil.")
4311 (defvar org-mode-map)
4312 (defvar org-mode-hook nil)
4313 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4314 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4315 (defvar org-table-buffer-is-an nil)
4316 (defconst org-outline-regexp "\\*+ ")
4318 ;;;###autoload
4319 (define-derived-mode org-mode outline-mode "Org"
4320 "Outline-based notes management and organizer, alias
4321 \"Carsten's outline-mode for keeping track of everything.\"
4323 Org-mode develops organizational tasks around a NOTES file which
4324 contains information about projects as plain text. Org-mode is
4325 implemented on top of outline-mode, which is ideal to keep the content
4326 of large files well structured. It supports ToDo items, deadlines and
4327 time stamps, which magically appear in the diary listing of the Emacs
4328 calendar. Tables are easily created with a built-in table editor.
4329 Plain text URL-like links connect to websites, emails (VM), Usenet
4330 messages (Gnus), BBDB entries, and any files related to the project.
4331 For printing and sharing of notes, an Org-mode file (or a part of it)
4332 can be exported as a structured ASCII or HTML file.
4334 The following commands are available:
4336 \\{org-mode-map}"
4338 ;; Get rid of Outline menus, they are not needed
4339 ;; Need to do this here because define-derived-mode sets up
4340 ;; the keymap so late. Still, it is a waste to call this each time
4341 ;; we switch another buffer into org-mode.
4342 (if (featurep 'xemacs)
4343 (when (boundp 'outline-mode-menu-heading)
4344 ;; Assume this is Greg's port, it used easymenu
4345 (easy-menu-remove outline-mode-menu-heading)
4346 (easy-menu-remove outline-mode-menu-show)
4347 (easy-menu-remove outline-mode-menu-hide))
4348 (define-key org-mode-map [menu-bar headings] 'undefined)
4349 (define-key org-mode-map [menu-bar hide] 'undefined)
4350 (define-key org-mode-map [menu-bar show] 'undefined))
4352 (easy-menu-add org-org-menu)
4353 (easy-menu-add org-tbl-menu)
4354 (org-install-agenda-files-menu)
4355 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4356 (org-add-to-invisibility-spec '(org-cwidth))
4357 (when (featurep 'xemacs)
4358 (org-set-local 'line-move-ignore-invisible t))
4359 (org-set-local 'outline-regexp org-outline-regexp)
4360 (org-set-local 'outline-level 'org-outline-level)
4361 (when (and org-ellipsis
4362 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4363 (fboundp 'make-glyph-code))
4364 (unless org-display-table
4365 (setq org-display-table (make-display-table)))
4366 (set-display-table-slot
4367 org-display-table 4
4368 (vconcat (mapcar
4369 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4370 org-ellipsis)))
4371 (if (stringp org-ellipsis) org-ellipsis "..."))))
4372 (setq buffer-display-table org-display-table))
4373 (org-set-regexps-and-options)
4374 ;; Calc embedded
4375 (org-set-local 'calc-embedded-open-mode "# ")
4376 (modify-syntax-entry ?# "<")
4377 (modify-syntax-entry ?@ "w")
4378 (if org-startup-truncated (setq truncate-lines t))
4379 (org-set-local 'font-lock-unfontify-region-function
4380 'org-unfontify-region)
4381 ;; Activate before-change-function
4382 (org-set-local 'org-table-may-need-update t)
4383 (org-add-hook 'before-change-functions 'org-before-change-function nil
4384 'local)
4385 ;; Check for running clock before killing a buffer
4386 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4387 ;; Paragraphs and auto-filling
4388 (org-set-autofill-regexps)
4389 (setq indent-line-function 'org-indent-line-function)
4390 (org-update-radio-target-regexp)
4392 ;; Comment characters
4393 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4394 (org-set-local 'comment-padding " ")
4396 ;; Make isearch reveal context
4397 (if (or (featurep 'xemacs)
4398 (not (boundp 'outline-isearch-open-invisible-function)))
4399 ;; Emacs 21 and XEmacs make use of the hook
4400 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4401 ;; Emacs 22 deals with this through a special variable
4402 (org-set-local 'outline-isearch-open-invisible-function
4403 (lambda (&rest ignore) (org-show-context 'isearch))))
4405 ;; If empty file that did not turn on org-mode automatically, make it to.
4406 (if (and org-insert-mode-line-in-empty-file
4407 (interactive-p)
4408 (= (point-min) (point-max)))
4409 (insert "# -*- mode: org -*-\n\n"))
4411 (unless org-inhibit-startup
4412 (when org-startup-align-all-tables
4413 (let ((bmp (buffer-modified-p)))
4414 (org-table-map-tables 'org-table-align)
4415 (set-buffer-modified-p bmp)))
4416 (org-cycle-hide-drawers 'all)
4417 (cond
4418 ((eq org-startup-folded t)
4419 (org-cycle '(4)))
4420 ((eq org-startup-folded 'content)
4421 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4422 (org-cycle '(4)) (org-cycle '(4)))))))
4424 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4426 (defsubst org-call-with-arg (command arg)
4427 "Call COMMAND interactively, but pretend prefix are was ARG."
4428 (let ((current-prefix-arg arg)) (call-interactively command)))
4430 (defsubst org-current-line (&optional pos)
4431 (save-excursion
4432 (and pos (goto-char pos))
4433 ;; works also in narrowed buffer, because we start at 1, not point-min
4434 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4436 (defun org-current-time ()
4437 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4438 (if (> org-time-stamp-rounding-minutes 0)
4439 (let ((r org-time-stamp-rounding-minutes)
4440 (time (decode-time)))
4441 (apply 'encode-time
4442 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4443 (nthcdr 2 time))))
4444 (current-time)))
4446 (defun org-add-props (string plist &rest props)
4447 "Add text properties to entire string, from beginning to end.
4448 PLIST may be a list of properties, PROPS are individual properties and values
4449 that will be added to PLIST. Returns the string that was modified."
4450 (add-text-properties
4451 0 (length string) (if props (append plist props) plist) string)
4452 string)
4453 (put 'org-add-props 'lisp-indent-function 2)
4456 ;;;; Font-Lock stuff, including the activators
4458 (defvar org-mouse-map (make-sparse-keymap))
4459 (org-defkey org-mouse-map
4460 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4461 (org-defkey org-mouse-map
4462 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4463 (when org-mouse-1-follows-link
4464 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4465 (when org-tab-follows-link
4466 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4467 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4468 (when org-return-follows-link
4469 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4470 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4472 (require 'font-lock)
4474 (defconst org-non-link-chars "]\t\n\r<>")
4475 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4476 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4477 (defvar org-link-re-with-space nil
4478 "Matches a link with spaces, optional angular brackets around it.")
4479 (defvar org-link-re-with-space2 nil
4480 "Matches a link with spaces, optional angular brackets around it.")
4481 (defvar org-angle-link-re nil
4482 "Matches link with angular brackets, spaces are allowed.")
4483 (defvar org-plain-link-re nil
4484 "Matches plain link, without spaces.")
4485 (defvar org-bracket-link-regexp nil
4486 "Matches a link in double brackets.")
4487 (defvar org-bracket-link-analytic-regexp nil
4488 "Regular expression used to analyze links.
4489 Here is what the match groups contain after a match:
4490 1: http:
4491 2: http
4492 3: path
4493 4: [desc]
4494 5: desc")
4495 (defvar org-any-link-re nil
4496 "Regular expression matching any link.")
4498 (defun org-make-link-regexps ()
4499 "Update the link regular expressions.
4500 This should be called after the variable `org-link-types' has changed."
4501 (setq org-link-re-with-space
4502 (concat
4503 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4504 "\\([^" org-non-link-chars " ]"
4505 "[^" org-non-link-chars "]*"
4506 "[^" org-non-link-chars " ]\\)>?")
4507 org-link-re-with-space2
4508 (concat
4509 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4510 "\\([^" org-non-link-chars " ]"
4511 "[^]\t\n\r]*"
4512 "[^" org-non-link-chars " ]\\)>?")
4513 org-angle-link-re
4514 (concat
4515 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4516 "\\([^" org-non-link-chars " ]"
4517 "[^" org-non-link-chars "]*"
4518 "\\)>")
4519 org-plain-link-re
4520 (concat
4521 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4522 "\\([^]\t\n\r<>,;() ]+\\)")
4523 org-bracket-link-regexp
4524 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4525 org-bracket-link-analytic-regexp
4526 (concat
4527 "\\[\\["
4528 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4529 "\\([^]]+\\)"
4530 "\\]"
4531 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4532 "\\]")
4533 org-any-link-re
4534 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4535 org-angle-link-re "\\)\\|\\("
4536 org-plain-link-re "\\)")))
4538 (org-make-link-regexps)
4540 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4541 "Regular expression for fast time stamp matching.")
4542 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4543 "Regular expression for fast time stamp matching.")
4544 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4545 "Regular expression matching time strings for analysis.
4546 This one does not require the space after the date.")
4547 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4548 "Regular expression matching time strings for analysis.")
4549 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4550 "Regular expression matching time stamps, with groups.")
4551 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4552 "Regular expression matching time stamps (also [..]), with groups.")
4553 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4554 "Regular expression matching a time stamp range.")
4555 (defconst org-tr-regexp-both
4556 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4557 "Regular expression matching a time stamp range.")
4558 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4559 org-ts-regexp "\\)?")
4560 "Regular expression matching a time stamp or time stamp range.")
4561 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4562 org-ts-regexp-both "\\)?")
4563 "Regular expression matching a time stamp or time stamp range.
4564 The time stamps may be either active or inactive.")
4566 (defvar org-emph-face nil)
4568 (defun org-do-emphasis-faces (limit)
4569 "Run through the buffer and add overlays to links."
4570 (let (rtn)
4571 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4572 (if (not (= (char-after (match-beginning 3))
4573 (char-after (match-beginning 4))))
4574 (progn
4575 (setq rtn t)
4576 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4577 'face
4578 (nth 1 (assoc (match-string 3)
4579 org-emphasis-alist)))
4580 (add-text-properties (match-beginning 2) (match-end 2)
4581 '(font-lock-multiline t))
4582 (backward-char 1))))
4583 rtn))
4585 (defun org-emphasize (&optional char)
4586 "Insert or change an emphasis, i.e. a font like bold or italic.
4587 If there is an active region, change that region to a new emphasis.
4588 If there is no region, just insert the marker characters and position
4589 the cursor between them.
4590 CHAR should be either the marker character, or the first character of the
4591 HTML tag associated with that emphasis. If CHAR is a space, the means
4592 to remove the emphasis of the selected region.
4593 If char is not given (for example in an interactive call) it
4594 will be prompted for."
4595 (interactive)
4596 (let ((eal org-emphasis-alist) e det
4597 (erc org-emphasis-regexp-components)
4598 (prompt "")
4599 (string "") beg end move tag c s)
4600 (if (org-region-active-p)
4601 (setq beg (region-beginning) end (region-end)
4602 string (buffer-substring beg end))
4603 (setq move t))
4605 (while (setq e (pop eal))
4606 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4607 c (aref tag 0))
4608 (push (cons c (string-to-char (car e))) det)
4609 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4610 (substring tag 1)))))
4611 (unless char
4612 (message "%s" (concat "Emphasis marker or tag:" prompt))
4613 (setq char (read-char-exclusive)))
4614 (setq char (or (cdr (assoc char det)) char))
4615 (if (equal char ?\ )
4616 (setq s "" move nil)
4617 (unless (assoc (char-to-string char) org-emphasis-alist)
4618 (error "No such emphasis marker: \"%c\"" char))
4619 (setq s (char-to-string char)))
4620 (while (and (> (length string) 1)
4621 (equal (substring string 0 1) (substring string -1))
4622 (assoc (substring string 0 1) org-emphasis-alist))
4623 (setq string (substring string 1 -1)))
4624 (setq string (concat s string s))
4625 (if beg (delete-region beg end))
4626 (unless (or (bolp)
4627 (string-match (concat "[" (nth 0 erc) "\n]")
4628 (char-to-string (char-before (point)))))
4629 (insert " "))
4630 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4631 (char-to-string (char-after (point))))
4632 (insert " ") (backward-char 1))
4633 (insert string)
4634 (and move (backward-char 1))))
4636 (defconst org-nonsticky-props
4637 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4639 (defun org-activate-plain-links (limit)
4640 "Run through the buffer and add overlays to links."
4641 (catch 'exit
4642 (let (f)
4643 (while (re-search-forward org-plain-link-re limit t)
4644 (setq f (get-text-property (match-beginning 0) 'face))
4645 (if (or (eq f 'org-tag)
4646 (and (listp f) (memq 'org-tag f)))
4648 (add-text-properties (match-beginning 0) (match-end 0)
4649 (list 'mouse-face 'highlight
4650 'rear-nonsticky org-nonsticky-props
4651 'keymap org-mouse-map
4653 (throw 'exit t))))))
4655 (defun org-activate-angle-links (limit)
4656 "Run through the buffer and add overlays to links."
4657 (if (re-search-forward org-angle-link-re limit t)
4658 (progn
4659 (add-text-properties (match-beginning 0) (match-end 0)
4660 (list 'mouse-face 'highlight
4661 'rear-nonsticky org-nonsticky-props
4662 'keymap org-mouse-map
4664 t)))
4666 (defmacro org-maybe-intangible (props)
4667 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4668 In emacs 21, invisible text is not avoided by the command loop, so the
4669 intangible property is needed to make sure point skips this text.
4670 In Emacs 22, this is not necessary. The intangible text property has
4671 led to problems with flyspell. These problems are fixed in flyspell.el,
4672 but we still avoid setting the property in Emacs 22 and later.
4673 We use a macro so that the test can happen at compilation time."
4674 (if (< emacs-major-version 22)
4675 `(append '(intangible t) ,props)
4676 props))
4678 (defun org-activate-bracket-links (limit)
4679 "Run through the buffer and add overlays to bracketed links."
4680 (if (re-search-forward org-bracket-link-regexp limit t)
4681 (let* ((help (concat "LINK: "
4682 (org-match-string-no-properties 1)))
4683 ;; FIXME: above we should remove the escapes.
4684 ;; but that requires another match, protecting match data,
4685 ;; a lot of overhead for font-lock.
4686 (ip (org-maybe-intangible
4687 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4688 'keymap org-mouse-map 'mouse-face 'highlight
4689 'help-echo help)))
4690 (vp (list 'rear-nonsticky org-nonsticky-props
4691 'keymap org-mouse-map 'mouse-face 'highlight
4692 'help-echo help)))
4693 ;; We need to remove the invisible property here. Table narrowing
4694 ;; may have made some of this invisible.
4695 (remove-text-properties (match-beginning 0) (match-end 0)
4696 '(invisible nil))
4697 (if (match-end 3)
4698 (progn
4699 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4700 (add-text-properties (match-beginning 3) (match-end 3) vp)
4701 (add-text-properties (match-end 3) (match-end 0) ip))
4702 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4703 (add-text-properties (match-beginning 1) (match-end 1) vp)
4704 (add-text-properties (match-end 1) (match-end 0) ip))
4705 t)))
4707 (defun org-activate-dates (limit)
4708 "Run through the buffer and add overlays to dates."
4709 (if (re-search-forward org-tsr-regexp-both limit t)
4710 (progn
4711 (add-text-properties (match-beginning 0) (match-end 0)
4712 (list 'mouse-face 'highlight
4713 'rear-nonsticky org-nonsticky-props
4714 'keymap org-mouse-map))
4715 (when org-display-custom-times
4716 (if (match-end 3)
4717 (org-display-custom-time (match-beginning 3) (match-end 3)))
4718 (org-display-custom-time (match-beginning 1) (match-end 1)))
4719 t)))
4721 (defvar org-target-link-regexp nil
4722 "Regular expression matching radio targets in plain text.")
4723 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4724 "Regular expression matching a link target.")
4725 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4726 "Regular expression matching a radio target.")
4727 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4728 "Regular expression matching any target.")
4730 (defun org-activate-target-links (limit)
4731 "Run through the buffer and add overlays to target matches."
4732 (when org-target-link-regexp
4733 (let ((case-fold-search t))
4734 (if (re-search-forward org-target-link-regexp limit t)
4735 (progn
4736 (add-text-properties (match-beginning 0) (match-end 0)
4737 (list 'mouse-face 'highlight
4738 'rear-nonsticky org-nonsticky-props
4739 'keymap org-mouse-map
4740 'help-echo "Radio target link"
4741 'org-linked-text t))
4742 t)))))
4744 (defun org-update-radio-target-regexp ()
4745 "Find all radio targets in this file and update the regular expression."
4746 (interactive)
4747 (when (memq 'radio org-activate-links)
4748 (setq org-target-link-regexp
4749 (org-make-target-link-regexp (org-all-targets 'radio)))
4750 (org-restart-font-lock)))
4752 (defun org-hide-wide-columns (limit)
4753 (let (s e)
4754 (setq s (text-property-any (point) (or limit (point-max))
4755 'org-cwidth t))
4756 (when s
4757 (setq e (next-single-property-change s 'org-cwidth))
4758 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4759 (goto-char e)
4760 t)))
4762 (defun org-restart-font-lock ()
4763 "Restart font-lock-mode, to force refontification."
4764 (when (and (boundp 'font-lock-mode) font-lock-mode)
4765 (font-lock-mode -1)
4766 (font-lock-mode 1)))
4768 (defun org-all-targets (&optional radio)
4769 "Return a list of all targets in this file.
4770 With optional argument RADIO, only find radio targets."
4771 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4772 rtn)
4773 (save-excursion
4774 (goto-char (point-min))
4775 (while (re-search-forward re nil t)
4776 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4777 rtn)))
4779 (defun org-make-target-link-regexp (targets)
4780 "Make regular expression matching all strings in TARGETS.
4781 The regular expression finds the targets also if there is a line break
4782 between words."
4783 (and targets
4784 (concat
4785 "\\<\\("
4786 (mapconcat
4787 (lambda (x)
4788 (while (string-match " +" x)
4789 (setq x (replace-match "\\s-+" t t x)))
4791 targets
4792 "\\|")
4793 "\\)\\>")))
4795 (defun org-activate-tags (limit)
4796 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4797 (progn
4798 (add-text-properties (match-beginning 1) (match-end 1)
4799 (list 'mouse-face 'highlight
4800 'rear-nonsticky org-nonsticky-props
4801 'keymap org-mouse-map))
4802 t)))
4804 (defun org-outline-level ()
4805 (save-excursion
4806 (looking-at outline-regexp)
4807 (if (match-beginning 1)
4808 (+ (org-get-string-indentation (match-string 1)) 1000)
4809 (1- (- (match-end 0) (match-beginning 0))))))
4811 (defvar org-font-lock-keywords nil)
4813 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
4814 "Regular expression matching a property line.")
4816 (defun org-set-font-lock-defaults ()
4817 (let* ((em org-fontify-emphasized-text)
4818 (lk org-activate-links)
4819 (org-font-lock-extra-keywords
4820 (list
4821 ;; Headlines
4822 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4823 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4824 ;; Table lines
4825 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4826 (1 'org-table))
4827 ;; Links
4828 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4829 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4830 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4831 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4832 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4833 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4834 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4835 '(org-hide-wide-columns (0 nil append))
4836 ;; TODO lines
4837 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4838 '(1 (org-get-todo-face 1) t))
4839 ;; DONE
4840 (if org-fontify-done-headline
4841 (list (concat "^[*]+ +\\<\\("
4842 (mapconcat 'regexp-quote org-done-keywords "\\|")
4843 "\\)\\(.*\\)")
4844 '(2 'org-headline-done t))
4845 nil)
4846 ;; Priorities
4847 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4848 ;; Special keywords
4849 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4850 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4851 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4852 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4853 ;; Emphasis
4854 (if em
4855 (if (featurep 'xemacs)
4856 '(org-do-emphasis-faces (0 nil append))
4857 '(org-do-emphasis-faces)))
4858 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4859 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4860 2 'bold prepend)
4861 (if org-provide-checkbox-statistics
4862 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4863 (0 (org-get-checkbox-statistics-face) t)))
4864 ;; COMMENT
4865 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4866 "\\|" org-quote-string "\\)\\>")
4867 '(1 'org-special-keyword t))
4868 '("^#.*" (0 'font-lock-comment-face t))
4869 ;; Code
4870 '("^[ \t]*\\(:.*\\)" (1 'org-code t))
4871 ;; Table internals
4872 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4873 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4874 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4875 ;; Drawers
4876 (list org-drawer-regexp '(0 'org-special-keyword t))
4877 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4878 ;; Properties
4879 (list org-property-re
4880 '(1 'org-special-keyword t)
4881 '(3 'org-property-value t))
4882 (if org-format-transports-properties-p
4883 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4884 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4886 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4887 ;; Now set the full font-lock-keywords
4888 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4889 (org-set-local 'font-lock-defaults
4890 '(org-font-lock-keywords t nil nil backward-paragraph))
4891 (kill-local-variable 'font-lock-keywords) nil))
4893 (defvar org-m nil)
4894 (defvar org-l nil)
4895 (defvar org-f nil)
4896 (defun org-get-level-face (n)
4897 "Get the right face for match N in font-lock matching of healdines."
4898 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4899 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4900 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4901 (cond
4902 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4903 ((eq n 2) org-f)
4904 (t (if org-level-color-stars-only nil org-f))))
4906 (defun org-get-todo-face (kwd)
4907 "Get the right face for a TODO keyword KWD.
4908 If KWD is a number, get the corresponding match group."
4909 (if (numberp kwd) (setq kwd (match-string kwd)))
4910 (or (cdr (assoc kwd org-todo-keyword-faces))
4911 (and (member kwd org-done-keywords) 'org-done)
4912 'org-todo))
4914 (defun org-unfontify-region (beg end &optional maybe_loudly)
4915 "Remove fontification and activation overlays from links."
4916 (font-lock-default-unfontify-region beg end)
4917 (let* ((buffer-undo-list t)
4918 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4919 (inhibit-modification-hooks t)
4920 deactivate-mark buffer-file-name buffer-file-truename)
4921 (remove-text-properties beg end
4922 '(mouse-face t keymap t org-linked-text t
4923 invisible t intangible t))))
4925 ;;;; Visibility cycling, including org-goto and indirect buffer
4927 ;;; Cycling
4929 (defvar org-cycle-global-status nil)
4930 (make-variable-buffer-local 'org-cycle-global-status)
4931 (defvar org-cycle-subtree-status nil)
4932 (make-variable-buffer-local 'org-cycle-subtree-status)
4934 ;;;###autoload
4935 (defun org-cycle (&optional arg)
4936 "Visibility cycling for Org-mode.
4938 - When this function is called with a prefix argument, rotate the entire
4939 buffer through 3 states (global cycling)
4940 1. OVERVIEW: Show only top-level headlines.
4941 2. CONTENTS: Show all headlines of all levels, but no body text.
4942 3. SHOW ALL: Show everything.
4944 - When point is at the beginning of a headline, rotate the subtree started
4945 by this line through 3 different states (local cycling)
4946 1. FOLDED: Only the main headline is shown.
4947 2. CHILDREN: The main headline and the direct children are shown.
4948 From this state, you can move to one of the children
4949 and zoom in further.
4950 3. SUBTREE: Show the entire subtree, including body text.
4952 - When there is a numeric prefix, go up to a heading with level ARG, do
4953 a `show-subtree' and return to the previous cursor position. If ARG
4954 is negative, go up that many levels.
4956 - When point is not at the beginning of a headline, execute
4957 `indent-relative', like TAB normally does. See the option
4958 `org-cycle-emulate-tab' for details.
4960 - Special case: if point is at the beginning of the buffer and there is
4961 no headline in line 1, this function will act as if called with prefix arg.
4962 But only if also the variable `org-cycle-global-at-bob' is t."
4963 (interactive "P")
4964 (let* ((outline-regexp
4965 (if (and (org-mode-p) org-cycle-include-plain-lists)
4966 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4967 outline-regexp))
4968 (bob-special (and org-cycle-global-at-bob (bobp)
4969 (not (looking-at outline-regexp))))
4970 (org-cycle-hook
4971 (if bob-special
4972 (delq 'org-optimize-window-after-visibility-change
4973 (copy-sequence org-cycle-hook))
4974 org-cycle-hook))
4975 (pos (point)))
4977 (if (or bob-special (equal arg '(4)))
4978 ;; special case: use global cycling
4979 (setq arg t))
4981 (cond
4983 ((org-at-table-p 'any)
4984 ;; Enter the table or move to the next field in the table
4985 (or (org-table-recognize-table.el)
4986 (progn
4987 (if arg (org-table-edit-field t)
4988 (org-table-justify-field-maybe)
4989 (call-interactively 'org-table-next-field)))))
4991 ((eq arg t) ;; Global cycling
4993 (cond
4994 ((and (eq last-command this-command)
4995 (eq org-cycle-global-status 'overview))
4996 ;; We just created the overview - now do table of contents
4997 ;; This can be slow in very large buffers, so indicate action
4998 (message "CONTENTS...")
4999 (org-content)
5000 (message "CONTENTS...done")
5001 (setq org-cycle-global-status 'contents)
5002 (run-hook-with-args 'org-cycle-hook 'contents))
5004 ((and (eq last-command this-command)
5005 (eq org-cycle-global-status 'contents))
5006 ;; We just showed the table of contents - now show everything
5007 (show-all)
5008 (message "SHOW ALL")
5009 (setq org-cycle-global-status 'all)
5010 (run-hook-with-args 'org-cycle-hook 'all))
5013 ;; Default action: go to overview
5014 (org-overview)
5015 (message "OVERVIEW")
5016 (setq org-cycle-global-status 'overview)
5017 (run-hook-with-args 'org-cycle-hook 'overview))))
5019 ((and org-drawers org-drawer-regexp
5020 (save-excursion
5021 (beginning-of-line 1)
5022 (looking-at org-drawer-regexp)))
5023 ;; Toggle block visibility
5024 (org-flag-drawer
5025 (not (get-char-property (match-end 0) 'invisible))))
5027 ((integerp arg)
5028 ;; Show-subtree, ARG levels up from here.
5029 (save-excursion
5030 (org-back-to-heading)
5031 (outline-up-heading (if (< arg 0) (- arg)
5032 (- (funcall outline-level) arg)))
5033 (org-show-subtree)))
5035 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5036 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5037 ;; At a heading: rotate between three different views
5038 (org-back-to-heading)
5039 (let ((goal-column 0) eoh eol eos)
5040 ;; First, some boundaries
5041 (save-excursion
5042 (org-back-to-heading)
5043 (save-excursion
5044 (beginning-of-line 2)
5045 (while (and (not (eobp)) ;; this is like `next-line'
5046 (get-char-property (1- (point)) 'invisible))
5047 (beginning-of-line 2)) (setq eol (point)))
5048 (outline-end-of-heading) (setq eoh (point))
5049 (org-end-of-subtree t)
5050 (unless (eobp)
5051 (skip-chars-forward " \t\n")
5052 (beginning-of-line 1) ; in case this is an item
5054 (setq eos (1- (point))))
5055 ;; Find out what to do next and set `this-command'
5056 (cond
5057 ((= eos eoh)
5058 ;; Nothing is hidden behind this heading
5059 (message "EMPTY ENTRY")
5060 (setq org-cycle-subtree-status nil)
5061 (save-excursion
5062 (goto-char eos)
5063 (outline-next-heading)
5064 (if (org-invisible-p) (org-flag-heading nil))))
5065 ((or (>= eol eos)
5066 (not (string-match "\\S-" (buffer-substring eol eos))))
5067 ;; Entire subtree is hidden in one line: open it
5068 (org-show-entry)
5069 (show-children)
5070 (message "CHILDREN")
5071 (save-excursion
5072 (goto-char eos)
5073 (outline-next-heading)
5074 (if (org-invisible-p) (org-flag-heading nil)))
5075 (setq org-cycle-subtree-status 'children)
5076 (run-hook-with-args 'org-cycle-hook 'children))
5077 ((and (eq last-command this-command)
5078 (eq org-cycle-subtree-status 'children))
5079 ;; We just showed the children, now show everything.
5080 (org-show-subtree)
5081 (message "SUBTREE")
5082 (setq org-cycle-subtree-status 'subtree)
5083 (run-hook-with-args 'org-cycle-hook 'subtree))
5085 ;; Default action: hide the subtree.
5086 (hide-subtree)
5087 (message "FOLDED")
5088 (setq org-cycle-subtree-status 'folded)
5089 (run-hook-with-args 'org-cycle-hook 'folded)))))
5091 ;; TAB emulation
5092 (buffer-read-only (org-back-to-heading))
5094 ((org-try-cdlatex-tab))
5096 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5097 (or (not (bolp))
5098 (not (looking-at outline-regexp))))
5099 (call-interactively (global-key-binding "\t")))
5101 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5102 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5103 (or (and (eq org-cycle-emulate-tab 'white)
5104 (= (match-end 0) (point-at-eol)))
5105 (and (eq org-cycle-emulate-tab 'whitestart)
5106 (>= (match-end 0) pos))))
5108 (eq org-cycle-emulate-tab t))
5109 (if (and (looking-at "[ \n\r\t]")
5110 (string-match "^[ \t]*$" (buffer-substring
5111 (point-at-bol) (point))))
5112 (progn
5113 (beginning-of-line 1)
5114 (and (looking-at "[ \t]+") (replace-match ""))))
5115 (call-interactively (global-key-binding "\t")))
5117 (t (save-excursion
5118 (org-back-to-heading)
5119 (org-cycle))))))
5121 ;;;###autoload
5122 (defun org-global-cycle (&optional arg)
5123 "Cycle the global visibility. For details see `org-cycle'."
5124 (interactive "P")
5125 (let ((org-cycle-include-plain-lists
5126 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5127 (if (integerp arg)
5128 (progn
5129 (show-all)
5130 (hide-sublevels arg)
5131 (setq org-cycle-global-status 'contents))
5132 (org-cycle '(4)))))
5134 (defun org-overview ()
5135 "Switch to overview mode, shoing only top-level headlines.
5136 Really, this shows all headlines with level equal or greater than the level
5137 of the first headline in the buffer. This is important, because if the
5138 first headline is not level one, then (hide-sublevels 1) gives confusing
5139 results."
5140 (interactive)
5141 (let ((level (save-excursion
5142 (goto-char (point-min))
5143 (if (re-search-forward (concat "^" outline-regexp) nil t)
5144 (progn
5145 (goto-char (match-beginning 0))
5146 (funcall outline-level))))))
5147 (and level (hide-sublevels level))))
5149 (defun org-content (&optional arg)
5150 "Show all headlines in the buffer, like a table of contents.
5151 With numerical argument N, show content up to level N."
5152 (interactive "P")
5153 (save-excursion
5154 ;; Visit all headings and show their offspring
5155 (and (integerp arg) (org-overview))
5156 (goto-char (point-max))
5157 (catch 'exit
5158 (while (and (progn (condition-case nil
5159 (outline-previous-visible-heading 1)
5160 (error (goto-char (point-min))))
5162 (looking-at outline-regexp))
5163 (if (integerp arg)
5164 (show-children (1- arg))
5165 (show-branches))
5166 (if (bobp) (throw 'exit nil))))))
5169 (defun org-optimize-window-after-visibility-change (state)
5170 "Adjust the window after a change in outline visibility.
5171 This function is the default value of the hook `org-cycle-hook'."
5172 (when (get-buffer-window (current-buffer))
5173 (cond
5174 ; ((eq state 'overview) (org-first-headline-recenter 1))
5175 ; ((eq state 'overview) (org-beginning-of-line))
5176 ((eq state 'content) nil)
5177 ((eq state 'all) nil)
5178 ((eq state 'folded) nil)
5179 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5180 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5183 (defun org-cycle-show-empty-lines (state)
5184 "Show empty lines above all visible headlines.
5185 The region to be covered depends on STATE when called through
5186 `org-cycle-hook'. Lisp program can use t for STATE to get the
5187 entire buffer covered. Note that an empty line is only shown if there
5188 are at least `org-cycle-separator-lines' empty lines before the headeline."
5189 (when (> org-cycle-separator-lines 0)
5190 (save-excursion
5191 (let* ((n org-cycle-separator-lines)
5192 (re (cond
5193 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5194 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5195 (t (let ((ns (number-to-string (- n 2))))
5196 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5197 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5198 beg end)
5199 (cond
5200 ((memq state '(overview contents t))
5201 (setq beg (point-min) end (point-max)))
5202 ((memq state '(children folded))
5203 (setq beg (point) end (progn (org-end-of-subtree t t)
5204 (beginning-of-line 2)
5205 (point)))))
5206 (when beg
5207 (goto-char beg)
5208 (while (re-search-forward re end t)
5209 (if (not (get-char-property (match-end 1) 'invisible))
5210 (outline-flag-region
5211 (match-beginning 1) (match-end 1) nil)))))))
5212 ;; Never hide empty lines at the end of the file.
5213 (save-excursion
5214 (goto-char (point-max))
5215 (outline-previous-heading)
5216 (outline-end-of-heading)
5217 (if (and (looking-at "[ \t\n]+")
5218 (= (match-end 0) (point-max)))
5219 (outline-flag-region (point) (match-end 0) nil))))
5221 (defun org-subtree-end-visible-p ()
5222 "Is the end of the current subtree visible?"
5223 (pos-visible-in-window-p
5224 (save-excursion (org-end-of-subtree t) (point))))
5226 (defun org-first-headline-recenter (&optional N)
5227 "Move cursor to the first headline and recenter the headline.
5228 Optional argument N means, put the headline into the Nth line of the window."
5229 (goto-char (point-min))
5230 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5231 (beginning-of-line)
5232 (recenter (prefix-numeric-value N))))
5234 ;;; Org-goto
5236 (defvar org-goto-window-configuration nil)
5237 (defvar org-goto-marker nil)
5238 (defvar org-goto-map
5239 (let ((map (make-sparse-keymap)))
5240 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5241 (while (setq cmd (pop cmds))
5242 (substitute-key-definition cmd cmd map global-map)))
5243 (suppress-keymap map)
5244 (org-defkey map "\C-m" 'org-goto-ret)
5245 (org-defkey map [(left)] 'org-goto-left)
5246 (org-defkey map [(right)] 'org-goto-right)
5247 (org-defkey map [(?q)] 'org-goto-quit)
5248 (org-defkey map [(control ?g)] 'org-goto-quit)
5249 (org-defkey map "\C-i" 'org-cycle)
5250 (org-defkey map [(tab)] 'org-cycle)
5251 (org-defkey map [(down)] 'outline-next-visible-heading)
5252 (org-defkey map [(up)] 'outline-previous-visible-heading)
5253 (org-defkey map "n" 'outline-next-visible-heading)
5254 (org-defkey map "p" 'outline-previous-visible-heading)
5255 (org-defkey map "f" 'outline-forward-same-level)
5256 (org-defkey map "b" 'outline-backward-same-level)
5257 (org-defkey map "u" 'outline-up-heading)
5258 (org-defkey map "/" 'org-occur)
5259 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5260 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5261 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5262 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5263 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5264 map))
5266 (defconst org-goto-help
5267 "Browse copy of buffer to find location or copy text.
5268 RET=jump to location [Q]uit and return to previous location
5269 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5272 (defun org-goto ()
5273 "Look up a different location in the current file, keeping current visibility.
5275 When you want look-up or go to a different location in a document, the
5276 fastest way is often to fold the entire buffer and then dive into the tree.
5277 This method has the disadvantage, that the previous location will be folded,
5278 which may not be what you want.
5280 This command works around this by showing a copy of the current buffer
5281 in an indirect buffer, in overview mode. You can dive into the tree in
5282 that copy, use org-occur and incremental search to find a location.
5283 When pressing RET or `Q', the command returns to the original buffer in
5284 which the visibility is still unchanged. After RET is will also jump to
5285 the location selected in the indirect buffer and expose the
5286 the headline hierarchy above."
5287 (interactive)
5288 (let* ((org-goto-start-pos (point))
5289 (selected-point
5290 (car (org-get-location (current-buffer) org-goto-help))))
5291 (if selected-point
5292 (progn
5293 (org-mark-ring-push org-goto-start-pos)
5294 (goto-char selected-point)
5295 (if (or (org-invisible-p) (org-invisible-p2))
5296 (org-show-context 'org-goto)))
5297 (message "Quit"))))
5299 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5300 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5302 (defun org-get-location (buf help)
5303 "Let the user select a location in the Org-mode buffer BUF.
5304 This function uses a recursive edit. It returns the selected position
5305 or nil."
5306 (let (org-goto-selected-point org-goto-exit-command)
5307 (save-excursion
5308 (save-window-excursion
5309 (delete-other-windows)
5310 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5311 (switch-to-buffer
5312 (condition-case nil
5313 (make-indirect-buffer (current-buffer) "*org-goto*")
5314 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5315 (with-output-to-temp-buffer "*Help*"
5316 (princ help))
5317 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5318 (setq buffer-read-only nil)
5319 (let ((org-startup-truncated t)
5320 (org-startup-folded nil)
5321 (org-startup-align-all-tables nil))
5322 (org-mode)
5323 (org-overview))
5324 (setq buffer-read-only t)
5325 (if (and (boundp 'org-goto-start-pos)
5326 (integer-or-marker-p org-goto-start-pos))
5327 (let ((org-show-hierarchy-above t)
5328 (org-show-siblings t)
5329 (org-show-following-heading t))
5330 (goto-char org-goto-start-pos)
5331 (and (org-invisible-p) (org-show-context)))
5332 (goto-char (point-min)))
5333 (org-beginning-of-line)
5334 (message "Select location and press RET")
5335 ;; now we make sure that during selection, ony very few keys work
5336 ;; and that it is impossible to switch to another window.
5337 ; (let ((gm (current-global-map))
5338 ; (overriding-local-map org-goto-map))
5339 ; (unwind-protect
5340 ; (progn
5341 ; (use-global-map org-goto-map)
5342 ; (recursive-edit))
5343 ; (use-global-map gm)))
5344 (use-local-map org-goto-map)
5345 (recursive-edit)
5347 (kill-buffer "*org-goto*")
5348 (cons org-goto-selected-point org-goto-exit-command)))
5350 (defun org-goto-ret (&optional arg)
5351 "Finish `org-goto' by going to the new location."
5352 (interactive "P")
5353 (setq org-goto-selected-point (point)
5354 org-goto-exit-command 'return)
5355 (throw 'exit nil))
5357 (defun org-goto-left ()
5358 "Finish `org-goto' by going to the new location."
5359 (interactive)
5360 (if (org-on-heading-p)
5361 (progn
5362 (beginning-of-line 1)
5363 (setq org-goto-selected-point (point)
5364 org-goto-exit-command 'left)
5365 (throw 'exit nil))
5366 (error "Not on a heading")))
5368 (defun org-goto-right ()
5369 "Finish `org-goto' by going to the new location."
5370 (interactive)
5371 (if (org-on-heading-p)
5372 (progn
5373 (setq org-goto-selected-point (point)
5374 org-goto-exit-command 'right)
5375 (throw 'exit nil))
5376 (error "Not on a heading")))
5378 (defun org-goto-quit ()
5379 "Finish `org-goto' without cursor motion."
5380 (interactive)
5381 (setq org-goto-selected-point nil)
5382 (setq org-goto-exit-command 'quit)
5383 (throw 'exit nil))
5385 ;;; Indirect buffer display of subtrees
5387 (defvar org-indirect-dedicated-frame nil
5388 "This is the frame being used for indirect tree display.")
5389 (defvar org-last-indirect-buffer nil)
5391 (defun org-tree-to-indirect-buffer (&optional arg)
5392 "Create indirect buffer and narrow it to current subtree.
5393 With numerical prefix ARG, go up to this level and then take that tree.
5394 If ARG is negative, go up that many levels.
5395 Normally this command removes the indirect buffer previously made
5396 with this command. However, when called with a C-u prefix, the last buffer
5397 is kept so that you can work with several indirect buffers at the same time.
5398 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5399 requests that a new frame be made for the new buffer, so that the dedicated
5400 frame is not changed."
5401 (interactive "P")
5402 (let ((cbuf (current-buffer))
5403 (cwin (selected-window))
5404 (pos (point))
5405 beg end level heading ibuf)
5406 (save-excursion
5407 (org-back-to-heading t)
5408 (when (numberp arg)
5409 (setq level (org-outline-level))
5410 (if (< arg 0) (setq arg (+ level arg)))
5411 (while (> (setq level (org-outline-level)) arg)
5412 (outline-up-heading 1 t)))
5413 (setq beg (point)
5414 heading (org-get-heading))
5415 (org-end-of-subtree t) (setq end (point)))
5416 (if (and (not arg)
5417 (buffer-live-p org-last-indirect-buffer))
5418 (kill-buffer org-last-indirect-buffer))
5419 (setq ibuf (org-get-indirect-buffer cbuf)
5420 org-last-indirect-buffer ibuf)
5421 (cond
5422 ((or (eq org-indirect-buffer-display 'new-frame)
5423 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5424 (select-frame (make-frame))
5425 (delete-other-windows)
5426 (switch-to-buffer ibuf)
5427 (org-set-frame-title heading))
5428 ((eq org-indirect-buffer-display 'dedicated-frame)
5429 (raise-frame
5430 (select-frame (or (and org-indirect-dedicated-frame
5431 (frame-live-p org-indirect-dedicated-frame)
5432 org-indirect-dedicated-frame)
5433 (setq org-indirect-dedicated-frame (make-frame)))))
5434 (delete-other-windows)
5435 (switch-to-buffer ibuf)
5436 (org-set-frame-title (concat "Indirect: " heading)))
5437 ((eq org-indirect-buffer-display 'current-window)
5438 (switch-to-buffer ibuf))
5439 ((eq org-indirect-buffer-display 'other-window)
5440 (pop-to-buffer ibuf))
5441 (t (error "Invalid value.")))
5442 (if (featurep 'xemacs)
5443 (save-excursion (org-mode) (turn-on-font-lock)))
5444 (narrow-to-region beg end)
5445 (show-all)
5446 (goto-char pos)
5447 (and (window-live-p cwin) (select-window cwin))))
5449 (defun org-get-indirect-buffer (&optional buffer)
5450 (setq buffer (or buffer (current-buffer)))
5451 (let ((n 1) (base (buffer-name buffer)) bname)
5452 (while (buffer-live-p
5453 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5454 (setq n (1+ n)))
5455 (condition-case nil
5456 (make-indirect-buffer buffer bname 'clone)
5457 (error (make-indirect-buffer buffer bname)))))
5459 (defun org-set-frame-title (title)
5460 "Set the title of the current frame to the string TITLE."
5461 ;; FIXME: how to name a single frame in XEmacs???
5462 (unless (featurep 'xemacs)
5463 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5465 ;;;; Structure editing
5467 ;;; Inserting headlines
5469 (defun org-insert-heading (&optional force-heading)
5470 "Insert a new heading or item with same depth at point.
5471 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5472 If point is at the beginning of a headline, insert a sibling before the
5473 current headline. If point is in the middle of a headline, split the headline
5474 at that position and make the rest of the headline part of the sibling below
5475 the current headline."
5476 (interactive "P")
5477 (if (= (buffer-size) 0)
5478 (insert "\n* ")
5479 (when (or force-heading (not (org-insert-item)))
5480 (let* ((head (save-excursion
5481 (condition-case nil
5482 (progn
5483 (org-back-to-heading)
5484 (match-string 0))
5485 (error "*"))))
5486 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5487 pos)
5488 (cond
5489 ((and (org-on-heading-p) (bolp)
5490 (or (bobp)
5491 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5492 (open-line (if blank 2 1)))
5493 ((and (bolp)
5494 (or (bobp)
5495 (save-excursion
5496 (backward-char 1) (not (org-invisible-p)))))
5497 nil)
5498 (t (newline (if blank 2 1))))
5499 (insert head) (just-one-space)
5500 (setq pos (point))
5501 (end-of-line 1)
5502 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5503 (run-hooks 'org-insert-heading-hook)))))
5505 (defun org-insert-heading-after-current ()
5506 "Insert a new heading with same level as current, after current subtree."
5507 (interactive)
5508 (org-back-to-heading)
5509 (org-insert-heading)
5510 (org-move-subtree-down)
5511 (end-of-line 1))
5513 (defun org-insert-todo-heading (arg)
5514 "Insert a new heading with the same level and TODO state as current heading.
5515 If the heading has no TODO state, or if the state is DONE, use the first
5516 state (TODO by default). Also with prefix arg, force first state."
5517 (interactive "P")
5518 (when (not (org-insert-item 'checkbox))
5519 (org-insert-heading)
5520 (save-excursion
5521 (org-back-to-heading)
5522 (outline-previous-heading)
5523 (looking-at org-todo-line-regexp))
5524 (if (or arg
5525 (not (match-beginning 2))
5526 (member (match-string 2) org-done-keywords))
5527 (insert (car org-todo-keywords-1) " ")
5528 (insert (match-string 2) " "))))
5530 (defun org-insert-subheading (arg)
5531 "Insert a new subheading and demote it.
5532 Works for outline headings and for plain lists alike."
5533 (interactive "P")
5534 (org-insert-heading arg)
5535 (cond
5536 ((org-on-heading-p) (org-do-demote))
5537 ((org-at-item-p) (org-indent-item 1))))
5539 (defun org-insert-todo-subheading (arg)
5540 "Insert a new subheading with TODO keyword or checkbox and demote it.
5541 Works for outline headings and for plain lists alike."
5542 (interactive "P")
5543 (org-insert-todo-heading arg)
5544 (cond
5545 ((org-on-heading-p) (org-do-demote))
5546 ((org-at-item-p) (org-indent-item 1))))
5548 ;;; Promotion and Demotion
5550 (defun org-promote-subtree ()
5551 "Promote the entire subtree.
5552 See also `org-promote'."
5553 (interactive)
5554 (save-excursion
5555 (org-map-tree 'org-promote))
5556 (org-fix-position-after-promote))
5558 (defun org-demote-subtree ()
5559 "Demote the entire subtree. See `org-demote'.
5560 See also `org-promote'."
5561 (interactive)
5562 (save-excursion
5563 (org-map-tree 'org-demote))
5564 (org-fix-position-after-promote))
5567 (defun org-do-promote ()
5568 "Promote the current heading higher up the tree.
5569 If the region is active in `transient-mark-mode', promote all headings
5570 in the region."
5571 (interactive)
5572 (save-excursion
5573 (if (org-region-active-p)
5574 (org-map-region 'org-promote (region-beginning) (region-end))
5575 (org-promote)))
5576 (org-fix-position-after-promote))
5578 (defun org-do-demote ()
5579 "Demote the current heading lower down the tree.
5580 If the region is active in `transient-mark-mode', demote all headings
5581 in the region."
5582 (interactive)
5583 (save-excursion
5584 (if (org-region-active-p)
5585 (org-map-region 'org-demote (region-beginning) (region-end))
5586 (org-demote)))
5587 (org-fix-position-after-promote))
5589 (defun org-fix-position-after-promote ()
5590 "Make sure that after pro/demotion cursor position is right."
5591 (let ((pos (point)))
5592 (when (save-excursion
5593 (beginning-of-line 1)
5594 (looking-at org-todo-line-regexp)
5595 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5596 (cond ((eobp) (insert " "))
5597 ((eolp) (insert " "))
5598 ((equal (char-after) ?\ ) (forward-char 1))))))
5600 (defun org-reduced-level (l)
5601 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5603 (defun org-get-legal-level (level &optional change)
5604 "Rectify a level change under the influence of `org-odd-levels-only'
5605 LEVEL is a current level, CHANGE is by how much the level should be
5606 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5607 even level numbers will become the next higher odd number."
5608 (if org-odd-levels-only
5609 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5610 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5611 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5612 (max 1 (+ level change))))
5614 (defun org-promote ()
5615 "Promote the current heading higher up the tree.
5616 If the region is active in `transient-mark-mode', promote all headings
5617 in the region."
5618 (org-back-to-heading t)
5619 (let* ((level (save-match-data (funcall outline-level)))
5620 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5621 (diff (abs (- level (length up-head) -1))))
5622 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5623 (replace-match up-head nil t)
5624 ;; Fixup tag positioning
5625 (and org-auto-align-tags (org-set-tags nil t))
5626 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5628 (defun org-demote ()
5629 "Demote the current heading lower down the tree.
5630 If the region is active in `transient-mark-mode', demote all headings
5631 in the region."
5632 (org-back-to-heading t)
5633 (let* ((level (save-match-data (funcall outline-level)))
5634 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5635 (diff (abs (- level (length down-head) -1))))
5636 (replace-match down-head nil t)
5637 ;; Fixup tag positioning
5638 (and org-auto-align-tags (org-set-tags nil t))
5639 (if org-adapt-indentation (org-fixup-indentation diff))))
5641 (defun org-map-tree (fun)
5642 "Call FUN for every heading underneath the current one."
5643 (org-back-to-heading)
5644 (let ((level (funcall outline-level)))
5645 (save-excursion
5646 (funcall fun)
5647 (while (and (progn
5648 (outline-next-heading)
5649 (> (funcall outline-level) level))
5650 (not (eobp)))
5651 (funcall fun)))))
5653 (defun org-map-region (fun beg end)
5654 "Call FUN for every heading between BEG and END."
5655 (let ((org-ignore-region t))
5656 (save-excursion
5657 (setq end (copy-marker end))
5658 (goto-char beg)
5659 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5660 (< (point) end))
5661 (funcall fun))
5662 (while (and (progn
5663 (outline-next-heading)
5664 (< (point) end))
5665 (not (eobp)))
5666 (funcall fun)))))
5668 (defun org-fixup-indentation (diff)
5669 "Change the indentation in the current entry by DIFF
5670 However, if any line in the current entry has no indentation, or if it
5671 would end up with no indentation after the change, nothing at all is done."
5672 (save-excursion
5673 (let ((end (save-excursion (outline-next-heading)
5674 (point-marker)))
5675 (prohibit (if (> diff 0)
5676 "^\\S-"
5677 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5678 col)
5679 (unless (save-excursion (end-of-line 1)
5680 (re-search-forward prohibit end t))
5681 (while (re-search-forward "^[ \t]+" end t)
5682 (goto-char (match-end 0))
5683 (setq col (current-column))
5684 (if (< diff 0) (replace-match ""))
5685 (indent-to (+ diff col))))
5686 (move-marker end nil))))
5688 (defun org-convert-to-odd-levels ()
5689 "Convert an org-mode file with all levels allowed to one with odd levels.
5690 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5691 level 5 etc."
5692 (interactive)
5693 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5694 (let ((org-odd-levels-only nil) n)
5695 (save-excursion
5696 (goto-char (point-min))
5697 (while (re-search-forward "^\\*\\*+ " nil t)
5698 (setq n (- (length (match-string 0)) 2))
5699 (while (>= (setq n (1- n)) 0)
5700 (org-demote))
5701 (end-of-line 1))))))
5704 (defun org-convert-to-oddeven-levels ()
5705 "Convert an org-mode file with only odd levels to one with odd and even levels.
5706 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5707 section with an even level, conversion would destroy the structure of the file. An error
5708 is signaled in this case."
5709 (interactive)
5710 (goto-char (point-min))
5711 ;; First check if there are no even levels
5712 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5713 (org-show-context t)
5714 (error "Not all levels are odd in this file. Conversion not possible."))
5715 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5716 (let ((org-odd-levels-only nil) n)
5717 (save-excursion
5718 (goto-char (point-min))
5719 (while (re-search-forward "^\\*\\*+ " nil t)
5720 (setq n (/ (length (1- (match-string 0))) 2))
5721 (while (>= (setq n (1- n)) 0)
5722 (org-promote))
5723 (end-of-line 1))))))
5725 (defun org-tr-level (n)
5726 "Make N odd if required."
5727 (if org-odd-levels-only (1+ (/ n 2)) n))
5729 ;;; Vertical tree motion, cutting and pasting of subtrees
5731 (defun org-move-subtree-up (&optional arg)
5732 "Move the current subtree up past ARG headlines of the same level."
5733 (interactive "p")
5734 (org-move-subtree-down (- (prefix-numeric-value arg))))
5736 (defun org-move-subtree-down (&optional arg)
5737 "Move the current subtree down past ARG headlines of the same level."
5738 (interactive "p")
5739 (setq arg (prefix-numeric-value arg))
5740 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5741 'outline-get-last-sibling))
5742 (ins-point (make-marker))
5743 (cnt (abs arg))
5744 beg end txt folded)
5745 ;; Select the tree
5746 (org-back-to-heading)
5747 (setq beg (point))
5748 (save-match-data
5749 (save-excursion (outline-end-of-heading)
5750 (setq folded (org-invisible-p)))
5751 (outline-end-of-subtree))
5752 (outline-next-heading)
5753 (setq end (point))
5754 ;; Find insertion point, with error handling
5755 (goto-char beg)
5756 (while (> cnt 0)
5757 (or (and (funcall movfunc) (looking-at outline-regexp))
5758 (progn (goto-char beg)
5759 (error "Cannot move past superior level or buffer limit")))
5760 (setq cnt (1- cnt)))
5761 (if (> arg 0)
5762 ;; Moving forward - still need to move over subtree
5763 (progn (outline-end-of-subtree)
5764 (outline-next-heading)
5765 (if (not (or (looking-at (concat "^" outline-regexp))
5766 (bolp)))
5767 (newline))))
5768 (move-marker ins-point (point))
5769 (setq txt (buffer-substring beg end))
5770 (delete-region beg end)
5771 (insert txt)
5772 (or (bolp) (insert "\n"))
5773 (goto-char ins-point)
5774 (if folded (hide-subtree))
5775 (move-marker ins-point nil)))
5777 (defvar org-subtree-clip ""
5778 "Clipboard for cut and paste of subtrees.
5779 This is actually only a copy of the kill, because we use the normal kill
5780 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5782 (defvar org-subtree-clip-folded nil
5783 "Was the last copied subtree folded?
5784 This is used to fold the tree back after pasting.")
5786 (defun org-cut-subtree ()
5787 "Cut the current subtree into the clipboard.
5788 This is a short-hand for marking the subtree and then cutting it."
5789 (interactive)
5790 (org-copy-subtree 'cut))
5792 (defun org-copy-subtree (&optional cut)
5793 "Cut the current subtree into the clipboard.
5794 This is a short-hand for marking the subtree and then copying it.
5795 If CUT is non-nil, actually cut the subtree."
5796 (interactive)
5797 (let (beg end folded)
5798 (if (interactive-p)
5799 (org-back-to-heading nil) ; take what looks like a subtree
5800 (org-back-to-heading t)) ; take what is really there
5801 (setq beg (point))
5802 (save-match-data
5803 (save-excursion (outline-end-of-heading)
5804 (setq folded (org-invisible-p)))
5805 (outline-end-of-subtree))
5806 (if (equal (char-after) ?\n) (forward-char 1))
5807 (setq end (point))
5808 (goto-char beg)
5809 (when (> end beg)
5810 (setq org-subtree-clip-folded folded)
5811 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5812 (setq org-subtree-clip (current-kill 0))
5813 (message "%s: Subtree with %d characters"
5814 (if cut "Cut" "Copied")
5815 (length org-subtree-clip)))))
5817 (defun org-paste-subtree (&optional level tree)
5818 "Paste the clipboard as a subtree, with modification of headline level.
5819 The entire subtree is promoted or demoted in order to match a new headline
5820 level. By default, the new level is derived from the visible headings
5821 before and after the insertion point, and taken to be the inferior headline
5822 level of the two. So if the previous visible heading is level 3 and the
5823 next is level 4 (or vice versa), level 4 will be used for insertion.
5824 This makes sure that the subtree remains an independent subtree and does
5825 not swallow low level entries.
5827 You can also force a different level, either by using a numeric prefix
5828 argument, or by inserting the heading marker by hand. For example, if the
5829 cursor is after \"*****\", then the tree will be shifted to level 5.
5831 If you want to insert the tree as is, just use \\[yank].
5833 If optional TREE is given, use this text instead of the kill ring."
5834 (interactive "P")
5835 (unless (org-kill-is-subtree-p tree)
5836 (error
5837 (substitute-command-keys
5838 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5839 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5840 (^re (concat "^\\(" outline-regexp "\\)"))
5841 (re (concat "\\(" outline-regexp "\\)"))
5842 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5844 (old-level (if (string-match ^re txt)
5845 (- (match-end 0) (match-beginning 0) 1)
5846 -1))
5847 (force-level (cond (level (prefix-numeric-value level))
5848 ((string-match
5849 ^re_ (buffer-substring (point-at-bol) (point)))
5850 (- (match-end 0) (match-beginning 0)))
5851 (t nil)))
5852 (previous-level (save-excursion
5853 (condition-case nil
5854 (progn
5855 (outline-previous-visible-heading 1)
5856 (if (looking-at re)
5857 (- (match-end 0) (match-beginning 0))
5859 (error 1))))
5860 (next-level (save-excursion
5861 (condition-case nil
5862 (progn
5863 (outline-next-visible-heading 1)
5864 (if (looking-at re)
5865 (- (match-end 0) (match-beginning 0))
5867 (error 1))))
5868 (new-level (or force-level (max previous-level next-level)))
5869 (shift (if (or (= old-level -1)
5870 (= new-level -1)
5871 (= old-level new-level))
5873 (- new-level old-level)))
5874 (shift1 shift)
5875 (delta (if (> shift 0) -1 1))
5876 (func (if (> shift 0) 'org-demote 'org-promote))
5877 (org-odd-levels-only nil)
5878 beg end)
5879 ;; Remove the forced level indicator
5880 (if force-level
5881 (delete-region (point-at-bol) (point)))
5882 ;; Paste
5883 (beginning-of-line 1)
5884 (setq beg (point))
5885 (insert txt)
5886 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
5887 (setq end (point))
5888 (goto-char beg)
5889 ;; Shift if necessary
5890 (unless (= shift 0)
5891 (save-restriction
5892 (narrow-to-region beg end)
5893 (while (not (= shift 0))
5894 (org-map-region func (point-min) (point-max))
5895 (setq shift (+ delta shift)))
5896 (goto-char (point-min))))
5897 (when (interactive-p)
5898 (message "Clipboard pasted as level %d subtree" new-level))
5899 (if (and kill-ring
5900 (eq org-subtree-clip (current-kill 0))
5901 org-subtree-clip-folded)
5902 ;; The tree was folded before it was killed/copied
5903 (hide-subtree))))
5905 (defun org-kill-is-subtree-p (&optional txt)
5906 "Check if the current kill is an outline subtree, or a set of trees.
5907 Returns nil if kill does not start with a headline, or if the first
5908 headline level is not the largest headline level in the tree.
5909 So this will actually accept several entries of equal levels as well,
5910 which is OK for `org-paste-subtree'.
5911 If optional TXT is given, check this string instead of the current kill."
5912 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5913 (start-level (and kill
5914 (string-match (concat "\\`" org-outline-regexp) kill)
5915 (- (match-end 0) (match-beginning 0) 1)))
5916 (re (concat "^" org-outline-regexp))
5917 (start 1))
5918 (if (not start-level)
5919 (progn
5920 nil) ;; does not even start with a heading
5921 (catch 'exit
5922 (while (setq start (string-match re kill (1+ start)))
5923 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5924 (throw 'exit nil)))
5925 t))))
5927 (defun org-narrow-to-subtree ()
5928 "Narrow buffer to the current subtree."
5929 (interactive)
5930 (save-excursion
5931 (narrow-to-region
5932 (progn (org-back-to-heading) (point))
5933 (progn (org-end-of-subtree t t) (point)))))
5936 ;;; Outline Sorting
5938 (defun org-sort (with-case)
5939 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5940 (interactive "P")
5941 (if (org-at-table-p)
5942 (org-call-with-arg 'org-table-sort-lines with-case)
5943 (org-call-with-arg 'org-sort-entries with-case)))
5945 (defun org-sort-entries (&optional with-case sorting-type)
5946 "Sort entries on a certain level of an outline tree.
5947 If there is an active region, the entries in the region are sorted.
5948 Else, if the cursor is before the first entry, sort the top-level items.
5949 Else, the children of the entry at point are sorted.
5951 Sorting can be alphabetically, numerically, and by date/time as given by
5952 the first time stamp in the entry. The command prompts for the sorting
5953 type unless it has been given to the function through the SORTING-TYPE
5954 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5956 Comparing entries ignores case by default. However, with an optional argument
5957 WITH-CASE, the sorting considers case as well. With two prefix arguments
5958 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5959 (interactive "P")
5960 (let ((unique (equal with-case '(16)))
5961 start beg end entries stars re re2 p nentries (nremoved 0)
5962 last txt what)
5963 ;; Find beginning and end of region to sort
5964 (cond
5965 ((org-region-active-p)
5966 ;; we will sort the region
5967 (setq end (region-end)
5968 what "region")
5969 (goto-char (region-beginning))
5970 (if (not (org-on-heading-p)) (outline-next-heading))
5971 (setq start (point)))
5972 ((or (org-on-heading-p)
5973 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5974 ;; we will sort the children of the current headline
5975 (org-back-to-heading)
5976 (setq start (point) end (org-end-of-subtree) what "children")
5977 (goto-char start)
5978 (show-subtree)
5979 (outline-next-heading))
5981 ;; we will sort the top-level entries in this file
5982 (goto-char (point-min))
5983 (or (org-on-heading-p) (outline-next-heading))
5984 (setq start (point) end (point-max) what "top-level")
5985 (goto-char start)
5986 (show-all)))
5987 (setq beg (point))
5988 (if (>= (point) end) (error "Nothing to sort"))
5989 (looking-at "\\(\\*+\\)")
5990 (setq stars (match-string 1)
5991 re (concat "^" (regexp-quote stars) " +")
5992 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5993 txt (buffer-substring beg end))
5994 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5995 (if (and (not (equal stars "*")) (string-match re2 txt))
5996 (error "Region to sort contains a level above the first entry"))
5997 ;; Make a list that can be sorted.
5998 ;; The car is the string for comparison, the cdr is the subtree
5999 (message "Sorting entries...")
6000 (setq entries
6001 (mapcar
6002 (lambda (x)
6003 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
6004 (cons (match-string 0 x) x))
6005 (org-split-string txt re)))
6007 ;; Sort the list
6008 (save-excursion
6009 (goto-char start)
6010 (setq entries (org-do-sort entries what with-case sorting-type)))
6012 ;; Delete the old stuff
6013 (goto-char beg)
6014 (kill-region beg end)
6015 (setq nentries (length entries))
6016 ;; Insert the sorted entries, and remove duplicates if this is required
6017 (while (setq p (pop entries))
6018 (if (and unique (equal last (setq last (org-trim (cdr p)))))
6019 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
6020 (insert stars " " (cdr p))))
6021 (goto-char start)
6022 (message "Sorting entries...done (%d entries%s)"
6023 nentries
6024 (if unique (format ", %d duplicates removed" nremoved) ""))))
6026 (defvar org-priority-regexp) ; defined later in the file
6028 (defun org-do-sort (table what &optional with-case sorting-type)
6029 "Sort TABLE of WHAT according to SORTING-TYPE.
6030 The user will be prompted for the SORTING-TYPE if the call to this
6031 function does not specify it. WHAT is only for the prompt, to indicate
6032 what is being sorted. The sorting key will be extracted from
6033 the car of the elements of the table.
6034 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6035 (unless sorting-type
6036 (message
6037 "Sort %s: [a]lphabetic. [n]umeric. [t]ime [p]riority. A/N/T/P means reversed:"
6038 what)
6039 (setq sorting-type (read-char-exclusive)))
6040 (let ((dcst (downcase sorting-type))
6041 extractfun comparefun)
6042 ;; Define the appropriate functions
6043 (cond
6044 ((= dcst ?n)
6045 (setq extractfun 'string-to-number
6046 comparefun (if (= dcst sorting-type) '< '>)))
6047 ((= dcst ?a)
6048 (setq extractfun (if with-case 'identity 'downcase)
6049 comparefun (if (= dcst sorting-type)
6050 'string<
6051 (lambda (a b) (and (not (string< a b))
6052 (not (string= a b)))))))
6053 ((= dcst ?t)
6054 (setq extractfun
6055 (lambda (x)
6056 (if (string-match org-ts-regexp x)
6057 (time-to-seconds
6058 (org-time-string-to-time (match-string 0 x)))
6060 comparefun (if (= dcst sorting-type) '< '>)))
6061 ((= dcst ?p)
6062 (setq extractfun
6063 (lambda (x)
6064 (if (string-match org-priority-regexp x)
6065 (string-to-char (match-string 2 x))
6066 org-default-priority))
6067 comparefun (if (= dcst sorting-type) '< '>)))
6068 (t (error "Invalid sorting type `%c'" sorting-type)))
6070 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6071 table)
6072 (lambda (a b) (funcall comparefun (car a) (car b))))))
6074 ;;;; Plain list items, including checkboxes
6076 ;;; Plain list items
6078 (defun org-at-item-p ()
6079 "Is point in a line starting a hand-formatted item?"
6080 (let ((llt org-plain-list-ordered-item-terminator))
6081 (save-excursion
6082 (goto-char (point-at-bol))
6083 (looking-at
6084 (cond
6085 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6086 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6087 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6088 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6090 (defun org-in-item-p ()
6091 "It the cursor inside a plain list item.
6092 Does not have to be the first line."
6093 (save-excursion
6094 (condition-case nil
6095 (progn
6096 (org-beginning-of-item)
6097 (org-at-item-p)
6099 (error nil))))
6101 (defun org-insert-item (&optional checkbox)
6102 "Insert a new item at the current level.
6103 Return t when things worked, nil when we are not in an item."
6104 (when (save-excursion
6105 (condition-case nil
6106 (progn
6107 (org-beginning-of-item)
6108 (org-at-item-p)
6109 (if (org-invisible-p) (error "Invisible item"))
6111 (error nil)))
6112 (let* ((bul (match-string 0))
6113 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6114 (match-end 0)))
6115 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6116 pos)
6117 (cond
6118 ((and (org-at-item-p) (<= (point) eow))
6119 ;; before the bullet
6120 (beginning-of-line 1)
6121 (open-line (if blank 2 1)))
6122 ((<= (point) eow)
6123 (beginning-of-line 1))
6124 (t (newline (if blank 2 1))))
6125 (insert bul (if checkbox "[ ]" ""))
6126 (just-one-space)
6127 (setq pos (point))
6128 (end-of-line 1)
6129 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6130 (org-maybe-renumber-ordered-list)
6131 (and checkbox (org-update-checkbox-count-maybe))
6134 ;;; Checkboxes
6136 (defun org-at-item-checkbox-p ()
6137 "Is point at a line starting a plain-list item with a checklet?"
6138 (and (org-at-item-p)
6139 (save-excursion
6140 (goto-char (match-end 0))
6141 (skip-chars-forward " \t")
6142 (looking-at "\\[[- X]\\]"))))
6144 (defun org-toggle-checkbox (&optional arg)
6145 "Toggle the checkbox in the current line."
6146 (interactive "P")
6147 (catch 'exit
6148 (let (beg end status (firstnew 'unknown))
6149 (cond
6150 ((org-region-active-p)
6151 (setq beg (region-beginning) end (region-end)))
6152 ((org-on-heading-p)
6153 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6154 ((org-at-item-checkbox-p)
6155 (save-excursion
6156 (replace-match
6157 (cond (arg "[-]")
6158 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6159 (t "[ ]"))
6160 t t))
6161 (throw 'exit t))
6162 (t (error "Not at a checkbox or heading, and no active region")))
6163 (save-excursion
6164 (goto-char beg)
6165 (while (< (point) end)
6166 (when (org-at-item-checkbox-p)
6167 (setq status (equal (match-string 0) "[X]"))
6168 (when (eq firstnew 'unknown)
6169 (setq firstnew (not status)))
6170 (replace-match
6171 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6172 (beginning-of-line 2)))))
6173 (org-update-checkbox-count-maybe))
6175 (defun org-update-checkbox-count-maybe ()
6176 "Update checkbox statistics unless turned off by user."
6177 (when org-provide-checkbox-statistics
6178 (org-update-checkbox-count)))
6180 (defun org-update-checkbox-count (&optional all)
6181 "Update the checkbox statistics in the current section.
6182 This will find all statistic cookies like [57%] and [6/12] and update them
6183 with the current numbers. With optional prefix argument ALL, do this for
6184 the whole buffer."
6185 (interactive "P")
6186 (save-excursion
6187 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6188 (beg (condition-case nil
6189 (progn (outline-back-to-heading) (point))
6190 (error (point-min))))
6191 (end (move-marker (make-marker)
6192 (progn (outline-next-heading) (point))))
6193 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6194 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6195 b1 e1 f1 c-on c-off lim (cstat 0))
6196 (when all
6197 (goto-char (point-min))
6198 (outline-next-heading)
6199 (setq beg (point) end (point-max)))
6200 (goto-char beg)
6201 (while (re-search-forward re end t)
6202 (setq cstat (1+ cstat)
6203 b1 (match-beginning 0)
6204 e1 (match-end 0)
6205 f1 (match-beginning 1)
6206 lim (cond
6207 ((org-on-heading-p) (outline-next-heading) (point))
6208 ((org-at-item-p) (org-end-of-item) (point))
6209 (t nil))
6210 c-on 0 c-off 0)
6211 (goto-char e1)
6212 (when lim
6213 (while (re-search-forward re-box lim t)
6214 (if (member (match-string 2) '("[ ]" "[-]"))
6215 (setq c-off (1+ c-off))
6216 (setq c-on (1+ c-on))))
6217 ; (delete-region b1 e1)
6218 (goto-char b1)
6219 (insert (if f1
6220 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6221 (format "[%d/%d]" c-on (+ c-on c-off))))
6222 (and (looking-at "\\[.*?\\]")
6223 (replace-match ""))))
6224 (when (interactive-p)
6225 (message "Checkbox satistics updated %s (%d places)"
6226 (if all "in entire file" "in current outline entry") cstat)))))
6228 (defun org-get-checkbox-statistics-face ()
6229 "Select the face for checkbox statistics.
6230 The face will be `org-done' when all relevant boxes are checked. Otherwise
6231 it will be `org-todo'."
6232 (if (match-end 1)
6233 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6234 (if (and (> (match-end 2) (match-beginning 2))
6235 (equal (match-string 2) (match-string 3)))
6236 'org-done
6237 'org-todo)))
6239 (defun org-get-indentation (&optional line)
6240 "Get the indentation of the current line, interpreting tabs.
6241 When LINE is given, assume it represents a line and compute its indentation."
6242 (if line
6243 (if (string-match "^ *" (org-remove-tabs line))
6244 (match-end 0))
6245 (save-excursion
6246 (beginning-of-line 1)
6247 (skip-chars-forward " \t")
6248 (current-column))))
6250 (defun org-remove-tabs (s &optional width)
6251 "Replace tabulators in S with spaces.
6252 Assumes that s is a single line, starting in column 0."
6253 (setq width (or width tab-width))
6254 (while (string-match "\t" s)
6255 (setq s (replace-match
6256 (make-string
6257 (- (* width (/ (+ (match-beginning 0) width) width))
6258 (match-beginning 0)) ?\ )
6259 t t s)))
6262 (defun org-fix-indentation (line ind)
6263 "Fix indentation in LINE.
6264 IND is a cons cell with target and minimum indentation.
6265 If the current indenation in LINE is smaller than the minimum,
6266 leave it alone. If it is larger than ind, set it to the target."
6267 (let* ((l (org-remove-tabs line))
6268 (i (org-get-indentation l))
6269 (i1 (car ind)) (i2 (cdr ind)))
6270 (if (>= i i2) (setq l (substring line i2)))
6271 (if (> i1 0)
6272 (concat (make-string i1 ?\ ) l)
6273 l)))
6275 (defcustom org-empty-line-terminates-plain-lists nil
6276 "Non-nil means, an empty line ends all plain list levels.
6277 When nil, empty lines are part of the preceeding item."
6278 :group 'org-plain-lists
6279 :type 'boolean)
6281 (defun org-beginning-of-item ()
6282 "Go to the beginning of the current hand-formatted item.
6283 If the cursor is not in an item, throw an error."
6284 (interactive)
6285 (let ((pos (point))
6286 (limit (save-excursion
6287 (condition-case nil
6288 (progn
6289 (org-back-to-heading)
6290 (beginning-of-line 2) (point))
6291 (error (point-min)))))
6292 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6293 ind ind1)
6294 (if (org-at-item-p)
6295 (beginning-of-line 1)
6296 (beginning-of-line 1)
6297 (skip-chars-forward " \t")
6298 (setq ind (current-column))
6299 (if (catch 'exit
6300 (while t
6301 (beginning-of-line 0)
6302 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6304 (if (looking-at "[ \t]*$")
6305 (setq ind1 ind-empty)
6306 (skip-chars-forward " \t")
6307 (setq ind1 (current-column)))
6308 (if (< ind1 ind)
6309 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6311 (goto-char pos)
6312 (error "Not in an item")))))
6314 (defun org-end-of-item ()
6315 "Go to the end of the current hand-formatted item.
6316 If the cursor is not in an item, throw an error."
6317 (interactive)
6318 (let* ((pos (point))
6319 ind1
6320 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6321 (limit (save-excursion (outline-next-heading) (point)))
6322 (ind (save-excursion
6323 (org-beginning-of-item)
6324 (skip-chars-forward " \t")
6325 (current-column)))
6326 (end (catch 'exit
6327 (while t
6328 (beginning-of-line 2)
6329 (if (eobp) (throw 'exit (point)))
6330 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6331 (if (looking-at "[ \t]*$")
6332 (setq ind1 ind-empty)
6333 (skip-chars-forward " \t")
6334 (setq ind1 (current-column)))
6335 (if (<= ind1 ind)
6336 (throw 'exit (point-at-bol)))))))
6337 (if end
6338 (goto-char end)
6339 (goto-char pos)
6340 (error "Not in an item"))))
6342 (defun org-next-item ()
6343 "Move to the beginning of the next item in the current plain list.
6344 Error if not at a plain list, or if this is the last item in the list."
6345 (interactive)
6346 (let (ind ind1 (pos (point)))
6347 (org-beginning-of-item)
6348 (setq ind (org-get-indentation))
6349 (org-end-of-item)
6350 (setq ind1 (org-get-indentation))
6351 (unless (and (org-at-item-p) (= ind ind1))
6352 (goto-char pos)
6353 (error "On last item"))))
6355 (defun org-previous-item ()
6356 "Move to the beginning of the previous item in the current plain list.
6357 Error if not at a plain list, or if this is the first item in the list."
6358 (interactive)
6359 (let (beg ind ind1 (pos (point)))
6360 (org-beginning-of-item)
6361 (setq beg (point))
6362 (setq ind (org-get-indentation))
6363 (goto-char beg)
6364 (catch 'exit
6365 (while t
6366 (beginning-of-line 0)
6367 (if (looking-at "[ \t]*$")
6369 (if (<= (setq ind1 (org-get-indentation)) ind)
6370 (throw 'exit t)))))
6371 (condition-case nil
6372 (if (or (not (org-at-item-p))
6373 (< ind1 (1- ind)))
6374 (error "")
6375 (org-beginning-of-item))
6376 (error (goto-char pos)
6377 (error "On first item")))))
6379 (defun org-move-item-down ()
6380 "Move the plain list item at point down, i.e. swap with following item.
6381 Subitems (items with larger indentation) are considered part of the item,
6382 so this really moves item trees."
6383 (interactive)
6384 (let (beg end ind ind1 (pos (point)) txt)
6385 (org-beginning-of-item)
6386 (setq beg (point))
6387 (setq ind (org-get-indentation))
6388 (org-end-of-item)
6389 (setq end (point))
6390 (setq ind1 (org-get-indentation))
6391 (if (and (org-at-item-p) (= ind ind1))
6392 (progn
6393 (org-end-of-item)
6394 (setq txt (buffer-substring beg end))
6395 (save-excursion
6396 (delete-region beg end))
6397 (setq pos (point))
6398 (insert txt)
6399 (goto-char pos)
6400 (org-maybe-renumber-ordered-list))
6401 (goto-char pos)
6402 (error "Cannot move this item further down"))))
6404 (defun org-move-item-up (arg)
6405 "Move the plain list item at point up, i.e. swap with previous item.
6406 Subitems (items with larger indentation) are considered part of the item,
6407 so this really moves item trees."
6408 (interactive "p")
6409 (let (beg end ind ind1 (pos (point)) txt)
6410 (org-beginning-of-item)
6411 (setq beg (point))
6412 (setq ind (org-get-indentation))
6413 (org-end-of-item)
6414 (setq end (point))
6415 (goto-char beg)
6416 (catch 'exit
6417 (while t
6418 (beginning-of-line 0)
6419 (if (looking-at "[ \t]*$")
6420 (if org-empty-line-terminates-plain-lists
6421 (progn
6422 (goto-char pos)
6423 (error "Cannot move this item further up"))
6424 nil)
6425 (if (<= (setq ind1 (org-get-indentation)) ind)
6426 (throw 'exit t)))))
6427 (condition-case nil
6428 (org-beginning-of-item)
6429 (error (goto-char beg)
6430 (error "Cannot move this item further up")))
6431 (setq ind1 (org-get-indentation))
6432 (if (and (org-at-item-p) (= ind ind1))
6433 (progn
6434 (setq txt (buffer-substring beg end))
6435 (save-excursion
6436 (delete-region beg end))
6437 (setq pos (point))
6438 (insert txt)
6439 (goto-char pos)
6440 (org-maybe-renumber-ordered-list))
6441 (goto-char pos)
6442 (error "Cannot move this item further up"))))
6444 (defun org-maybe-renumber-ordered-list ()
6445 "Renumber the ordered list at point if setup allows it.
6446 This tests the user option `org-auto-renumber-ordered-lists' before
6447 doing the renumbering."
6448 (interactive)
6449 (when (and org-auto-renumber-ordered-lists
6450 (org-at-item-p))
6451 (if (match-beginning 3)
6452 (org-renumber-ordered-list 1)
6453 (org-fix-bullet-type))))
6455 (defun org-maybe-renumber-ordered-list-safe ()
6456 (condition-case nil
6457 (save-excursion
6458 (org-maybe-renumber-ordered-list))
6459 (error nil)))
6461 (defun org-cycle-list-bullet (&optional which)
6462 "Cycle through the different itemize/enumerate bullets.
6463 This cycle the entire list level through the sequence:
6465 `-' -> `+' -> `*' -> `1.' -> `1)'
6467 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6468 0 meand `-', 1 means `+' etc."
6469 (interactive "P")
6470 (org-preserve-lc
6471 (org-beginning-of-item-list)
6472 (org-at-item-p)
6473 (beginning-of-line 1)
6474 (let ((current (match-string 0)) new)
6475 (setq new (cond
6476 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6477 ((string-match "-" current) "+")
6478 ((string-match "\\+" current)
6479 (if (looking-at "\\S-") "1." "*"))
6480 ((string-match "\\*" current) "1.")
6481 ((string-match "\\." current) "1)")
6482 ((string-match ")" current) "-")
6483 (t (error "This should not happen"))))
6484 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6485 (org-fix-bullet-type)
6486 (org-maybe-renumber-ordered-list))))
6488 (defun org-get-string-indentation (s)
6489 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6490 (let ((n -1) (i 0) (w tab-width) c)
6491 (catch 'exit
6492 (while (< (setq n (1+ n)) (length s))
6493 (setq c (aref s n))
6494 (cond ((= c ?\ ) (setq i (1+ i)))
6495 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6496 (t (throw 'exit t)))))
6499 (defun org-renumber-ordered-list (arg)
6500 "Renumber an ordered plain list.
6501 Cursor needs to be in the first line of an item, the line that starts
6502 with something like \"1.\" or \"2)\"."
6503 (interactive "p")
6504 (unless (and (org-at-item-p)
6505 (match-beginning 3))
6506 (error "This is not an ordered list"))
6507 (let ((line (org-current-line))
6508 (col (current-column))
6509 (ind (org-get-string-indentation
6510 (buffer-substring (point-at-bol) (match-beginning 3))))
6511 ;; (term (substring (match-string 3) -1))
6512 ind1 (n (1- arg))
6513 fmt)
6514 ;; find where this list begins
6515 (org-beginning-of-item-list)
6516 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6517 (setq fmt (concat "%d" (match-string 1)))
6518 (beginning-of-line 0)
6519 ;; walk forward and replace these numbers
6520 (catch 'exit
6521 (while t
6522 (catch 'next
6523 (beginning-of-line 2)
6524 (if (eobp) (throw 'exit nil))
6525 (if (looking-at "[ \t]*$") (throw 'next nil))
6526 (skip-chars-forward " \t") (setq ind1 (current-column))
6527 (if (> ind1 ind) (throw 'next t))
6528 (if (< ind1 ind) (throw 'exit t))
6529 (if (not (org-at-item-p)) (throw 'exit nil))
6530 (delete-region (match-beginning 2) (match-end 2))
6531 (goto-char (match-beginning 2))
6532 (insert (format fmt (setq n (1+ n)))))))
6533 (goto-line line)
6534 (move-to-column col)))
6536 (defun org-fix-bullet-type ()
6537 "Make sure all items in this list have the same bullet as the firsst item."
6538 (interactive)
6539 (unless (org-at-item-p) (error "This is not a list"))
6540 (let ((line (org-current-line))
6541 (col (current-column))
6542 (ind (current-indentation))
6543 ind1 bullet)
6544 ;; find where this list begins
6545 (org-beginning-of-item-list)
6546 (beginning-of-line 1)
6547 ;; find out what the bullet type is
6548 (looking-at "[ \t]*\\(\\S-+\\)")
6549 (setq bullet (match-string 1))
6550 ;; walk forward and replace these numbers
6551 (beginning-of-line 0)
6552 (catch 'exit
6553 (while t
6554 (catch 'next
6555 (beginning-of-line 2)
6556 (if (eobp) (throw 'exit nil))
6557 (if (looking-at "[ \t]*$") (throw 'next nil))
6558 (skip-chars-forward " \t") (setq ind1 (current-column))
6559 (if (> ind1 ind) (throw 'next t))
6560 (if (< ind1 ind) (throw 'exit t))
6561 (if (not (org-at-item-p)) (throw 'exit nil))
6562 (skip-chars-forward " \t")
6563 (looking-at "\\S-+")
6564 (replace-match bullet))))
6565 (goto-line line)
6566 (move-to-column col)
6567 (if (string-match "[0-9]" bullet)
6568 (org-renumber-ordered-list 1))))
6570 (defun org-beginning-of-item-list ()
6571 "Go to the beginning of the current item list.
6572 I.e. to the first item in this list."
6573 (interactive)
6574 (org-beginning-of-item)
6575 (let ((pos (point-at-bol))
6576 (ind (org-get-indentation))
6577 ind1)
6578 ;; find where this list begins
6579 (catch 'exit
6580 (while t
6581 (catch 'next
6582 (beginning-of-line 0)
6583 (if (looking-at "[ \t]*$")
6584 (throw (if (bobp) 'exit 'next) t))
6585 (skip-chars-forward " \t") (setq ind1 (current-column))
6586 (if (or (< ind1 ind)
6587 (and (= ind1 ind)
6588 (not (org-at-item-p)))
6589 (bobp))
6590 (throw 'exit t)
6591 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6592 (goto-char pos)))
6594 (defvar org-last-indent-begin-marker (make-marker))
6595 (defvar org-last-indent-end-marker (make-marker))
6597 (defun org-outdent-item (arg)
6598 "Outdent a local list item."
6599 (interactive "p")
6600 (org-indent-item (- arg)))
6602 (defun org-indent-item (arg)
6603 "Indent a local list item."
6604 (interactive "p")
6605 (unless (org-at-item-p)
6606 (error "Not on an item"))
6607 (save-excursion
6608 (let (beg end ind ind1 tmp delta ind-down ind-up)
6609 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6610 (setq beg org-last-indent-begin-marker
6611 end org-last-indent-end-marker)
6612 (org-beginning-of-item)
6613 (setq beg (move-marker org-last-indent-begin-marker (point)))
6614 (org-end-of-item)
6615 (setq end (move-marker org-last-indent-end-marker (point))))
6616 (goto-char beg)
6617 (setq tmp (org-item-indent-positions)
6618 ind (car tmp)
6619 ind-down (nth 2 tmp)
6620 ind-up (nth 1 tmp)
6621 delta (if (> arg 0)
6622 (if ind-down (- ind-down ind) 2)
6623 (if ind-up (- ind-up ind) -2)))
6624 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6625 (while (< (point) end)
6626 (beginning-of-line 1)
6627 (skip-chars-forward " \t") (setq ind1 (current-column))
6628 (delete-region (point-at-bol) (point))
6629 (or (eolp) (indent-to-column (+ ind1 delta)))
6630 (beginning-of-line 2))))
6631 (org-fix-bullet-type)
6632 (org-maybe-renumber-ordered-list-safe)
6633 (save-excursion
6634 (beginning-of-line 0)
6635 (condition-case nil (org-beginning-of-item) (error nil))
6636 (org-maybe-renumber-ordered-list-safe)))
6638 (defun org-item-indent-positions ()
6639 "Return indentation for plain list items.
6640 This returns a list with three values: The current indentation, the
6641 parent indentation and the indentation a child should habe.
6642 Assumes cursor in item line."
6643 (let* ((bolpos (point-at-bol))
6644 (ind (org-get-indentation))
6645 ind-down ind-up pos)
6646 (save-excursion
6647 (org-beginning-of-item-list)
6648 (skip-chars-backward "\n\r \t")
6649 (when (org-in-item-p)
6650 (org-beginning-of-item)
6651 (setq ind-up (org-get-indentation))))
6652 (setq pos (point))
6653 (save-excursion
6654 (cond
6655 ((and (condition-case nil (progn (org-previous-item) t)
6656 (error nil))
6657 (or (forward-char 1) t)
6658 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6659 (setq ind-down (org-get-indentation)))
6660 ((and (goto-char pos)
6661 (org-at-item-p))
6662 (goto-char (match-end 0))
6663 (skip-chars-forward " \t")
6664 (setq ind-down (current-column)))))
6665 (list ind ind-up ind-down)))
6667 ;;; The orgstruct minor mode
6669 ;; Define a minor mode which can be used in other modes in order to
6670 ;; integrate the org-mode structure editing commands.
6672 ;; This is really a hack, because the org-mode structure commands use
6673 ;; keys which normally belong to the major mode. Here is how it
6674 ;; works: The minor mode defines all the keys necessary to operate the
6675 ;; structure commands, but wraps the commands into a function which
6676 ;; tests if the cursor is currently at a headline or a plain list
6677 ;; item. If that is the case, the structure command is used,
6678 ;; temporarily setting many Org-mode variables like regular
6679 ;; expressions for filling etc. However, when any of those keys is
6680 ;; used at a different location, function uses `key-binding' to look
6681 ;; up if the key has an associated command in another currently active
6682 ;; keymap (minor modes, major mode, global), and executes that
6683 ;; command. There might be problems if any of the keys is otherwise
6684 ;; used as a prefix key.
6686 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6687 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6688 ;; addresses this by checking explicitly for both bindings.
6690 (defvar orgstruct-mode-map (make-sparse-keymap)
6691 "Keymap for the minor `orgstruct-mode'.")
6693 (defvar org-local-vars nil
6694 "List of local variables, for use by `orgstruct-mode'")
6696 ;;;###autoload
6697 (define-minor-mode orgstruct-mode
6698 "Toggle the minor more `orgstruct-mode'.
6699 This mode is for using Org-mode structure commands in other modes.
6700 The following key behave as if Org-mode was active, if the cursor
6701 is on a headline, or on a plain list item (both in the definition
6702 of Org-mode).
6704 M-up Move entry/item up
6705 M-down Move entry/item down
6706 M-left Promote
6707 M-right Demote
6708 M-S-up Move entry/item up
6709 M-S-down Move entry/item down
6710 M-S-left Promote subtree
6711 M-S-right Demote subtree
6712 M-q Fill paragraph and items like in Org-mode
6713 C-c ^ Sort entries
6714 C-c - Cycle list bullet
6715 TAB Cycle item visibility
6716 M-RET Insert new heading/item
6717 S-M-RET Insert new TODO heading / Chekbox item
6718 C-c C-c Set tags / toggle checkbox"
6719 nil " OrgStruct" nil
6720 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6722 ;;;###autoload
6723 (defun turn-on-orgstruct ()
6724 "Unconditionally turn on `orgstruct-mode'."
6725 (orgstruct-mode 1))
6727 ;;;###autoload
6728 (defun turn-on-orgstruct++ ()
6729 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6730 In addition to setting orgstruct-mode, this also exports all indentation and
6731 autofilling variables from org-mode into the buffer. Note that turning
6732 off orgstruct-mode will *not* remove these additonal settings."
6733 (orgstruct-mode 1)
6734 (let (var val)
6735 (mapc
6736 (lambda (x)
6737 (when (string-match
6738 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6739 (symbol-name (car x)))
6740 (setq var (car x) val (nth 1 x))
6741 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6742 org-local-vars)))
6744 (defun orgstruct-error ()
6745 "Error when there is no default binding for a structure key."
6746 (interactive)
6747 (error "This key is has no function outside structure elements"))
6749 (defun orgstruct-setup ()
6750 "Setup orgstruct keymaps."
6751 (let ((nfunc 0)
6752 (bindings
6753 (list
6754 '([(meta up)] org-metaup)
6755 '([(meta down)] org-metadown)
6756 '([(meta left)] org-metaleft)
6757 '([(meta right)] org-metaright)
6758 '([(meta shift up)] org-shiftmetaup)
6759 '([(meta shift down)] org-shiftmetadown)
6760 '([(meta shift left)] org-shiftmetaleft)
6761 '([(meta shift right)] org-shiftmetaright)
6762 '([(shift up)] org-shiftup)
6763 '([(shift down)] org-shiftdown)
6764 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6765 '("\M-q" fill-paragraph)
6766 '("\C-c^" org-sort)
6767 '("\C-c-" org-cycle-list-bullet)))
6768 elt key fun cmd)
6769 (while (setq elt (pop bindings))
6770 (setq nfunc (1+ nfunc))
6771 (setq key (org-key (car elt))
6772 fun (nth 1 elt)
6773 cmd (orgstruct-make-binding fun nfunc key))
6774 (org-defkey orgstruct-mode-map key cmd))
6776 ;; Special treatment needed for TAB and RET
6777 (org-defkey orgstruct-mode-map [(tab)]
6778 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6779 (org-defkey orgstruct-mode-map "\C-i"
6780 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6782 (org-defkey orgstruct-mode-map "\M-\C-m"
6783 (orgstruct-make-binding 'org-insert-heading 105
6784 "\M-\C-m" [(meta return)]))
6785 (org-defkey orgstruct-mode-map [(meta return)]
6786 (orgstruct-make-binding 'org-insert-heading 106
6787 [(meta return)] "\M-\C-m"))
6789 (org-defkey orgstruct-mode-map [(shift meta return)]
6790 (orgstruct-make-binding 'org-insert-todo-heading 107
6791 [(meta return)] "\M-\C-m"))
6793 (unless org-local-vars
6794 (setq org-local-vars (org-get-local-variables)))
6798 (defun orgstruct-make-binding (fun n &rest keys)
6799 "Create a function for binding in the structure minor mode.
6800 FUN is the command to call inside a table. N is used to create a unique
6801 command name. KEYS are keys that should be checked in for a command
6802 to execute outside of tables."
6803 (eval
6804 (list 'defun
6805 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6806 '(arg)
6807 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6808 "Outside of structure, run the binding of `"
6809 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6810 "'.")
6811 '(interactive "p")
6812 (list 'if
6813 '(org-context-p 'headline 'item)
6814 (list 'org-run-like-in-org-mode (list 'quote fun))
6815 (list 'let '(orgstruct-mode)
6816 (list 'call-interactively
6817 (append '(or)
6818 (mapcar (lambda (k)
6819 (list 'key-binding k))
6820 keys)
6821 '('orgstruct-error))))))))
6823 (defun org-context-p (&rest contexts)
6824 "Check if local context is and of CONTEXTS.
6825 Possible values in the list of contexts are `table', `headline', and `item'."
6826 (let ((pos (point)))
6827 (goto-char (point-at-bol))
6828 (prog1 (or (and (memq 'table contexts)
6829 (looking-at "[ \t]*|"))
6830 (and (memq 'headline contexts)
6831 (looking-at "\\*+"))
6832 (and (memq 'item contexts)
6833 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6834 (goto-char pos))))
6836 (defun org-get-local-variables ()
6837 "Return a list of all local variables in an org-mode buffer."
6838 (let (varlist)
6839 (with-current-buffer (get-buffer-create "*Org tmp*")
6840 (erase-buffer)
6841 (org-mode)
6842 (setq varlist (buffer-local-variables)))
6843 (kill-buffer "*Org tmp*")
6844 (delq nil
6845 (mapcar
6846 (lambda (x)
6847 (setq x
6848 (if (symbolp x)
6849 (list x)
6850 (list (car x) (list 'quote (cdr x)))))
6851 (if (string-match
6852 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6853 (symbol-name (car x)))
6854 x nil))
6855 varlist))))
6857 ;;;###autoload
6858 (defun org-run-like-in-org-mode (cmd)
6859 (unless org-local-vars
6860 (setq org-local-vars (org-get-local-variables)))
6861 (eval (list 'let org-local-vars
6862 (list 'call-interactively (list 'quote cmd)))))
6864 ;;;; Archiving
6866 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6868 (defun org-archive-subtree (&optional find-done)
6869 "Move the current subtree to the archive.
6870 The archive can be a certain top-level heading in the current file, or in
6871 a different file. The tree will be moved to that location, the subtree
6872 heading be marked DONE, and the current time will be added.
6874 When called with prefix argument FIND-DONE, find whole trees without any
6875 open TODO items and archive them (after getting confirmation from the user).
6876 If the cursor is not at a headline when this comand is called, try all level
6877 1 trees. If the cursor is on a headline, only try the direct children of
6878 this heading."
6879 (interactive "P")
6880 (if find-done
6881 (org-archive-all-done)
6882 ;; Save all relevant TODO keyword-relatex variables
6884 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6885 (tr-org-todo-keywords-1 org-todo-keywords-1)
6886 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6887 (tr-org-done-keywords org-done-keywords)
6888 (tr-org-todo-regexp org-todo-regexp)
6889 (tr-org-todo-line-regexp org-todo-line-regexp)
6890 (tr-org-odd-levels-only org-odd-levels-only)
6891 (this-buffer (current-buffer))
6892 (org-archive-location org-archive-location)
6893 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6894 (file (abbreviate-file-name (buffer-file-name)))
6895 (time (format-time-string
6896 (substring (cdr org-time-stamp-formats) 1 -1)
6897 (current-time)))
6898 afile heading buffer level newfile-p
6899 category todo priority ltags itags prop)
6901 ;; Try to find a local archive location
6902 (save-excursion
6903 (save-restriction
6904 (widen)
6905 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6906 (if (and prop (string-match "\\S-" prop))
6907 (setq org-archive-location prop)
6908 (if (or (re-search-backward re nil t)
6909 (re-search-forward re nil t))
6910 (setq org-archive-location (match-string 1))))))
6912 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6913 (progn
6914 (setq afile (format (match-string 1 org-archive-location)
6915 (file-name-nondirectory buffer-file-name))
6916 heading (match-string 2 org-archive-location)))
6917 (error "Invalid `org-archive-location'"))
6918 (if (> (length afile) 0)
6919 (setq newfile-p (not (file-exists-p afile))
6920 buffer (find-file-noselect afile))
6921 (setq buffer (current-buffer)))
6922 (unless buffer
6923 (error "Cannot access file \"%s\"" afile))
6924 (if (and (> (length heading) 0)
6925 (string-match "^\\*+" heading))
6926 (setq level (match-end 0))
6927 (setq heading nil level 0))
6928 (save-excursion
6929 (org-back-to-heading t)
6930 ;; Get context information that will be lost by moving the tree
6931 (org-refresh-category-properties)
6932 (setq category (org-get-category)
6933 todo (and (looking-at org-todo-line-regexp)
6934 (match-string 2))
6935 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
6936 ltags (org-get-tags)
6937 itags (org-delete-all ltags (org-get-tags-at)))
6938 (setq ltags (mapconcat 'identity ltags " ")
6939 itags (mapconcat 'identity itags " "))
6940 ;; We first only copy, in case something goes wrong
6941 ;; we need to protect this-command, to avoid kill-region sets it,
6942 ;; which would lead to duplication of subtrees
6943 (let (this-command) (org-copy-subtree))
6944 (set-buffer buffer)
6945 ;; Enforce org-mode for the archive buffer
6946 (if (not (org-mode-p))
6947 ;; Force the mode for future visits.
6948 (let ((org-insert-mode-line-in-empty-file t)
6949 (org-inhibit-startup t))
6950 (call-interactively 'org-mode)))
6951 (when newfile-p
6952 (goto-char (point-max))
6953 (insert (format "\nArchived entries from file %s\n\n"
6954 (buffer-file-name this-buffer))))
6955 ;; Force the TODO keywords of the original buffer
6956 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6957 (org-todo-keywords-1 tr-org-todo-keywords-1)
6958 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6959 (org-done-keywords tr-org-done-keywords)
6960 (org-todo-regexp tr-org-todo-regexp)
6961 (org-todo-line-regexp tr-org-todo-line-regexp)
6962 (org-odd-levels-only
6963 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6964 org-odd-levels-only
6965 tr-org-odd-levels-only)))
6966 (goto-char (point-min))
6967 (if heading
6968 (progn
6969 (if (re-search-forward
6970 (concat "^" (regexp-quote heading)
6971 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6972 nil t)
6973 (goto-char (match-end 0))
6974 ;; Heading not found, just insert it at the end
6975 (goto-char (point-max))
6976 (or (bolp) (insert "\n"))
6977 (insert "\n" heading "\n")
6978 (end-of-line 0))
6979 ;; Make the subtree visible
6980 (show-subtree)
6981 (org-end-of-subtree t)
6982 (skip-chars-backward " \t\r\n")
6983 (and (looking-at "[ \t\r\n]*")
6984 (replace-match "\n\n")))
6985 ;; No specific heading, just go to end of file.
6986 (goto-char (point-max)) (insert "\n"))
6987 ;; Paste
6988 (org-paste-subtree (org-get-legal-level level 1))
6990 ;; Mark the entry as done
6991 (when (and org-archive-mark-done
6992 (looking-at org-todo-line-regexp)
6993 (or (not (match-end 2))
6994 (not (member (match-string 2) org-done-keywords))))
6995 (let (org-log-done)
6996 (org-todo
6997 (car (or (member org-archive-mark-done org-done-keywords)
6998 org-done-keywords)))))
7000 ;; Add the context info
7001 (when org-archive-save-context-info
7002 (let ((l org-archive-save-context-info) e n v)
7003 (while (setq e (pop l))
7004 (when (and (setq v (symbol-value e))
7005 (stringp v) (string-match "\\S-" v))
7006 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7007 (org-entry-put (point) n v)))))
7009 ;; Save the buffer, if it is not the same buffer.
7010 (if (not (eq this-buffer buffer)) (save-buffer))))
7011 ;; Here we are back in the original buffer. Everything seems to have
7012 ;; worked. So now cut the tree and finish up.
7013 (let (this-command) (org-cut-subtree))
7014 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7015 (message "Subtree archived %s"
7016 (if (eq this-buffer buffer)
7017 (concat "under heading: " heading)
7018 (concat "in file: " (abbreviate-file-name afile)))))))
7020 (defun org-refresh-category-properties ()
7021 "Refresh category text properties in teh buffer."
7022 (let ((def-cat (cond
7023 ((null org-category)
7024 (if buffer-file-name
7025 (file-name-sans-extension
7026 (file-name-nondirectory buffer-file-name))
7027 "???"))
7028 ((symbolp org-category) (symbol-name org-category))
7029 (t org-category)))
7030 beg end cat pos optionp)
7031 (org-unmodified
7032 (save-excursion
7033 (save-restriction
7034 (widen)
7035 (goto-char (point-min))
7036 (put-text-property (point) (point-max) 'org-category def-cat)
7037 (while (re-search-forward
7038 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7039 (setq pos (match-end 0)
7040 optionp (equal (char-after (match-beginning 0)) ?#)
7041 cat (org-trim (match-string 2)))
7042 (if optionp
7043 (setq beg (point-at-bol) end (point-max))
7044 (org-back-to-heading t)
7045 (setq beg (point) end (org-end-of-subtree t t)))
7046 (put-text-property beg end 'org-category cat)
7047 (goto-char pos)))))))
7049 (defun org-archive-all-done (&optional tag)
7050 "Archive sublevels of the current tree without open TODO items.
7051 If the cursor is not on a headline, try all level 1 trees. If
7052 it is on a headline, try all direct children.
7053 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7054 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7055 (rea (concat ".*:" org-archive-tag ":"))
7056 (begm (make-marker))
7057 (endm (make-marker))
7058 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7059 "Move subtree to archive (no open TODO items)? "))
7060 beg end (cntarch 0))
7061 (if (org-on-heading-p)
7062 (progn
7063 (setq re1 (concat "^" (regexp-quote
7064 (make-string
7065 (1+ (- (match-end 0) (match-beginning 0)))
7066 ?*))
7067 " "))
7068 (move-marker begm (point))
7069 (move-marker endm (org-end-of-subtree t)))
7070 (setq re1 "^* ")
7071 (move-marker begm (point-min))
7072 (move-marker endm (point-max)))
7073 (save-excursion
7074 (goto-char begm)
7075 (while (re-search-forward re1 endm t)
7076 (setq beg (match-beginning 0)
7077 end (save-excursion (org-end-of-subtree t) (point)))
7078 (goto-char beg)
7079 (if (re-search-forward re end t)
7080 (goto-char end)
7081 (goto-char beg)
7082 (if (and (or (not tag) (not (looking-at rea)))
7083 (y-or-n-p question))
7084 (progn
7085 (if tag
7086 (org-toggle-tag org-archive-tag 'on)
7087 (org-archive-subtree))
7088 (setq cntarch (1+ cntarch)))
7089 (goto-char end)))))
7090 (message "%d trees archived" cntarch)))
7092 (defun org-cycle-hide-drawers (state)
7093 "Re-hide all drawers after a visibility state change."
7094 (when (and (org-mode-p)
7095 (not (memq state '(overview folded))))
7096 (save-excursion
7097 (let* ((globalp (memq state '(contents all)))
7098 (beg (if globalp (point-min) (point)))
7099 (end (if globalp (point-max) (org-end-of-subtree t))))
7100 (goto-char beg)
7101 (while (re-search-forward org-drawer-regexp end t)
7102 (org-flag-drawer t))))))
7104 (defun org-flag-drawer (flag)
7105 (save-excursion
7106 (beginning-of-line 1)
7107 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7108 (let ((b (match-end 0)))
7109 (if (re-search-forward
7110 "^[ \t]*:END:"
7111 (save-excursion (outline-next-heading) (point)) t)
7112 (outline-flag-region b (point-at-eol) flag)
7113 (error ":END: line missing"))))))
7115 (defun org-cycle-hide-archived-subtrees (state)
7116 "Re-hide all archived subtrees after a visibility state change."
7117 (when (and (not org-cycle-open-archived-trees)
7118 (not (memq state '(overview folded))))
7119 (save-excursion
7120 (let* ((globalp (memq state '(contents all)))
7121 (beg (if globalp (point-min) (point)))
7122 (end (if globalp (point-max) (org-end-of-subtree t))))
7123 (org-hide-archived-subtrees beg end)
7124 (goto-char beg)
7125 (if (looking-at (concat ".*:" org-archive-tag ":"))
7126 (message (substitute-command-keys
7127 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7129 (defun org-force-cycle-archived ()
7130 "Cycle subtree even if it is archived."
7131 (interactive)
7132 (setq this-command 'org-cycle)
7133 (let ((org-cycle-open-archived-trees t))
7134 (call-interactively 'org-cycle)))
7136 (defun org-hide-archived-subtrees (beg end)
7137 "Re-hide all archived subtrees after a visibility state change."
7138 (save-excursion
7139 (let* ((re (concat ":" org-archive-tag ":")))
7140 (goto-char beg)
7141 (while (re-search-forward re end t)
7142 (and (org-on-heading-p) (hide-subtree))
7143 (org-end-of-subtree t)))))
7145 (defun org-toggle-tag (tag &optional onoff)
7146 "Toggle the tag TAG for the current line.
7147 If ONOFF is `on' or `off', don't toggle but set to this state."
7148 (unless (org-on-heading-p t) (error "Not on headling"))
7149 (let (res current)
7150 (save-excursion
7151 (beginning-of-line)
7152 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7153 (point-at-eol) t)
7154 (progn
7155 (setq current (match-string 1))
7156 (replace-match ""))
7157 (setq current ""))
7158 (setq current (nreverse (org-split-string current ":")))
7159 (cond
7160 ((eq onoff 'on)
7161 (setq res t)
7162 (or (member tag current) (push tag current)))
7163 ((eq onoff 'off)
7164 (or (not (member tag current)) (setq current (delete tag current))))
7165 (t (if (member tag current)
7166 (setq current (delete tag current))
7167 (setq res t)
7168 (push tag current))))
7169 (end-of-line 1)
7170 (when current
7171 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
7172 (org-set-tags nil t)
7173 res)
7174 (run-hooks 'org-after-tags-change-hook)))
7176 (defun org-toggle-archive-tag (&optional arg)
7177 "Toggle the archive tag for the current headline.
7178 With prefix ARG, check all children of current headline and offer tagging
7179 the children that do not contain any open TODO items."
7180 (interactive "P")
7181 (if arg
7182 (org-archive-all-done 'tag)
7183 (let (set)
7184 (save-excursion
7185 (org-back-to-heading t)
7186 (setq set (org-toggle-tag org-archive-tag))
7187 (when set (hide-subtree)))
7188 (and set (beginning-of-line 1))
7189 (message "Subtree %s" (if set "archived" "unarchived")))))
7192 ;;;; Tables
7194 ;;; The table editor
7196 ;; Watch out: Here we are talking about two different kind of tables.
7197 ;; Most of the code is for the tables created with the Org-mode table editor.
7198 ;; Sometimes, we talk about tables created and edited with the table.el
7199 ;; Emacs package. We call the former org-type tables, and the latter
7200 ;; table.el-type tables.
7202 (defun org-before-change-function (beg end)
7203 "Every change indicates that a table might need an update."
7204 (setq org-table-may-need-update t))
7206 (defconst org-table-line-regexp "^[ \t]*|"
7207 "Detects an org-type table line.")
7208 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7209 "Detects an org-type table line.")
7210 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7211 "Detects a table line marked for automatic recalculation.")
7212 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7213 "Detects a table line marked for automatic recalculation.")
7214 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7215 "Detects a table line marked for automatic recalculation.")
7216 (defconst org-table-hline-regexp "^[ \t]*|-"
7217 "Detects an org-type table hline.")
7218 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7219 "Detects a table-type table hline.")
7220 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7221 "Detects an org-type or table-type table.")
7222 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7223 "Searching from within a table (any type) this finds the first line
7224 outside the table.")
7225 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7226 "Searching from within a table (any type) this finds the first line
7227 outside the table.")
7229 (defvar org-table-last-highlighted-reference nil)
7230 (defvar org-table-formula-history nil)
7232 (defvar org-table-column-names nil
7233 "Alist with column names, derived from the `!' line.")
7234 (defvar org-table-column-name-regexp nil
7235 "Regular expression matching the current column names.")
7236 (defvar org-table-local-parameters nil
7237 "Alist with parameter names, derived from the `$' line.")
7238 (defvar org-table-named-field-locations nil
7239 "Alist with locations of named fields.")
7241 (defvar org-table-current-line-types nil
7242 "Table row types, non-nil only for the duration of a comand.")
7243 (defvar org-table-current-begin-line nil
7244 "Table begin line, non-nil only for the duration of a comand.")
7245 (defvar org-table-current-begin-pos nil
7246 "Table begin position, non-nil only for the duration of a comand.")
7247 (defvar org-table-dlines nil
7248 "Vector of data line line numbers in the current table.")
7249 (defvar org-table-hlines nil
7250 "Vector of hline line numbers in the current table.")
7252 (defconst org-table-range-regexp
7253 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7254 ;; 1 2 3 4 5
7255 "Regular expression for matching ranges in formulas.")
7257 (defconst org-table-range-regexp2
7258 (concat
7259 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7260 "\\.\\."
7261 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7262 "Match a range for reference display.")
7264 (defconst org-table-translate-regexp
7265 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7266 "Match a reference that needs translation, for reference display.")
7268 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7270 (defun org-table-create-with-table.el ()
7271 "Use the table.el package to insert a new table.
7272 If there is already a table at point, convert between Org-mode tables
7273 and table.el tables."
7274 (interactive)
7275 (require 'table)
7276 (cond
7277 ((org-at-table.el-p)
7278 (if (y-or-n-p "Convert table to Org-mode table? ")
7279 (org-table-convert)))
7280 ((org-at-table-p)
7281 (if (y-or-n-p "Convert table to table.el table? ")
7282 (org-table-convert)))
7283 (t (call-interactively 'table-insert))))
7285 (defun org-table-create-or-convert-from-region (arg)
7286 "Convert region to table, or create an empty table.
7287 If there is an active region, convert it to a table, using the function
7288 `org-table-convert-region'. See the documentation of that function
7289 to learn how the prefix argument is interpreted to determine the field
7290 separator.
7291 If there is no such region, create an empty table with `org-table-create'."
7292 (interactive "P")
7293 (if (org-region-active-p)
7294 (org-table-convert-region (region-beginning) (region-end) arg)
7295 (org-table-create arg)))
7297 (defun org-table-create (&optional size)
7298 "Query for a size and insert a table skeleton.
7299 SIZE is a string Columns x Rows like for example \"3x2\"."
7300 (interactive "P")
7301 (unless size
7302 (setq size (read-string
7303 (concat "Table size Columns x Rows [e.g. "
7304 org-table-default-size "]: ")
7305 "" nil org-table-default-size)))
7307 (let* ((pos (point))
7308 (indent (make-string (current-column) ?\ ))
7309 (split (org-split-string size " *x *"))
7310 (rows (string-to-number (nth 1 split)))
7311 (columns (string-to-number (car split)))
7312 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7313 "\n")))
7314 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7315 (point-at-bol) (point)))
7316 (beginning-of-line 1)
7317 (newline))
7318 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7319 (dotimes (i rows) (insert line))
7320 (goto-char pos)
7321 (if (> rows 1)
7322 ;; Insert a hline after the first row.
7323 (progn
7324 (end-of-line 1)
7325 (insert "\n|-")
7326 (goto-char pos)))
7327 (org-table-align)))
7329 (defun org-table-convert-region (beg0 end0 &optional separator)
7330 "Convert region to a table.
7331 The region goes from BEG0 to END0, but these borders will be moved
7332 slightly, to make sure a beginning of line in the first line is included.
7334 SEPARATOR specifies the field separator in the lines. It can have the
7335 following values:
7337 '(4) Use the comma as a field separator
7338 '(16) Use a TAB as field separator
7339 integer When a number, use that many spaces as field separator
7340 nil When nil, the command tries to be smart and figure out the
7341 separator in the following way:
7342 - when each line contains a TAB, assume TAB-separated material
7343 - when each line contains a comme, assume CSV material
7344 - else, assume one or more SPACE charcters as separator."
7345 (interactive "rP")
7346 (let* ((beg (min beg0 end0))
7347 (end (max beg0 end0))
7348 sep-re re)
7349 (goto-char beg)
7350 (beginning-of-line 1)
7351 (setq beg (move-marker (make-marker) (point)))
7352 (goto-char end)
7353 (if (bolp) (backward-char 1) (end-of-line 1))
7354 (setq end (move-marker (make-marker) (point)))
7355 ;; Get the right field separator
7356 (unless separator
7357 (goto-char beg)
7358 (setq separator
7359 (cond
7360 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7361 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7362 (t 1))))
7363 (setq re (cond
7364 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7365 ((equal separator '(16)) "^\\|\t")
7366 ((integerp separator)
7367 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7368 (t (error "This should not happen"))))
7369 (goto-char beg)
7370 (while (re-search-forward re end t)
7371 (replace-match "| " t t))
7372 (goto-char beg)
7373 (insert " ")
7374 (org-table-align)))
7376 (defun org-table-import (file arg)
7377 "Import FILE as a table.
7378 The file is assumed to be tab-separated. Such files can be produced by most
7379 spreadsheet and database applications. If no tabs (at least one per line)
7380 are found, lines will be split on whitespace into fields."
7381 (interactive "f\nP")
7382 (or (bolp) (newline))
7383 (let ((beg (point))
7384 (pm (point-max)))
7385 (insert-file-contents file)
7386 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7388 (defun org-table-export ()
7389 "Export table as a tab-separated file.
7390 Such a file can be imported into a spreadsheet program like Excel."
7391 (interactive)
7392 (let* ((beg (org-table-begin))
7393 (end (org-table-end))
7394 (table (buffer-substring beg end))
7395 (file (read-file-name "Export table to: "))
7396 buf)
7397 (unless (or (not (file-exists-p file))
7398 (y-or-n-p (format "Overwrite file %s? " file)))
7399 (error "Abort"))
7400 (with-current-buffer (find-file-noselect file)
7401 (setq buf (current-buffer))
7402 (erase-buffer)
7403 (fundamental-mode)
7404 (insert table)
7405 (goto-char (point-min))
7406 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7407 (replace-match "" t t)
7408 (end-of-line 1))
7409 (goto-char (point-min))
7410 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7411 (replace-match "" t t)
7412 (goto-char (min (1+ (point)) (point-max))))
7413 (goto-char (point-min))
7414 (while (re-search-forward "^-[-+]*$" nil t)
7415 (replace-match "")
7416 (if (looking-at "\n")
7417 (delete-char 1)))
7418 (goto-char (point-min))
7419 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7420 (replace-match "\t" t t))
7421 (save-buffer))
7422 (kill-buffer buf)))
7424 (defvar org-table-aligned-begin-marker (make-marker)
7425 "Marker at the beginning of the table last aligned.
7426 Used to check if cursor still is in that table, to minimize realignment.")
7427 (defvar org-table-aligned-end-marker (make-marker)
7428 "Marker at the end of the table last aligned.
7429 Used to check if cursor still is in that table, to minimize realignment.")
7430 (defvar org-table-last-alignment nil
7431 "List of flags for flushright alignment, from the last re-alignment.
7432 This is being used to correctly align a single field after TAB or RET.")
7433 (defvar org-table-last-column-widths nil
7434 "List of max width of fields in each column.
7435 This is being used to correctly align a single field after TAB or RET.")
7436 (defvar org-table-overlay-coordinates nil
7437 "Overlay coordinates after each align of a table.")
7438 (make-variable-buffer-local 'org-table-overlay-coordinates)
7440 (defvar org-last-recalc-line nil)
7441 (defconst org-narrow-column-arrow "=>"
7442 "Used as display property in narrowed table columns.")
7444 (defun org-table-align ()
7445 "Align the table at point by aligning all vertical bars."
7446 (interactive)
7447 (let* (
7448 ;; Limits of table
7449 (beg (org-table-begin))
7450 (end (org-table-end))
7451 ;; Current cursor position
7452 (linepos (org-current-line))
7453 (colpos (org-table-current-column))
7454 (winstart (window-start))
7455 (winstartline (org-current-line (min winstart (1- (point-max)))))
7456 lines (new "") lengths l typenums ty fields maxfields i
7457 column
7458 (indent "") cnt frac
7459 rfmt hfmt
7460 (spaces '(1 . 1))
7461 (sp1 (car spaces))
7462 (sp2 (cdr spaces))
7463 (rfmt1 (concat
7464 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7465 (hfmt1 (concat
7466 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7467 emptystrings links dates narrow fmax f1 len c e)
7468 (untabify beg end)
7469 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7470 ;; Check if we have links or dates
7471 (goto-char beg)
7472 (setq links (re-search-forward org-bracket-link-regexp end t))
7473 (goto-char beg)
7474 (setq dates (and org-display-custom-times
7475 (re-search-forward org-ts-regexp-both end t)))
7476 ;; Make sure the link properties are right
7477 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7478 ;; Make sure the date properties are right
7479 (when dates (goto-char beg) (while (org-activate-dates end)))
7481 ;; Check if we are narrowing any columns
7482 (goto-char beg)
7483 (setq narrow (and org-format-transports-properties-p
7484 (re-search-forward "<[0-9]+>" end t)))
7485 ;; Get the rows
7486 (setq lines (org-split-string
7487 (buffer-substring beg end) "\n"))
7488 ;; Store the indentation of the first line
7489 (if (string-match "^ *" (car lines))
7490 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7491 ;; Mark the hlines by setting the corresponding element to nil
7492 ;; At the same time, we remove trailing space.
7493 (setq lines (mapcar (lambda (l)
7494 (if (string-match "^ *|-" l)
7496 (if (string-match "[ \t]+$" l)
7497 (substring l 0 (match-beginning 0))
7498 l)))
7499 lines))
7500 ;; Get the data fields by splitting the lines.
7501 (setq fields (mapcar
7502 (lambda (l)
7503 (org-split-string l " *| *"))
7504 (delq nil (copy-sequence lines))))
7505 ;; How many fields in the longest line?
7506 (condition-case nil
7507 (setq maxfields (apply 'max (mapcar 'length fields)))
7508 (error
7509 (kill-region beg end)
7510 (org-table-create org-table-default-size)
7511 (error "Empty table - created default table")))
7512 ;; A list of empty strings to fill any short rows on output
7513 (setq emptystrings (make-list maxfields ""))
7514 ;; Check for special formatting.
7515 (setq i -1)
7516 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7517 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7518 ;; Check if there is an explicit width specified
7519 (when narrow
7520 (setq c column fmax nil)
7521 (while c
7522 (setq e (pop c))
7523 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7524 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7525 ;; Find fields that are wider than fmax, and shorten them
7526 (when fmax
7527 (loop for xx in column do
7528 (when (and (stringp xx)
7529 (> (org-string-width xx) fmax))
7530 (org-add-props xx nil
7531 'help-echo
7532 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7533 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7534 (unless (> f1 1)
7535 (error "Cannot narrow field starting with wide link \"%s\""
7536 (match-string 0 xx)))
7537 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7538 (add-text-properties (- f1 2) f1
7539 (list 'display org-narrow-column-arrow)
7540 xx)))))
7541 ;; Get the maximum width for each column
7542 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7543 ;; Get the fraction of numbers, to decide about alignment of the column
7544 (setq cnt 0 frac 0.0)
7545 (loop for x in column do
7546 (if (equal x "")
7548 (setq frac ( / (+ (* frac cnt)
7549 (if (string-match org-table-number-regexp x) 1 0))
7550 (setq cnt (1+ cnt))))))
7551 (push (>= frac org-table-number-fraction) typenums))
7552 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7554 ;; Store the alignment of this table, for later editing of single fields
7555 (setq org-table-last-alignment typenums
7556 org-table-last-column-widths lengths)
7558 ;; With invisible characters, `format' does not get the field width right
7559 ;; So we need to make these fields wide by hand.
7560 (when links
7561 (loop for i from 0 upto (1- maxfields) do
7562 (setq len (nth i lengths))
7563 (loop for j from 0 upto (1- (length fields)) do
7564 (setq c (nthcdr i (car (nthcdr j fields))))
7565 (if (and (stringp (car c))
7566 (string-match org-bracket-link-regexp (car c))
7567 (< (org-string-width (car c)) len))
7568 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7570 ;; Compute the formats needed for output of the table
7571 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7572 (while (setq l (pop lengths))
7573 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7574 (setq rfmt (concat rfmt (format rfmt1 ty l))
7575 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7576 (setq rfmt (concat rfmt "\n")
7577 hfmt (concat (substring hfmt 0 -1) "|\n"))
7579 (setq new (mapconcat
7580 (lambda (l)
7581 (if l (apply 'format rfmt
7582 (append (pop fields) emptystrings))
7583 hfmt))
7584 lines ""))
7585 ;; Replace the old one
7586 (delete-region beg end)
7587 (move-marker end nil)
7588 (move-marker org-table-aligned-begin-marker (point))
7589 (insert new)
7590 (move-marker org-table-aligned-end-marker (point))
7591 (when (and orgtbl-mode (not (org-mode-p)))
7592 (goto-char org-table-aligned-begin-marker)
7593 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7594 ;; Try to move to the old location
7595 (goto-line winstartline)
7596 (setq winstart (point-at-bol))
7597 (goto-line linepos)
7598 (set-window-start (selected-window) winstart 'noforce)
7599 (org-table-goto-column colpos)
7600 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7601 (setq org-table-may-need-update nil)
7604 (defun org-string-width (s)
7605 "Compute width of string, ignoring invisible characters.
7606 This ignores character with invisibility property `org-link', and also
7607 characters with property `org-cwidth', because these will become invisible
7608 upon the next fontification round."
7609 (let (b l)
7610 (when (or (eq t buffer-invisibility-spec)
7611 (assq 'org-link buffer-invisibility-spec))
7612 (while (setq b (text-property-any 0 (length s)
7613 'invisible 'org-link s))
7614 (setq s (concat (substring s 0 b)
7615 (substring s (or (next-single-property-change
7616 b 'invisible s) (length s)))))))
7617 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7618 (setq s (concat (substring s 0 b)
7619 (substring s (or (next-single-property-change
7620 b 'org-cwidth s) (length s))))))
7621 (setq l (string-width s) b -1)
7622 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7623 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7626 (defun org-table-begin (&optional table-type)
7627 "Find the beginning of the table and return its position.
7628 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7629 (save-excursion
7630 (if (not (re-search-backward
7631 (if table-type org-table-any-border-regexp
7632 org-table-border-regexp)
7633 nil t))
7634 (progn (goto-char (point-min)) (point))
7635 (goto-char (match-beginning 0))
7636 (beginning-of-line 2)
7637 (point))))
7639 (defun org-table-end (&optional table-type)
7640 "Find the end of the table and return its position.
7641 With argument TABLE-TYPE, go to the end of a table.el-type table."
7642 (save-excursion
7643 (if (not (re-search-forward
7644 (if table-type org-table-any-border-regexp
7645 org-table-border-regexp)
7646 nil t))
7647 (goto-char (point-max))
7648 (goto-char (match-beginning 0)))
7649 (point-marker)))
7651 (defun org-table-justify-field-maybe (&optional new)
7652 "Justify the current field, text to left, number to right.
7653 Optional argument NEW may specify text to replace the current field content."
7654 (cond
7655 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7656 ((org-at-table-hline-p))
7657 ((and (not new)
7658 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7659 (current-buffer)))
7660 (< (point) org-table-aligned-begin-marker)
7661 (>= (point) org-table-aligned-end-marker)))
7662 ;; This is not the same table, force a full re-align
7663 (setq org-table-may-need-update t))
7664 (t ;; realign the current field, based on previous full realign
7665 (let* ((pos (point)) s
7666 (col (org-table-current-column))
7667 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7668 l f n o e)
7669 (when (> col 0)
7670 (skip-chars-backward "^|\n")
7671 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7672 (progn
7673 (setq s (match-string 1)
7674 o (match-string 0)
7675 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7676 e (not (= (match-beginning 2) (match-end 2))))
7677 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7678 l (if e "|" (setq org-table-may-need-update t) ""))
7679 n (format f s))
7680 (if new
7681 (if (<= (length new) l) ;; FIXME: length -> str-width?
7682 (setq n (format f new))
7683 (setq n (concat new "|") org-table-may-need-update t)))
7684 (or (equal n o)
7685 (let (org-table-may-need-update)
7686 (replace-match n t t))))
7687 (setq org-table-may-need-update t))
7688 (goto-char pos))))))
7690 (defun org-table-next-field ()
7691 "Go to the next field in the current table, creating new lines as needed.
7692 Before doing so, re-align the table if necessary."
7693 (interactive)
7694 (org-table-maybe-eval-formula)
7695 (org-table-maybe-recalculate-line)
7696 (if (and org-table-automatic-realign
7697 org-table-may-need-update)
7698 (org-table-align))
7699 (let ((end (org-table-end)))
7700 (if (org-at-table-hline-p)
7701 (end-of-line 1))
7702 (condition-case nil
7703 (progn
7704 (re-search-forward "|" end)
7705 (if (looking-at "[ \t]*$")
7706 (re-search-forward "|" end))
7707 (if (and (looking-at "-")
7708 org-table-tab-jumps-over-hlines
7709 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7710 (goto-char (match-beginning 1)))
7711 (if (looking-at "-")
7712 (progn
7713 (beginning-of-line 0)
7714 (org-table-insert-row 'below))
7715 (if (looking-at " ") (forward-char 1))))
7716 (error
7717 (org-table-insert-row 'below)))))
7719 (defun org-table-previous-field ()
7720 "Go to the previous field in the table.
7721 Before doing so, re-align the table if necessary."
7722 (interactive)
7723 (org-table-justify-field-maybe)
7724 (org-table-maybe-recalculate-line)
7725 (if (and org-table-automatic-realign
7726 org-table-may-need-update)
7727 (org-table-align))
7728 (if (org-at-table-hline-p)
7729 (end-of-line 1))
7730 (re-search-backward "|" (org-table-begin))
7731 (re-search-backward "|" (org-table-begin))
7732 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7733 (re-search-backward "|" (org-table-begin)))
7734 (if (looking-at "| ?")
7735 (goto-char (match-end 0))))
7737 (defun org-table-next-row ()
7738 "Go to the next row (same column) in the current table.
7739 Before doing so, re-align the table if necessary."
7740 (interactive)
7741 (org-table-maybe-eval-formula)
7742 (org-table-maybe-recalculate-line)
7743 (if (or (looking-at "[ \t]*$")
7744 (save-excursion (skip-chars-backward " \t") (bolp)))
7745 (newline)
7746 (if (and org-table-automatic-realign
7747 org-table-may-need-update)
7748 (org-table-align))
7749 (let ((col (org-table-current-column)))
7750 (beginning-of-line 2)
7751 (if (or (not (org-at-table-p))
7752 (org-at-table-hline-p))
7753 (progn
7754 (beginning-of-line 0)
7755 (org-table-insert-row 'below)))
7756 (org-table-goto-column col)
7757 (skip-chars-backward "^|\n\r")
7758 (if (looking-at " ") (forward-char 1)))))
7760 (defun org-table-copy-down (n)
7761 "Copy a field down in the current column.
7762 If the field at the cursor is empty, copy into it the content of the nearest
7763 non-empty field above. With argument N, use the Nth non-empty field.
7764 If the current field is not empty, it is copied down to the next row, and
7765 the cursor is moved with it. Therefore, repeating this command causes the
7766 column to be filled row-by-row.
7767 If the variable `org-table-copy-increment' is non-nil and the field is an
7768 integer or a timestamp, it will be incremented while copying. In the case of
7769 a timestamp, if the cursor is on the year, change the year. If it is on the
7770 month or the day, change that. Point will stay on the current date field
7771 in order to easily repeat the interval."
7772 (interactive "p")
7773 (let* ((colpos (org-table-current-column))
7774 (col (current-column))
7775 (field (org-table-get-field))
7776 (non-empty (string-match "[^ \t]" field))
7777 (beg (org-table-begin))
7778 txt)
7779 (org-table-check-inside-data-field)
7780 (if non-empty
7781 (progn
7782 (setq txt (org-trim field))
7783 (org-table-next-row)
7784 (org-table-blank-field))
7785 (save-excursion
7786 (setq txt
7787 (catch 'exit
7788 (while (progn (beginning-of-line 1)
7789 (re-search-backward org-table-dataline-regexp
7790 beg t))
7791 (org-table-goto-column colpos t)
7792 (if (and (looking-at
7793 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7794 (= (setq n (1- n)) 0))
7795 (throw 'exit (match-string 1))))))))
7796 (if txt
7797 (progn
7798 (if (and org-table-copy-increment
7799 (string-match "^[0-9]+$" txt))
7800 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7801 (insert txt)
7802 (move-to-column col)
7803 (if (and org-table-copy-increment (org-at-timestamp-p t))
7804 (org-timestamp-up 1)
7805 (org-table-maybe-recalculate-line))
7806 (org-table-align)
7807 (move-to-column col))
7808 (error "No non-empty field found"))))
7810 (defun org-table-check-inside-data-field ()
7811 "Is point inside a table data field?
7812 I.e. not on a hline or before the first or after the last column?
7813 This actually throws an error, so it aborts the current command."
7814 (if (or (not (org-at-table-p))
7815 (= (org-table-current-column) 0)
7816 (org-at-table-hline-p)
7817 (looking-at "[ \t]*$"))
7818 (error "Not in table data field")))
7820 (defvar org-table-clip nil
7821 "Clipboard for table regions.")
7823 (defun org-table-blank-field ()
7824 "Blank the current table field or active region."
7825 (interactive)
7826 (org-table-check-inside-data-field)
7827 (if (and (interactive-p) (org-region-active-p))
7828 (let (org-table-clip)
7829 (org-table-cut-region (region-beginning) (region-end)))
7830 (skip-chars-backward "^|")
7831 (backward-char 1)
7832 (if (looking-at "|[^|\n]+")
7833 (let* ((pos (match-beginning 0))
7834 (match (match-string 0))
7835 (len (org-string-width match)))
7836 (replace-match (concat "|" (make-string (1- len) ?\ )))
7837 (goto-char (+ 2 pos))
7838 (substring match 1)))))
7840 (defun org-table-get-field (&optional n replace)
7841 "Return the value of the field in column N of current row.
7842 N defaults to current field.
7843 If REPLACE is a string, replace field with this value. The return value
7844 is always the old value."
7845 (and n (org-table-goto-column n))
7846 (skip-chars-backward "^|\n")
7847 (backward-char 1)
7848 (if (looking-at "|[^|\r\n]*")
7849 (let* ((pos (match-beginning 0))
7850 (val (buffer-substring (1+ pos) (match-end 0))))
7851 (if replace
7852 (replace-match (concat "|" replace) t t))
7853 (goto-char (min (point-at-eol) (+ 2 pos)))
7854 val)
7855 (forward-char 1) ""))
7857 (defun org-table-field-info (arg)
7858 "Show info about the current field, and highlight any reference at point."
7859 (interactive "P")
7860 (org-table-get-specials)
7861 (save-excursion
7862 (let* ((pos (point))
7863 (col (org-table-current-column))
7864 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7865 (name (car (rassoc (list (org-current-line) col)
7866 org-table-named-field-locations)))
7867 (eql (org-table-get-stored-formulas))
7868 (dline (org-table-current-dline))
7869 (ref (format "@%d$%d" dline col))
7870 (ref1 (org-table-convert-refs-to-an ref))
7871 (fequation (or (assoc name eql) (assoc ref eql)))
7872 (cequation (assoc (int-to-string col) eql))
7873 (eqn (or fequation cequation)))
7874 (goto-char pos)
7875 (condition-case nil
7876 (org-table-show-reference 'local)
7877 (error nil))
7878 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7879 dline col
7880 (if cname (concat " or $" cname) "")
7881 dline col ref1
7882 (if name (concat " or $" name) "")
7883 ;; FIXME: formula info not correct if special table line
7884 (if eqn
7885 (concat ", formula: "
7886 (org-table-formula-to-user
7887 (concat
7888 (if (string-match "^[$@]"(car eqn)) "" "$")
7889 (car eqn) "=" (cdr eqn))))
7890 "")))))
7892 (defun org-table-current-column ()
7893 "Find out which column we are in.
7894 When called interactively, column is also displayed in echo area."
7895 (interactive)
7896 (if (interactive-p) (org-table-check-inside-data-field))
7897 (save-excursion
7898 (let ((cnt 0) (pos (point)))
7899 (beginning-of-line 1)
7900 (while (search-forward "|" pos t)
7901 (setq cnt (1+ cnt)))
7902 (if (interactive-p) (message "This is table column %d" cnt))
7903 cnt)))
7905 (defun org-table-current-dline ()
7906 "Find out what table data line we are in.
7907 Only datalins count for this."
7908 (interactive)
7909 (if (interactive-p) (org-table-check-inside-data-field))
7910 (save-excursion
7911 (let ((cnt 0) (pos (point)))
7912 (goto-char (org-table-begin))
7913 (while (<= (point) pos)
7914 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7915 (beginning-of-line 2))
7916 (if (interactive-p) (message "This is table line %d" cnt))
7917 cnt)))
7919 (defun org-table-goto-column (n &optional on-delim force)
7920 "Move the cursor to the Nth column in the current table line.
7921 With optional argument ON-DELIM, stop with point before the left delimiter
7922 of the field.
7923 If there are less than N fields, just go to after the last delimiter.
7924 However, when FORCE is non-nil, create new columns if necessary."
7925 (interactive "p")
7926 (let ((pos (point-at-eol)))
7927 (beginning-of-line 1)
7928 (when (> n 0)
7929 (while (and (> (setq n (1- n)) -1)
7930 (or (search-forward "|" pos t)
7931 (and force
7932 (progn (end-of-line 1)
7933 (skip-chars-backward "^|")
7934 (insert " | "))))))
7935 ; (backward-char 2) t)))))
7936 (when (and force (not (looking-at ".*|")))
7937 (save-excursion (end-of-line 1) (insert " | ")))
7938 (if on-delim
7939 (backward-char 1)
7940 (if (looking-at " ") (forward-char 1))))))
7942 (defun org-at-table-p (&optional table-type)
7943 "Return t if the cursor is inside an org-type table.
7944 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7945 (if org-enable-table-editor
7946 (save-excursion
7947 (beginning-of-line 1)
7948 (looking-at (if table-type org-table-any-line-regexp
7949 org-table-line-regexp)))
7950 nil))
7952 (defun org-at-table.el-p ()
7953 "Return t if and only if we are at a table.el table."
7954 (and (org-at-table-p 'any)
7955 (save-excursion
7956 (goto-char (org-table-begin 'any))
7957 (looking-at org-table1-hline-regexp))))
7959 (defun org-table-recognize-table.el ()
7960 "If there is a table.el table nearby, recognize it and move into it."
7961 (if org-table-tab-recognizes-table.el
7962 (if (org-at-table.el-p)
7963 (progn
7964 (beginning-of-line 1)
7965 (if (looking-at org-table-dataline-regexp)
7967 (if (looking-at org-table1-hline-regexp)
7968 (progn
7969 (beginning-of-line 2)
7970 (if (looking-at org-table-any-border-regexp)
7971 (beginning-of-line -1)))))
7972 (if (re-search-forward "|" (org-table-end t) t)
7973 (progn
7974 (require 'table)
7975 (if (table--at-cell-p (point))
7977 (message "recognizing table.el table...")
7978 (table-recognize-table)
7979 (message "recognizing table.el table...done")))
7980 (error "This should not happen..."))
7982 nil)
7983 nil))
7985 (defun org-at-table-hline-p ()
7986 "Return t if the cursor is inside a hline in a table."
7987 (if org-enable-table-editor
7988 (save-excursion
7989 (beginning-of-line 1)
7990 (looking-at org-table-hline-regexp))
7991 nil))
7993 (defun org-table-insert-column ()
7994 "Insert a new column into the table."
7995 (interactive)
7996 (if (not (org-at-table-p))
7997 (error "Not at a table"))
7998 (org-table-find-dataline)
7999 (let* ((col (max 1 (org-table-current-column)))
8000 (beg (org-table-begin))
8001 (end (org-table-end))
8002 ;; Current cursor position
8003 (linepos (org-current-line))
8004 (colpos col))
8005 (goto-char beg)
8006 (while (< (point) end)
8007 (if (org-at-table-hline-p)
8009 (org-table-goto-column col t)
8010 (insert "| "))
8011 (beginning-of-line 2))
8012 (move-marker end nil)
8013 (goto-line linepos)
8014 (org-table-goto-column colpos)
8015 (org-table-align)
8016 (org-table-fix-formulas "$" nil (1- col) 1)))
8018 (defun org-table-find-dataline ()
8019 "Find a dataline in the current table, which is needed for column commands."
8020 (if (and (org-at-table-p)
8021 (not (org-at-table-hline-p)))
8023 (let ((col (current-column))
8024 (end (org-table-end)))
8025 (move-to-column col)
8026 (while (and (< (point) end)
8027 (or (not (= (current-column) col))
8028 (org-at-table-hline-p)))
8029 (beginning-of-line 2)
8030 (move-to-column col))
8031 (if (and (org-at-table-p)
8032 (not (org-at-table-hline-p)))
8034 (error
8035 "Please position cursor in a data line for column operations")))))
8037 (defun org-table-delete-column ()
8038 "Delete a column from the table."
8039 (interactive)
8040 (if (not (org-at-table-p))
8041 (error "Not at a table"))
8042 (org-table-find-dataline)
8043 (org-table-check-inside-data-field)
8044 (let* ((col (org-table-current-column))
8045 (beg (org-table-begin))
8046 (end (org-table-end))
8047 ;; Current cursor position
8048 (linepos (org-current-line))
8049 (colpos col))
8050 (goto-char beg)
8051 (while (< (point) end)
8052 (if (org-at-table-hline-p)
8054 (org-table-goto-column col t)
8055 (and (looking-at "|[^|\n]+|")
8056 (replace-match "|")))
8057 (beginning-of-line 2))
8058 (move-marker end nil)
8059 (goto-line linepos)
8060 (org-table-goto-column colpos)
8061 (org-table-align)
8062 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8063 col -1 col)))
8065 (defun org-table-move-column-right ()
8066 "Move column to the right."
8067 (interactive)
8068 (org-table-move-column nil))
8069 (defun org-table-move-column-left ()
8070 "Move column to the left."
8071 (interactive)
8072 (org-table-move-column 'left))
8074 (defun org-table-move-column (&optional left)
8075 "Move the current column to the right. With arg LEFT, move to the left."
8076 (interactive "P")
8077 (if (not (org-at-table-p))
8078 (error "Not at a table"))
8079 (org-table-find-dataline)
8080 (org-table-check-inside-data-field)
8081 (let* ((col (org-table-current-column))
8082 (col1 (if left (1- col) col))
8083 (beg (org-table-begin))
8084 (end (org-table-end))
8085 ;; Current cursor position
8086 (linepos (org-current-line))
8087 (colpos (if left (1- col) (1+ col))))
8088 (if (and left (= col 1))
8089 (error "Cannot move column further left"))
8090 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8091 (error "Cannot move column further right"))
8092 (goto-char beg)
8093 (while (< (point) end)
8094 (if (org-at-table-hline-p)
8096 (org-table-goto-column col1 t)
8097 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8098 (replace-match "|\\2|\\1|")))
8099 (beginning-of-line 2))
8100 (move-marker end nil)
8101 (goto-line linepos)
8102 (org-table-goto-column colpos)
8103 (org-table-align)
8104 (org-table-fix-formulas
8105 "$" (list (cons (number-to-string col) (number-to-string colpos))
8106 (cons (number-to-string colpos) (number-to-string col))))))
8108 (defun org-table-move-row-down ()
8109 "Move table row down."
8110 (interactive)
8111 (org-table-move-row nil))
8112 (defun org-table-move-row-up ()
8113 "Move table row up."
8114 (interactive)
8115 (org-table-move-row 'up))
8117 (defun org-table-move-row (&optional up)
8118 "Move the current table line down. With arg UP, move it up."
8119 (interactive "P")
8120 (let* ((col (current-column))
8121 (pos (point))
8122 (hline1p (save-excursion (beginning-of-line 1)
8123 (looking-at org-table-hline-regexp)))
8124 (dline1 (org-table-current-dline))
8125 (dline2 (+ dline1 (if up -1 1)))
8126 (tonew (if up 0 2))
8127 txt hline2p)
8128 (beginning-of-line tonew)
8129 (unless (org-at-table-p)
8130 (goto-char pos)
8131 (error "Cannot move row further"))
8132 (setq hline2p (looking-at org-table-hline-regexp))
8133 (goto-char pos)
8134 (beginning-of-line 1)
8135 (setq pos (point))
8136 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8137 (delete-region (point) (1+ (point-at-eol)))
8138 (beginning-of-line tonew)
8139 (insert txt)
8140 (beginning-of-line 0)
8141 (move-to-column col)
8142 (unless (or hline1p hline2p)
8143 (org-table-fix-formulas
8144 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8145 (cons (number-to-string dline2) (number-to-string dline1)))))))
8147 (defun org-table-insert-row (&optional arg)
8148 "Insert a new row above the current line into the table.
8149 With prefix ARG, insert below the current line."
8150 (interactive "P")
8151 (if (not (org-at-table-p))
8152 (error "Not at a table"))
8153 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8154 (new (org-table-clean-line line)))
8155 ;; Fix the first field if necessary
8156 (if (string-match "^[ \t]*| *[#$] *|" line)
8157 (setq new (replace-match (match-string 0 line) t t new)))
8158 (beginning-of-line (if arg 2 1))
8159 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8160 (beginning-of-line 0)
8161 (re-search-forward "| ?" (point-at-eol) t)
8162 (and (or org-table-may-need-update org-table-overlay-coordinates)
8163 (org-table-align))
8164 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8166 (defun org-table-insert-hline (&optional above)
8167 "Insert a horizontal-line below the current line into the table.
8168 With prefix ABOVE, insert above the current line."
8169 (interactive "P")
8170 (if (not (org-at-table-p))
8171 (error "Not at a table"))
8172 (let ((line (org-table-clean-line
8173 (buffer-substring (point-at-bol) (point-at-eol))))
8174 (col (current-column)))
8175 (while (string-match "|\\( +\\)|" line)
8176 (setq line (replace-match
8177 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8178 ?-) "|") t t line)))
8179 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8180 (beginning-of-line (if above 1 2))
8181 (insert line "\n")
8182 (beginning-of-line (if above 1 -1))
8183 (move-to-column col)
8184 (and org-table-overlay-coordinates (org-table-align))))
8186 (defun org-table-hline-and-move (&optional same-column)
8187 "Insert a hline and move to the row below that line."
8188 (interactive "P")
8189 (let ((col (org-table-current-column)))
8190 (org-table-maybe-eval-formula)
8191 (org-table-maybe-recalculate-line)
8192 (org-table-insert-hline)
8193 (end-of-line 2)
8194 (if (looking-at "\n[ \t]*|-")
8195 (progn (insert "\n|") (org-table-align))
8196 (org-table-next-field))
8197 (if same-column (org-table-goto-column col))))
8199 (defun org-table-clean-line (s)
8200 "Convert a table line S into a string with only \"|\" and space.
8201 In particular, this does handle wide and invisible characters."
8202 (if (string-match "^[ \t]*|-" s)
8203 ;; It's a hline, just map the characters
8204 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8205 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8206 (setq s (replace-match
8207 (concat "|" (make-string (org-string-width (match-string 1 s))
8208 ?\ ) "|")
8209 t t s)))
8212 (defun org-table-kill-row ()
8213 "Delete the current row or horizontal line from the table."
8214 (interactive)
8215 (if (not (org-at-table-p))
8216 (error "Not at a table"))
8217 (let ((col (current-column))
8218 (dline (org-table-current-dline)))
8219 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8220 (if (not (org-at-table-p)) (beginning-of-line 0))
8221 (move-to-column col)
8222 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8223 dline -1 dline)))
8226 (defun org-table-sort-lines (with-case &optional sorting-type)
8227 "Sort table lines according to the column at point.
8229 The position of point indicates the column to be used for
8230 sorting, and the range of lines is the range between the nearest
8231 horizontal separator lines, or the entire table of no such lines
8232 exist. If point is before the first column, you will be prompted
8233 for the sorting column. If there is an active region, the mark
8234 specifies the first line and the sorting column, while point
8235 should be in the last line to be included into the sorting.
8237 The command then prompts for the sorting type which can be
8238 alphabetically, numerically, or by time (as given in a time stamp
8239 in the field). Sorting in reverse order is also possible.
8241 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8243 If SORTING-TYPE is specified when this function is called from a Lisp
8244 program, no prompting will take place. SORTING-TYPE must be a character,
8245 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8246 should be done in reverse order."
8247 (interactive "P")
8248 (let* ((thisline (org-current-line))
8249 (thiscol (org-table-current-column))
8250 beg end bcol ecol tend tbeg column lns pos)
8251 (when (equal thiscol 0)
8252 (if (interactive-p)
8253 (setq thiscol
8254 (string-to-number
8255 (read-string "Use column N for sorting: ")))
8256 (setq thiscol 1))
8257 (org-table-goto-column thiscol))
8258 (org-table-check-inside-data-field)
8259 (if (org-region-active-p)
8260 (progn
8261 (setq beg (region-beginning) end (region-end))
8262 (goto-char beg)
8263 (setq column (org-table-current-column)
8264 beg (point-at-bol))
8265 (goto-char end)
8266 (setq end (point-at-bol 2)))
8267 (setq column (org-table-current-column)
8268 pos (point)
8269 tbeg (org-table-begin)
8270 tend (org-table-end))
8271 (if (re-search-backward org-table-hline-regexp tbeg t)
8272 (setq beg (point-at-bol 2))
8273 (goto-char tbeg)
8274 (setq beg (point-at-bol 1)))
8275 (goto-char pos)
8276 (if (re-search-forward org-table-hline-regexp tend t)
8277 (setq end (point-at-bol 1))
8278 (goto-char tend)
8279 (setq end (point-at-bol))))
8280 (setq beg (move-marker (make-marker) beg)
8281 end (move-marker (make-marker) end))
8282 (untabify beg end)
8283 (goto-char beg)
8284 (org-table-goto-column column)
8285 (skip-chars-backward "^|")
8286 (setq bcol (current-column))
8287 (org-table-goto-column (1+ column))
8288 (skip-chars-backward "^|")
8289 (setq ecol (1- (current-column)))
8290 (org-table-goto-column column)
8291 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8292 (org-split-string (buffer-substring beg end) "\n")))
8293 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8294 (delete-region beg end)
8295 (move-marker beg nil)
8296 (move-marker end nil)
8297 (insert (mapconcat 'cdr lns "\n") "\n")
8298 (goto-line thisline)
8299 (org-table-goto-column thiscol)
8300 (message "%d lines sorted, based on column %d" (length lns) column)))
8302 (defun org-table-cut-region (beg end)
8303 "Copy region in table to the clipboard and blank all relevant fields."
8304 (interactive "r")
8305 (org-table-copy-region beg end 'cut))
8307 (defun org-table-copy-region (beg end &optional cut)
8308 "Copy rectangular region in table to clipboard.
8309 A special clipboard is used which can only be accessed
8310 with `org-table-paste-rectangle'."
8311 (interactive "rP")
8312 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8313 region cols
8314 (rpl (if cut " " nil)))
8315 (goto-char beg)
8316 (org-table-check-inside-data-field)
8317 (setq l01 (org-current-line)
8318 c01 (org-table-current-column))
8319 (goto-char end)
8320 (org-table-check-inside-data-field)
8321 (setq l02 (org-current-line)
8322 c02 (org-table-current-column))
8323 (setq l1 (min l01 l02) l2 (max l01 l02)
8324 c1 (min c01 c02) c2 (max c01 c02))
8325 (catch 'exit
8326 (while t
8327 (catch 'nextline
8328 (if (> l1 l2) (throw 'exit t))
8329 (goto-line l1)
8330 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8331 (setq cols nil ic1 c1 ic2 c2)
8332 (while (< ic1 (1+ ic2))
8333 (push (org-table-get-field ic1 rpl) cols)
8334 (setq ic1 (1+ ic1)))
8335 (push (nreverse cols) region)
8336 (setq l1 (1+ l1)))))
8337 (setq org-table-clip (nreverse region))
8338 (if cut (org-table-align))
8339 org-table-clip))
8341 (defun org-table-paste-rectangle ()
8342 "Paste a rectangular region into a table.
8343 The upper right corner ends up in the current field. All involved fields
8344 will be overwritten. If the rectangle does not fit into the present table,
8345 the table is enlarged as needed. The process ignores horizontal separator
8346 lines."
8347 (interactive)
8348 (unless (and org-table-clip (listp org-table-clip))
8349 (error "First cut/copy a region to paste!"))
8350 (org-table-check-inside-data-field)
8351 (let* ((clip org-table-clip)
8352 (line (org-current-line))
8353 (col (org-table-current-column))
8354 (org-enable-table-editor t)
8355 (org-table-automatic-realign nil)
8356 c cols field)
8357 (while (setq cols (pop clip))
8358 (while (org-at-table-hline-p) (beginning-of-line 2))
8359 (if (not (org-at-table-p))
8360 (progn (end-of-line 0) (org-table-next-field)))
8361 (setq c col)
8362 (while (setq field (pop cols))
8363 (org-table-goto-column c nil 'force)
8364 (org-table-get-field nil field)
8365 (setq c (1+ c)))
8366 (beginning-of-line 2))
8367 (goto-line line)
8368 (org-table-goto-column col)
8369 (org-table-align)))
8371 (defun org-table-convert ()
8372 "Convert from `org-mode' table to table.el and back.
8373 Obviously, this only works within limits. When an Org-mode table is
8374 converted to table.el, all horizontal separator lines get lost, because
8375 table.el uses these as cell boundaries and has no notion of horizontal lines.
8376 A table.el table can be converted to an Org-mode table only if it does not
8377 do row or column spanning. Multiline cells will become multiple cells.
8378 Beware, Org-mode does not test if the table can be successfully converted - it
8379 blindly applies a recipe that works for simple tables."
8380 (interactive)
8381 (require 'table)
8382 (if (org-at-table.el-p)
8383 ;; convert to Org-mode table
8384 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8385 (end (move-marker (make-marker) (org-table-end t))))
8386 (table-unrecognize-region beg end)
8387 (goto-char beg)
8388 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8389 (replace-match ""))
8390 (goto-char beg))
8391 (if (org-at-table-p)
8392 ;; convert to table.el table
8393 (let ((beg (move-marker (make-marker) (org-table-begin)))
8394 (end (move-marker (make-marker) (org-table-end))))
8395 ;; first, get rid of all horizontal lines
8396 (goto-char beg)
8397 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8398 (replace-match ""))
8399 ;; insert a hline before first
8400 (goto-char beg)
8401 (org-table-insert-hline 'above)
8402 (beginning-of-line -1)
8403 ;; insert a hline after each line
8404 (while (progn (beginning-of-line 3) (< (point) end))
8405 (org-table-insert-hline))
8406 (goto-char beg)
8407 (setq end (move-marker end (org-table-end)))
8408 ;; replace "+" at beginning and ending of hlines
8409 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8410 (replace-match "\\1+-"))
8411 (goto-char beg)
8412 (while (re-search-forward "-|[ \t]*$" end t)
8413 (replace-match "-+"))
8414 (goto-char beg)))))
8416 (defun org-table-wrap-region (arg)
8417 "Wrap several fields in a column like a paragraph.
8418 This is useful if you'd like to spread the contents of a field over several
8419 lines, in order to keep the table compact.
8421 If there is an active region, and both point and mark are in the same column,
8422 the text in the column is wrapped to minimum width for the given number of
8423 lines. Generally, this makes the table more compact. A prefix ARG may be
8424 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8425 formats the selected text to two lines. If the region was longer than two
8426 lines, the remaining lines remain empty. A negative prefix argument reduces
8427 the current number of lines by that amount. The wrapped text is pasted back
8428 into the table. If you formatted it to more lines than it was before, fields
8429 further down in the table get overwritten - so you might need to make space in
8430 the table first.
8432 If there is no region, the current field is split at the cursor position and
8433 the text fragment to the right of the cursor is prepended to the field one
8434 line down.
8436 If there is no region, but you specify a prefix ARG, the current field gets
8437 blank, and the content is appended to the field above."
8438 (interactive "P")
8439 (org-table-check-inside-data-field)
8440 (if (org-region-active-p)
8441 ;; There is a region: fill as a paragraph
8442 (let* ((beg (region-beginning))
8443 (cline (save-excursion (goto-char beg) (org-current-line)))
8444 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8445 nlines)
8446 (org-table-cut-region (region-beginning) (region-end))
8447 (if (> (length (car org-table-clip)) 1)
8448 (error "Region must be limited to single column"))
8449 (setq nlines (if arg
8450 (if (< arg 1)
8451 (+ (length org-table-clip) arg)
8452 arg)
8453 (length org-table-clip)))
8454 (setq org-table-clip
8455 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8456 nil nlines)))
8457 (goto-line cline)
8458 (org-table-goto-column ccol)
8459 (org-table-paste-rectangle))
8460 ;; No region, split the current field at point
8461 (if arg
8462 ;; combine with field above
8463 (let ((s (org-table-blank-field))
8464 (col (org-table-current-column)))
8465 (beginning-of-line 0)
8466 (while (org-at-table-hline-p) (beginning-of-line 0))
8467 (org-table-goto-column col)
8468 (skip-chars-forward "^|")
8469 (skip-chars-backward " ")
8470 (insert " " (org-trim s))
8471 (org-table-align))
8472 ;; split field
8473 (when (looking-at "\\([^|]+\\)+|")
8474 (let ((s (match-string 1)))
8475 (replace-match " |")
8476 (goto-char (match-beginning 0))
8477 (org-table-next-row)
8478 (insert (org-trim s) " ")
8479 (org-table-align))))))
8481 (defvar org-field-marker nil)
8483 (defun org-table-edit-field (arg)
8484 "Edit table field in a different window.
8485 This is mainly useful for fields that contain hidden parts.
8486 When called with a \\[universal-argument] prefix, just make the full field visible so that
8487 it can be edited in place."
8488 (interactive "P")
8489 (if arg
8490 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8491 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8492 (remove-text-properties b e '(org-cwidth t invisible t
8493 display t intangible t))
8494 (if (and (boundp 'font-lock-mode) font-lock-mode)
8495 (font-lock-fontify-block)))
8496 (let ((pos (move-marker (make-marker) (point)))
8497 (field (org-table-get-field))
8498 (cw (current-window-configuration))
8500 (org-switch-to-buffer-other-window "*Org tmp*")
8501 (erase-buffer)
8502 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8503 (let ((org-inhibit-startup t)) (org-mode))
8504 (goto-char (setq p (point-max)))
8505 (insert (org-trim field))
8506 (remove-text-properties p (point-max)
8507 '(invisible t org-cwidth t display t
8508 intangible t))
8509 (goto-char p)
8510 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8511 (org-set-local 'org-window-configuration cw)
8512 (org-set-local 'org-field-marker pos)
8513 (message "Edit and finish with C-c C-c"))))
8515 (defun org-table-finish-edit-field ()
8516 "Finish editing a table data field.
8517 Remove all newline characters, insert the result into the table, realign
8518 the table and kill the editing buffer."
8519 (let ((pos org-field-marker)
8520 (cw org-window-configuration)
8521 (cb (current-buffer))
8522 text)
8523 (goto-char (point-min))
8524 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8525 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8526 (replace-match " "))
8527 (setq text (org-trim (buffer-string)))
8528 (set-window-configuration cw)
8529 (kill-buffer cb)
8530 (select-window (get-buffer-window (marker-buffer pos)))
8531 (goto-char pos)
8532 (move-marker pos nil)
8533 (org-table-check-inside-data-field)
8534 (org-table-get-field nil text)
8535 (org-table-align)
8536 (message "New field value inserted")))
8538 (defun org-trim (s)
8539 "Remove whitespace at beginning and end of string."
8540 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8541 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8544 (defun org-wrap (string &optional width lines)
8545 "Wrap string to either a number of lines, or a width in characters.
8546 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8547 that costs. If there is a word longer than WIDTH, the text is actually
8548 wrapped to the length of that word.
8549 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8550 many lines, whatever width that takes.
8551 The return value is a list of lines, without newlines at the end."
8552 (let* ((words (org-split-string string "[ \t\n]+"))
8553 (maxword (apply 'max (mapcar 'org-string-width words)))
8554 w ll)
8555 (cond (width
8556 (org-do-wrap words (max maxword width)))
8557 (lines
8558 (setq w maxword)
8559 (setq ll (org-do-wrap words maxword))
8560 (if (<= (length ll) lines)
8562 (setq ll words)
8563 (while (> (length ll) lines)
8564 (setq w (1+ w))
8565 (setq ll (org-do-wrap words w)))
8566 ll))
8567 (t (error "Cannot wrap this")))))
8570 (defun org-do-wrap (words width)
8571 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8572 (let (lines line)
8573 (while words
8574 (setq line (pop words))
8575 (while (and words (< (+ (length line) (length (car words))) width))
8576 (setq line (concat line " " (pop words))))
8577 (setq lines (push line lines)))
8578 (nreverse lines)))
8580 (defun org-split-string (string &optional separators)
8581 "Splits STRING into substrings at SEPARATORS.
8582 No empty strings are returned if there are matches at the beginning
8583 and end of string."
8584 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8585 (start 0)
8586 notfirst
8587 (list nil))
8588 (while (and (string-match rexp string
8589 (if (and notfirst
8590 (= start (match-beginning 0))
8591 (< start (length string)))
8592 (1+ start) start))
8593 (< (match-beginning 0) (length string)))
8594 (setq notfirst t)
8595 (or (eq (match-beginning 0) 0)
8596 (and (eq (match-beginning 0) (match-end 0))
8597 (eq (match-beginning 0) start))
8598 (setq list
8599 (cons (substring string start (match-beginning 0))
8600 list)))
8601 (setq start (match-end 0)))
8602 (or (eq start (length string))
8603 (setq list
8604 (cons (substring string start)
8605 list)))
8606 (nreverse list)))
8608 (defun org-table-map-tables (function)
8609 "Apply FUNCTION to the start of all tables in the buffer."
8610 (save-excursion
8611 (save-restriction
8612 (widen)
8613 (goto-char (point-min))
8614 (while (re-search-forward org-table-any-line-regexp nil t)
8615 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8616 (beginning-of-line 1)
8617 (if (looking-at org-table-line-regexp)
8618 (save-excursion (funcall function)))
8619 (re-search-forward org-table-any-border-regexp nil 1))))
8620 (message "Mapping tables: done"))
8622 (defvar org-timecnt) ; dynamically scoped parameter
8624 (defun org-table-sum (&optional beg end nlast)
8625 "Sum numbers in region of current table column.
8626 The result will be displayed in the echo area, and will be available
8627 as kill to be inserted with \\[yank].
8629 If there is an active region, it is interpreted as a rectangle and all
8630 numbers in that rectangle will be summed. If there is no active
8631 region and point is located in a table column, sum all numbers in that
8632 column.
8634 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8635 numbers are assumed to be times as well (in decimal hours) and the
8636 numbers are added as such.
8638 If NLAST is a number, only the NLAST fields will actually be summed."
8639 (interactive)
8640 (save-excursion
8641 (let (col (org-timecnt 0) diff h m s org-table-clip)
8642 (cond
8643 ((and beg end)) ; beg and end given explicitly
8644 ((org-region-active-p)
8645 (setq beg (region-beginning) end (region-end)))
8647 (setq col (org-table-current-column))
8648 (goto-char (org-table-begin))
8649 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8650 (error "No table data"))
8651 (org-table-goto-column col)
8652 (setq beg (point))
8653 (goto-char (org-table-end))
8654 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8655 (error "No table data"))
8656 (org-table-goto-column col)
8657 (setq end (point))))
8658 (let* ((items (apply 'append (org-table-copy-region beg end)))
8659 (items1 (cond ((not nlast) items)
8660 ((>= nlast (length items)) items)
8661 (t (setq items (reverse items))
8662 (setcdr (nthcdr (1- nlast) items) nil)
8663 (nreverse items))))
8664 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8665 items1)))
8666 (res (apply '+ numbers))
8667 (sres (if (= org-timecnt 0)
8668 (format "%g" res)
8669 (setq diff (* 3600 res)
8670 h (floor (/ diff 3600)) diff (mod diff 3600)
8671 m (floor (/ diff 60)) diff (mod diff 60)
8672 s diff)
8673 (format "%d:%02d:%02d" h m s))))
8674 (kill-new sres)
8675 (if (interactive-p)
8676 (message "%s"
8677 (substitute-command-keys
8678 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8679 (length numbers) sres))))
8680 sres))))
8682 (defun org-table-get-number-for-summing (s)
8683 (let (n)
8684 (if (string-match "^ *|? *" s)
8685 (setq s (replace-match "" nil nil s)))
8686 (if (string-match " *|? *$" s)
8687 (setq s (replace-match "" nil nil s)))
8688 (setq n (string-to-number s))
8689 (cond
8690 ((and (string-match "0" s)
8691 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8692 ((string-match "\\`[ \t]+\\'" s) nil)
8693 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8694 (let ((h (string-to-number (or (match-string 1 s) "0")))
8695 (m (string-to-number (or (match-string 2 s) "0")))
8696 (s (string-to-number (or (match-string 4 s) "0"))))
8697 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8698 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8699 ((equal n 0) nil)
8700 (t n))))
8702 (defun org-table-current-field-formula (&optional key noerror)
8703 "Return the formula active for the current field.
8704 Assumes that specials are in place.
8705 If KEY is given, return the key to this formula.
8706 Otherwise return the formula preceeded with \"=\" or \":=\"."
8707 (let* ((name (car (rassoc (list (org-current-line)
8708 (org-table-current-column))
8709 org-table-named-field-locations)))
8710 (col (org-table-current-column))
8711 (scol (int-to-string col))
8712 (ref (format "@%d$%d" (org-table-current-dline) col))
8713 (stored-list (org-table-get-stored-formulas noerror))
8714 (ass (or (assoc name stored-list)
8715 (assoc ref stored-list)
8716 (assoc scol stored-list))))
8717 (if key
8718 (car ass)
8719 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8720 (cdr ass))))))
8722 (defun org-table-get-formula (&optional equation named)
8723 "Read a formula from the minibuffer, offer stored formula as default.
8724 When NAMED is non-nil, look for a named equation."
8725 (let* ((stored-list (org-table-get-stored-formulas))
8726 (name (car (rassoc (list (org-current-line)
8727 (org-table-current-column))
8728 org-table-named-field-locations)))
8729 (ref (format "@%d$%d" (org-table-current-dline)
8730 (org-table-current-column)))
8731 (refass (assoc ref stored-list))
8732 (scol (if named
8733 (if name name ref)
8734 (int-to-string (org-table-current-column))))
8735 (dummy (and (or name refass) (not named)
8736 (not (y-or-n-p "Replace field formula with column formula? " ))
8737 (error "Abort")))
8738 (name (or name ref))
8739 (org-table-may-need-update nil)
8740 (stored (cdr (assoc scol stored-list)))
8741 (eq (cond
8742 ((and stored equation (string-match "^ *=? *$" equation))
8743 stored)
8744 ((stringp equation)
8745 equation)
8746 (t (org-table-formula-from-user
8747 (read-string
8748 (org-table-formula-to-user
8749 (format "%s formula %s%s="
8750 (if named "Field" "Column")
8751 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8752 scol))
8753 (if stored (org-table-formula-to-user stored) "")
8754 'org-table-formula-history
8755 )))))
8756 mustsave)
8757 (when (not (string-match "\\S-" eq))
8758 ;; remove formula
8759 (setq stored-list (delq (assoc scol stored-list) stored-list))
8760 (org-table-store-formulas stored-list)
8761 (error "Formula removed"))
8762 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8763 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8764 (if (and name (not named))
8765 ;; We set the column equation, delete the named one.
8766 (setq stored-list (delq (assoc name stored-list) stored-list)
8767 mustsave t))
8768 (if stored
8769 (setcdr (assoc scol stored-list) eq)
8770 (setq stored-list (cons (cons scol eq) stored-list)))
8771 (if (or mustsave (not (equal stored eq)))
8772 (org-table-store-formulas stored-list))
8773 eq))
8775 (defun org-table-store-formulas (alist)
8776 "Store the list of formulas below the current table."
8777 (setq alist (sort alist 'org-table-formula-less-p))
8778 (save-excursion
8779 (goto-char (org-table-end))
8780 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8781 (progn
8782 ;; don't overwrite TBLFM, we might use text properties to store stuff
8783 (goto-char (match-beginning 2))
8784 (delete-region (match-beginning 2) (match-end 0)))
8785 (insert "#+TBLFM:"))
8786 (insert " "
8787 (mapconcat (lambda (x)
8788 (concat
8789 (if (equal (string-to-char (car x)) ?@) "" "$")
8790 (car x) "=" (cdr x)))
8791 alist "::")
8792 "\n")))
8794 (defsubst org-table-formula-make-cmp-string (a)
8795 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8796 (concat
8797 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8798 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8799 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8801 (defun org-table-formula-less-p (a b)
8802 "Compare two formulas for sorting."
8803 (let ((as (org-table-formula-make-cmp-string (car a)))
8804 (bs (org-table-formula-make-cmp-string (car b))))
8805 (and as bs (string< as bs))))
8807 (defun org-table-get-stored-formulas (&optional noerror)
8808 "Return an alist with the stored formulas directly after current table."
8809 (interactive)
8810 (let (scol eq eq-alist strings string seen)
8811 (save-excursion
8812 (goto-char (org-table-end))
8813 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8814 (setq strings (org-split-string (match-string 2) " *:: *"))
8815 (while (setq string (pop strings))
8816 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8817 (setq scol (if (match-end 2)
8818 (match-string 2 string)
8819 (match-string 1 string))
8820 eq (match-string 3 string)
8821 eq-alist (cons (cons scol eq) eq-alist))
8822 (if (member scol seen)
8823 (if noerror
8824 (progn
8825 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8826 (ding)
8827 (sit-for 2))
8828 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8829 (push scol seen))))))
8830 (nreverse eq-alist)))
8832 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8833 "Modify the equations after the table structure has been edited.
8834 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8835 For all numbers larger than LIMIT, shift them by DELTA."
8836 (save-excursion
8837 (goto-char (org-table-end))
8838 (when (looking-at "#\\+TBLFM:")
8839 (let ((re (concat key "\\([0-9]+\\)"))
8840 (re2
8841 (when remove
8842 (if (equal key "$")
8843 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8844 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8845 s n a)
8846 (when remove
8847 (while (re-search-forward re2 (point-at-eol) t)
8848 (replace-match "")))
8849 (while (re-search-forward re (point-at-eol) t)
8850 (setq s (match-string 1) n (string-to-number s))
8851 (cond
8852 ((setq a (assoc s replace))
8853 (replace-match (concat key (cdr a)) t t))
8854 ((and limit (> n limit))
8855 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8857 (defun org-table-get-specials ()
8858 "Get the column names and local parameters for this table."
8859 (save-excursion
8860 (let ((beg (org-table-begin)) (end (org-table-end))
8861 names name fields fields1 field cnt
8862 c v l line col types dlines hlines)
8863 (setq org-table-column-names nil
8864 org-table-local-parameters nil
8865 org-table-named-field-locations nil
8866 org-table-current-begin-line nil
8867 org-table-current-begin-pos nil
8868 org-table-current-line-types nil)
8869 (goto-char beg)
8870 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8871 (setq names (org-split-string (match-string 1) " *| *")
8872 cnt 1)
8873 (while (setq name (pop names))
8874 (setq cnt (1+ cnt))
8875 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8876 (push (cons name (int-to-string cnt)) org-table-column-names))))
8877 (setq org-table-column-names (nreverse org-table-column-names))
8878 (setq org-table-column-name-regexp
8879 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8880 (goto-char beg)
8881 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8882 (setq fields (org-split-string (match-string 1) " *| *"))
8883 (while (setq field (pop fields))
8884 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8885 (push (cons (match-string 1 field) (match-string 2 field))
8886 org-table-local-parameters))))
8887 (goto-char beg)
8888 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8889 (setq c (match-string 1)
8890 fields (org-split-string (match-string 2) " *| *"))
8891 (save-excursion
8892 (beginning-of-line (if (equal c "_") 2 0))
8893 (setq line (org-current-line) col 1)
8894 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8895 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8896 (while (and fields1 (setq field (pop fields)))
8897 (setq v (pop fields1) col (1+ col))
8898 (when (and (stringp field) (stringp v)
8899 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8900 (push (cons field v) org-table-local-parameters)
8901 (push (list field line col) org-table-named-field-locations))))
8902 ;; Analyse the line types
8903 (goto-char beg)
8904 (setq org-table-current-begin-line (org-current-line)
8905 org-table-current-begin-pos (point)
8906 l org-table-current-begin-line)
8907 (while (looking-at "[ \t]*|\\(-\\)?")
8908 (push (if (match-end 1) 'hline 'dline) types)
8909 (if (match-end 1) (push l hlines) (push l dlines))
8910 (beginning-of-line 2)
8911 (setq l (1+ l)))
8912 (setq org-table-current-line-types (apply 'vector (nreverse types))
8913 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8914 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8916 (defun org-table-maybe-eval-formula ()
8917 "Check if the current field starts with \"=\" or \":=\".
8918 If yes, store the formula and apply it."
8919 ;; We already know we are in a table. Get field will only return a formula
8920 ;; when appropriate. It might return a separator line, but no problem.
8921 (when org-table-formula-evaluate-inline
8922 (let* ((field (org-trim (or (org-table-get-field) "")))
8923 named eq)
8924 (when (string-match "^:?=\\(.*\\)" field)
8925 (setq named (equal (string-to-char field) ?:)
8926 eq (match-string 1 field))
8927 (if (or (fboundp 'calc-eval)
8928 (equal (substring eq 0 (min 2 (length eq))) "'("))
8929 (org-table-eval-formula (if named '(4) nil)
8930 (org-table-formula-from-user eq))
8931 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8933 (defvar org-recalc-commands nil
8934 "List of commands triggering the recalculation of a line.
8935 Will be filled automatically during use.")
8937 (defvar org-recalc-marks
8938 '((" " . "Unmarked: no special line, no automatic recalculation")
8939 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8940 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8941 ("!" . "Column name definition line. Reference in formula as $name.")
8942 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8943 ("_" . "Names for values in row below this one.")
8944 ("^" . "Names for values in row above this one.")))
8946 (defun org-table-rotate-recalc-marks (&optional newchar)
8947 "Rotate the recalculation mark in the first column.
8948 If in any row, the first field is not consistent with a mark,
8949 insert a new column for the markers.
8950 When there is an active region, change all the lines in the region,
8951 after prompting for the marking character.
8952 After each change, a message will be displayed indicating the meaning
8953 of the new mark."
8954 (interactive)
8955 (unless (org-at-table-p) (error "Not at a table"))
8956 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8957 (beg (org-table-begin))
8958 (end (org-table-end))
8959 (l (org-current-line))
8960 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8961 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8962 (have-col
8963 (save-excursion
8964 (goto-char beg)
8965 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8966 (col (org-table-current-column))
8967 (forcenew (car (assoc newchar org-recalc-marks)))
8968 epos new)
8969 (when l1
8970 (message "Change region to what mark? Type # * ! $ or SPC: ")
8971 (setq newchar (char-to-string (read-char-exclusive))
8972 forcenew (car (assoc newchar org-recalc-marks))))
8973 (if (and newchar (not forcenew))
8974 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8975 newchar))
8976 (if l1 (goto-line l1))
8977 (save-excursion
8978 (beginning-of-line 1)
8979 (unless (looking-at org-table-dataline-regexp)
8980 (error "Not at a table data line")))
8981 (unless have-col
8982 (org-table-goto-column 1)
8983 (org-table-insert-column)
8984 (org-table-goto-column (1+ col)))
8985 (setq epos (point-at-eol))
8986 (save-excursion
8987 (beginning-of-line 1)
8988 (org-table-get-field
8989 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8990 (concat " "
8991 (setq new (or forcenew
8992 (cadr (member (match-string 1) marks))))
8993 " ")
8994 " # ")))
8995 (if (and l1 l2)
8996 (progn
8997 (goto-line l1)
8998 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8999 (and (looking-at org-table-dataline-regexp)
9000 (org-table-get-field 1 (concat " " new " "))))
9001 (goto-line l1)))
9002 (if (not (= epos (point-at-eol))) (org-table-align))
9003 (goto-line l)
9004 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9006 (defun org-table-maybe-recalculate-line ()
9007 "Recompute the current line if marked for it, and if we haven't just done it."
9008 (interactive)
9009 (and org-table-allow-automatic-line-recalculation
9010 (not (and (memq last-command org-recalc-commands)
9011 (equal org-last-recalc-line (org-current-line))))
9012 (save-excursion (beginning-of-line 1)
9013 (looking-at org-table-auto-recalculate-regexp))
9014 (org-table-recalculate) t))
9016 (defvar org-table-formula-debug nil
9017 "Non-nil means, debug table formulas.
9018 When nil, simply write \"#ERROR\" in corrupted fields.")
9019 (make-variable-buffer-local 'org-table-formula-debug)
9021 (defvar modes)
9022 (defsubst org-set-calc-mode (var &optional value)
9023 (if (stringp var)
9024 (setq var (assoc var '(("D" calc-angle-mode deg)
9025 ("R" calc-angle-mode rad)
9026 ("F" calc-prefer-frac t)
9027 ("S" calc-symbolic-mode t)))
9028 value (nth 2 var) var (nth 1 var)))
9029 (if (memq var modes)
9030 (setcar (cdr (memq var modes)) value)
9031 (cons var (cons value modes)))
9032 modes)
9034 (defun org-table-eval-formula (&optional arg equation
9035 suppress-align suppress-const
9036 suppress-store suppress-analysis)
9037 "Replace the table field value at the cursor by the result of a calculation.
9039 This function makes use of Dave Gillespie's Calc package, in my view the
9040 most exciting program ever written for GNU Emacs. So you need to have Calc
9041 installed in order to use this function.
9043 In a table, this command replaces the value in the current field with the
9044 result of a formula. It also installs the formula as the \"current\" column
9045 formula, by storing it in a special line below the table. When called
9046 with a `C-u' prefix, the current field must ba a named field, and the
9047 formula is installed as valid in only this specific field.
9049 When called with two `C-u' prefixes, insert the active equation
9050 for the field back into the current field, so that it can be
9051 edited there. This is useful in order to use \\[org-table-show-reference]
9052 to check the referenced fields.
9054 When called, the command first prompts for a formula, which is read in
9055 the minibuffer. Previously entered formulas are available through the
9056 history list, and the last used formula is offered as a default.
9057 These stored formulas are adapted correctly when moving, inserting, or
9058 deleting columns with the corresponding commands.
9060 The formula can be any algebraic expression understood by the Calc package.
9061 For details, see the Org-mode manual.
9063 This function can also be called from Lisp programs and offers
9064 additional arguments: EQUATION can be the formula to apply. If this
9065 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9066 used to speed-up recursive calls by by-passing unnecessary aligns.
9067 SUPPRESS-CONST suppresses the interpretation of constants in the
9068 formula, assuming that this has been done already outside the function.
9069 SUPPRESS-STORE means the formula should not be stored, either because
9070 it is already stored, or because it is a modified equation that should
9071 not overwrite the stored one."
9072 (interactive "P")
9073 (org-table-check-inside-data-field)
9074 (or suppress-analysis (org-table-get-specials))
9075 (if (equal arg '(16))
9076 (let ((eq (org-table-current-field-formula)))
9077 (or eq (error "No equation active for current field"))
9078 (org-table-get-field nil eq)
9079 (org-table-align)
9080 (setq org-table-may-need-update t))
9081 (let* (fields
9082 (ndown (if (integerp arg) arg 1))
9083 (org-table-automatic-realign nil)
9084 (case-fold-search nil)
9085 (down (> ndown 1))
9086 (formula (if (and equation suppress-store)
9087 equation
9088 (org-table-get-formula equation (equal arg '(4)))))
9089 (n0 (org-table-current-column))
9090 (modes (copy-sequence org-calc-default-modes))
9091 (numbers nil) ; was a variable, now fixed default
9092 (keep-empty nil)
9093 n form form0 bw fmt x ev orig c lispp literal)
9094 ;; Parse the format string. Since we have a lot of modes, this is
9095 ;; a lot of work. However, I think calc still uses most of the time.
9096 (if (string-match ";" formula)
9097 (let ((tmp (org-split-string formula ";")))
9098 (setq formula (car tmp)
9099 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9100 (nth 1 tmp)))
9101 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9102 (setq c (string-to-char (match-string 1 fmt))
9103 n (string-to-number (match-string 2 fmt)))
9104 (if (= c ?p)
9105 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9106 (setq modes (org-set-calc-mode
9107 'calc-float-format
9108 (list (cdr (assoc c '((?n . float) (?f . fix)
9109 (?s . sci) (?e . eng))))
9110 n))))
9111 (setq fmt (replace-match "" t t fmt)))
9112 (if (string-match "[NT]" fmt)
9113 (setq numbers (equal (match-string 0 fmt) "N")
9114 fmt (replace-match "" t t fmt)))
9115 (if (string-match "L" fmt)
9116 (setq literal t
9117 fmt (replace-match "" t t fmt)))
9118 (if (string-match "E" fmt)
9119 (setq keep-empty t
9120 fmt (replace-match "" t t fmt)))
9121 (while (string-match "[DRFS]" fmt)
9122 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9123 (setq fmt (replace-match "" t t fmt)))
9124 (unless (string-match "\\S-" fmt)
9125 (setq fmt nil))))
9126 (if (and (not suppress-const) org-table-formula-use-constants)
9127 (setq formula (org-table-formula-substitute-names formula)))
9128 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9129 (while (> ndown 0)
9130 (setq fields (org-split-string
9131 (org-no-properties
9132 (buffer-substring (point-at-bol) (point-at-eol)))
9133 " *| *"))
9134 (if (eq numbers t)
9135 (setq fields (mapcar
9136 (lambda (x) (number-to-string (string-to-number x)))
9137 fields)))
9138 (setq ndown (1- ndown))
9139 (setq form (copy-sequence formula)
9140 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9141 (if (and lispp literal) (setq lispp 'literal))
9142 ;; Check for old vertical references
9143 (setq form (org-rewrite-old-row-references form))
9144 ;; Insert complex ranges
9145 (while (string-match org-table-range-regexp form)
9146 (setq form
9147 (replace-match
9148 (save-match-data
9149 (org-table-make-reference
9150 (org-table-get-range (match-string 0 form) nil n0)
9151 keep-empty numbers lispp))
9152 t t form)))
9153 ;; Insert simple ranges
9154 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9155 (setq form
9156 (replace-match
9157 (save-match-data
9158 (org-table-make-reference
9159 (org-sublist
9160 fields (string-to-number (match-string 1 form))
9161 (string-to-number (match-string 2 form)))
9162 keep-empty numbers lispp))
9163 t t form)))
9164 (setq form0 form)
9165 ;; Insert the references to fields in same row
9166 (while (string-match "\\$\\([0-9]+\\)" form)
9167 (setq n (string-to-number (match-string 1 form))
9168 x (nth (1- (if (= n 0) n0 n)) fields))
9169 (unless x (error "Invalid field specifier \"%s\""
9170 (match-string 0 form)))
9171 (setq form (replace-match
9172 (save-match-data
9173 (org-table-make-reference x nil numbers lispp))
9174 t t form)))
9176 (if lispp
9177 (setq ev (condition-case nil
9178 (eval (eval (read form)))
9179 (error "#ERROR"))
9180 ev (if (numberp ev) (number-to-string ev) ev))
9181 (or (fboundp 'calc-eval)
9182 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9183 (setq ev (calc-eval (cons form modes)
9184 (if numbers 'num))))
9186 (when org-table-formula-debug
9187 (with-output-to-temp-buffer "*Substitution History*"
9188 (princ (format "Substitution history of formula
9189 Orig: %s
9190 $xyz-> %s
9191 @r$c-> %s
9192 $1-> %s\n" orig formula form0 form))
9193 (if (listp ev)
9194 (princ (format " %s^\nError: %s"
9195 (make-string (car ev) ?\-) (nth 1 ev)))
9196 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9197 ev (or fmt "NONE")
9198 (if fmt (format fmt (string-to-number ev)) ev)))))
9199 (setq bw (get-buffer-window "*Substitution History*"))
9200 (shrink-window-if-larger-than-buffer bw)
9201 (unless (and (interactive-p) (not ndown))
9202 (unless (let (inhibit-redisplay)
9203 (y-or-n-p "Debugging Formula. Continue to next? "))
9204 (org-table-align)
9205 (error "Abort"))
9206 (delete-window bw)
9207 (message "")))
9208 (if (listp ev) (setq fmt nil ev "#ERROR"))
9209 (org-table-justify-field-maybe
9210 (if fmt (format fmt (string-to-number ev)) ev))
9211 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9212 (call-interactively 'org-return)
9213 (setq ndown 0)))
9214 (and down (org-table-maybe-recalculate-line))
9215 (or suppress-align (and org-table-may-need-update
9216 (org-table-align))))))
9218 (defun org-table-put-field-property (prop value)
9219 (save-excursion
9220 (put-text-property (progn (skip-chars-backward "^|") (point))
9221 (progn (skip-chars-forward "^|") (point))
9222 prop value)))
9224 (defun org-table-get-range (desc &optional tbeg col highlight)
9225 "Get a calc vector from a column, accorting to descriptor DESC.
9226 Optional arguments TBEG and COL can give the beginning of the table and
9227 the current column, to avoid unnecessary parsing.
9228 HIGHLIGHT means, just highlight the range."
9229 (if (not (equal (string-to-char desc) ?@))
9230 (setq desc (concat "@" desc)))
9231 (save-excursion
9232 (or tbeg (setq tbeg (org-table-begin)))
9233 (or col (setq col (org-table-current-column)))
9234 (let ((thisline (org-current-line))
9235 beg end c1 c2 r1 r2 rangep tmp)
9236 (unless (string-match org-table-range-regexp desc)
9237 (error "Invalid table range specifier `%s'" desc))
9238 (setq rangep (match-end 3)
9239 r1 (and (match-end 1) (match-string 1 desc))
9240 r2 (and (match-end 4) (match-string 4 desc))
9241 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9242 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9244 (and c1 (setq c1 (+ (string-to-number c1)
9245 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9246 (and c2 (setq c2 (+ (string-to-number c2)
9247 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9248 (if (equal r1 "") (setq r1 nil))
9249 (if (equal r2 "") (setq r2 nil))
9250 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9251 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9252 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9253 (if (not r1) (setq r1 thisline))
9254 (if (not r2) (setq r2 thisline))
9255 (if (not c1) (setq c1 col))
9256 (if (not c2) (setq c2 col))
9257 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9258 ;; just one field
9259 (progn
9260 (goto-line r1)
9261 (while (not (looking-at org-table-dataline-regexp))
9262 (beginning-of-line 2))
9263 (prog1 (org-trim (org-table-get-field c1))
9264 (if highlight (org-table-highlight-rectangle (point) (point)))))
9265 ;; A range, return a vector
9266 ;; First sort the numbers to get a regular ractangle
9267 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9268 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9269 (goto-line r1)
9270 (while (not (looking-at org-table-dataline-regexp))
9271 (beginning-of-line 2))
9272 (org-table-goto-column c1)
9273 (setq beg (point))
9274 (goto-line r2)
9275 (while (not (looking-at org-table-dataline-regexp))
9276 (beginning-of-line 0))
9277 (org-table-goto-column c2)
9278 (setq end (point))
9279 (if highlight
9280 (org-table-highlight-rectangle
9281 beg (progn (skip-chars-forward "^|\n") (point))))
9282 ;; return string representation of calc vector
9283 (mapcar 'org-trim
9284 (apply 'append (org-table-copy-region beg end)))))))
9286 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9287 "Analyze descriptor DESC and retrieve the corresponding line number.
9288 The cursor is currently in line CLINE, the table begins in line BLINE,
9289 and TABLE is a vector with line types."
9290 (if (string-match "^[0-9]+$" desc)
9291 (aref org-table-dlines (string-to-number desc))
9292 (setq cline (or cline (org-current-line))
9293 bline (or bline org-table-current-begin-line)
9294 table (or table org-table-current-line-types))
9295 (if (or
9296 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9297 ;; 1 2 3 4 5 6
9298 (and (not (match-end 3)) (not (match-end 6)))
9299 (and (match-end 3) (match-end 6) (not (match-end 5))))
9300 (error "invalid row descriptor `%s'" desc))
9301 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9302 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9303 (odir (and (match-end 5) (match-string 5 desc)))
9304 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9305 (i (- cline bline))
9306 (rel (and (match-end 6)
9307 (or (and (match-end 1) (not (match-end 3)))
9308 (match-end 5)))))
9309 (if (and hn (not hdir))
9310 (progn
9311 (setq i 0 hdir "+")
9312 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9313 (if (and (not hn) on (not odir))
9314 (error "should never happen");;(aref org-table-dlines on)
9315 (if (and hn (> hn 0))
9316 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9317 (if on
9318 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9319 (+ bline i)))))
9321 (defun org-find-row-type (table i type backwards relative n)
9322 (let ((l (length table)))
9323 (while (> n 0)
9324 (while (and (setq i (+ i (if backwards -1 1)))
9325 (>= i 0) (< i l)
9326 (not (eq (aref table i) type))
9327 (if (and relative (eq (aref table i) 'hline))
9328 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9329 t)))
9330 (setq n (1- n)))
9331 (if (or (< i 0) (>= i l))
9332 (error "Row descriptior leads outside table")
9333 i)))
9335 (defun org-rewrite-old-row-references (s)
9336 (if (string-match "&[-+0-9I]" s)
9337 (error "Formula contains old &row reference, please rewrite using @-syntax")
9340 (defun org-table-make-reference (elements keep-empty numbers lispp)
9341 "Convert list ELEMENTS to something appropriate to insert into formula.
9342 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9343 NUMBERS indicates that everything should be converted to numbers.
9344 LISPP means to return something appropriate for a Lisp list."
9345 (if (stringp elements) ; just a single val
9346 (if lispp
9347 (if (eq lispp 'literal)
9348 elements
9349 (prin1-to-string (if numbers (string-to-number elements) elements)))
9350 (if (equal elements "") (setq elements "0"))
9351 (if numbers (number-to-string (string-to-number elements)) elements))
9352 (unless keep-empty
9353 (setq elements
9354 (delq nil
9355 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9356 elements))))
9357 (setq elements (or elements '("0")))
9358 (if lispp
9359 (mapconcat
9360 (lambda (x)
9361 (if (eq lispp 'literal)
9363 (prin1-to-string (if numbers (string-to-number x) x))))
9364 elements " ")
9365 (concat "[" (mapconcat
9366 (lambda (x)
9367 (if numbers (number-to-string (string-to-number x)) x))
9368 elements
9369 ",") "]"))))
9371 (defun org-table-recalculate (&optional all noalign)
9372 "Recalculate the current table line by applying all stored formulas.
9373 With prefix arg ALL, do this for all lines in the table."
9374 (interactive "P")
9375 (or (memq this-command org-recalc-commands)
9376 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9377 (unless (org-at-table-p) (error "Not at a table"))
9378 (if (equal all '(16))
9379 (org-table-iterate)
9380 (org-table-get-specials)
9381 (let* ((eqlist (sort (org-table-get-stored-formulas)
9382 (lambda (a b) (string< (car a) (car b)))))
9383 (inhibit-redisplay (not debug-on-error))
9384 (line-re org-table-dataline-regexp)
9385 (thisline (org-current-line))
9386 (thiscol (org-table-current-column))
9387 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9388 ;; Insert constants in all formulas
9389 (setq eqlist
9390 (mapcar (lambda (x)
9391 (setcdr x (org-table-formula-substitute-names (cdr x)))
9393 eqlist))
9394 ;; Split the equation list
9395 (while (setq eq (pop eqlist))
9396 (if (<= (string-to-char (car eq)) ?9)
9397 (push eq eqlnum)
9398 (push eq eqlname)))
9399 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9400 (if all
9401 (progn
9402 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9403 (goto-char (setq beg (org-table-begin)))
9404 (if (re-search-forward org-table-calculate-mark-regexp end t)
9405 ;; This is a table with marked lines, compute selected lines
9406 (setq line-re org-table-recalculate-regexp)
9407 ;; Move forward to the first non-header line
9408 (if (and (re-search-forward org-table-dataline-regexp end t)
9409 (re-search-forward org-table-hline-regexp end t)
9410 (re-search-forward org-table-dataline-regexp end t))
9411 (setq beg (match-beginning 0))
9412 nil))) ;; just leave beg where it is
9413 (setq beg (point-at-bol)
9414 end (move-marker (make-marker) (1+ (point-at-eol)))))
9415 (goto-char beg)
9416 (and all (message "Re-applying formulas to full table..."))
9418 ;; First find the named fields, and mark them untouchanble
9419 (remove-text-properties beg end '(org-untouchable t))
9420 (while (setq eq (pop eqlname))
9421 (setq name (car eq)
9422 a (assoc name org-table-named-field-locations))
9423 (and (not a)
9424 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9425 (setq a (list name
9426 (aref org-table-dlines
9427 (string-to-number (match-string 1 name)))
9428 (string-to-number (match-string 2 name)))))
9429 (when (and a (or all (equal (nth 1 a) thisline)))
9430 (message "Re-applying formula to field: %s" name)
9431 (goto-line (nth 1 a))
9432 (org-table-goto-column (nth 2 a))
9433 (push (append a (list (cdr eq))) eqlname1)
9434 (org-table-put-field-property :org-untouchable t)))
9436 ;; Now evauluate the column formulas, but skip fields covered by
9437 ;; field formulas
9438 (goto-char beg)
9439 (while (re-search-forward line-re end t)
9440 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9441 ;; Unprotected line, recalculate
9442 (and all (message "Re-applying formulas to full table...(line %d)"
9443 (setq cnt (1+ cnt))))
9444 (setq org-last-recalc-line (org-current-line))
9445 (setq eql eqlnum)
9446 (while (setq entry (pop eql))
9447 (goto-line org-last-recalc-line)
9448 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9449 (unless (get-text-property (point) :org-untouchable)
9450 (org-table-eval-formula nil (cdr entry)
9451 'noalign 'nocst 'nostore 'noanalysis)))))
9453 ;; Now evaluate the field formulas
9454 (while (setq eq (pop eqlname1))
9455 (message "Re-applying formula to field: %s" (car eq))
9456 (goto-line (nth 1 eq))
9457 (org-table-goto-column (nth 2 eq))
9458 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9459 'nostore 'noanalysis))
9461 (goto-line thisline)
9462 (org-table-goto-column thiscol)
9463 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9464 (or noalign (and org-table-may-need-update (org-table-align))
9465 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9467 ;; back to initial position
9468 (message "Re-applying formulas...done")
9469 (goto-line thisline)
9470 (org-table-goto-column thiscol)
9471 (or noalign (and org-table-may-need-update (org-table-align))
9472 (and all (message "Re-applying formulas...done"))))))
9474 (defun org-table-iterate (&optional arg)
9475 "Recalculate the table until it does not change anymore."
9476 (interactive "P")
9477 (let ((imax (if arg (prefix-numeric-value arg) 10))
9478 (i 0)
9479 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9480 thistbl)
9481 (catch 'exit
9482 (while (< i imax)
9483 (setq i (1+ i))
9484 (org-table-recalculate 'all)
9485 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9486 (if (not (string= lasttbl thistbl))
9487 (setq lasttbl thistbl)
9488 (if (> i 1)
9489 (message "Convergence after %d iterations" i)
9490 (message "Table was already stable"))
9491 (throw 'exit t)))
9492 (error "No convergence after %d iterations" i))))
9494 (defun org-table-formula-substitute-names (f)
9495 "Replace $const with values in string F."
9496 (let ((start 0) a (f1 f))
9497 ;; First, check for column names
9498 (while (setq start (string-match org-table-column-name-regexp f start))
9499 (setq start (1+ start))
9500 (setq a (assoc (match-string 1 f) org-table-column-names))
9501 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9502 ;; Parameters and constants
9503 (setq start 0)
9504 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9505 (setq start (1+ start))
9506 (if (setq a (save-match-data
9507 (org-table-get-constant (match-string 1 f))))
9508 (setq f (replace-match (concat "(" a ")") t t f))))
9509 (if org-table-formula-debug
9510 (put-text-property 0 (length f) :orig-formula f1 f))
9513 (defun org-table-get-constant (const)
9514 "Find the value for a parameter or constant in a formula.
9515 Parameters get priority."
9516 (or (cdr (assoc const org-table-local-parameters))
9517 (cdr (assoc const org-table-formula-constants-local))
9518 (cdr (assoc const org-table-formula-constants))
9519 (and (fboundp 'constants-get) (constants-get const))
9520 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9521 (org-entry-get nil (substring const 5) 'inherit))
9522 "#UNDEFINED_NAME"))
9524 (defvar org-table-fedit-map
9525 (let ((map (make-sparse-keymap)))
9526 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9527 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9528 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9529 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9530 (org-defkey map "\C-c?" 'org-table-show-reference)
9531 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9532 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9533 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9534 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9535 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9536 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9537 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9538 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9539 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9540 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9541 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9542 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9543 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9544 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9545 map))
9547 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9548 '("Edit-Formulas"
9549 ["Finish and Install" org-table-fedit-finish t]
9550 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9551 ["Abort" org-table-fedit-abort t]
9552 "--"
9553 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9554 ["Complete Lisp Symbol" lisp-complete-symbol t]
9555 "--"
9556 "Shift Reference at Point"
9557 ["Up" org-table-fedit-ref-up t]
9558 ["Down" org-table-fedit-ref-down t]
9559 ["Left" org-table-fedit-ref-left t]
9560 ["Right" org-table-fedit-ref-right t]
9562 "Change Test Row for Column Formulas"
9563 ["Up" org-table-fedit-line-up t]
9564 ["Down" org-table-fedit-line-down t]
9565 "--"
9566 ["Scroll Table Window" org-table-fedit-scroll t]
9567 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9568 ["Show Table Grid" org-table-fedit-toggle-coordinates
9569 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9570 org-table-overlay-coordinates)]
9571 "--"
9572 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9573 :style toggle :selected org-table-buffer-is-an]))
9575 (defvar org-pos)
9577 (defun org-table-edit-formulas ()
9578 "Edit the formulas of the current table in a separate buffer."
9579 (interactive)
9580 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9581 (beginning-of-line 0))
9582 (unless (org-at-table-p) (error "Not at a table"))
9583 (org-table-get-specials)
9584 (let ((key (org-table-current-field-formula 'key 'noerror))
9585 (eql (sort (org-table-get-stored-formulas 'noerror)
9586 'org-table-formula-less-p))
9587 (pos (move-marker (make-marker) (point)))
9588 (startline 1)
9589 (wc (current-window-configuration))
9590 (titles '((column . "# Column Formulas\n")
9591 (field . "# Field Formulas\n")
9592 (named . "# Named Field Formulas\n")))
9593 entry s type title)
9594 (org-switch-to-buffer-other-window "*Edit Formulas*")
9595 (erase-buffer)
9596 ;; Keep global-font-lock-mode from turning on font-lock-mode
9597 (let ((font-lock-global-modes '(not fundamental-mode)))
9598 (fundamental-mode))
9599 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9600 (org-set-local 'org-pos pos)
9601 (org-set-local 'org-window-configuration wc)
9602 (use-local-map org-table-fedit-map)
9603 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9604 (easy-menu-add org-table-fedit-menu)
9605 (setq startline (org-current-line))
9606 (while (setq entry (pop eql))
9607 (setq type (cond
9608 ((equal (string-to-char (car entry)) ?@) 'field)
9609 ((string-match "^[0-9]" (car entry)) 'column)
9610 (t 'named)))
9611 (when (setq title (assq type titles))
9612 (or (bobp) (insert "\n"))
9613 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9614 (setq titles (delq title titles)))
9615 (if (equal key (car entry)) (setq startline (org-current-line)))
9616 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9617 (car entry) " = " (cdr entry) "\n"))
9618 (remove-text-properties 0 (length s) '(face nil) s)
9619 (insert s))
9620 (if (eq org-table-use-standard-references t)
9621 (org-table-fedit-toggle-ref-type))
9622 (goto-line startline)
9623 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9625 (defun org-table-fedit-post-command ()
9626 (when (not (memq this-command '(lisp-complete-symbol)))
9627 (let ((win (selected-window)))
9628 (save-excursion
9629 (condition-case nil
9630 (org-table-show-reference)
9631 (error nil))
9632 (select-window win)))))
9634 (defun org-table-formula-to-user (s)
9635 "Convert a formula from internal to user representation."
9636 (if (eq org-table-use-standard-references t)
9637 (org-table-convert-refs-to-an s)
9640 (defun org-table-formula-from-user (s)
9641 "Convert a formula from user to internal representation."
9642 (if org-table-use-standard-references
9643 (org-table-convert-refs-to-rc s)
9646 (defun org-table-convert-refs-to-rc (s)
9647 "Convert spreadsheet references from AB7 to @7$28.
9648 Works for single references, but also for entire formulas and even the
9649 full TBLFM line."
9650 (let ((start 0))
9651 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9652 (cond
9653 ((match-end 3)
9654 ;; format match, just advance
9655 (setq start (match-end 0)))
9656 ((and (> (match-beginning 0) 0)
9657 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9658 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9659 ;; 3.e5 or something like this.
9660 (setq start (match-end 0)))
9662 (setq start (match-beginning 0)
9663 s (replace-match
9664 (if (equal (match-string 2 s) "&")
9665 (format "$%d" (org-letters-to-number (match-string 1 s)))
9666 (format "@%d$%d"
9667 (string-to-number (match-string 2 s))
9668 (org-letters-to-number (match-string 1 s))))
9669 t t s)))))
9672 (defun org-table-convert-refs-to-an (s)
9673 "Convert spreadsheet references from to @7$28 to AB7.
9674 Works for single references, but also for entire formulas and even the
9675 full TBLFM line."
9676 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9677 (setq s (replace-match
9678 (format "%s%d"
9679 (org-number-to-letters
9680 (string-to-number (match-string 2 s)))
9681 (string-to-number (match-string 1 s)))
9682 t t s)))
9683 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9684 (setq s (replace-match (concat "\\1"
9685 (org-number-to-letters
9686 (string-to-number (match-string 2 s))) "&")
9687 t nil s)))
9690 (defun org-letters-to-number (s)
9691 "Convert a base 26 number represented by letters into an integer.
9692 For example: AB -> 28."
9693 (let ((n 0))
9694 (setq s (upcase s))
9695 (while (> (length s) 0)
9696 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9697 s (substring s 1)))
9700 (defun org-number-to-letters (n)
9701 "Convert an integer into a base 26 number represented by letters.
9702 For example: 28 -> AB."
9703 (let ((s ""))
9704 (while (> n 0)
9705 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9706 n (/ (1- n) 26)))
9709 (defun org-table-fedit-convert-buffer (function)
9710 "Convert all references in this buffer, using FUNTION."
9711 (let ((line (org-current-line)))
9712 (goto-char (point-min))
9713 (while (not (eobp))
9714 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9715 (delete-region (point) (point-at-eol))
9716 (or (eobp) (forward-char 1)))
9717 (goto-line line)))
9719 (defun org-table-fedit-toggle-ref-type ()
9720 "Convert all references in the buffer from B3 to @3$2 and back."
9721 (interactive)
9722 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9723 (org-table-fedit-convert-buffer
9724 (if org-table-buffer-is-an
9725 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9726 (message "Reference type switched to %s"
9727 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9729 (defun org-table-fedit-ref-up ()
9730 "Shift the reference at point one row/hline up."
9731 (interactive)
9732 (org-table-fedit-shift-reference 'up))
9733 (defun org-table-fedit-ref-down ()
9734 "Shift the reference at point one row/hline down."
9735 (interactive)
9736 (org-table-fedit-shift-reference 'down))
9737 (defun org-table-fedit-ref-left ()
9738 "Shift the reference at point one field to the left."
9739 (interactive)
9740 (org-table-fedit-shift-reference 'left))
9741 (defun org-table-fedit-ref-right ()
9742 "Shift the reference at point one field to the right."
9743 (interactive)
9744 (org-table-fedit-shift-reference 'right))
9746 (defun org-table-fedit-shift-reference (dir)
9747 (cond
9748 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9749 (if (memq dir '(left right))
9750 (org-rematch-and-replace 1 (eq dir 'left))
9751 (error "Cannot shift reference in this direction")))
9752 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9753 ;; A B3-like reference
9754 (if (memq dir '(up down))
9755 (org-rematch-and-replace 2 (eq dir 'up))
9756 (org-rematch-and-replace 1 (eq dir 'left))))
9757 ((org-at-regexp-p
9758 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9759 ;; An internal reference
9760 (if (memq dir '(up down))
9761 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9762 (org-rematch-and-replace 5 (eq dir 'left))))))
9764 (defun org-rematch-and-replace (n &optional decr hline)
9765 "Re-match the group N, and replace it with the shifted refrence."
9766 (or (match-end n) (error "Cannot shift reference in this direction"))
9767 (goto-char (match-beginning n))
9768 (and (looking-at (regexp-quote (match-string n)))
9769 (replace-match (org-shift-refpart (match-string 0) decr hline)
9770 t t)))
9772 (defun org-shift-refpart (ref &optional decr hline)
9773 "Shift a refrence part REF.
9774 If DECR is set, decrease the references row/column, else increase.
9775 If HLINE is set, this may be a hline reference, it certainly is not
9776 a translation reference."
9777 (save-match-data
9778 (let* ((sign (string-match "^[-+]" ref)) n)
9780 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9781 (cond
9782 ((and hline (string-match "^I+" ref))
9783 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9784 (setq n (+ n (if decr -1 1)))
9785 (if (= n 0) (setq n (+ n (if decr -1 1))))
9786 (if sign
9787 (setq sign (if (< n 0) "-" "+") n (abs n))
9788 (setq n (max 1 n)))
9789 (concat sign (make-string n ?I)))
9791 ((string-match "^[0-9]+" ref)
9792 (setq n (string-to-number (concat sign ref)))
9793 (setq n (+ n (if decr -1 1)))
9794 (if sign
9795 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9796 (number-to-string (max 1 n))))
9798 ((string-match "^[a-zA-Z]+" ref)
9799 (org-number-to-letters
9800 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9802 (t (error "Cannot shift reference"))))))
9804 (defun org-table-fedit-toggle-coordinates ()
9805 "Toggle the display of coordinates in the refrenced table."
9806 (interactive)
9807 (let ((pos (marker-position org-pos)))
9808 (with-current-buffer (marker-buffer org-pos)
9809 (save-excursion
9810 (goto-char pos)
9811 (org-table-toggle-coordinate-overlays)))))
9813 (defun org-table-fedit-finish (&optional arg)
9814 "Parse the buffer for formula definitions and install them.
9815 With prefix ARG, apply the new formulas to the table."
9816 (interactive "P")
9817 (org-table-remove-rectangle-highlight)
9818 (if org-table-use-standard-references
9819 (progn
9820 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9821 (setq org-table-buffer-is-an nil)))
9822 (let ((pos org-pos) eql var form)
9823 (goto-char (point-min))
9824 (while (re-search-forward
9825 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9826 nil t)
9827 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9828 form (match-string 3))
9829 (setq form (org-trim form))
9830 (when (not (equal form ""))
9831 (while (string-match "[ \t]*\n[ \t]*" form)
9832 (setq form (replace-match " " t t form)))
9833 (when (assoc var eql)
9834 (error "Double formulas for %s" var))
9835 (push (cons var form) eql)))
9836 (setq org-pos nil)
9837 (set-window-configuration org-window-configuration)
9838 (select-window (get-buffer-window (marker-buffer pos)))
9839 (goto-char pos)
9840 (unless (org-at-table-p)
9841 (error "Lost table position - cannot install formulae"))
9842 (org-table-store-formulas eql)
9843 (move-marker pos nil)
9844 (kill-buffer "*Edit Formulas*")
9845 (if arg
9846 (org-table-recalculate 'all)
9847 (message "New formulas installed - press C-u C-c C-c to apply."))))
9849 (defun org-table-fedit-abort ()
9850 "Abort editing formulas, without installing the changes."
9851 (interactive)
9852 (org-table-remove-rectangle-highlight)
9853 (let ((pos org-pos))
9854 (set-window-configuration org-window-configuration)
9855 (select-window (get-buffer-window (marker-buffer pos)))
9856 (goto-char pos)
9857 (move-marker pos nil)
9858 (message "Formula editing aborted without installing changes")))
9860 (defun org-table-fedit-lisp-indent ()
9861 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9862 (interactive)
9863 (let ((pos (point)) beg end ind)
9864 (beginning-of-line 1)
9865 (cond
9866 ((looking-at "[ \t]")
9867 (goto-char pos)
9868 (call-interactively 'lisp-indent-line))
9869 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9870 ((not (fboundp 'pp-buffer))
9871 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9872 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9873 (goto-char (- (match-end 0) 2))
9874 (setq beg (point))
9875 (setq ind (make-string (current-column) ?\ ))
9876 (condition-case nil (forward-sexp 1)
9877 (error
9878 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9879 (setq end (point))
9880 (save-restriction
9881 (narrow-to-region beg end)
9882 (if (eq last-command this-command)
9883 (progn
9884 (goto-char (point-min))
9885 (setq this-command nil)
9886 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9887 (replace-match " ")))
9888 (pp-buffer)
9889 (untabify (point-min) (point-max))
9890 (goto-char (1+ (point-min)))
9891 (while (re-search-forward "^." nil t)
9892 (beginning-of-line 1)
9893 (insert ind))
9894 (goto-char (point-max))
9895 (backward-delete-char 1)))
9896 (goto-char beg))
9897 (t nil))))
9899 (defvar org-show-positions nil)
9901 (defun org-table-show-reference (&optional local)
9902 "Show the location/value of the $ expression at point."
9903 (interactive)
9904 (org-table-remove-rectangle-highlight)
9905 (catch 'exit
9906 (let ((pos (if local (point) org-pos))
9907 (face2 'highlight)
9908 (org-inhibit-highlight-removal t)
9909 (win (selected-window))
9910 (org-show-positions nil)
9911 var name e what match dest)
9912 (if local (org-table-get-specials))
9913 (setq what (cond
9914 ((or (org-at-regexp-p org-table-range-regexp2)
9915 (org-at-regexp-p org-table-translate-regexp)
9916 (org-at-regexp-p org-table-range-regexp))
9917 (setq match
9918 (save-match-data
9919 (org-table-convert-refs-to-rc (match-string 0))))
9920 'range)
9921 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9922 ((org-at-regexp-p "\\$[0-9]+") 'column)
9923 ((not local) nil)
9924 (t (error "No reference at point")))
9925 match (and what (or match (match-string 0))))
9926 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9927 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9928 'secondary-selection))
9929 (org-add-hook 'before-change-functions
9930 'org-table-remove-rectangle-highlight)
9931 (if (eq what 'name) (setq var (substring match 1)))
9932 (when (eq what 'range)
9933 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9934 (setq match (org-table-formula-substitute-names match)))
9935 (unless local
9936 (save-excursion
9937 (end-of-line 1)
9938 (re-search-backward "^\\S-" nil t)
9939 (beginning-of-line 1)
9940 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9941 (setq dest
9942 (save-match-data
9943 (org-table-convert-refs-to-rc (match-string 1))))
9944 (org-table-add-rectangle-overlay
9945 (match-beginning 1) (match-end 1) face2))))
9946 (if (and (markerp pos) (marker-buffer pos))
9947 (if (get-buffer-window (marker-buffer pos))
9948 (select-window (get-buffer-window (marker-buffer pos)))
9949 (org-switch-to-buffer-other-window (get-buffer-window
9950 (marker-buffer pos)))))
9951 (goto-char pos)
9952 (org-table-force-dataline)
9953 (when dest
9954 (setq name (substring dest 1))
9955 (cond
9956 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9957 (setq e (assoc name org-table-named-field-locations))
9958 (goto-line (nth 1 e))
9959 (org-table-goto-column (nth 2 e)))
9960 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9961 (let ((l (string-to-number (match-string 1 dest)))
9962 (c (string-to-number (match-string 2 dest))))
9963 (goto-line (aref org-table-dlines l))
9964 (org-table-goto-column c)))
9965 (t (org-table-goto-column (string-to-number name))))
9966 (move-marker pos (point))
9967 (org-table-highlight-rectangle nil nil face2))
9968 (cond
9969 ((equal dest match))
9970 ((not match))
9971 ((eq what 'range)
9972 (condition-case nil
9973 (save-excursion
9974 (org-table-get-range match nil nil 'highlight))
9975 (error nil)))
9976 ((setq e (assoc var org-table-named-field-locations))
9977 (goto-line (nth 1 e))
9978 (org-table-goto-column (nth 2 e))
9979 (org-table-highlight-rectangle (point) (point))
9980 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9981 ((setq e (assoc var org-table-column-names))
9982 (org-table-goto-column (string-to-number (cdr e)))
9983 (org-table-highlight-rectangle (point) (point))
9984 (goto-char (org-table-begin))
9985 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9986 (org-table-end) t)
9987 (progn
9988 (goto-char (match-beginning 1))
9989 (org-table-highlight-rectangle)
9990 (message "Named column (column %s)" (cdr e)))
9991 (error "Column name not found")))
9992 ((eq what 'column)
9993 ;; column number
9994 (org-table-goto-column (string-to-number (substring match 1)))
9995 (org-table-highlight-rectangle (point) (point))
9996 (message "Column %s" (substring match 1)))
9997 ((setq e (assoc var org-table-local-parameters))
9998 (goto-char (org-table-begin))
9999 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10000 (progn
10001 (goto-char (match-beginning 1))
10002 (org-table-highlight-rectangle)
10003 (message "Local parameter."))
10004 (error "Parameter not found")))
10006 (cond
10007 ((not var) (error "No reference at point"))
10008 ((setq e (assoc var org-table-formula-constants-local))
10009 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10010 var (cdr e)))
10011 ((setq e (assoc var org-table-formula-constants))
10012 (message "Constant: $%s=%s in `org-table-formula-constants'."
10013 var (cdr e)))
10014 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10015 (message "Constant: $%s=%s, from `constants.el'%s."
10016 var e (format " (%s units)" constants-unit-system)))
10017 (t (error "Undefined name $%s" var)))))
10018 (goto-char pos)
10019 (when (and org-show-positions
10020 (not (memq this-command '(org-table-fedit-scroll
10021 org-table-fedit-scroll-down))))
10022 (push pos org-show-positions)
10023 (push org-table-current-begin-pos org-show-positions)
10024 (let ((min (apply 'min org-show-positions))
10025 (max (apply 'max org-show-positions)))
10026 (goto-char min) (recenter 0)
10027 (goto-char max)
10028 (or (pos-visible-in-window-p max) (recenter -1))))
10029 (select-window win))))
10031 (defun org-table-force-dataline ()
10032 "Make sure the cursor is in a dataline in a table."
10033 (unless (save-excursion
10034 (beginning-of-line 1)
10035 (looking-at org-table-dataline-regexp))
10036 (let* ((re org-table-dataline-regexp)
10037 (p1 (save-excursion (re-search-forward re nil 'move)))
10038 (p2 (save-excursion (re-search-backward re nil 'move))))
10039 (cond ((and p1 p2)
10040 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10041 p1 p2)))
10042 ((or p1 p2) (goto-char (or p1 p2)))
10043 (t (error "No table dataline around here"))))))
10045 (defun org-table-fedit-line-up ()
10046 "Move cursor one line up in the window showing the table."
10047 (interactive)
10048 (org-table-fedit-move 'previous-line))
10050 (defun org-table-fedit-line-down ()
10051 "Move cursor one line down in the window showing the table."
10052 (interactive)
10053 (org-table-fedit-move 'next-line))
10055 (defun org-table-fedit-move (command)
10056 "Move the cursor in the window shoinw the table.
10057 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10058 (let ((org-table-allow-automatic-line-recalculation nil)
10059 (pos org-pos) (win (selected-window)) p)
10060 (select-window (get-buffer-window (marker-buffer org-pos)))
10061 (setq p (point))
10062 (call-interactively command)
10063 (while (and (org-at-table-p)
10064 (org-at-table-hline-p))
10065 (call-interactively command))
10066 (or (org-at-table-p) (goto-char p))
10067 (move-marker pos (point))
10068 (select-window win)))
10070 (defun org-table-fedit-scroll (N)
10071 (interactive "p")
10072 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10073 (scroll-other-window N)))
10075 (defun org-table-fedit-scroll-down (N)
10076 (interactive "p")
10077 (org-table-fedit-scroll (- N)))
10079 (defvar org-table-rectangle-overlays nil)
10081 (defun org-table-add-rectangle-overlay (beg end &optional face)
10082 "Add a new overlay."
10083 (let ((ov (org-make-overlay beg end)))
10084 (org-overlay-put ov 'face (or face 'secondary-selection))
10085 (push ov org-table-rectangle-overlays)))
10087 (defun org-table-highlight-rectangle (&optional beg end face)
10088 "Highlight rectangular region in a table."
10089 (setq beg (or beg (point)) end (or end (point)))
10090 (let ((b (min beg end))
10091 (e (max beg end))
10092 l1 c1 l2 c2 tmp)
10093 (and (boundp 'org-show-positions)
10094 (setq org-show-positions (cons b (cons e org-show-positions))))
10095 (goto-char (min beg end))
10096 (setq l1 (org-current-line)
10097 c1 (org-table-current-column))
10098 (goto-char (max beg end))
10099 (setq l2 (org-current-line)
10100 c2 (org-table-current-column))
10101 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10102 (goto-line l1)
10103 (beginning-of-line 1)
10104 (loop for line from l1 to l2 do
10105 (when (looking-at org-table-dataline-regexp)
10106 (org-table-goto-column c1)
10107 (skip-chars-backward "^|\n") (setq beg (point))
10108 (org-table-goto-column c2)
10109 (skip-chars-forward "^|\n") (setq end (point))
10110 (org-table-add-rectangle-overlay beg end face))
10111 (beginning-of-line 2))
10112 (goto-char b))
10113 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10115 (defun org-table-remove-rectangle-highlight (&rest ignore)
10116 "Remove the rectangle overlays."
10117 (unless org-inhibit-highlight-removal
10118 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10119 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10120 (setq org-table-rectangle-overlays nil)))
10122 (defvar org-table-coordinate-overlays nil
10123 "Collects the cooordinate grid overlays, so that they can be removed.")
10124 (make-variable-buffer-local 'org-table-coordinate-overlays)
10126 (defun org-table-overlay-coordinates ()
10127 "Add overlays to the table at point, to show row/column coordinates."
10128 (interactive)
10129 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10130 (setq org-table-coordinate-overlays nil)
10131 (save-excursion
10132 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10133 (goto-char (org-table-begin))
10134 (while (org-at-table-p)
10135 (setq eol (point-at-eol))
10136 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10137 (push ov org-table-coordinate-overlays)
10138 (setq hline (looking-at org-table-hline-regexp))
10139 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10140 (format "%4d" (setq id (1+ id)))))
10141 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10142 (when hline
10143 (setq ic 0)
10144 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10145 (setq beg (1+ (match-beginning 0))
10146 ic (1+ ic)
10147 s1 (concat "$" (int-to-string ic))
10148 s2 (org-number-to-letters ic)
10149 str (if (eq org-table-use-standard-references t) s2 s1))
10150 (setq ov (org-make-overlay beg (+ beg (length str))))
10151 (push ov org-table-coordinate-overlays)
10152 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10153 (beginning-of-line 2)))))
10155 (defun org-table-toggle-coordinate-overlays ()
10156 "Toggle the display of Row/Column numbers in tables."
10157 (interactive)
10158 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10159 (message "Row/Column number display turned %s"
10160 (if org-table-overlay-coordinates "on" "off"))
10161 (if (and (org-at-table-p) org-table-overlay-coordinates)
10162 (org-table-align))
10163 (unless org-table-overlay-coordinates
10164 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10165 (setq org-table-coordinate-overlays nil)))
10167 (defun org-table-toggle-formula-debugger ()
10168 "Toggle the formula debugger in tables."
10169 (interactive)
10170 (setq org-table-formula-debug (not org-table-formula-debug))
10171 (message "Formula debugging has been turned %s"
10172 (if org-table-formula-debug "on" "off")))
10174 ;;; The orgtbl minor mode
10176 ;; Define a minor mode which can be used in other modes in order to
10177 ;; integrate the org-mode table editor.
10179 ;; This is really a hack, because the org-mode table editor uses several
10180 ;; keys which normally belong to the major mode, for example the TAB and
10181 ;; RET keys. Here is how it works: The minor mode defines all the keys
10182 ;; necessary to operate the table editor, but wraps the commands into a
10183 ;; function which tests if the cursor is currently inside a table. If that
10184 ;; is the case, the table editor command is executed. However, when any of
10185 ;; those keys is used outside a table, the function uses `key-binding' to
10186 ;; look up if the key has an associated command in another currently active
10187 ;; keymap (minor modes, major mode, global), and executes that command.
10188 ;; There might be problems if any of the keys used by the table editor is
10189 ;; otherwise used as a prefix key.
10191 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10192 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10193 ;; addresses this by checking explicitly for both bindings.
10195 ;; The optimized version (see variable `orgtbl-optimized') takes over
10196 ;; all keys which are bound to `self-insert-command' in the *global map*.
10197 ;; Some modes bind other commands to simple characters, for example
10198 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10199 ;; active, this binding is ignored inside tables and replaced with a
10200 ;; modified self-insert.
10202 (defvar orgtbl-mode nil
10203 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10204 table editor in arbitrary modes.")
10205 (make-variable-buffer-local 'orgtbl-mode)
10207 (defvar orgtbl-mode-map (make-keymap)
10208 "Keymap for `orgtbl-mode'.")
10210 ;;;###autoload
10211 (defun turn-on-orgtbl ()
10212 "Unconditionally turn on `orgtbl-mode'."
10213 (orgtbl-mode 1))
10215 (defvar org-old-auto-fill-inhibit-regexp nil
10216 "Local variable used by `orgtbl-mode'")
10218 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10219 "Matches a line belonging to an orgtbl.")
10221 (defconst orgtbl-extra-font-lock-keywords
10222 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10223 0 (quote 'org-table) 'prepend))
10224 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10226 ;;;###autoload
10227 (defun orgtbl-mode (&optional arg)
10228 "The `org-mode' table editor as a minor mode for use in other modes."
10229 (interactive)
10230 (if (org-mode-p)
10231 ;; Exit without error, in case some hook functions calls this
10232 ;; by accident in org-mode.
10233 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10234 (setq orgtbl-mode
10235 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10236 (if orgtbl-mode
10237 (progn
10238 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10239 ;; Make sure we are first in minor-mode-map-alist
10240 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10241 (and c (setq minor-mode-map-alist
10242 (cons c (delq c minor-mode-map-alist)))))
10243 (org-set-local (quote org-table-may-need-update) t)
10244 (org-add-hook 'before-change-functions 'org-before-change-function
10245 nil 'local)
10246 (org-set-local 'org-old-auto-fill-inhibit-regexp
10247 auto-fill-inhibit-regexp)
10248 (org-set-local 'auto-fill-inhibit-regexp
10249 (if auto-fill-inhibit-regexp
10250 (concat orgtbl-line-start-regexp "\\|"
10251 auto-fill-inhibit-regexp)
10252 orgtbl-line-start-regexp))
10253 (org-add-to-invisibility-spec '(org-cwidth))
10254 (when (fboundp 'font-lock-add-keywords)
10255 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10256 (org-restart-font-lock))
10257 (easy-menu-add orgtbl-mode-menu)
10258 (run-hooks 'orgtbl-mode-hook))
10259 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10260 (org-cleanup-narrow-column-properties)
10261 (org-remove-from-invisibility-spec '(org-cwidth))
10262 (remove-hook 'before-change-functions 'org-before-change-function t)
10263 (when (fboundp 'font-lock-remove-keywords)
10264 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10265 (org-restart-font-lock))
10266 (easy-menu-remove orgtbl-mode-menu)
10267 (force-mode-line-update 'all))))
10269 (defun org-cleanup-narrow-column-properties ()
10270 "Remove all properties related to narrow-column invisibility."
10271 (let ((s 1))
10272 (while (setq s (text-property-any s (point-max)
10273 'display org-narrow-column-arrow))
10274 (remove-text-properties s (1+ s) '(display t)))
10275 (setq s 1)
10276 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10277 (remove-text-properties s (1+ s) '(org-cwidth t)))
10278 (setq s 1)
10279 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10280 (remove-text-properties s (1+ s) '(invisible t)))))
10282 ;; Install it as a minor mode.
10283 (put 'orgtbl-mode :included t)
10284 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10285 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10287 (defun orgtbl-make-binding (fun n &rest keys)
10288 "Create a function for binding in the table minor mode.
10289 FUN is the command to call inside a table. N is used to create a unique
10290 command name. KEYS are keys that should be checked in for a command
10291 to execute outside of tables."
10292 (eval
10293 (list 'defun
10294 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10295 '(arg)
10296 (concat "In tables, run `" (symbol-name fun) "'.\n"
10297 "Outside of tables, run the binding of `"
10298 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10299 "'.")
10300 '(interactive "p")
10301 (list 'if
10302 '(org-at-table-p)
10303 (list 'call-interactively (list 'quote fun))
10304 (list 'let '(orgtbl-mode)
10305 (list 'call-interactively
10306 (append '(or)
10307 (mapcar (lambda (k)
10308 (list 'key-binding k))
10309 keys)
10310 '('orgtbl-error))))))))
10312 (defun orgtbl-error ()
10313 "Error when there is no default binding for a table key."
10314 (interactive)
10315 (error "This key is has no function outside tables"))
10317 (defun orgtbl-setup ()
10318 "Setup orgtbl keymaps."
10319 (let ((nfunc 0)
10320 (bindings
10321 (list
10322 '([(meta shift left)] org-table-delete-column)
10323 '([(meta left)] org-table-move-column-left)
10324 '([(meta right)] org-table-move-column-right)
10325 '([(meta shift right)] org-table-insert-column)
10326 '([(meta shift up)] org-table-kill-row)
10327 '([(meta shift down)] org-table-insert-row)
10328 '([(meta up)] org-table-move-row-up)
10329 '([(meta down)] org-table-move-row-down)
10330 '("\C-c\C-w" org-table-cut-region)
10331 '("\C-c\M-w" org-table-copy-region)
10332 '("\C-c\C-y" org-table-paste-rectangle)
10333 '("\C-c-" org-table-insert-hline)
10334 '("\C-c}" org-table-toggle-coordinate-overlays)
10335 '("\C-c{" org-table-toggle-formula-debugger)
10336 '("\C-m" org-table-next-row)
10337 '([(shift return)] org-table-copy-down)
10338 '("\C-c\C-q" org-table-wrap-region)
10339 '("\C-c?" org-table-field-info)
10340 '("\C-c " org-table-blank-field)
10341 '("\C-c+" org-table-sum)
10342 '("\C-c=" org-table-eval-formula)
10343 '("\C-c'" org-table-edit-formulas)
10344 '("\C-c`" org-table-edit-field)
10345 '("\C-c*" org-table-recalculate)
10346 '("\C-c|" org-table-create-or-convert-from-region)
10347 '("\C-c^" org-table-sort-lines)
10348 '([(control ?#)] org-table-rotate-recalc-marks)))
10349 elt key fun cmd)
10350 (while (setq elt (pop bindings))
10351 (setq nfunc (1+ nfunc))
10352 (setq key (org-key (car elt))
10353 fun (nth 1 elt)
10354 cmd (orgtbl-make-binding fun nfunc key))
10355 (org-defkey orgtbl-mode-map key cmd))
10357 ;; Special treatment needed for TAB and RET
10358 (org-defkey orgtbl-mode-map [(return)]
10359 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10360 (org-defkey orgtbl-mode-map "\C-m"
10361 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10363 (org-defkey orgtbl-mode-map [(tab)]
10364 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10365 (org-defkey orgtbl-mode-map "\C-i"
10366 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10368 (org-defkey orgtbl-mode-map [(shift tab)]
10369 (orgtbl-make-binding 'org-table-previous-field 104
10370 [(shift tab)] [(tab)] "\C-i"))
10372 (org-defkey orgtbl-mode-map "\M-\C-m"
10373 (orgtbl-make-binding 'org-table-wrap-region 105
10374 "\M-\C-m" [(meta return)]))
10375 (org-defkey orgtbl-mode-map [(meta return)]
10376 (orgtbl-make-binding 'org-table-wrap-region 106
10377 [(meta return)] "\M-\C-m"))
10379 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10380 (when orgtbl-optimized
10381 ;; If the user wants maximum table support, we need to hijack
10382 ;; some standard editing functions
10383 (org-remap orgtbl-mode-map
10384 'self-insert-command 'orgtbl-self-insert-command
10385 'delete-char 'org-delete-char
10386 'delete-backward-char 'org-delete-backward-char)
10387 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10388 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10389 '("OrgTbl"
10390 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10391 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10392 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10393 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10394 "--"
10395 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10396 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10397 ["Copy Field from Above"
10398 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10399 "--"
10400 ("Column"
10401 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10402 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10403 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10404 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10405 ("Row"
10406 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10407 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10408 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10409 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10410 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10411 "--"
10412 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10413 ("Rectangle"
10414 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10415 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10416 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10417 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10418 "--"
10419 ("Radio tables"
10420 ["Insert table template" orgtbl-insert-radio-table
10421 (assq major-mode orgtbl-radio-table-templates)]
10422 ["Comment/uncomment table" orgtbl-toggle-comment t])
10423 "--"
10424 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10425 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10426 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10427 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10428 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10429 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10430 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10431 ["Sum Column/Rectangle" org-table-sum
10432 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10433 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10434 ["Debug Formulas"
10435 org-table-toggle-formula-debugger :active (org-at-table-p)
10436 :keys "C-c {"
10437 :style toggle :selected org-table-formula-debug]
10438 ["Show Col/Row Numbers"
10439 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10440 :keys "C-c }"
10441 :style toggle :selected org-table-overlay-coordinates]
10445 (defun orgtbl-ctrl-c-ctrl-c (arg)
10446 "If the cursor is inside a table, realign the table.
10447 It it is a table to be sent away to a receiver, do it.
10448 With prefix arg, also recompute table."
10449 (interactive "P")
10450 (let ((pos (point)) action)
10451 (save-excursion
10452 (beginning-of-line 1)
10453 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10454 ((looking-at "[ \t]*|") pos)
10455 ((looking-at "#\\+TBLFM:") 'recalc))))
10456 (cond
10457 ((integerp action)
10458 (goto-char action)
10459 (org-table-maybe-eval-formula)
10460 (if arg
10461 (call-interactively 'org-table-recalculate)
10462 (org-table-maybe-recalculate-line))
10463 (call-interactively 'org-table-align)
10464 (orgtbl-send-table 'maybe))
10465 ((eq action 'recalc)
10466 (save-excursion
10467 (beginning-of-line 1)
10468 (skip-chars-backward " \r\n\t")
10469 (if (org-at-table-p)
10470 (org-call-with-arg 'org-table-recalculate t))))
10471 (t (let (orgtbl-mode)
10472 (call-interactively (key-binding "\C-c\C-c")))))))
10474 (defun orgtbl-tab (arg)
10475 "Justification and field motion for `orgtbl-mode'."
10476 (interactive "P")
10477 (if arg (org-table-edit-field t)
10478 (org-table-justify-field-maybe)
10479 (org-table-next-field)))
10481 (defun orgtbl-ret ()
10482 "Justification and field motion for `orgtbl-mode'."
10483 (interactive)
10484 (org-table-justify-field-maybe)
10485 (org-table-next-row))
10487 (defun orgtbl-self-insert-command (N)
10488 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10489 If the cursor is in a table looking at whitespace, the whitespace is
10490 overwritten, and the table is not marked as requiring realignment."
10491 (interactive "p")
10492 (if (and (org-at-table-p)
10494 (and org-table-auto-blank-field
10495 (member last-command
10496 '(orgtbl-hijacker-command-100
10497 orgtbl-hijacker-command-101
10498 orgtbl-hijacker-command-102
10499 orgtbl-hijacker-command-103
10500 orgtbl-hijacker-command-104
10501 orgtbl-hijacker-command-105))
10502 (org-table-blank-field))
10504 (eq N 1)
10505 (looking-at "[^|\n]* +|"))
10506 (let (org-table-may-need-update)
10507 (goto-char (1- (match-end 0)))
10508 (delete-backward-char 1)
10509 (goto-char (match-beginning 0))
10510 (self-insert-command N))
10511 (setq org-table-may-need-update t)
10512 (let (orgtbl-mode)
10513 (call-interactively (key-binding (vector last-input-event))))))
10515 (defun org-force-self-insert (N)
10516 "Needed to enforce self-insert under remapping."
10517 (interactive "p")
10518 (self-insert-command N))
10520 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10521 "Regula expression matching exponentials as produced by calc.")
10523 (defvar org-table-clean-did-remove-column nil)
10525 (defun orgtbl-export (table target)
10526 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10527 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10528 org-table-last-alignment org-table-last-column-widths
10529 maxcol column)
10530 (if (not (fboundp func))
10531 (error "Cannot export orgtbl table to %s" target))
10532 (setq lines (org-table-clean-before-export lines))
10533 (setq table
10534 (mapcar
10535 (lambda (x)
10536 (if (string-match org-table-hline-regexp x)
10537 'hline
10538 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10539 lines))
10540 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10541 table)))
10542 (loop for i from (1- maxcol) downto 0 do
10543 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10544 (setq column (delq nil column))
10545 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10546 (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))
10547 (funcall func table nil)))
10549 (defun orgtbl-send-table (&optional maybe)
10550 "Send a tranformed version of this table to the receiver position.
10551 With argument MAYBE, fail quietly if no transformation is defined for
10552 this table."
10553 (interactive)
10554 (catch 'exit
10555 (unless (org-at-table-p) (error "Not at a table"))
10556 ;; when non-interactive, we assume align has just happened.
10557 (when (interactive-p) (org-table-align))
10558 (save-excursion
10559 (goto-char (org-table-begin))
10560 (beginning-of-line 0)
10561 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10562 (if maybe
10563 (throw 'exit nil)
10564 (error "Don't know how to transform this table."))))
10565 (let* ((name (match-string 1))
10567 (transform (intern (match-string 2)))
10568 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10569 (skip (plist-get params :skip))
10570 (skipcols (plist-get params :skipcols))
10571 (txt (buffer-substring-no-properties
10572 (org-table-begin) (org-table-end)))
10573 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10574 (lines (org-table-clean-before-export lines))
10575 (i0 (if org-table-clean-did-remove-column 2 1))
10576 (table (mapcar
10577 (lambda (x)
10578 (if (string-match org-table-hline-regexp x)
10579 'hline
10580 (org-remove-by-index
10581 (org-split-string (org-trim x) "\\s-*|\\s-*")
10582 skipcols i0)))
10583 lines))
10584 (fun (if (= i0 2) 'cdr 'identity))
10585 (org-table-last-alignment
10586 (org-remove-by-index (funcall fun org-table-last-alignment)
10587 skipcols i0))
10588 (org-table-last-column-widths
10589 (org-remove-by-index (funcall fun org-table-last-column-widths)
10590 skipcols i0)))
10592 (unless (fboundp transform)
10593 (error "No such transformation function %s" transform))
10594 (setq txt (funcall transform table params))
10595 ;; Find the insertion place
10596 (save-excursion
10597 (goto-char (point-min))
10598 (unless (re-search-forward
10599 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10600 (error "Don't know where to insert translated table"))
10601 (goto-char (match-beginning 0))
10602 (beginning-of-line 2)
10603 (setq beg (point))
10604 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10605 (error "Cannot find end of insertion region"))
10606 (beginning-of-line 1)
10607 (delete-region beg (point))
10608 (goto-char beg)
10609 (insert txt "\n"))
10610 (message "Table converted and installed at receiver location"))))
10612 (defun org-remove-by-index (list indices &optional i0)
10613 "Remove the elements in LIST with indices in INDICES.
10614 First element has index 0, or I0 if given."
10615 (if (not indices)
10616 list
10617 (if (integerp indices) (setq indices (list indices)))
10618 (setq i0 (1- (or i0 0)))
10619 (delq :rm (mapcar (lambda (x)
10620 (setq i0 (1+ i0))
10621 (if (memq i0 indices) :rm x))
10622 list))))
10624 (defun orgtbl-toggle-comment ()
10625 "Comment or uncomment the orgtbl at point."
10626 (interactive)
10627 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10628 (re2 (concat "^" orgtbl-line-start-regexp))
10629 (commented (save-excursion (beginning-of-line 1)
10630 (cond ((looking-at re1) t)
10631 ((looking-at re2) nil)
10632 (t (error "Not at an org table")))))
10633 (re (if commented re1 re2))
10634 beg end)
10635 (save-excursion
10636 (beginning-of-line 1)
10637 (while (looking-at re) (beginning-of-line 0))
10638 (beginning-of-line 2)
10639 (setq beg (point))
10640 (while (looking-at re) (beginning-of-line 2))
10641 (setq end (point)))
10642 (comment-region beg end (if commented '(4) nil))))
10644 (defun orgtbl-insert-radio-table ()
10645 "Insert a radio table template appropriate for this major mode."
10646 (interactive)
10647 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10648 (txt (nth 1 e))
10649 name pos)
10650 (unless e (error "No radio table setup defined for %s" major-mode))
10651 (setq name (read-string "Table name: "))
10652 (while (string-match "%n" txt)
10653 (setq txt (replace-match name t t txt)))
10654 (or (bolp) (insert "\n"))
10655 (setq pos (point))
10656 (insert txt)
10657 (goto-char pos)))
10659 (defun org-get-param (params header i sym &optional hsym)
10660 "Get parameter value for symbol SYM.
10661 If this is a header line, actually get the value for the symbol with an
10662 additional \"h\" inserted after the colon.
10663 If the value is a protperty list, get the element for the current column.
10664 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10665 (let ((val (plist-get params sym)))
10666 (and hsym header (setq val (or (plist-get params hsym) val)))
10667 (if (consp val) (plist-get val i) val)))
10669 (defun orgtbl-to-generic (table params)
10670 "Convert the orgtbl-mode TABLE to some other format.
10671 This generic routine can be used for many standard cases.
10672 TABLE is a list, each entry either the symbol `hline' for a horizontal
10673 separator line, or a list of fields for that line.
10674 PARAMS is a property list of parameters that can influence the conversion.
10675 For the generic converter, some parameters are obligatory: You need to
10676 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10677 :splice, you must have :tstart and :tend.
10679 Valid parameters are
10681 :tstart String to start the table. Ignored when :splice is t.
10682 :tend String to end the table. Ignored when :splice is t.
10684 :splice When set to t, return only table body lines, don't wrap
10685 them into :tstart and :tend. Default is nil.
10687 :hline String to be inserted on horizontal separation lines.
10688 May be nil to ignore hlines.
10690 :lstart String to start a new table line.
10691 :lend String to end a table line
10692 :sep Separator between two fields
10693 :lfmt Format for entire line, with enough %s to capture all fields.
10694 If this is present, :lstart, :lend, and :sep are ignored.
10695 :fmt A format to be used to wrap the field, should contain
10696 %s for the original field value. For example, to wrap
10697 everything in dollars, you could use :fmt \"$%s$\".
10698 This may also be a property list with column numbers and
10699 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10701 :hlstart :hlend :hlsep :hlfmt :hfmt
10702 Same as above, specific for the header lines in the table.
10703 All lines before the first hline are treated as header.
10704 If any of these is not present, the data line value is used.
10706 :efmt Use this format to print numbers with exponentials.
10707 The format should have %s twice for inserting mantissa
10708 and exponent, for example \"%s\\\\times10^{%s}\". This
10709 may also be a property list with column numbers and
10710 formats. :fmt will still be applied after :efmt.
10712 In addition to this, the parameters :skip and :skipcols are always handled
10713 directly by `orgtbl-send-table'. See manual."
10714 (interactive)
10715 (let* ((p params)
10716 (splicep (plist-get p :splice))
10717 (hline (plist-get p :hline))
10718 rtn line i fm efm lfmt h)
10720 ;; Do we have a header?
10721 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10722 (setq h t))
10724 ;; Put header
10725 (unless splicep
10726 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10728 ;; Now loop over all lines
10729 (while (setq line (pop table))
10730 (if (eq line 'hline)
10731 ;; A horizontal separator line
10732 (progn (if hline (push hline rtn))
10733 (setq h nil)) ; no longer in header
10734 ;; A normal line. Convert the fields, push line onto the result list
10735 (setq i 0)
10736 (setq line
10737 (mapcar
10738 (lambda (f)
10739 (setq i (1+ i)
10740 fm (org-get-param p h i :fmt :hfmt)
10741 efm (org-get-param p h i :efmt))
10742 (if (and efm (string-match orgtbl-exp-regexp f))
10743 (setq f (format
10744 efm (match-string 1 f) (match-string 2 f))))
10745 (if fm (setq f (format fm f)))
10747 line))
10748 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10749 (push (apply 'format lfmt line) rtn)
10750 (push (concat
10751 (org-get-param p h i :lstart :hlstart)
10752 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10753 (org-get-param p h i :lend :hlend))
10754 rtn))))
10756 (unless splicep
10757 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10759 (mapconcat 'identity (nreverse rtn) "\n")))
10761 (defun orgtbl-to-latex (table params)
10762 "Convert the orgtbl-mode TABLE to LaTeX.
10763 TABLE is a list, each entry either the symbol `hline' for a horizontal
10764 separator line, or a list of fields for that line.
10765 PARAMS is a property list of parameters that can influence the conversion.
10766 Supports all parameters from `orgtbl-to-generic'. Most important for
10767 LaTeX are:
10769 :splice When set to t, return only table body lines, don't wrap
10770 them into a tabular environment. Default is nil.
10772 :fmt A format to be used to wrap the field, should contain %s for the
10773 original field value. For example, to wrap everything in dollars,
10774 use :fmt \"$%s$\". This may also be a property list with column
10775 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10777 :efmt Format for transforming numbers with exponentials. The format
10778 should have %s twice for inserting mantissa and exponent, for
10779 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10780 This may also be a property list with column numbers and formats.
10782 The general parameters :skip and :skipcols have already been applied when
10783 this function is called."
10784 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10785 org-table-last-alignment ""))
10786 (params2
10787 (list
10788 :tstart (concat "\\begin{tabular}{" alignment "}")
10789 :tend "\\end{tabular}"
10790 :lstart "" :lend " \\\\" :sep " & "
10791 :efmt "%s\\,(%s)" :hline "\\hline")))
10792 (orgtbl-to-generic table (org-combine-plists params2 params))))
10794 (defun orgtbl-to-html (table params)
10795 "Convert the orgtbl-mode TABLE to LaTeX.
10796 TABLE is a list, each entry either the symbol `hline' for a horizontal
10797 separator line, or a list of fields for that line.
10798 PARAMS is a property list of parameters that can influence the conversion.
10799 Currently this function recognizes the following parameters:
10801 :splice When set to t, return only table body lines, don't wrap
10802 them into a <table> environment. Default is nil.
10804 The general parameters :skip and :skipcols have already been applied when
10805 this function is called. The function does *not* use `orgtbl-to-generic',
10806 so you cannot specify parameters for it."
10807 (let* ((splicep (plist-get params :splice))
10808 html)
10809 ;; Just call the formatter we already have
10810 ;; We need to make text lines for it, so put the fields back together.
10811 (setq html (org-format-org-table-html
10812 (mapcar
10813 (lambda (x)
10814 (if (eq x 'hline)
10815 "|----+----|"
10816 (concat "| " (mapconcat 'identity x " | ") " |")))
10817 table)
10818 splicep))
10819 (if (string-match "\n+\\'" html)
10820 (setq html (replace-match "" t t html)))
10821 html))
10823 (defun orgtbl-to-texinfo (table params)
10824 "Convert the orgtbl-mode TABLE to TeXInfo.
10825 TABLE is a list, each entry either the symbol `hline' for a horizontal
10826 separator line, or a list of fields for that line.
10827 PARAMS is a property list of parameters that can influence the conversion.
10828 Supports all parameters from `orgtbl-to-generic'. Most important for
10829 TeXInfo are:
10831 :splice nil/t When set to t, return only table body lines, don't wrap
10832 them into a multitable environment. Default is nil.
10834 :fmt fmt A format to be used to wrap the field, should contain
10835 %s for the original field value. For example, to wrap
10836 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10837 This may also be a property list with column numbers and
10838 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10840 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10841 are computed automatically from the width of the columns
10842 under org-mode.
10844 The general parameters :skip and :skipcols have already been applied when
10845 this function is called."
10846 (let* ((total (float (apply '+ org-table-last-column-widths)))
10847 (colfrac (or (plist-get params :cf)
10848 (mapconcat
10849 (lambda (x) (format "%.3f" (/ (float x) total)))
10850 org-table-last-column-widths " ")))
10851 (params2
10852 (list
10853 :tstart (concat "@multitable @columnfractions " colfrac)
10854 :tend "@end multitable"
10855 :lstart "@item " :lend "" :sep " @tab "
10856 :hlstart "@headitem ")))
10857 (orgtbl-to-generic table (org-combine-plists params2 params))))
10859 ;;;; Link Stuff
10861 ;;; Link abbreviations
10863 (defun org-link-expand-abbrev (link)
10864 "Apply replacements as defined in `org-link-abbrev-alist."
10865 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10866 (let* ((key (match-string 1 link))
10867 (as (or (assoc key org-link-abbrev-alist-local)
10868 (assoc key org-link-abbrev-alist)))
10869 (tag (and (match-end 2) (match-string 3 link)))
10870 rpl)
10871 (if (not as)
10872 link
10873 (setq rpl (cdr as))
10874 (cond
10875 ((symbolp rpl) (funcall rpl tag))
10876 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10877 (t (concat rpl tag)))))
10878 link))
10880 ;;; Storing and inserting links
10882 (defvar org-insert-link-history nil
10883 "Minibuffer history for links inserted with `org-insert-link'.")
10885 (defvar org-stored-links nil
10886 "Contains the links stored with `org-store-link'.")
10888 (defvar org-store-link-plist nil
10889 "Plist with info about the most recently link created with `org-store-link'.")
10891 (defvar org-link-protocols nil
10892 "Link protocols added to Org-mode using `org-add-link-type'.")
10894 (defvar org-store-link-functions nil
10895 "List of functions that are called to create and store a link.
10896 Each function will be called in turn until one returns a non-nil
10897 value. Each function should check if it is responsible for creating
10898 this link (for example by looking at the major mode).
10899 If not, it must exit and return nil.
10900 If yes, it should return a non-nil value after a calling
10901 `org-store-link-properties' with a list of properties and values.
10902 Special properties are:
10904 :type The link prefix. like \"http\". This must be given.
10905 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10906 This is obligatory as well.
10907 :description Optional default description for the second pair
10908 of brackets in an Org-mode link. The user can still change
10909 this when inserting this link into an Org-mode buffer.
10911 In addition to these, any additional properties can be specified
10912 and then used in remember templates.")
10914 (defun org-add-link-type (type &optional follow publish)
10915 "Add TYPE to the list of `org-link-types'.
10916 Re-compute all regular expressions depending on `org-link-types'
10917 FOLLOW and PUBLISH are two functions. Both take the link path as
10918 an argument.
10919 FOLLOW should do whatever is necessary to follow the link, for example
10920 to find a file or display a mail message.
10921 PUBLISH takes the path and retuns the string that should be used when
10922 this document is published."
10923 (add-to-list 'org-link-types type t)
10924 (org-make-link-regexps)
10925 (add-to-list 'org-link-protocols
10926 (list type follow publish)))
10928 (defun org-add-agenda-custom-command (entry)
10929 "Replace or add a command in `org-agenda-custom-commands'.
10930 This is mostly for hacking and trying a new command - once the command
10931 works you probably want to add it to `org-agenda-custom-commands' for good."
10932 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
10933 (if ass
10934 (setcdr ass (cdr entry))
10935 (push entry org-agenda-custom-commands))))
10937 ;;;###autoload
10938 (defun org-store-link (arg)
10939 "\\<org-mode-map>Store an org-link to the current location.
10940 This link can later be inserted into an org-buffer with
10941 \\[org-insert-link].
10942 For some link types, a prefix arg is interpreted:
10943 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10944 For file links, arg negates `org-context-in-file-links'."
10945 (interactive "P")
10946 (setq org-store-link-plist nil) ; reset
10947 (let (link cpltxt desc description search txt)
10948 (cond
10950 ((run-hook-with-args-until-success 'org-store-link-functions)
10951 (setq link (plist-get org-store-link-plist :link)
10952 desc (or (plist-get org-store-link-plist :description) link)))
10954 ((eq major-mode 'bbdb-mode)
10955 (let ((name (bbdb-record-name (bbdb-current-record)))
10956 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10957 (setq cpltxt (concat "bbdb:" (or name company))
10958 link (org-make-link cpltxt))
10959 (org-store-link-props :type "bbdb" :name name :company company)))
10961 ((eq major-mode 'Info-mode)
10962 (setq link (org-make-link "info:"
10963 (file-name-nondirectory Info-current-file)
10964 ":" Info-current-node))
10965 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10966 ":" Info-current-node))
10967 (org-store-link-props :type "info" :file Info-current-file
10968 :node Info-current-node))
10970 ((eq major-mode 'calendar-mode)
10971 (let ((cd (calendar-cursor-to-date)))
10972 (setq link
10973 (format-time-string
10974 (car org-time-stamp-formats)
10975 (apply 'encode-time
10976 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10977 nil nil nil))))
10978 (org-store-link-props :type "calendar" :date cd)))
10980 ((or (eq major-mode 'vm-summary-mode)
10981 (eq major-mode 'vm-presentation-mode))
10982 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10983 (vm-follow-summary-cursor)
10984 (save-excursion
10985 (vm-select-folder-buffer)
10986 (let* ((message (car vm-message-pointer))
10987 (folder buffer-file-name)
10988 (subject (vm-su-subject message))
10989 (to (vm-get-header-contents message "To"))
10990 (from (vm-get-header-contents message "From"))
10991 (message-id (vm-su-message-id message)))
10992 (org-store-link-props :type "vm" :from from :to to :subject subject
10993 :message-id message-id)
10994 (setq message-id (org-remove-angle-brackets message-id))
10995 (setq folder (abbreviate-file-name folder))
10996 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10997 folder)
10998 (setq folder (replace-match "" t t folder)))
10999 (setq cpltxt (org-email-link-description))
11000 (setq link (org-make-link "vm:" folder "#" message-id)))))
11002 ((eq major-mode 'wl-summary-mode)
11003 (let* ((msgnum (wl-summary-message-number))
11004 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11005 msgnum 'message-id))
11006 (wl-message-entity
11007 (if (fboundp 'elmo-message-entity)
11008 (elmo-message-entity
11009 wl-summary-buffer-elmo-folder msgnum)
11010 (elmo-msgdb-overview-get-entity
11011 msgnum (wl-summary-buffer-msgdb))))
11012 (from (wl-summary-line-from))
11013 (to (car (elmo-message-entity-field wl-message-entity 'to)))
11014 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11015 (wl-summary-line-subject))))
11016 (org-store-link-props :type "wl" :from from :to to
11017 :subject subject :message-id message-id)
11018 (setq message-id (org-remove-angle-brackets message-id))
11019 (setq cpltxt (org-email-link-description))
11020 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11021 "#" message-id))))
11023 ((or (equal major-mode 'mh-folder-mode)
11024 (equal major-mode 'mh-show-mode))
11025 (let ((from (org-mhe-get-header "From:"))
11026 (to (org-mhe-get-header "To:"))
11027 (message-id (org-mhe-get-header "Message-Id:"))
11028 (subject (org-mhe-get-header "Subject:")))
11029 (org-store-link-props :type "mh" :from from :to to
11030 :subject subject :message-id message-id)
11031 (setq cpltxt (org-email-link-description))
11032 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11033 (org-remove-angle-brackets message-id)))))
11035 ((eq major-mode 'rmail-mode)
11036 (save-excursion
11037 (save-restriction
11038 (rmail-narrow-to-non-pruned-header)
11039 (let ((folder buffer-file-name)
11040 (message-id (mail-fetch-field "message-id"))
11041 (from (mail-fetch-field "from"))
11042 (to (mail-fetch-field "to"))
11043 (subject (mail-fetch-field "subject")))
11044 (org-store-link-props
11045 :type "rmail" :from from :to to
11046 :subject subject :message-id message-id)
11047 (setq message-id (org-remove-angle-brackets message-id))
11048 (setq cpltxt (org-email-link-description))
11049 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11051 ((eq major-mode 'gnus-group-mode)
11052 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11053 (gnus-group-group-name)) ; version
11054 ((fboundp 'gnus-group-name)
11055 (gnus-group-name))
11056 (t "???"))))
11057 (unless group (error "Not on a group"))
11058 (org-store-link-props :type "gnus" :group group)
11059 (setq cpltxt (concat
11060 (if (org-xor arg org-usenet-links-prefer-google)
11061 "http://groups.google.com/groups?group="
11062 "gnus:")
11063 group)
11064 link (org-make-link cpltxt))))
11066 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11067 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11068 (let* ((group gnus-newsgroup-name)
11069 (article (gnus-summary-article-number))
11070 (header (gnus-summary-article-header article))
11071 (from (mail-header-from header))
11072 (message-id (mail-header-id header))
11073 (date (mail-header-date header))
11074 (subject (gnus-summary-subject-string)))
11075 (org-store-link-props :type "gnus" :from from :subject subject
11076 :message-id message-id :group group)
11077 (setq cpltxt (org-email-link-description))
11078 (if (org-xor arg org-usenet-links-prefer-google)
11079 (setq link
11080 (concat
11081 cpltxt "\n "
11082 (format "http://groups.google.com/groups?as_umsgid=%s"
11083 (org-fixup-message-id-for-http message-id))))
11084 (setq link (org-make-link "gnus:" group
11085 "#" (number-to-string article))))))
11087 ((eq major-mode 'w3-mode)
11088 (setq cpltxt (url-view-url t)
11089 link (org-make-link cpltxt))
11090 (org-store-link-props :type "w3" :url (url-view-url t)))
11092 ((eq major-mode 'w3m-mode)
11093 (setq cpltxt (or w3m-current-title w3m-current-url)
11094 link (org-make-link w3m-current-url))
11095 (org-store-link-props :type "w3m" :url (url-view-url t)))
11097 ((setq search (run-hook-with-args-until-success
11098 'org-create-file-search-functions))
11099 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11100 "::" search))
11101 (setq cpltxt (or description link)))
11103 ((eq major-mode 'image-mode)
11104 (setq cpltxt (concat "file:"
11105 (abbreviate-file-name buffer-file-name))
11106 link (org-make-link cpltxt))
11107 (org-store-link-props :type "image" :file buffer-file-name))
11109 ((eq major-mode 'dired-mode)
11110 ;; link to the file in the current line
11111 (setq cpltxt (concat "file:"
11112 (abbreviate-file-name
11113 (expand-file-name
11114 (dired-get-filename nil t))))
11115 link (org-make-link cpltxt)))
11117 ((and buffer-file-name (org-mode-p))
11118 ;; Just link to current headline
11119 (setq cpltxt (concat "file:"
11120 (abbreviate-file-name buffer-file-name)))
11121 ;; Add a context search string
11122 (when (org-xor org-context-in-file-links arg)
11123 ;; Check if we are on a target
11124 (if (org-in-regexp "<<\\(.*?\\)>>")
11125 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11126 (setq txt (cond
11127 ((org-on-heading-p) nil)
11128 ((org-region-active-p)
11129 (buffer-substring (region-beginning) (region-end)))
11130 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11131 (when (or (null txt) (string-match "\\S-" txt))
11132 (setq cpltxt
11133 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11134 desc "NONE"))))
11135 (if (string-match "::\\'" cpltxt)
11136 (setq cpltxt (substring cpltxt 0 -2)))
11137 (setq link (org-make-link cpltxt)))
11139 ((buffer-file-name (buffer-base-buffer))
11140 ;; Just link to this file here.
11141 (setq cpltxt (concat "file:"
11142 (abbreviate-file-name
11143 (buffer-file-name (buffer-base-buffer)))))
11144 ;; Add a context string
11145 (when (org-xor org-context-in-file-links arg)
11146 (setq txt (if (org-region-active-p)
11147 (buffer-substring (region-beginning) (region-end))
11148 (buffer-substring (point-at-bol) (point-at-eol))))
11149 ;; Only use search option if there is some text.
11150 (when (string-match "\\S-" txt)
11151 (setq cpltxt
11152 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11153 desc "NONE")))
11154 (setq link (org-make-link cpltxt)))
11156 ((interactive-p)
11157 (error "Cannot link to a buffer which is not visiting a file"))
11159 (t (setq link nil)))
11161 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11162 (setq link (or link cpltxt)
11163 desc (or desc cpltxt))
11164 (if (equal desc "NONE") (setq desc nil))
11166 (if (and (interactive-p) link)
11167 (progn
11168 (setq org-stored-links
11169 (cons (list link desc) org-stored-links))
11170 (message "Stored: %s" (or desc link)))
11171 (and link (org-make-link-string link desc)))))
11173 (defun org-store-link-props (&rest plist)
11174 "Store link properties, extract names and addresses."
11175 (let (x adr)
11176 (when (setq x (plist-get plist :from))
11177 (setq adr (mail-extract-address-components x))
11178 (plist-put plist :fromname (car adr))
11179 (plist-put plist :fromaddress (nth 1 adr)))
11180 (when (setq x (plist-get plist :to))
11181 (setq adr (mail-extract-address-components x))
11182 (plist-put plist :toname (car adr))
11183 (plist-put plist :toaddress (nth 1 adr))))
11184 (let ((from (plist-get plist :from))
11185 (to (plist-get plist :to)))
11186 (when (and from to org-from-is-user-regexp)
11187 (plist-put plist :fromto
11188 (if (string-match org-from-is-user-regexp from)
11189 (concat "to %t")
11190 (concat "from %f")))))
11191 (setq org-store-link-plist plist))
11193 (defun org-email-link-description (&optional fmt)
11194 "Return the description part of an email link.
11195 This takes information from `org-store-link-plist' and formats it
11196 according to FMT (default from `org-email-link-description-format')."
11197 (setq fmt (or fmt org-email-link-description-format))
11198 (let* ((p org-store-link-plist)
11199 (to (plist-get p :toaddress))
11200 (from (plist-get p :fromaddress))
11201 (table
11202 (list
11203 (cons "%c" (plist-get p :fromto))
11204 (cons "%F" (plist-get p :from))
11205 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11206 (cons "%T" (plist-get p :to))
11207 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11208 (cons "%s" (plist-get p :subject))
11209 (cons "%m" (plist-get p :message-id)))))
11210 (when (string-match "%c" fmt)
11211 ;; Check if the user wrote this message
11212 (if (and org-from-is-user-regexp from to
11213 (save-match-data (string-match org-from-is-user-regexp from)))
11214 (setq fmt (replace-match "to %t" t t fmt))
11215 (setq fmt (replace-match "from %f" t t fmt))))
11216 (org-replace-escapes fmt table)))
11218 (defun org-make-org-heading-search-string (&optional string heading)
11219 "Make search string for STRING or current headline."
11220 (interactive)
11221 (let ((s (or string (org-get-heading))))
11222 (unless (and string (not heading))
11223 ;; We are using a headline, clean up garbage in there.
11224 (if (string-match org-todo-regexp s)
11225 (setq s (replace-match "" t t s)))
11226 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11227 (setq s (replace-match "" t t s)))
11228 (setq s (org-trim s))
11229 (if (string-match (concat "^\\(" org-quote-string "\\|"
11230 org-comment-string "\\)") s)
11231 (setq s (replace-match "" t t s)))
11232 (while (string-match org-ts-regexp s)
11233 (setq s (replace-match "" t t s))))
11234 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11235 (setq s (replace-match " " t t s)))
11236 (or string (setq s (concat "*" s))) ; Add * for headlines
11237 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11239 (defun org-make-link (&rest strings)
11240 "Concatenate STRINGS."
11241 (apply 'concat strings))
11243 (defun org-make-link-string (link &optional description)
11244 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11245 (unless (string-match "\\S-" link)
11246 (error "Empty link"))
11247 (when (stringp description)
11248 ;; Remove brackets from the description, they are fatal.
11249 (while (string-match "\\[\\|\\]" description)
11250 (setq description (replace-match "" t t description))))
11251 (when (equal (org-link-escape link) description)
11252 ;; No description needed, it is identical
11253 (setq description nil))
11254 (when (and (not description)
11255 (not (equal link (org-link-escape link))))
11256 (setq description link))
11257 (concat "[[" (org-link-escape link) "]"
11258 (if description (concat "[" description "]") "")
11259 "]"))
11261 (defconst org-link-escape-chars
11262 '((" " . "%20")
11263 ("[" . "%5B")
11264 ("]" . "%5d")
11265 ("\340" . "%E0") ; `a
11266 ("\342" . "%E2") ; ^a
11267 ("\347" . "%E7") ; ,c
11268 ("\350" . "%E8") ; `e
11269 ("\351" . "%E9") ; 'e
11270 ("\352" . "%EA") ; ^e
11271 ("\356" . "%EE") ; ^i
11272 ("\364" . "%F4") ; ^o
11273 ("\371" . "%F9") ; `u
11274 ("\373" . "%FB") ; ^u
11275 (";" . "%3B")
11276 ("?" . "%3F")
11277 ("=" . "%3D")
11278 ("+" . "%2B")
11280 "Association list of escapes for some characters problematic in links.
11281 This is the list that is used for internal purposes.")
11283 (defconst org-link-escape-chars-browser
11284 '((" " . "%20"))
11285 "Association list of escapes for some characters problematic in links.
11286 This is the list that is used before handing over to the browser.")
11288 (defun org-link-escape (text &optional table)
11289 "Escape charaters in TEXT that are problematic for links."
11290 (setq table (or table org-link-escape-chars))
11291 (when text
11292 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11293 table "\\|")))
11294 (while (string-match re text)
11295 (setq text
11296 (replace-match
11297 (cdr (assoc (match-string 0 text) table))
11298 t t text)))
11299 text)))
11301 (defun org-link-unescape (text &optional table)
11302 "Reverse the action of `org-link-escape'."
11303 (setq table (or table org-link-escape-chars))
11304 (when text
11305 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11306 table "\\|")))
11307 (while (string-match re text)
11308 (setq text
11309 (replace-match
11310 (car (rassoc (match-string 0 text) table))
11311 t t text)))
11312 text)))
11314 (defun org-xor (a b)
11315 "Exclusive or."
11316 (if a (not b) b))
11318 (defun org-get-header (header)
11319 "Find a header field in the current buffer."
11320 (save-excursion
11321 (goto-char (point-min))
11322 (let ((case-fold-search t) s)
11323 (cond
11324 ((eq header 'from)
11325 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11326 (setq s (match-string 1)))
11327 (while (string-match "\"" s)
11328 (setq s (replace-match "" t t s)))
11329 (if (string-match "[<(].*" s)
11330 (setq s (replace-match "" t t s))))
11331 ((eq header 'message-id)
11332 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11333 (setq s (match-string 1))))
11334 ((eq header 'subject)
11335 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11336 (setq s (match-string 1)))))
11337 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11338 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11339 s)))
11342 (defun org-fixup-message-id-for-http (s)
11343 "Replace special characters in a message id, so it can be used in an http query."
11344 (while (string-match "<" s)
11345 (setq s (replace-match "%3C" t t s)))
11346 (while (string-match ">" s)
11347 (setq s (replace-match "%3E" t t s)))
11348 (while (string-match "@" s)
11349 (setq s (replace-match "%40" t t s)))
11352 ;;;###autoload
11353 (defun org-insert-link-global ()
11354 "Insert a link like Org-mode does.
11355 This command can be called in any mode to insert a link in Org-mode syntax."
11356 (interactive)
11357 (org-run-like-in-org-mode 'org-insert-link))
11359 (defun org-insert-link (&optional complete-file)
11360 "Insert a link. At the prompt, enter the link.
11362 Completion can be used to select a link previously stored with
11363 `org-store-link'. When the empty string is entered (i.e. if you just
11364 press RET at the prompt), the link defaults to the most recently
11365 stored link. As SPC triggers completion in the minibuffer, you need to
11366 use M-SPC or C-q SPC to force the insertion of a space character.
11368 You will also be prompted for a description, and if one is given, it will
11369 be displayed in the buffer instead of the link.
11371 If there is already a link at point, this command will allow you to edit link
11372 and description parts.
11374 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11375 selected using completion. The path to the file will be relative to
11376 the current directory if the file is in the current directory or a
11377 subdirectory. Otherwise, the link will be the absolute path as
11378 completed in the minibuffer (i.e. normally ~/path/to/file).
11380 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11381 is in the current directory or below.
11382 With three \\[universal-argument] prefixes, negate the meaning of
11383 `org-keep-stored-link-after-insertion'."
11384 (interactive "P")
11385 (let* ((wcf (current-window-configuration))
11386 (region (if (org-region-active-p)
11387 (buffer-substring (region-beginning) (region-end))))
11388 (remove (and region (list (region-beginning) (region-end))))
11389 (desc region)
11390 tmphist ; byte-compile incorrectly complains about this
11391 link entry file)
11392 (cond
11393 ((org-in-regexp org-bracket-link-regexp 1)
11394 ;; We do have a link at point, and we are going to edit it.
11395 (setq remove (list (match-beginning 0) (match-end 0)))
11396 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11397 (setq link (read-string "Link: "
11398 (org-link-unescape
11399 (org-match-string-no-properties 1)))))
11400 ((or (org-in-regexp org-angle-link-re)
11401 (org-in-regexp org-plain-link-re))
11402 ;; Convert to bracket link
11403 (setq remove (list (match-beginning 0) (match-end 0))
11404 link (read-string "Link: "
11405 (org-remove-angle-brackets (match-string 0)))))
11406 ((equal complete-file '(4))
11407 ;; Completing read for file names.
11408 (setq file (read-file-name "File: "))
11409 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11410 (pwd1 (file-name-as-directory (abbreviate-file-name
11411 (expand-file-name ".")))))
11412 (cond
11413 ((equal complete-file '(16))
11414 (setq link (org-make-link
11415 "file:"
11416 (abbreviate-file-name (expand-file-name file)))))
11417 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11418 (setq link (org-make-link "file:" (match-string 1 file))))
11419 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11420 (expand-file-name file))
11421 (setq link (org-make-link
11422 "file:" (match-string 1 (expand-file-name file)))))
11423 (t (setq link (org-make-link "file:" file))))))
11425 ;; Read link, with completion for stored links.
11426 (with-output-to-temp-buffer "*Org Links*"
11427 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11428 (when org-stored-links
11429 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11430 (princ (mapconcat
11431 (lambda (x)
11432 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11433 (reverse org-stored-links) "\n"))))
11434 (let ((cw (selected-window)))
11435 (select-window (get-buffer-window "*Org Links*"))
11436 (shrink-window-if-larger-than-buffer)
11437 (setq truncate-lines t)
11438 (select-window cw))
11439 ;; Fake a link history, containing the stored links.
11440 (setq tmphist (append (mapcar 'car org-stored-links)
11441 org-insert-link-history))
11442 (unwind-protect
11443 (setq link (org-completing-read
11444 "Link: "
11445 (append
11446 (mapcar (lambda (x) (list (concat (car x) ":")))
11447 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11448 (mapcar (lambda (x) (list (concat x ":")))
11449 org-link-types))
11450 nil nil nil
11451 'tmphist
11452 (or (car (car org-stored-links)))))
11453 (set-window-configuration wcf)
11454 (kill-buffer "*Org Links*"))
11455 (setq entry (assoc link org-stored-links))
11456 (or entry (push link org-insert-link-history))
11457 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11458 (not org-keep-stored-link-after-insertion))
11459 (setq org-stored-links (delq (assoc link org-stored-links)
11460 org-stored-links)))
11461 (setq desc (or desc (nth 1 entry)))))
11463 (if (string-match org-plain-link-re link)
11464 ;; URL-like link, normalize the use of angular brackets.
11465 (setq link (org-make-link (org-remove-angle-brackets link))))
11467 ;; Check if we are linking to the current file with a search option
11468 ;; If yes, simplify the link by using only the search option.
11469 (when (and buffer-file-name
11470 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11471 (let* ((path (match-string 1 link))
11472 (case-fold-search nil)
11473 (search (match-string 2 link)))
11474 (save-match-data
11475 (if (equal (file-truename buffer-file-name) (file-truename path))
11476 ;; We are linking to this same file, with a search option
11477 (setq link search)))))
11479 ;; Check if we can/should use a relative path. If yes, simplify the link
11480 (when (string-match "\\<file:\\(.*\\)" link)
11481 (let* ((path (match-string 1 link))
11482 (origpath path)
11483 (desc-is-link (equal link desc))
11484 (case-fold-search nil))
11485 (cond
11486 ((eq org-link-file-path-type 'absolute)
11487 (setq path (abbreviate-file-name (expand-file-name path))))
11488 ((eq org-link-file-path-type 'noabbrev)
11489 (setq path (expand-file-name path)))
11490 ((eq org-link-file-path-type 'relative)
11491 (setq path (file-relative-name path)))
11493 (save-match-data
11494 (if (string-match (concat "^" (regexp-quote
11495 (file-name-as-directory
11496 (expand-file-name "."))))
11497 (expand-file-name path))
11498 ;; We are linking a file with relative path name.
11499 (setq path (substring (expand-file-name path)
11500 (match-end 0)))))))
11501 (setq link (concat "file:" path))
11502 (if (equal desc origpath)
11503 (setq desc path))))
11505 (setq desc (read-string "Description: " desc))
11506 (unless (string-match "\\S-" desc) (setq desc nil))
11507 (if remove (apply 'delete-region remove))
11508 (insert (org-make-link-string link desc))))
11510 (defun org-completing-read (&rest args)
11511 (let ((minibuffer-local-completion-map
11512 (copy-keymap minibuffer-local-completion-map)))
11513 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11514 (apply 'completing-read args)))
11516 ;;; Opening/following a link
11517 (defvar org-link-search-failed nil)
11519 (defun org-next-link ()
11520 "Move forward to the next link.
11521 If the link is in hidden text, expose it."
11522 (interactive)
11523 (when (and org-link-search-failed (eq this-command last-command))
11524 (goto-char (point-min))
11525 (message "Link search wrapped back to beginning of buffer"))
11526 (setq org-link-search-failed nil)
11527 (let* ((pos (point))
11528 (ct (org-context))
11529 (a (assoc :link ct)))
11530 (if a (goto-char (nth 2 a)))
11531 (if (re-search-forward org-any-link-re nil t)
11532 (progn
11533 (goto-char (match-beginning 0))
11534 (if (org-invisible-p) (org-show-context)))
11535 (goto-char pos)
11536 (setq org-link-search-failed t)
11537 (error "No further link found"))))
11539 (defun org-previous-link ()
11540 "Move backward to the previous link.
11541 If the link is in hidden text, expose it."
11542 (interactive)
11543 (when (and org-link-search-failed (eq this-command last-command))
11544 (goto-char (point-max))
11545 (message "Link search wrapped back to end of buffer"))
11546 (setq org-link-search-failed nil)
11547 (let* ((pos (point))
11548 (ct (org-context))
11549 (a (assoc :link ct)))
11550 (if a (goto-char (nth 1 a)))
11551 (if (re-search-backward org-any-link-re nil t)
11552 (progn
11553 (goto-char (match-beginning 0))
11554 (if (org-invisible-p) (org-show-context)))
11555 (goto-char pos)
11556 (setq org-link-search-failed t)
11557 (error "No further link found"))))
11559 (defun org-find-file-at-mouse (ev)
11560 "Open file link or URL at mouse."
11561 (interactive "e")
11562 (mouse-set-point ev)
11563 (org-open-at-point 'in-emacs))
11565 (defun org-open-at-mouse (ev)
11566 "Open file link or URL at mouse."
11567 (interactive "e")
11568 (mouse-set-point ev)
11569 (org-open-at-point))
11571 (defvar org-window-config-before-follow-link nil
11572 "The window configuration before following a link.
11573 This is saved in case the need arises to restore it.")
11575 (defvar org-open-link-marker (make-marker)
11576 "Marker pointing to the location where `org-open-at-point; was called.")
11578 ;;;###autoload
11579 (defun org-open-at-point-global ()
11580 "Follow a link like Org-mode does.
11581 This command can be called in any mode to follow a link that has
11582 Org-mode syntax."
11583 (interactive)
11584 (org-run-like-in-org-mode 'org-open-at-point))
11586 (defun org-open-at-point (&optional in-emacs)
11587 "Open link at or after point.
11588 If there is no link at point, this function will search forward up to
11589 the end of the current subtree.
11590 Normally, files will be opened by an appropriate application. If the
11591 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11592 (interactive "P")
11593 (move-marker org-open-link-marker (point))
11594 (setq org-window-config-before-follow-link (current-window-configuration))
11595 (org-remove-occur-highlights nil nil t)
11596 (if (org-at-timestamp-p t)
11597 (org-follow-timestamp-link)
11598 (let (type path link line search (pos (point)))
11599 (catch 'match
11600 (save-excursion
11601 (skip-chars-forward "^]\n\r")
11602 (when (org-in-regexp org-bracket-link-regexp)
11603 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11604 (while (string-match " *\n *" link)
11605 (setq link (replace-match " " t t link)))
11606 (setq link (org-link-expand-abbrev link))
11607 (if (string-match org-link-re-with-space2 link)
11608 (setq type (match-string 1 link) path (match-string 2 link))
11609 (setq type "thisfile" path link))
11610 (throw 'match t)))
11612 (when (get-text-property (point) 'org-linked-text)
11613 (setq type "thisfile"
11614 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11615 (1+ (point)) (point))
11616 path (buffer-substring
11617 (previous-single-property-change pos 'org-linked-text)
11618 (next-single-property-change pos 'org-linked-text)))
11619 (throw 'match t))
11621 (save-excursion
11622 (when (or (org-in-regexp org-angle-link-re)
11623 (org-in-regexp org-plain-link-re))
11624 (setq type (match-string 1) path (match-string 2))
11625 (throw 'match t)))
11626 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11627 (setq type "tree-match"
11628 path (match-string 1))
11629 (throw 'match t))
11630 (save-excursion
11631 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11632 (setq type "tags"
11633 path (match-string 1))
11634 (while (string-match ":" path)
11635 (setq path (replace-match "+" t t path)))
11636 (throw 'match t))))
11637 (unless path
11638 (error "No link found"))
11639 ;; Remove any trailing spaces in path
11640 (if (string-match " +\\'" path)
11641 (setq path (replace-match "" t t path)))
11643 (cond
11645 ((assoc type org-link-protocols)
11646 (funcall (nth 1 (assoc type org-link-protocols)) path))
11648 ((equal type "mailto")
11649 (let ((cmd (car org-link-mailto-program))
11650 (args (cdr org-link-mailto-program)) args1
11651 (address path) (subject "") a)
11652 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11653 (setq address (match-string 1 path)
11654 subject (org-link-escape (match-string 2 path))))
11655 (while args
11656 (cond
11657 ((not (stringp (car args))) (push (pop args) args1))
11658 (t (setq a (pop args))
11659 (if (string-match "%a" a)
11660 (setq a (replace-match address t t a)))
11661 (if (string-match "%s" a)
11662 (setq a (replace-match subject t t a)))
11663 (push a args1))))
11664 (apply cmd (nreverse args1))))
11666 ((member type '("http" "https" "ftp" "news"))
11667 (browse-url (concat type ":" (org-link-escape
11668 path org-link-escape-chars-browser))))
11670 ((string= type "tags")
11671 (org-tags-view in-emacs path))
11672 ((string= type "thisfile")
11673 (if in-emacs
11674 (switch-to-buffer-other-window
11675 (org-get-buffer-for-internal-link (current-buffer)))
11676 (org-mark-ring-push))
11677 (let ((cmd `(org-link-search
11678 ,path
11679 ,(cond ((equal in-emacs '(4)) 'occur)
11680 ((equal in-emacs '(16)) 'org-occur)
11681 (t nil))
11682 ,pos)))
11683 (condition-case nil (eval cmd)
11684 (error (progn (widen) (eval cmd))))))
11686 ((string= type "tree-match")
11687 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11689 ((string= type "file")
11690 (if (string-match "::\\([0-9]+\\)\\'" path)
11691 (setq line (string-to-number (match-string 1 path))
11692 path (substring path 0 (match-beginning 0)))
11693 (if (string-match "::\\(.+\\)\\'" path)
11694 (setq search (match-string 1 path)
11695 path (substring path 0 (match-beginning 0)))))
11696 (org-open-file path in-emacs line search))
11698 ((string= type "news")
11699 (org-follow-gnus-link path))
11701 ((string= type "bbdb")
11702 (org-follow-bbdb-link path))
11704 ((string= type "info")
11705 (org-follow-info-link path))
11707 ((string= type "gnus")
11708 (let (group article)
11709 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11710 (error "Error in Gnus link"))
11711 (setq group (match-string 1 path)
11712 article (match-string 3 path))
11713 (org-follow-gnus-link group article)))
11715 ((string= type "vm")
11716 (let (folder article)
11717 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11718 (error "Error in VM link"))
11719 (setq folder (match-string 1 path)
11720 article (match-string 3 path))
11721 ;; in-emacs is the prefix arg, will be interpreted as read-only
11722 (org-follow-vm-link folder article in-emacs)))
11724 ((string= type "wl")
11725 (let (folder article)
11726 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11727 (error "Error in Wanderlust link"))
11728 (setq folder (match-string 1 path)
11729 article (match-string 3 path))
11730 (org-follow-wl-link folder article)))
11732 ((string= type "mhe")
11733 (let (folder article)
11734 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11735 (error "Error in MHE link"))
11736 (setq folder (match-string 1 path)
11737 article (match-string 3 path))
11738 (org-follow-mhe-link folder article)))
11740 ((string= type "rmail")
11741 (let (folder article)
11742 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11743 (error "Error in RMAIL link"))
11744 (setq folder (match-string 1 path)
11745 article (match-string 3 path))
11746 (org-follow-rmail-link folder article)))
11748 ((string= type "shell")
11749 (let ((cmd path))
11750 ;; The following is only for backward compatibility
11751 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11752 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11753 (if (or (not org-confirm-shell-link-function)
11754 (funcall org-confirm-shell-link-function
11755 (format "Execute \"%s\" in shell? "
11756 (org-add-props cmd nil
11757 'face 'org-warning))))
11758 (progn
11759 (message "Executing %s" cmd)
11760 (shell-command cmd))
11761 (error "Abort"))))
11763 ((string= type "elisp")
11764 (let ((cmd path))
11765 (if (or (not org-confirm-elisp-link-function)
11766 (funcall org-confirm-elisp-link-function
11767 (format "Execute \"%s\" as elisp? "
11768 (org-add-props cmd nil
11769 'face 'org-warning))))
11770 (message "%s => %s" cmd (eval (read cmd)))
11771 (error "Abort"))))
11774 (browse-url-at-point)))))
11775 (move-marker org-open-link-marker nil))
11778 ;;; File search
11780 (defvar org-create-file-search-functions nil
11781 "List of functions to construct the right search string for a file link.
11782 These functions are called in turn with point at the location to
11783 which the link should point.
11785 A function in the hook should first test if it would like to
11786 handle this file type, for example by checking the major-mode or
11787 the file extension. If it decides not to handle this file, it
11788 should just return nil to give other functions a chance. If it
11789 does handle the file, it must return the search string to be used
11790 when following the link. The search string will be part of the
11791 file link, given after a double colon, and `org-open-at-point'
11792 will automatically search for it. If special measures must be
11793 taken to make the search successful, another function should be
11794 added to the companion hook `org-execute-file-search-functions',
11795 which see.
11797 A function in this hook may also use `setq' to set the variable
11798 `description' to provide a suggestion for the descriptive text to
11799 be used for this link when it gets inserted into an Org-mode
11800 buffer with \\[org-insert-link].")
11802 (defvar org-execute-file-search-functions nil
11803 "List of functions to execute a file search triggered by a link.
11805 Functions added to this hook must accept a single argument, the
11806 search string that was part of the file link, the part after the
11807 double colon. The function must first check if it would like to
11808 handle this search, for example by checking the major-mode or the
11809 file extension. If it decides not to handle this search, it
11810 should just return nil to give other functions a chance. If it
11811 does handle the search, it must return a non-nil value to keep
11812 other functions from trying.
11814 Each function can access the current prefix argument through the
11815 variable `current-prefix-argument'. Note that a single prefix is
11816 used to force opening a link in Emacs, so it may be good to only
11817 use a numeric or double prefix to guide the search function.
11819 In case this is needed, a function in this hook can also restore
11820 the window configuration before `org-open-at-point' was called using:
11822 (set-window-configuration org-window-config-before-follow-link)")
11824 (defun org-link-search (s &optional type avoid-pos)
11825 "Search for a link search option.
11826 If S is surrounded by forward slashes, it is interpreted as a
11827 regular expression. In org-mode files, this will create an `org-occur'
11828 sparse tree. In ordinary files, `occur' will be used to list matches.
11829 If the current buffer is in `dired-mode', grep will be used to search
11830 in all files. If AVOID-POS is given, ignore matches near that position."
11831 (let ((case-fold-search t)
11832 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11833 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11834 (append '(("") (" ") ("\t") ("\n"))
11835 org-emphasis-alist)
11836 "\\|") "\\)"))
11837 (pos (point))
11838 (pre "") (post "")
11839 words re0 re1 re2 re3 re4 re5 re2a reall)
11840 (cond
11841 ;; First check if there are any special
11842 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11843 ;; Now try the builtin stuff
11844 ((save-excursion
11845 (goto-char (point-min))
11846 (and
11847 (re-search-forward
11848 (concat "<<" (regexp-quote s0) ">>") nil t)
11849 (setq pos (match-beginning 0))))
11850 ;; There is an exact target for this
11851 (goto-char pos))
11852 ((string-match "^/\\(.*\\)/$" s)
11853 ;; A regular expression
11854 (cond
11855 ((org-mode-p)
11856 (org-occur (match-string 1 s)))
11857 ;;((eq major-mode 'dired-mode)
11858 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11859 (t (org-do-occur (match-string 1 s)))))
11861 ;; A normal search strings
11862 (when (equal (string-to-char s) ?*)
11863 ;; Anchor on headlines, post may include tags.
11864 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11865 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11866 s (substring s 1)))
11867 (remove-text-properties
11868 0 (length s)
11869 '(face nil mouse-face nil keymap nil fontified nil) s)
11870 ;; Make a series of regular expressions to find a match
11871 (setq words (org-split-string s "[ \n\r\t]+")
11872 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11873 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11874 "\\)" markers)
11875 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11876 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11877 re1 (concat pre re2 post)
11878 re3 (concat pre re4 post)
11879 re5 (concat pre ".*" re4)
11880 re2 (concat pre re2)
11881 re2a (concat pre re2a)
11882 re4 (concat pre re4)
11883 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11884 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11885 re5 "\\)"
11887 (cond
11888 ((eq type 'org-occur) (org-occur reall))
11889 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11890 (t (goto-char (point-min))
11891 (if (or (org-search-not-self 1 re0 nil t)
11892 (org-search-not-self 1 re1 nil t)
11893 (org-search-not-self 1 re2 nil t)
11894 (org-search-not-self 1 re2a nil t)
11895 (org-search-not-self 1 re3 nil t)
11896 (org-search-not-self 1 re4 nil t)
11897 (org-search-not-self 1 re5 nil t)
11899 (goto-char (match-beginning 1))
11900 (goto-char pos)
11901 (error "No match")))))
11903 ;; Normal string-search
11904 (goto-char (point-min))
11905 (if (search-forward s nil t)
11906 (goto-char (match-beginning 0))
11907 (error "No match"))))
11908 (and (org-mode-p) (org-show-context 'link-search))))
11910 (defun org-search-not-self (group &rest args)
11911 "Execute `re-search-forward', but only accept matches that do not
11912 enclose the position of `org-open-link-marker'."
11913 (let ((m org-open-link-marker))
11914 (catch 'exit
11915 (while (apply 're-search-forward args)
11916 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11917 (goto-char (match-end group))
11918 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11919 (> (match-beginning 0) (marker-position m))
11920 (< (match-end 0) (marker-position m)))
11921 (save-match-data
11922 (or (not (org-in-regexp
11923 org-bracket-link-analytic-regexp 1))
11924 (not (match-end 4)) ; no description
11925 (and (<= (match-beginning 4) (point))
11926 (>= (match-end 4) (point))))))
11927 (throw 'exit (point))))))))
11929 (defun org-get-buffer-for-internal-link (buffer)
11930 "Return a buffer to be used for displaying the link target of internal links."
11931 (cond
11932 ((not org-display-internal-link-with-indirect-buffer)
11933 buffer)
11934 ((string-match "(Clone)$" (buffer-name buffer))
11935 (message "Buffer is already a clone, not making another one")
11936 ;; we also do not modify visibility in this case
11937 buffer)
11938 (t ; make a new indirect buffer for displaying the link
11939 (let* ((bn (buffer-name buffer))
11940 (ibn (concat bn "(Clone)"))
11941 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11942 (with-current-buffer ib (org-overview))
11943 ib))))
11945 (defun org-do-occur (regexp &optional cleanup)
11946 "Call the Emacs command `occur'.
11947 If CLEANUP is non-nil, remove the printout of the regular expression
11948 in the *Occur* buffer. This is useful if the regex is long and not useful
11949 to read."
11950 (occur regexp)
11951 (when cleanup
11952 (let ((cwin (selected-window)) win beg end)
11953 (when (setq win (get-buffer-window "*Occur*"))
11954 (select-window win))
11955 (goto-char (point-min))
11956 (when (re-search-forward "match[a-z]+" nil t)
11957 (setq beg (match-end 0))
11958 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11959 (setq end (1- (match-beginning 0)))))
11960 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11961 (goto-char (point-min))
11962 (select-window cwin))))
11964 ;;; The mark ring for links jumps
11966 (defvar org-mark-ring nil
11967 "Mark ring for positions before jumps in Org-mode.")
11968 (defvar org-mark-ring-last-goto nil
11969 "Last position in the mark ring used to go back.")
11970 ;; Fill and close the ring
11971 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11972 (loop for i from 1 to org-mark-ring-length do
11973 (push (make-marker) org-mark-ring))
11974 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11975 org-mark-ring)
11977 (defun org-mark-ring-push (&optional pos buffer)
11978 "Put the current position or POS into the mark ring and rotate it."
11979 (interactive)
11980 (setq pos (or pos (point)))
11981 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11982 (move-marker (car org-mark-ring)
11983 (or pos (point))
11984 (or buffer (current-buffer)))
11985 (message
11986 (substitute-command-keys
11987 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11989 (defun org-mark-ring-goto (&optional n)
11990 "Jump to the previous position in the mark ring.
11991 With prefix arg N, jump back that many stored positions. When
11992 called several times in succession, walk through the entire ring.
11993 Org-mode commands jumping to a different position in the current file,
11994 or to another Org-mode file, automatically push the old position
11995 onto the ring."
11996 (interactive "p")
11997 (let (p m)
11998 (if (eq last-command this-command)
11999 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12000 (setq p org-mark-ring))
12001 (setq org-mark-ring-last-goto p)
12002 (setq m (car p))
12003 (switch-to-buffer (marker-buffer m))
12004 (goto-char m)
12005 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12007 (defun org-remove-angle-brackets (s)
12008 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12009 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12011 (defun org-add-angle-brackets (s)
12012 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12013 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12016 ;;; Following specific links
12018 (defun org-follow-timestamp-link ()
12019 (cond
12020 ((org-at-date-range-p t)
12021 (let ((org-agenda-start-on-weekday)
12022 (t1 (match-string 1))
12023 (t2 (match-string 2)))
12024 (setq t1 (time-to-days (org-time-string-to-time t1))
12025 t2 (time-to-days (org-time-string-to-time t2)))
12026 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12027 ((org-at-timestamp-p t)
12028 (org-agenda-list nil (time-to-days (org-time-string-to-time
12029 (substring (match-string 1) 0 10)))
12031 (t (error "This should not happen"))))
12034 (defun org-follow-bbdb-link (name)
12035 "Follow a BBDB link to NAME."
12036 (require 'bbdb)
12037 (let ((inhibit-redisplay (not debug-on-error))
12038 (bbdb-electric-p nil))
12039 (catch 'exit
12040 ;; Exact match on name
12041 (bbdb-name (concat "\\`" name "\\'") nil)
12042 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12043 ;; Exact match on name
12044 (bbdb-company (concat "\\`" name "\\'") nil)
12045 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12046 ;; Partial match on name
12047 (bbdb-name name nil)
12048 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12049 ;; Partial match on company
12050 (bbdb-company name nil)
12051 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12052 ;; General match including network address and notes
12053 (bbdb name nil)
12054 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12055 (delete-window (get-buffer-window "*BBDB*"))
12056 (error "No matching BBDB record")))))
12058 (defun org-follow-info-link (name)
12059 "Follow an info file & node link to NAME."
12060 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12061 (string-match "\\(.*\\)" name))
12062 (progn
12063 (require 'info)
12064 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12065 (Info-find-node (match-string 1 name) (match-string 2 name))
12066 (Info-find-node (match-string 1 name) "Top")))
12067 (message (concat "Could not open: " name))))
12069 (defun org-follow-gnus-link (&optional group article)
12070 "Follow a Gnus link to GROUP and ARTICLE."
12071 (require 'gnus)
12072 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12073 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12074 (cond ((and group article)
12075 (gnus-group-read-group 1 nil group)
12076 (gnus-summary-goto-article (string-to-number article) nil t))
12077 (group (gnus-group-jump-to-group group))))
12079 (defun org-follow-vm-link (&optional folder article readonly)
12080 "Follow a VM link to FOLDER and ARTICLE."
12081 (require 'vm)
12082 (setq article (org-add-angle-brackets article))
12083 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12084 ;; ange-ftp or efs or tramp access
12085 (let ((user (or (match-string 1 folder) (user-login-name)))
12086 (host (match-string 2 folder))
12087 (file (match-string 3 folder)))
12088 (cond
12089 ((featurep 'tramp)
12090 ;; use tramp to access the file
12091 (if (featurep 'xemacs)
12092 (setq folder (format "[%s@%s]%s" user host file))
12093 (setq folder (format "/%s@%s:%s" user host file))))
12095 ;; use ange-ftp or efs
12096 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12097 (setq folder (format "/%s@%s:%s" user host file))))))
12098 (when folder
12099 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12100 (sit-for 0.1)
12101 (when article
12102 (vm-select-folder-buffer)
12103 (widen)
12104 (let ((case-fold-search t))
12105 (goto-char (point-min))
12106 (if (not (re-search-forward
12107 (concat "^" "message-id: *" (regexp-quote article))))
12108 (error "Could not find the specified message in this folder"))
12109 (vm-isearch-update)
12110 (vm-isearch-narrow)
12111 (vm-beginning-of-message)
12112 (vm-summarize)))))
12114 (defun org-follow-wl-link (folder article)
12115 "Follow a Wanderlust link to FOLDER and ARTICLE."
12116 (if (and (string= folder "%")
12117 article
12118 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12119 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12120 ;; Thus, we recompose folder and article ids.
12121 (setq folder (format "%s#%s" folder (match-string 1 article))
12122 article (match-string 3 article)))
12123 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12124 (error "No such folder: %s" folder))
12125 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12126 (and article
12127 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12128 (wl-summary-redisplay)))
12130 (defun org-follow-rmail-link (folder article)
12131 "Follow an RMAIL link to FOLDER and ARTICLE."
12132 (setq article (org-add-angle-brackets article))
12133 (let (message-number)
12134 (save-excursion
12135 (save-window-excursion
12136 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12137 (setq message-number
12138 (save-restriction
12139 (widen)
12140 (goto-char (point-max))
12141 (if (re-search-backward
12142 (concat "^Message-ID:\\s-+" (regexp-quote
12143 (or article "")))
12144 nil t)
12145 (rmail-what-message))))))
12146 (if message-number
12147 (progn
12148 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12149 (rmail-show-message message-number)
12150 message-number)
12151 (error "Message not found"))))
12153 ;;; mh-e integration based on planner-mode
12154 (defun org-mhe-get-message-real-folder ()
12155 "Return the name of the current message real folder, so if you use
12156 sequences, it will now work."
12157 (save-excursion
12158 (let* ((folder
12159 (if (equal major-mode 'mh-folder-mode)
12160 mh-current-folder
12161 ;; Refer to the show buffer
12162 mh-show-folder-buffer))
12163 (end-index
12164 (if (boundp 'mh-index-folder)
12165 (min (length mh-index-folder) (length folder))))
12167 ;; a simple test on mh-index-data does not work, because
12168 ;; mh-index-data is always nil in a show buffer.
12169 (if (and (boundp 'mh-index-folder)
12170 (string= mh-index-folder (substring folder 0 end-index)))
12171 (if (equal major-mode 'mh-show-mode)
12172 (save-window-excursion
12173 (let (pop-up-frames)
12174 (when (buffer-live-p (get-buffer folder))
12175 (progn
12176 (pop-to-buffer folder)
12177 (org-mhe-get-message-folder-from-index)
12180 (org-mhe-get-message-folder-from-index)
12182 folder
12186 (defun org-mhe-get-message-folder-from-index ()
12187 "Returns the name of the message folder in a index folder buffer."
12188 (save-excursion
12189 (mh-index-previous-folder)
12190 (re-search-forward "^\\(+.*\\)$" nil t)
12191 (message (match-string 1))))
12193 (defun org-mhe-get-message-folder ()
12194 "Return the name of the current message folder. Be careful if you
12195 use sequences."
12196 (save-excursion
12197 (if (equal major-mode 'mh-folder-mode)
12198 mh-current-folder
12199 ;; Refer to the show buffer
12200 mh-show-folder-buffer)))
12202 (defun org-mhe-get-message-num ()
12203 "Return the number of the current message. Be careful if you
12204 use sequences."
12205 (save-excursion
12206 (if (equal major-mode 'mh-folder-mode)
12207 (mh-get-msg-num nil)
12208 ;; Refer to the show buffer
12209 (mh-show-buffer-message-number))))
12211 (defun org-mhe-get-header (header)
12212 "Return a header of the message in folder mode. This will create a
12213 show buffer for the corresponding message. If you have a more clever
12214 idea..."
12215 (let* ((folder (org-mhe-get-message-folder))
12216 (num (org-mhe-get-message-num))
12217 (buffer (get-buffer-create (concat "show-" folder)))
12218 (header-field))
12219 (with-current-buffer buffer
12220 (mh-display-msg num folder)
12221 (if (equal major-mode 'mh-folder-mode)
12222 (mh-header-display)
12223 (mh-show-header-display))
12224 (set-buffer buffer)
12225 (setq header-field (mh-get-header-field header))
12226 (if (equal major-mode 'mh-folder-mode)
12227 (mh-show)
12228 (mh-show-show))
12229 header-field)))
12231 (defun org-follow-mhe-link (folder article)
12232 "Follow an MHE link to FOLDER and ARTICLE.
12233 If ARTICLE is nil FOLDER is shown. If the configuration variable
12234 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12235 ARTICLE is searched in all folders. Indexed searches (swish++,
12236 namazu, and others supported by MH-E) will always search in all
12237 folders."
12238 (require 'mh-e)
12239 (require 'mh-search)
12240 (require 'mh-utils)
12241 (mh-find-path)
12242 (if (not article)
12243 (mh-visit-folder (mh-normalize-folder-name folder))
12244 (setq article (org-add-angle-brackets article))
12245 (mh-search-choose)
12246 (if (equal mh-searcher 'pick)
12247 (progn
12248 (mh-search folder (list "--message-id" article))
12249 (when (and org-mhe-search-all-folders
12250 (not (org-mhe-get-message-real-folder)))
12251 (kill-this-buffer)
12252 (mh-search "+" (list "--message-id" article))))
12253 (mh-search "+" article))
12254 (if (org-mhe-get-message-real-folder)
12255 (mh-show-msg 1)
12256 (kill-this-buffer)
12257 (error "Message not found"))))
12259 ;;; BibTeX links
12261 ;; Use the custom search meachnism to construct and use search strings for
12262 ;; file links to BibTeX database entries.
12264 (defun org-create-file-search-in-bibtex ()
12265 "Create the search string and description for a BibTeX database entry."
12266 (when (eq major-mode 'bibtex-mode)
12267 ;; yes, we want to construct this search string.
12268 ;; Make a good description for this entry, using names, year and the title
12269 ;; Put it into the `description' variable which is dynamically scoped.
12270 (let ((bibtex-autokey-names 1)
12271 (bibtex-autokey-names-stretch 1)
12272 (bibtex-autokey-name-case-convert-function 'identity)
12273 (bibtex-autokey-name-separator " & ")
12274 (bibtex-autokey-additional-names " et al.")
12275 (bibtex-autokey-year-length 4)
12276 (bibtex-autokey-name-year-separator " ")
12277 (bibtex-autokey-titlewords 3)
12278 (bibtex-autokey-titleword-separator " ")
12279 (bibtex-autokey-titleword-case-convert-function 'identity)
12280 (bibtex-autokey-titleword-length 'infty)
12281 (bibtex-autokey-year-title-separator ": "))
12282 (setq description (bibtex-generate-autokey)))
12283 ;; Now parse the entry, get the key and return it.
12284 (save-excursion
12285 (bibtex-beginning-of-entry)
12286 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12288 (defun org-execute-file-search-in-bibtex (s)
12289 "Find the link search string S as a key for a database entry."
12290 (when (eq major-mode 'bibtex-mode)
12291 ;; Yes, we want to do the search in this file.
12292 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12293 (goto-char (point-min))
12294 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12295 (regexp-quote s) "[ \t\n]*,") nil t)
12296 (goto-char (match-beginning 0)))
12297 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12298 ;; Use double prefix to indicate that any web link should be browsed
12299 (let ((b (current-buffer)) (p (point)))
12300 ;; Restore the window configuration because we just use the web link
12301 (set-window-configuration org-window-config-before-follow-link)
12302 (save-excursion (set-buffer b) (goto-char p)
12303 (bibtex-url)))
12304 (recenter 0)) ; Move entry start to beginning of window
12305 ;; return t to indicate that the search is done.
12308 ;; Finally add the functions to the right hooks.
12309 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12310 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12312 ;; end of Bibtex link setup
12314 ;;; Following file links
12316 (defun org-open-file (path &optional in-emacs line search)
12317 "Open the file at PATH.
12318 First, this expands any special file name abbreviations. Then the
12319 configuration variable `org-file-apps' is checked if it contains an
12320 entry for this file type, and if yes, the corresponding command is launched.
12321 If no application is found, Emacs simply visits the file.
12322 With optional argument IN-EMACS, Emacs will visit the file.
12323 Optional LINE specifies a line to go to, optional SEARCH a string to
12324 search for. If LINE or SEARCH is given, the file will always be
12325 opened in Emacs.
12326 If the file does not exist, an error is thrown."
12327 (setq in-emacs (or in-emacs line search))
12328 (let* ((file (if (equal path "")
12329 buffer-file-name
12330 (substitute-in-file-name (expand-file-name path))))
12331 (apps (append org-file-apps (org-default-apps)))
12332 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12333 (dirp (if remp nil (file-directory-p file)))
12334 (dfile (downcase file))
12335 (old-buffer (current-buffer))
12336 (old-pos (point))
12337 (old-mode major-mode)
12338 ext cmd)
12339 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12340 (setq ext (match-string 1 dfile))
12341 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12342 (setq ext (match-string 1 dfile))))
12343 (if in-emacs
12344 (setq cmd 'emacs)
12345 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12346 (and dirp (cdr (assoc 'directory apps)))
12347 (cdr (assoc ext apps))
12348 (cdr (assoc t apps)))))
12349 (when (eq cmd 'mailcap)
12350 (require 'mailcap)
12351 (mailcap-parse-mailcaps)
12352 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12353 (command (mailcap-mime-info mime-type)))
12354 (if (stringp command)
12355 (setq cmd command)
12356 (setq cmd 'emacs))))
12357 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12358 (not (file-exists-p file))
12359 (not org-open-non-existing-files))
12360 (error "No such file: %s" file))
12361 (cond
12362 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12363 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12364 (if (string-match "['\"]%s['\"]" cmd)
12365 (setq cmd (replace-match "%s" t t cmd)))
12366 (setq cmd (format cmd (shell-quote-argument file)))
12367 (save-window-excursion
12368 (start-process-shell-command cmd nil cmd)))
12369 ((or (stringp cmd)
12370 (eq cmd 'emacs))
12371 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12372 (widen)
12373 (if line (goto-line line)
12374 (if search (org-link-search search))))
12375 ((consp cmd)
12376 (eval cmd))
12377 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12378 (and (org-mode-p) (eq old-mode 'org-mode)
12379 (or (not (equal old-buffer (current-buffer)))
12380 (not (equal old-pos (point))))
12381 (org-mark-ring-push old-pos old-buffer))))
12383 (defun org-default-apps ()
12384 "Return the default applications for this operating system."
12385 (cond
12386 ((eq system-type 'darwin)
12387 org-file-apps-defaults-macosx)
12388 ((eq system-type 'windows-nt)
12389 org-file-apps-defaults-windowsnt)
12390 (t org-file-apps-defaults-gnu)))
12392 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12393 (defun org-file-remote-p (file)
12394 "Test whether FILE specifies a location on a remote system.
12395 Return non-nil if the location is indeed remote.
12397 For example, the filename \"/user@host:/foo\" specifies a location
12398 on the system \"/user@host:\"."
12399 (cond ((fboundp 'file-remote-p)
12400 (file-remote-p file))
12401 ((fboundp 'tramp-handle-file-remote-p)
12402 (tramp-handle-file-remote-p file))
12403 ((and (boundp 'ange-ftp-name-format)
12404 (string-match (car ange-ftp-name-format) file))
12406 (t nil)))
12409 ;;;; Hooks for remember.el
12411 ;;;###autoload
12412 (defun org-remember-annotation ()
12413 "Return a link to the current location as an annotation for remember.el.
12414 If you are using Org-mode files as target for data storage with
12415 remember.el, then the annotations should include a link compatible with the
12416 conventions in Org-mode. This function returns such a link."
12417 (org-store-link nil))
12419 (defconst org-remember-help
12420 "Select a destination location for the note.
12421 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12422 RET on headline -> Store as sublevel entry to current headline
12423 RET at beg-of-buf -> Append to file as level 2 headline
12424 <left>/<right> -> before/after current headline, same headings level")
12426 (defvar org-remember-previous-location nil)
12427 (defvar org-force-remember-template-char) ;; dynamically scoped
12429 ;;;###autoload
12430 (defun org-remember-apply-template (&optional use-char skip-interactive)
12431 "Initialize *remember* buffer with template, invoke `org-mode'.
12432 This function should be placed into `remember-mode-hook' and in fact requires
12433 to be run from that hook to fucntion properly."
12434 (if org-remember-templates
12436 (let* ((char (or use-char
12437 (cond
12438 ((= (length org-remember-templates) 1)
12439 (caar org-remember-templates))
12440 ((and (boundp 'org-force-remember-template-char)
12441 org-force-remember-template-char)
12442 (if (string-p org-force-remember-template-char)
12443 (string-to-char org-force-remember-template-char)
12444 org-force-remember-template-char))
12446 (message "Select template: %s"
12447 (mapconcat
12448 (lambda (x) (char-to-string (car x)))
12449 org-remember-templates " "))
12450 (read-char-exclusive)))))
12451 (entry (cdr (assoc char org-remember-templates)))
12452 (tpl (car entry))
12453 (plist-p (if org-store-link-plist t nil))
12454 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12455 (string-match "\\S-" (nth 1 entry)))
12456 (nth 1 entry)
12457 org-default-notes-file))
12458 (headline (nth 2 entry))
12459 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12460 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12461 (v-u (concat "[" (substring v-t 1 -1) "]"))
12462 (v-U (concat "[" (substring v-T 1 -1) "]"))
12463 (v-i initial) ; defined in `remember-mode'
12464 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
12465 (v-A (if (and v-a
12466 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12467 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12468 v-a))
12469 (v-n user-full-name)
12470 (org-startup-folded nil)
12471 org-time-was-given org-end-time-was-given x prompt char time)
12472 (setq org-store-link-plist
12473 (append (list :annotation v-a :initial v-i)
12474 org-store-link-plist))
12475 (unless tpl (setq tpl "") (message "No template") (ding))
12476 (erase-buffer)
12477 (insert (substitute-command-keys
12478 (format
12479 "## Filing location: Select interactively, default, or last used:
12480 ## %s to select file and header location interactively.
12481 ## %s \"%s\" -> \"* %s\"
12482 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12483 ## To switch templates, use `\\[org-remember]'.\n\n"
12484 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12485 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12486 (abbreviate-file-name (or file org-default-notes-file))
12487 (or headline "")
12488 (or (car org-remember-previous-location) "???")
12489 (or (cdr org-remember-previous-location) "???"))))
12490 (insert tpl) (goto-char (point-min))
12491 ;; Simple %-escapes
12492 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12493 (when (and initial (equal (match-string 0) "%i"))
12494 (save-match-data
12495 (let* ((lead (buffer-substring
12496 (point-at-bol) (match-beginning 0))))
12497 (setq v-i (mapconcat 'identity
12498 (org-split-string initial "\n")
12499 (concat "\n" lead))))))
12500 (replace-match
12501 (or (eval (intern (concat "v-" (match-string 1)))) "")
12502 t t))
12503 ;; From the property list
12504 (when plist-p
12505 (goto-char (point-min))
12506 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12507 (and (setq x (plist-get org-store-link-plist
12508 (intern (match-string 1))))
12509 (replace-match x t t))))
12510 ;; Turn on org-mode in the remember buffer, set local variables
12511 (org-mode)
12512 (org-set-local 'org-finish-function 'remember-buffer)
12513 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12514 (org-set-local 'org-default-notes-file file))
12515 (if (and headline (stringp headline) (string-match "\\S-" headline))
12516 (org-set-local 'org-remember-default-headline headline))
12517 ;; Interactive template entries
12518 (goto-char (point-min))
12519 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12520 (setq char (if (match-end 3) (match-string 3))
12521 prompt (if (match-end 2) (match-string 2)))
12522 (goto-char (match-beginning 0))
12523 (replace-match "")
12524 (cond
12525 ((member char '("G" "g"))
12526 (let* ((org-last-tags-completion-table
12527 (org-global-tags-completion-table
12528 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12529 (org-add-colon-after-tag-completion t)
12530 (ins (completing-read
12531 (if prompt (concat prompt ": ") "Tags: ")
12532 'org-tags-completion-function nil nil nil
12533 'org-tags-history)))
12534 (setq ins (mapconcat 'identity
12535 (org-split-string ins (org-re "[^[:alnum:]]+"))
12536 ":"))
12537 (when (string-match "\\S-" ins)
12538 (or (equal (char-before) ?:) (insert ":"))
12539 (insert ins)
12540 (or (equal (char-after) ?:) (insert ":")))))
12541 (char
12542 (setq org-time-was-given (equal (upcase char) char))
12543 (setq time (org-read-date (equal (upcase char) "U") t nil
12544 prompt))
12545 (org-insert-time-stamp time org-time-was-given
12546 (member char '("u" "U"))
12547 nil nil (list org-end-time-was-given)))
12549 (insert (read-string
12550 (if prompt (concat prompt ": ") "Enter string"))))))
12551 (goto-char (point-min))
12552 (if (re-search-forward "%\\?" nil t)
12553 (replace-match "")
12554 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12555 (org-mode)
12556 (org-set-local 'org-finish-function 'remember-buffer)))
12558 ;;;###autoload
12559 (defun org-remember (&optional org-force-remember-template-char)
12560 "Call `remember'. If this is already a remember buffer, re-apply template.
12561 If there is an active region, make sure remember uses it as initial content
12562 of the remember buffer."
12563 (interactive)
12564 (if (eq org-finish-function 'remember-buffer)
12565 (progn
12566 (when (< (length org-remember-templates) 2)
12567 (error "No other template available"))
12568 (erase-buffer)
12569 (let ((annotation (plist-get org-store-link-plist :annotation))
12570 (initial (plist-get org-store-link-plist :initial)))
12571 (org-remember-apply-template))
12572 (message "Press C-c C-c to remember data"))
12573 (if (org-region-active-p)
12574 (remember (buffer-substring (point) (mark)))
12575 (call-interactively 'remember))))
12577 ;;;###autoload
12578 (defun org-remember-handler ()
12579 "Store stuff from remember.el into an org file.
12580 First prompts for an org file. If the user just presses return, the value
12581 of `org-default-notes-file' is used.
12582 Then the command offers the headings tree of the selected file in order to
12583 file the text at a specific location.
12584 You can either immediately press RET to get the note appended to the
12585 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12586 find a better place. Then press RET or <left> or <right> in insert the note.
12588 Key Cursor position Note gets inserted
12589 -----------------------------------------------------------------------------
12590 RET buffer-start as level 1 heading at end of file
12591 RET on headline as sublevel of the heading at cursor
12592 RET no heading at cursor position, level taken from context.
12593 Or use prefix arg to specify level manually.
12594 <left> on headline as same level, before current heading
12595 <right> on headline as same level, after current heading
12597 So the fastest way to store the note is to press RET RET to append it to
12598 the default file. This way your current train of thought is not
12599 interrupted, in accordance with the principles of remember.el.
12600 You can also get the fast execution without prompting by using
12601 C-u C-c C-c to exit the remember buffer. See also the variable
12602 `org-remember-store-without-prompt'.
12604 Before being stored away, the function ensures that the text has a
12605 headline, i.e. a first line that starts with a \"*\". If not, a headline
12606 is constructed from the current date and some additional data.
12608 If the variable `org-adapt-indentation' is non-nil, the entire text is
12609 also indented so that it starts in the same column as the headline
12610 \(i.e. after the stars).
12612 See also the variable `org-reverse-note-order'."
12613 (goto-char (point-min))
12614 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12615 (replace-match ""))
12616 (goto-char (point-max))
12617 (unless (equal (char-before) ?\n) (insert "\n"))
12618 (catch 'quit
12619 (let* ((txt (buffer-substring (point-min) (point-max)))
12620 (fastp (org-xor (equal current-prefix-arg '(4))
12621 org-remember-store-without-prompt))
12622 (file (if fastp org-default-notes-file (org-get-org-file)))
12623 (heading org-remember-default-headline)
12624 (visiting (org-find-base-buffer-visiting file))
12625 (org-startup-folded nil)
12626 (org-startup-align-all-tables nil)
12627 (org-goto-start-pos 1)
12628 spos exitcmd level indent reversed)
12629 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12630 (setq file (car org-remember-previous-location)
12631 heading (cdr org-remember-previous-location)))
12632 (setq current-prefix-arg nil)
12633 ;; Modify text so that it becomes a nice subtree which can be inserted
12634 ;; into an org tree.
12635 (let* ((lines (split-string txt "\n"))
12636 first)
12637 (setq first (car lines) lines (cdr lines))
12638 (if (string-match "^\\*+ " first)
12639 ;; Is already a headline
12640 (setq indent nil)
12641 ;; We need to add a headline: Use time and first buffer line
12642 (setq lines (cons first lines)
12643 first (concat "* " (current-time-string)
12644 " (" (remember-buffer-desc) ")")
12645 indent " "))
12646 (if (and org-adapt-indentation indent)
12647 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12648 (setq txt (concat first "\n"
12649 (mapconcat 'identity lines "\n"))))
12650 ;; Find the file
12651 (if (not visiting) (find-file-noselect file))
12652 (with-current-buffer (or visiting (get-file-buffer file))
12653 (unless (org-mode-p)
12654 (error "Target files for remember notes must be in Org-mode"))
12655 (save-excursion
12656 (save-restriction
12657 (widen)
12658 (and (goto-char (point-min))
12659 (not (re-search-forward "^\\* " nil t))
12660 (insert "\n* " (or heading "Notes") "\n"))
12661 (setq reversed (org-notes-order-reversed-p))
12663 ;; Find the default location
12664 (when (and heading (stringp heading) (string-match "\\S-" heading))
12665 (goto-char (point-min))
12666 (if (re-search-forward
12667 (concat "^\\*+[ \t]+" (regexp-quote heading)
12668 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12669 nil t)
12670 (setq org-goto-start-pos (match-beginning 0))
12671 (when fastp
12672 (goto-char (point-max))
12673 (unless (bolp) (newline))
12674 (insert "* " heading "\n")
12675 (setq org-goto-start-pos (point-at-bol 0)))))
12677 ;; Ask the User for a location
12678 (if fastp
12679 (setq spos org-goto-start-pos
12680 exitcmd 'return)
12681 (setq spos (org-get-location (current-buffer) org-remember-help)
12682 exitcmd (cdr spos)
12683 spos (car spos)))
12684 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12685 ; not handle this note
12686 (goto-char spos)
12687 (cond ((org-on-heading-p t)
12688 (org-back-to-heading t)
12689 (setq level (funcall outline-level))
12690 (cond
12691 ((eq exitcmd 'return)
12692 ;; sublevel of current
12693 (setq org-remember-previous-location
12694 (cons (abbreviate-file-name file)
12695 (org-get-heading 'notags)))
12696 (if reversed
12697 (outline-next-heading)
12698 (org-end-of-subtree)
12699 (if (not (bolp))
12700 (if (looking-at "[ \t]*\n")
12701 (beginning-of-line 2)
12702 (end-of-line 1)
12703 (insert "\n"))))
12704 (org-paste-subtree (org-get-legal-level level 1) txt))
12705 ((eq exitcmd 'left)
12706 ;; before current
12707 (org-paste-subtree level txt))
12708 ((eq exitcmd 'right)
12709 ;; after current
12710 (org-end-of-subtree t)
12711 (org-paste-subtree level txt))
12712 (t (error "This should not happen"))))
12714 ((and (bobp) (not reversed))
12715 ;; Put it at the end, one level below level 1
12716 (save-restriction
12717 (widen)
12718 (goto-char (point-max))
12719 (if (not (bolp)) (newline))
12720 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12722 ((and (bobp) reversed)
12723 ;; Put it at the start, as level 1
12724 (save-restriction
12725 (widen)
12726 (goto-char (point-min))
12727 (re-search-forward "^\\*+ " nil t)
12728 (beginning-of-line 1)
12729 (org-paste-subtree 1 txt)))
12731 ;; Put it right there, with automatic level determined by
12732 ;; org-paste-subtree or from prefix arg
12733 (org-paste-subtree
12734 (if (numberp current-prefix-arg) current-prefix-arg)
12735 txt)))
12736 (when remember-save-after-remembering
12737 (save-buffer)
12738 (if (not visiting) (kill-buffer (current-buffer)))))))))
12739 t) ;; return t to indicate that we took care of this note.
12741 (defun org-get-org-file ()
12742 "Read a filename, with default directory `org-directory'."
12743 (let ((default (or org-default-notes-file remember-data-file)))
12744 (read-file-name (format "File name [%s]: " default)
12745 (file-name-as-directory org-directory)
12746 default)))
12748 (defun org-notes-order-reversed-p ()
12749 "Check if the current file should receive notes in reversed order."
12750 (cond
12751 ((not org-reverse-note-order) nil)
12752 ((eq t org-reverse-note-order) t)
12753 ((not (listp org-reverse-note-order)) nil)
12754 (t (catch 'exit
12755 (let ((all org-reverse-note-order)
12756 entry)
12757 (while (setq entry (pop all))
12758 (if (string-match (car entry) buffer-file-name)
12759 (throw 'exit (cdr entry))))
12760 nil)))))
12762 ;;;; Dynamic blocks
12764 (defun org-find-dblock (name)
12765 "Find the first dynamic block with name NAME in the buffer.
12766 If not found, stay at current position and return nil."
12767 (let (pos)
12768 (save-excursion
12769 (goto-char (point-min))
12770 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12771 nil t)
12772 (match-beginning 0))))
12773 (if pos (goto-char pos))
12774 pos))
12776 (defconst org-dblock-start-re
12777 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12778 "Matches the startline of a dynamic block, with parameters.")
12780 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12781 "Matches the end of a dyhamic block.")
12783 (defun org-create-dblock (plist)
12784 "Create a dynamic block section, with parameters taken from PLIST.
12785 PLIST must containe a :name entry which is used as name of the block."
12786 (unless (bolp) (newline))
12787 (let ((name (plist-get plist :name)))
12788 (insert "#+BEGIN: " name)
12789 (while plist
12790 (if (eq (car plist) :name)
12791 (setq plist (cddr plist))
12792 (insert " " (prin1-to-string (pop plist)))))
12793 (insert "\n\n#+END:\n")
12794 (beginning-of-line -2)))
12796 (defun org-prepare-dblock ()
12797 "Prepare dynamic block for refresh.
12798 This empties the block, puts the cursor at the insert position and returns
12799 the property list including an extra property :name with the block name."
12800 (unless (looking-at org-dblock-start-re)
12801 (error "Not at a dynamic block"))
12802 (let* ((begdel (1+ (match-end 0)))
12803 (name (org-no-properties (match-string 1)))
12804 (params (append (list :name name)
12805 (read (concat "(" (match-string 3) ")")))))
12806 (unless (re-search-forward org-dblock-end-re nil t)
12807 (error "Dynamic block not terminated"))
12808 (delete-region begdel (match-beginning 0))
12809 (goto-char begdel)
12810 (open-line 1)
12811 params))
12813 (defun org-map-dblocks (&optional command)
12814 "Apply COMMAND to all dynamic blocks in the current buffer.
12815 If COMMAND is not given, use `org-update-dblock'."
12816 (let ((cmd (or command 'org-update-dblock))
12817 pos)
12818 (save-excursion
12819 (goto-char (point-min))
12820 (while (re-search-forward org-dblock-start-re nil t)
12821 (goto-char (setq pos (match-beginning 0)))
12822 (condition-case nil
12823 (funcall cmd)
12824 (error (message "Error during update of dynamic block")))
12825 (goto-char pos)
12826 (unless (re-search-forward org-dblock-end-re nil t)
12827 (error "Dynamic block not terminated"))))))
12829 (defun org-dblock-update (&optional arg)
12830 "User command for updating dynamic blocks.
12831 Update the dynamic block at point. With prefix ARG, update all dynamic
12832 blocks in the buffer."
12833 (interactive "P")
12834 (if arg
12835 (org-update-all-dblocks)
12836 (or (looking-at org-dblock-start-re)
12837 (org-beginning-of-dblock))
12838 (org-update-dblock)))
12840 (defun org-update-dblock ()
12841 "Update the dynamic block at point
12842 This means to empty the block, parse for parameters and then call
12843 the correct writing function."
12844 (save-window-excursion
12845 (let* ((pos (point))
12846 (line (org-current-line))
12847 (params (org-prepare-dblock))
12848 (name (plist-get params :name))
12849 (cmd (intern (concat "org-dblock-write:" name))))
12850 (message "Updating dynamic block `%s' at line %d..." name line)
12851 (funcall cmd params)
12852 (message "Updating dynamic block `%s' at line %d...done" name line)
12853 (goto-char pos))))
12855 (defun org-beginning-of-dblock ()
12856 "Find the beginning of the dynamic block at point.
12857 Error if there is no scuh block at point."
12858 (let ((pos (point))
12859 beg)
12860 (end-of-line 1)
12861 (if (and (re-search-backward org-dblock-start-re nil t)
12862 (setq beg (match-beginning 0))
12863 (re-search-forward org-dblock-end-re nil t)
12864 (> (match-end 0) pos))
12865 (goto-char beg)
12866 (goto-char pos)
12867 (error "Not in a dynamic block"))))
12869 (defun org-update-all-dblocks ()
12870 "Update all dynamic blocks in the buffer.
12871 This function can be used in a hook."
12872 (when (org-mode-p)
12873 (org-map-dblocks 'org-update-dblock)))
12876 ;;;; Completion
12878 (defconst org-additional-option-like-keywords
12879 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
12880 "ORGTBL" "HTML:" "LaTeX:"))
12882 (defun org-complete (&optional arg)
12883 "Perform completion on word at point.
12884 At the beginning of a headline, this completes TODO keywords as given in
12885 `org-todo-keywords'.
12886 If the current word is preceded by a backslash, completes the TeX symbols
12887 that are supported for HTML support.
12888 If the current word is preceded by \"#+\", completes special words for
12889 setting file options.
12890 In the line after \"#+STARTUP:, complete valid keywords.\"
12891 At all other locations, this simply calls the value of
12892 `org-completion-fallback-command'."
12893 (interactive "P")
12894 (org-without-partial-completion
12895 (catch 'exit
12896 (let* ((end (point))
12897 (beg1 (save-excursion
12898 (skip-chars-backward (org-re "[:alnum:]_@"))
12899 (point)))
12900 (beg (save-excursion
12901 (skip-chars-backward "a-zA-Z0-9_:$")
12902 (point)))
12903 (confirm (lambda (x) (stringp (car x))))
12904 (searchhead (equal (char-before beg) ?*))
12905 (tag (and (equal (char-before beg1) ?:)
12906 (equal (char-after (point-at-bol)) ?*)))
12907 (prop (and (equal (char-before beg1) ?:)
12908 (not (equal (char-after (point-at-bol)) ?*))))
12909 (texp (equal (char-before beg) ?\\))
12910 (link (equal (char-before beg) ?\[))
12911 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12912 beg)
12913 "#+"))
12914 (startup (string-match "^#\\+STARTUP:.*"
12915 (buffer-substring (point-at-bol) (point))))
12916 (completion-ignore-case opt)
12917 (type nil)
12918 (tbl nil)
12919 (table (cond
12920 (opt
12921 (setq type :opt)
12922 (append
12923 (mapcar
12924 (lambda (x)
12925 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12926 (cons (match-string 2 x) (match-string 1 x)))
12927 (org-split-string (org-get-current-options) "\n"))
12928 (mapcar 'list org-additional-option-like-keywords)))
12929 (startup
12930 (setq type :startup)
12931 org-startup-options)
12932 (link (append org-link-abbrev-alist-local
12933 org-link-abbrev-alist))
12934 (texp
12935 (setq type :tex)
12936 org-html-entities)
12937 ((string-match "\\`\\*+[ \t]+\\'"
12938 (buffer-substring (point-at-bol) beg))
12939 (setq type :todo)
12940 (mapcar 'list org-todo-keywords-1))
12941 (searchhead
12942 (setq type :searchhead)
12943 (save-excursion
12944 (goto-char (point-min))
12945 (while (re-search-forward org-todo-line-regexp nil t)
12946 (push (list
12947 (org-make-org-heading-search-string
12948 (match-string 3) t))
12949 tbl)))
12950 tbl)
12951 (tag (setq type :tag beg beg1)
12952 (or org-tag-alist (org-get-buffer-tags)))
12953 (prop (setq type :prop beg beg1)
12954 (mapcar 'list (org-buffer-property-keys)))
12955 (t (progn
12956 (call-interactively org-completion-fallback-command)
12957 (throw 'exit nil)))))
12958 (pattern (buffer-substring-no-properties beg end))
12959 (completion (try-completion pattern table confirm)))
12960 (cond ((eq completion t)
12961 (if (not (assoc (upcase pattern) table))
12962 (message "Already complete")
12963 (if (equal type :opt)
12964 (insert (substring (cdr (assoc (upcase pattern) table))
12965 (length pattern)))
12966 (if (memq type '(:tag :prop)) (insert ":")))))
12967 ((null completion)
12968 (message "Can't find completion for \"%s\"" pattern)
12969 (ding))
12970 ((not (string= pattern completion))
12971 (delete-region beg end)
12972 (if (string-match " +$" completion)
12973 (setq completion (replace-match "" t t completion)))
12974 (insert completion)
12975 (if (get-buffer-window "*Completions*")
12976 (delete-window (get-buffer-window "*Completions*")))
12977 (if (assoc completion table)
12978 (if (eq type :todo) (insert " ")
12979 (if (memq type '(:tag :prop)) (insert ":"))))
12980 (if (and (equal type :opt) (assoc completion table))
12981 (message "%s" (substitute-command-keys
12982 "Press \\[org-complete] again to insert example settings"))))
12984 (message "Making completion list...")
12985 (let ((list (sort (all-completions pattern table confirm)
12986 'string<)))
12987 (with-output-to-temp-buffer "*Completions*"
12988 (condition-case nil
12989 ;; Protection needed for XEmacs and emacs 21
12990 (display-completion-list list pattern)
12991 (error (display-completion-list list)))))
12992 (message "Making completion list...%s" "done")))))))
12994 ;;;; TODO, DEADLINE, Comments
12996 (defun org-toggle-comment ()
12997 "Change the COMMENT state of an entry."
12998 (interactive)
12999 (save-excursion
13000 (org-back-to-heading)
13001 (if (looking-at (concat outline-regexp
13002 "\\( *\\<" org-comment-string "\\>\\)"))
13003 (replace-match "" t t nil 1)
13004 (if (looking-at outline-regexp)
13005 (progn
13006 (goto-char (match-end 0))
13007 (insert org-comment-string " "))))))
13009 (defvar org-last-todo-state-is-todo nil
13010 "This is non-nil when the last TODO state change led to a TODO state.
13011 If the last change removed the TODO tag or switched to DONE, then
13012 this is nil.")
13014 (defvar org-setting-tags nil) ; dynamically skiped
13016 ;; FIXME: better place
13017 (defun org-property-or-variable-value (var &optional inherit)
13018 "Check if there is a property fixing the value of VAR.
13019 If yes, return this value. If not, return the current value of the variable."
13020 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13021 (if (and prop (stringp prop) (string-match "\\S-" prop))
13022 (read prop)
13023 (symbol-value var))))
13025 (defun org-todo (&optional arg)
13026 "Change the TODO state of an item.
13027 The state of an item is given by a keyword at the start of the heading,
13028 like
13029 *** TODO Write paper
13030 *** DONE Call mom
13032 The different keywords are specified in the variable `org-todo-keywords'.
13033 By default the available states are \"TODO\" and \"DONE\".
13034 So for this example: when the item starts with TODO, it is changed to DONE.
13035 When it starts with DONE, the DONE is removed. And when neither TODO nor
13036 DONE are present, add TODO at the beginning of the heading.
13038 With C-u prefix arg, use completion to determine the new state.
13039 With numeric prefix arg, switch to that state.
13041 For calling through lisp, arg is also interpreted in the following way:
13042 'none -> empty state
13043 \"\"(empty string) -> switch to empty state
13044 'done -> switch to DONE
13045 'nextset -> switch to the next set of keywords
13046 'previousset -> switch to the previous set of keywords
13047 \"WAITING\" -> switch to the specified keyword, but only if it
13048 really is a member of `org-todo-keywords'."
13049 (interactive "P")
13050 (save-excursion
13051 (org-back-to-heading)
13052 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13053 (or (looking-at (concat " +" org-todo-regexp " *"))
13054 (looking-at " *"))
13055 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
13056 (org-log-done (org-parse-local-options logging 'org-log-done))
13057 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13058 (this (match-string 1))
13059 (hl-pos (match-beginning 0))
13060 (head (org-get-todo-sequence-head this))
13061 (ass (assoc head org-todo-kwd-alist))
13062 (interpret (nth 1 ass))
13063 (done-word (nth 3 ass))
13064 (final-done-word (nth 4 ass))
13065 (last-state (or this ""))
13066 (completion-ignore-case t)
13067 (member (member this org-todo-keywords-1))
13068 (tail (cdr member))
13069 (state (cond
13070 ((and org-todo-key-trigger
13071 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13072 (and (not arg) org-use-fast-todo-selection
13073 (not (eq org-use-fast-todo-selection 'prefix)))))
13074 ;; Use fast selection
13075 (org-fast-todo-selection))
13076 ((and (equal arg '(4))
13077 (or (not org-use-fast-todo-selection)
13078 (not org-todo-key-trigger)))
13079 ;; Read a state with completion
13080 (completing-read "State: " (mapcar (lambda(x) (list x))
13081 org-todo-keywords-1)
13082 nil t))
13083 ((eq arg 'right)
13084 (if this
13085 (if tail (car tail) nil)
13086 (car org-todo-keywords-1)))
13087 ((eq arg 'left)
13088 (if (equal member org-todo-keywords-1)
13090 (if this
13091 (nth (- (length org-todo-keywords-1) (length tail) 2)
13092 org-todo-keywords-1)
13093 (org-last org-todo-keywords-1))))
13094 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13095 (setq arg nil))) ; hack to fall back to cycling
13096 (arg
13097 ;; user or caller requests a specific state
13098 (cond
13099 ((equal arg "") nil)
13100 ((eq arg 'none) nil)
13101 ((eq arg 'done) (or done-word (car org-done-keywords)))
13102 ((eq arg 'nextset)
13103 (or (car (cdr (member head org-todo-heads)))
13104 (car org-todo-heads)))
13105 ((eq arg 'previousset)
13106 (let ((org-todo-heads (reverse org-todo-heads)))
13107 (or (car (cdr (member head org-todo-heads)))
13108 (car org-todo-heads))))
13109 ((car (member arg org-todo-keywords-1)))
13110 ((nth (1- (prefix-numeric-value arg))
13111 org-todo-keywords-1))))
13112 ((null member) (or head (car org-todo-keywords-1)))
13113 ((equal this final-done-word) nil) ;; -> make empty
13114 ((null tail) nil) ;; -> first entry
13115 ((eq interpret 'sequence)
13116 (car tail))
13117 ((memq interpret '(type priority))
13118 (if (eq this-command last-command)
13119 (car tail)
13120 (if (> (length tail) 0)
13121 (or done-word (car org-done-keywords))
13122 nil)))
13123 (t nil)))
13124 (next (if state (concat " " state " ") " "))
13125 dostates)
13126 (replace-match next t t)
13127 (unless (pos-visible-in-window-p hl-pos)
13128 (message "TODO state changed to %s" (org-trim next)))
13129 (unless head
13130 (setq head (org-get-todo-sequence-head state)
13131 ass (assoc head org-todo-kwd-alist)
13132 interpret (nth 1 ass)
13133 done-word (nth 3 ass)
13134 final-done-word (nth 4 ass)))
13135 (when (memq arg '(nextset previousset))
13136 (message "Keyword-Set %d/%d: %s"
13137 (- (length org-todo-sets) -1
13138 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13139 (length org-todo-sets)
13140 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13141 (setq org-last-todo-state-is-todo
13142 (not (member state org-done-keywords)))
13143 (when (and org-log-done (not (memq arg '(nextset previousset))))
13144 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13145 (or (not org-todo-log-states)
13146 (member state org-todo-log-states))))
13148 (cond
13149 ((and state (member state org-not-done-keywords)
13150 (not (member this org-not-done-keywords)))
13151 ;; This is now a todo state and was not one before
13152 ;; Remove any CLOSED timestamp, and possibly log the state change
13153 (org-add-planning-info nil nil 'closed)
13154 (and dostates (org-add-log-maybe 'state state 'findpos)))
13155 ((and state dostates)
13156 ;; This is a non-nil state, and we need to log it
13157 (org-add-log-maybe 'state state 'findpos))
13158 ((and (member state org-done-keywords)
13159 (not (member this org-done-keywords)))
13160 ;; It is now done, and it was not done before
13161 (org-add-planning-info 'closed (org-current-time))
13162 (org-add-log-maybe 'done state 'findpos))))
13163 ;; Fixup tag positioning
13164 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13165 (run-hooks 'org-after-todo-state-change-hook)
13166 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13167 (if (and arg (not (member state org-done-keywords)))
13168 (setq head (org-get-todo-sequence-head state)))
13169 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
13170 ;; Fixup cursor location if close to the keyword
13171 (if (and (outline-on-heading-p)
13172 (not (bolp))
13173 (save-excursion (beginning-of-line 1)
13174 (looking-at org-todo-line-regexp))
13175 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13176 (progn
13177 (goto-char (or (match-end 2) (match-end 1)))
13178 (just-one-space))))
13180 (defun org-get-todo-sequence-head (kwd)
13181 "Return the head of the TODO sequence to which KWD belongs.
13182 If KWD is not set, check if there is a text property remembering the
13183 right sequence."
13184 (let (p)
13185 (cond
13186 ((not kwd)
13187 (or (get-text-property (point-at-bol) 'org-todo-head)
13188 (progn
13189 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13190 nil (point-at-eol)))
13191 (get-text-property p 'org-todo-head))))
13192 ((not (member kwd org-todo-keywords-1))
13193 (car org-todo-keywords-1))
13194 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13196 (defun org-fast-todo-selection ()
13197 "Fast TODO keyword selection with single keys.
13198 Returns the new TODO keyword, or nil if no state change should occur."
13199 (let* ((fulltable org-todo-key-alist)
13200 (done-keywords org-done-keywords) ;; needed for the faces.
13201 (maxlen (apply 'max (mapcar
13202 (lambda (x)
13203 (if (stringp (car x)) (string-width (car x)) 0))
13204 fulltable)))
13205 (buf (current-buffer))
13206 (expert nil)
13207 (fwidth (+ maxlen 3 1 3))
13208 (ncol (/ (- (window-width) 4) fwidth))
13209 tg cnt e c char c1 c2 ntable tbl rtn
13210 groups ingroup)
13211 (save-window-excursion
13212 (if expert
13213 (set-buffer (get-buffer-create " *Org todo*"))
13214 ; (delete-other-windows)
13215 ; (split-window-vertically)
13216 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13217 (erase-buffer)
13218 (org-set-local 'org-done-keywords done-keywords)
13219 (setq tbl fulltable char ?a cnt 0)
13220 (while (setq e (pop tbl))
13221 (cond
13222 ((equal e '(:startgroup))
13223 (push '() groups) (setq ingroup t)
13224 (when (not (= cnt 0))
13225 (setq cnt 0)
13226 (insert "\n"))
13227 (insert "{ "))
13228 ((equal e '(:endgroup))
13229 (setq ingroup nil cnt 0)
13230 (insert "}\n"))
13232 (setq tg (car e) c (cdr e))
13233 (if ingroup (push tg (car groups)))
13234 (setq tg (org-add-props tg nil 'face
13235 (org-get-todo-face tg)))
13236 (if (and (= cnt 0) (not ingroup)) (insert " "))
13237 (insert "[" c "] " tg (make-string
13238 (- fwidth 4 (length tg)) ?\ ))
13239 (when (= (setq cnt (1+ cnt)) ncol)
13240 (insert "\n")
13241 (if ingroup (insert " "))
13242 (setq cnt 0)))))
13243 (insert "\n")
13244 (goto-char (point-min))
13245 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13246 (fit-window-to-buffer))
13247 (message "[a-z..]:Set [SPC]:clear")
13248 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13249 (cond
13250 ((or (= c ?\C-g)
13251 (and (= c ?q) (not (rassoc c fulltable))))
13252 (setq quit-flag t))
13253 ((= c ?\ ) nil)
13254 ((setq e (rassoc c fulltable) tg (car e))
13256 (t (setq quit-flag t))))))
13258 (defun org-get-repeat ()
13259 "Check if tere is a deadline/schedule with repeater in this entry."
13260 (save-match-data
13261 (save-excursion
13262 (org-back-to-heading t)
13263 (if (re-search-forward
13264 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13265 (match-string 1)))))
13267 (defvar org-last-changed-timestamp)
13268 (defvar org-log-post-message)
13269 (defun org-auto-repeat-maybe ()
13270 "Check if the current headline contains a repeated deadline/schedule.
13271 If yes, set TODO state back to what it was and change the base date
13272 of repeating deadline/scheduled time stamps to new date.
13273 This function should be run in the `org-after-todo-state-change-hook'."
13274 ;; last-state is dynamically scoped into this function
13275 (let* ((repeat (org-get-repeat))
13276 (aa (assoc last-state org-todo-kwd-alist))
13277 (interpret (nth 1 aa))
13278 (head (nth 2 aa))
13279 (done-word (nth 3 aa))
13280 (whata '(("d" . day) ("m" . month) ("y" . year)))
13281 (msg "Entry repeats: ")
13282 (org-log-done)
13283 re type n what ts)
13284 (when repeat
13285 (org-todo (if (eq interpret 'type) last-state head))
13286 (when (and org-log-repeat
13287 (not (memq 'org-add-log-note
13288 (default-value 'post-command-hook))))
13289 ;; Make sure a note is taken
13290 (let ((org-log-done '(done)))
13291 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13292 'findpos)))
13293 (org-back-to-heading t)
13294 (org-add-planning-info nil nil 'closed)
13295 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13296 org-deadline-time-regexp "\\)"))
13297 (while (re-search-forward
13298 re (save-excursion (outline-next-heading) (point)) t)
13299 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13300 ts (match-string (if (match-end 2) 2 4)))
13301 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13302 (setq n (string-to-number (match-string 1 ts))
13303 what (match-string 2 ts))
13304 (if (equal what "w") (setq n (* n 7) what "d"))
13305 (org-timestamp-change n (cdr (assoc what whata))))
13306 (setq msg (concat msg type org-last-changed-timestamp " ")))
13307 (setq org-log-post-message msg)
13308 (message msg))))
13310 (defun org-show-todo-tree (arg)
13311 "Make a compact tree which shows all headlines marked with TODO.
13312 The tree will show the lines where the regexp matches, and all higher
13313 headlines above the match.
13314 With \\[universal-argument] prefix, also show the DONE entries.
13315 With a numeric prefix N, construct a sparse tree for the Nth element
13316 of `org-todo-keywords-1'."
13317 (interactive "P")
13318 (let ((case-fold-search nil)
13319 (kwd-re
13320 (cond ((null arg) org-not-done-regexp)
13321 ((equal arg '(4))
13322 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13323 (mapcar 'list org-todo-keywords-1))))
13324 (concat "\\("
13325 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13326 "\\)\\>")))
13327 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13328 (regexp-quote (nth (1- (prefix-numeric-value arg))
13329 org-todo-keywords-1)))
13330 (t (error "Invalid prefix argument: %s" arg)))))
13331 (message "%d TODO entries found"
13332 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13334 (defun org-deadline (&optional remove)
13335 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13336 With argument REMOVE, remove any deadline from the item."
13337 (interactive "P")
13338 (if remove
13339 (progn
13340 (org-add-planning-info nil nil 'deadline)
13341 (message "Item no longer has a deadline."))
13342 (org-add-planning-info 'deadline nil 'closed)))
13344 (defun org-schedule (&optional remove)
13345 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13346 With argument REMOVE, remove any scheduling date from the item."
13347 (interactive "P")
13348 (if remove
13349 (progn
13350 (org-add-planning-info nil nil 'scheduled)
13351 (message "Item is no longer scheduled."))
13352 (org-add-planning-info 'scheduled nil 'closed)))
13354 (defun org-add-planning-info (what &optional time &rest remove)
13355 "Insert new timestamp with keyword in the line directly after the headline.
13356 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13357 If non is given, the user is prompted for a date.
13358 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13359 be removed."
13360 (interactive)
13361 (let (org-time-was-given org-end-time-was-given)
13362 (when what (setq time (or time (org-read-date nil 'to-time))))
13363 (when (and org-insert-labeled-timestamps-at-point
13364 (member what '(scheduled deadline)))
13365 (insert
13366 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13367 (org-insert-time-stamp time org-time-was-given
13368 nil nil nil (list org-end-time-was-given))
13369 (setq what nil))
13370 (save-excursion
13371 (save-restriction
13372 (let (col list elt ts buffer-invisibility-spec)
13373 (org-back-to-heading t)
13374 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13375 (goto-char (match-end 1))
13376 (setq col (current-column))
13377 (goto-char (match-end 0))
13378 (if (eobp) (insert "\n"))
13379 (forward-char 1)
13380 (if (and (not (looking-at outline-regexp))
13381 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13382 "[^\r\n]*"))
13383 (not (equal (match-string 1) org-clock-string)))
13384 (narrow-to-region (match-beginning 0) (match-end 0))
13385 (insert-before-markers "\n")
13386 (backward-char 1)
13387 (narrow-to-region (point) (point))
13388 (indent-to-column col))
13389 ;; Check if we have to remove something.
13390 (setq list (cons what remove))
13391 (while list
13392 (setq elt (pop list))
13393 (goto-char (point-min))
13394 (when (or (and (eq elt 'scheduled)
13395 (re-search-forward org-scheduled-time-regexp nil t))
13396 (and (eq elt 'deadline)
13397 (re-search-forward org-deadline-time-regexp nil t))
13398 (and (eq elt 'closed)
13399 (re-search-forward org-closed-time-regexp nil t)))
13400 (replace-match "")
13401 (if (looking-at "--+<[^>]+>") (replace-match ""))
13402 (if (looking-at " +") (replace-match ""))))
13403 (goto-char (point-max))
13404 (when what
13405 (insert
13406 (if (not (equal (char-before) ?\ )) " " "")
13407 (cond ((eq what 'scheduled) org-scheduled-string)
13408 ((eq what 'deadline) org-deadline-string)
13409 ((eq what 'closed) org-closed-string))
13410 " ")
13411 (setq ts (org-insert-time-stamp
13412 time
13413 (or org-time-was-given
13414 (and (eq what 'closed) org-log-done-with-time))
13415 (eq what 'closed)
13416 nil nil (list org-end-time-was-given)))
13417 (end-of-line 1))
13418 (goto-char (point-min))
13419 (widen)
13420 (if (looking-at "[ \t]+\r?\n")
13421 (replace-match ""))
13422 ts)))))
13424 (defvar org-log-note-marker (make-marker))
13425 (defvar org-log-note-purpose nil)
13426 (defvar org-log-note-state nil)
13427 (defvar org-log-note-window-configuration nil)
13428 (defvar org-log-note-return-to (make-marker))
13429 (defvar org-log-post-message nil
13430 "Message to be displayed after a log note has been stored.
13431 The auto-repeater uses this.")
13433 (defun org-add-log-maybe (&optional purpose state findpos)
13434 "Set up the post command hook to take a note."
13435 (save-excursion
13436 (when (and (listp org-log-done)
13437 (memq purpose org-log-done))
13438 (when findpos
13439 (org-back-to-heading t)
13440 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13441 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13442 "[^\r\n]*\\)?"))
13443 (goto-char (match-end 0))
13444 (unless org-log-states-order-reversed
13445 (and (= (char-after) ?\n) (forward-char 1))
13446 (org-skip-over-state-notes)
13447 (skip-chars-backward " \t\n\r")))
13448 (move-marker org-log-note-marker (point))
13449 (setq org-log-note-purpose purpose)
13450 (setq org-log-note-state state)
13451 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13453 (defun org-skip-over-state-notes ()
13454 "Skip past the list of State notes in an entry."
13455 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13456 (while (looking-at "[ \t]*- State")
13457 (condition-case nil
13458 (org-next-item)
13459 (error (org-end-of-item)))))
13461 (defun org-add-log-note (&optional purpose)
13462 "Pop up a window for taking a note, and add this note later at point."
13463 (remove-hook 'post-command-hook 'org-add-log-note)
13464 (setq org-log-note-window-configuration (current-window-configuration))
13465 (delete-other-windows)
13466 (move-marker org-log-note-return-to (point))
13467 (switch-to-buffer (marker-buffer org-log-note-marker))
13468 (goto-char org-log-note-marker)
13469 (org-switch-to-buffer-other-window "*Org Note*")
13470 (erase-buffer)
13471 (let ((org-inhibit-startup t)) (org-mode))
13472 (insert (format "# Insert note for %s, finish with C-c C-c, or cancel with C-u C-c C-c.\n\n"
13473 (cond
13474 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13475 ((eq org-log-note-purpose 'done) "closed todo item")
13476 ((eq org-log-note-purpose 'state) "state change")
13477 (t (error "This should not happen")))))
13478 (org-set-local 'org-finish-function 'org-store-log-note))
13480 (defun org-store-log-note ()
13481 "Finish taking a log note, and insert it to where it belongs."
13482 (let ((txt (buffer-string))
13483 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13484 lines ind)
13485 (kill-buffer (current-buffer))
13486 (if (string-match "^#.*\n[ \t\n]*" txt)
13487 (setq txt (replace-match "" t t txt)))
13488 (if (string-match "\\s-+\\'" txt)
13489 (setq txt (replace-match "" t t txt)))
13490 (setq lines (org-split-string txt "\n"))
13491 (when (and note (string-match "\\S-" note))
13492 (setq note
13493 (org-replace-escapes
13494 note
13495 (list (cons "%u" (user-login-name))
13496 (cons "%U" user-full-name)
13497 (cons "%t" (format-time-string
13498 (org-time-stamp-format 'long 'inactive)
13499 (current-time)))
13500 (cons "%s" (if org-log-note-state
13501 (concat "\"" org-log-note-state "\"")
13502 "")))))
13503 (if lines (setq note (concat note " \\\\")))
13504 (push note lines))
13505 (when current-prefix-arg (setq lines nil))
13506 (when lines
13507 (save-excursion
13508 (set-buffer (marker-buffer org-log-note-marker))
13509 (save-excursion
13510 (goto-char org-log-note-marker)
13511 (move-marker org-log-note-marker nil)
13512 (end-of-line 1)
13513 (if (not (bolp)) (insert "\n")) (indent-relative nil)
13514 (insert " - " (pop lines))
13515 (org-indent-line-function)
13516 (beginning-of-line 1)
13517 (looking-at "[ \t]*")
13518 (setq ind (concat (match-string 0) " "))
13519 (end-of-line 1)
13520 (while lines (insert "\n" ind (pop lines)))))))
13521 (set-window-configuration org-log-note-window-configuration)
13522 (with-current-buffer (marker-buffer org-log-note-return-to)
13523 (goto-char org-log-note-return-to))
13524 (move-marker org-log-note-return-to nil)
13525 (and org-log-post-message (message org-log-post-message)))
13527 (defvar org-occur-highlights nil)
13528 (make-variable-buffer-local 'org-occur-highlights)
13530 (defun org-occur (regexp &optional keep-previous callback)
13531 "Make a compact tree which shows all matches of REGEXP.
13532 The tree will show the lines where the regexp matches, and all higher
13533 headlines above the match. It will also show the heading after the match,
13534 to make sure editing the matching entry is easy.
13535 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13536 call to `org-occur' will be kept, to allow stacking of calls to this
13537 command.
13538 If CALLBACK is non-nil, it is a function which is called to confirm
13539 that the match should indeed be shown."
13540 (interactive "sRegexp: \nP")
13541 (or keep-previous (org-remove-occur-highlights nil nil t))
13542 (let ((cnt 0))
13543 (save-excursion
13544 (goto-char (point-min))
13545 (if (or (not keep-previous) ; do not want to keep
13546 (not org-occur-highlights)) ; no previous matches
13547 ;; hide everything
13548 (org-overview))
13549 (while (re-search-forward regexp nil t)
13550 (when (or (not callback)
13551 (save-match-data (funcall callback)))
13552 (setq cnt (1+ cnt))
13553 (when org-highlight-sparse-tree-matches
13554 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13555 (org-show-context 'occur-tree))))
13556 (when org-remove-highlights-with-change
13557 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13558 nil 'local))
13559 (unless org-sparse-tree-open-archived-trees
13560 (org-hide-archived-subtrees (point-min) (point-max)))
13561 (run-hooks 'org-occur-hook)
13562 (if (interactive-p)
13563 (message "%d match(es) for regexp %s" cnt regexp))
13564 cnt))
13566 (defun org-show-context (&optional key)
13567 "Make sure point and context and visible.
13568 How much context is shown depends upon the variables
13569 `org-show-hierarchy-above', `org-show-following-heading'. and
13570 `org-show-siblings'."
13571 (let ((heading-p (org-on-heading-p t))
13572 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13573 (following-p (org-get-alist-option org-show-following-heading key))
13574 (siblings-p (org-get-alist-option org-show-siblings key)))
13575 (catch 'exit
13576 ;; Show heading or entry text
13577 (if heading-p
13578 (org-flag-heading nil) ; only show the heading
13579 (and (or (org-invisible-p) (org-invisible-p2))
13580 (org-show-hidden-entry))) ; show entire entry
13581 (when following-p
13582 ;; Show next sibling, or heading below text
13583 (save-excursion
13584 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13585 (org-flag-heading nil))))
13586 (when siblings-p (org-show-siblings))
13587 (when hierarchy-p
13588 ;; show all higher headings, possibly with siblings
13589 (save-excursion
13590 (while (and (condition-case nil
13591 (progn (org-up-heading-all 1) t)
13592 (error nil))
13593 (not (bobp)))
13594 (org-flag-heading nil)
13595 (when siblings-p (org-show-siblings))))))))
13597 (defun org-reveal (&optional siblings)
13598 "Show current entry, hierarchy above it, and the following headline.
13599 This can be used to show a consistent set of context around locations
13600 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13601 not t for the search context.
13603 With optional argument SIBLINGS, on each level of the hierarchy all
13604 siblings are shown. This repairs the tree structure to what it would
13605 look like when opened with hierarchical calls to `org-cycle'."
13606 (interactive "P")
13607 (let ((org-show-hierarchy-above t)
13608 (org-show-following-heading t)
13609 (org-show-siblings (if siblings t org-show-siblings)))
13610 (org-show-context nil)))
13612 (defun org-highlight-new-match (beg end)
13613 "Highlight from BEG to END and mark the highlight is an occur headline."
13614 (let ((ov (org-make-overlay beg end)))
13615 (org-overlay-put ov 'face 'secondary-selection)
13616 (push ov org-occur-highlights)))
13618 (defun org-remove-occur-highlights (&optional beg end noremove)
13619 "Remove the occur highlights from the buffer.
13620 BEG and END are ignored. If NOREMOVE is nil, remove this function
13621 from the `before-change-functions' in the current buffer."
13622 (interactive)
13623 (unless org-inhibit-highlight-removal
13624 (mapc 'org-delete-overlay org-occur-highlights)
13625 (setq org-occur-highlights nil)
13626 (unless noremove
13627 (remove-hook 'before-change-functions
13628 'org-remove-occur-highlights 'local))))
13630 ;;;; Priorities
13632 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13633 "Regular expression matching the priority indicator.")
13635 (defvar org-remove-priority-next-time nil)
13637 (defun org-priority-up ()
13638 "Increase the priority of the current item."
13639 (interactive)
13640 (org-priority 'up))
13642 (defun org-priority-down ()
13643 "Decrease the priority of the current item."
13644 (interactive)
13645 (org-priority 'down))
13647 (defun org-priority (&optional action)
13648 "Change the priority of an item by ARG.
13649 ACTION can be `set', `up', `down', or a character."
13650 (interactive)
13651 (setq action (or action 'set))
13652 (let (current new news have remove)
13653 (save-excursion
13654 (org-back-to-heading)
13655 (if (looking-at org-priority-regexp)
13656 (setq current (string-to-char (match-string 2))
13657 have t)
13658 (setq current org-default-priority))
13659 (cond
13660 ((or (eq action 'set) (integerp action))
13661 (if (integerp action)
13662 (setq new action)
13663 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13664 (setq new (read-char-exclusive)))
13665 (if (and (= (upcase org-highest-priority) org-highest-priority)
13666 (= (upcase org-lowest-priority) org-lowest-priority))
13667 (setq new (upcase new)))
13668 (cond ((equal new ?\ ) (setq remove t))
13669 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13670 (error "Priority must be between `%c' and `%c'"
13671 org-highest-priority org-lowest-priority))))
13672 ((eq action 'up)
13673 (if (and (not have) (eq last-command this-command))
13674 (setq new org-lowest-priority)
13675 (setq new (if (and org-priority-start-cycle-with-default (not have))
13676 org-default-priority (1- current)))))
13677 ((eq action 'down)
13678 (if (and (not have) (eq last-command this-command))
13679 (setq new org-highest-priority)
13680 (setq new (if (and org-priority-start-cycle-with-default (not have))
13681 org-default-priority (1+ current)))))
13682 (t (error "Invalid action")))
13683 (if (or (< (upcase new) org-highest-priority)
13684 (> (upcase new) org-lowest-priority))
13685 (setq remove t))
13686 (setq news (format "%c" new))
13687 (if have
13688 (if remove
13689 (replace-match "" t t nil 1)
13690 (replace-match news t t nil 2))
13691 (if remove
13692 (error "No priority cookie found in line")
13693 (looking-at org-todo-line-regexp)
13694 (if (match-end 2)
13695 (progn
13696 (goto-char (match-end 2))
13697 (insert " [#" news "]"))
13698 (goto-char (match-beginning 3))
13699 (insert "[#" news "] ")))))
13700 (org-preserve-lc (org-set-tags nil 'align))
13701 (if remove
13702 (message "Priority removed")
13703 (message "Priority of current item set to %s" news))))
13706 (defun org-get-priority (s)
13707 "Find priority cookie and return priority."
13708 (save-match-data
13709 (if (not (string-match org-priority-regexp s))
13710 (* 1000 (- org-lowest-priority org-default-priority))
13711 (* 1000 (- org-lowest-priority
13712 (string-to-char (match-string 2 s)))))))
13714 ;;;; Tags
13716 (defun org-scan-tags (action matcher &optional todo-only)
13717 "Scan headline tags with inheritance and produce output ACTION.
13718 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13719 evaluated, testing if a given set of tags qualifies a headline for
13720 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13721 are included in the output."
13722 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13723 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13724 (org-re
13725 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13726 (props (list 'face nil
13727 'done-face 'org-done
13728 'undone-face nil
13729 'mouse-face 'highlight
13730 'org-not-done-regexp org-not-done-regexp
13731 'org-todo-regexp org-todo-regexp
13732 'keymap org-agenda-keymap
13733 'help-echo
13734 (format "mouse-2 or RET jump to org file %s"
13735 (abbreviate-file-name buffer-file-name))))
13736 (case-fold-search nil)
13737 lspos
13738 tags tags-list tags-alist (llast 0) rtn level category i txt
13739 todo marker entry priority)
13740 (save-excursion
13741 (goto-char (point-min))
13742 (when (eq action 'sparse-tree) (org-overview))
13743 (while (re-search-forward re nil t)
13744 (catch :skip
13745 (setq todo (if (match-end 1) (match-string 2))
13746 tags (if (match-end 4) (match-string 4)))
13747 (goto-char (setq lspos (1+ (match-beginning 0))))
13748 (setq level (org-reduced-level (funcall outline-level))
13749 category (org-get-category))
13750 (setq i llast llast level)
13751 ;; remove tag lists from same and sublevels
13752 (while (>= i level)
13753 (when (setq entry (assoc i tags-alist))
13754 (setq tags-alist (delete entry tags-alist)))
13755 (setq i (1- i)))
13756 ;; add the nex tags
13757 (when tags
13758 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13759 tags-alist
13760 (cons (cons level tags) tags-alist)))
13761 ;; compile tags for current headline
13762 (setq tags-list
13763 (if org-use-tag-inheritance
13764 (apply 'append (mapcar 'cdr tags-alist))
13765 tags))
13766 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13767 (eval matcher)
13768 (or (not org-agenda-skip-archived-trees)
13769 (not (member org-archive-tag tags-list))))
13770 (and (eq action 'agenda) (org-agenda-skip))
13771 ;; list this headline
13772 (if (eq action 'sparse-tree)
13773 (progn
13774 (org-show-context 'tags-tree))
13775 (setq txt (org-format-agenda-item
13777 (concat
13778 (if org-tags-match-list-sublevels
13779 (make-string (1- level) ?.) "")
13780 (org-get-heading))
13781 category tags-list)
13782 priority (org-get-priority txt))
13783 (goto-char lspos)
13784 (setq marker (org-agenda-new-marker))
13785 (org-add-props txt props
13786 'org-marker marker 'org-hd-marker marker 'org-category category
13787 'priority priority 'type "tagsmatch")
13788 (push txt rtn))
13789 ;; if we are to skip sublevels, jump to end of subtree
13790 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13791 (when (and (eq action 'sparse-tree)
13792 (not org-sparse-tree-open-archived-trees))
13793 (org-hide-archived-subtrees (point-min) (point-max)))
13794 (nreverse rtn)))
13796 (defvar todo-only) ;; dynamically scoped
13798 (defun org-tags-sparse-tree (&optional todo-only match)
13799 "Create a sparse tree according to tags string MATCH.
13800 MATCH can contain positive and negative selection of tags, like
13801 \"+WORK+URGENT-WITHBOSS\".
13802 If optional argument TODO_ONLY is non-nil, only select lines that are
13803 also TODO lines."
13804 (interactive "P")
13805 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13807 (defvar org-cached-props nil)
13808 (defun org-cached-entry-get (pom property)
13809 (cdr (assoc property (or org-cached-props
13810 (setq org-cached-props
13811 (org-entry-properties pom))))))
13813 (defun org-global-tags-completion-table (&optional files)
13814 "Return the list of all tags in all agenda buffer/files."
13815 (save-excursion
13816 (org-uniquify
13817 (apply 'append
13818 (mapcar
13819 (lambda (file)
13820 (set-buffer (find-file-noselect file))
13821 (org-get-buffer-tags))
13822 (if (and files (car files))
13823 files
13824 (org-agenda-files)))))))
13826 (defun org-make-tags-matcher (match)
13827 "Create the TAGS//TODO matcher form for the selection string MATCH."
13828 ;; todo-only is scoped dynamically into this function, and the function
13829 ;; may change it it the matcher asksk for it.
13830 (unless match
13831 ;; Get a new match request, with completion
13832 (let ((org-last-tags-completion-table
13833 (org-global-tags-completion-table)))
13834 (setq match (completing-read
13835 "Match: " 'org-tags-completion-function nil nil nil
13836 'org-tags-history))))
13838 ;; Parse the string and create a lisp form
13839 (let ((match0 match)
13840 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13841 minus tag mm
13842 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13843 orterms term orlist re-p level-p prop-p pn pv)
13844 (if (string-match "/+" match)
13845 ;; match contains also a todo-matching request
13846 (progn
13847 (setq tagsmatch (substring match 0 (match-beginning 0))
13848 todomatch (substring match (match-end 0)))
13849 (if (string-match "^!" todomatch)
13850 (setq todo-only t todomatch (substring todomatch 1)))
13851 (if (string-match "^\\s-*$" todomatch)
13852 (setq todomatch nil)))
13853 ;; only matching tags
13854 (setq tagsmatch match todomatch nil))
13856 ;; Make the tags matcher
13857 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13858 (setq tagsmatcher t)
13859 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13860 (while (setq term (pop orterms))
13861 (while (and (equal (substring term -1) "\\") orterms)
13862 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13863 (while (string-match re term)
13864 (setq minus (and (match-end 1)
13865 (equal (match-string 1 term) "-"))
13866 tag (match-string 2 term)
13867 re-p (equal (string-to-char tag) ?{)
13868 level-p (match-end 3)
13869 prop-p (match-end 4)
13870 mm (cond
13871 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13872 (level-p `(= level ,(string-to-number
13873 (match-string 3 term))))
13874 (prop-p
13875 (setq pn (match-string 4 term)
13876 pv (match-string 5 term)
13877 re-p (equal (string-to-char pv) ?{)
13878 pv (substring pv 1 -1))
13879 (if re-p
13880 `(string-match ,pv (org-cached-entry-get nil ,pn))
13881 `(equal ,pv (org-cached-entry-get nil ,pn))))
13882 (t `(member ,(downcase tag) tags-list)))
13883 mm (if minus (list 'not mm) mm)
13884 term (substring term (match-end 0)))
13885 (push mm tagsmatcher))
13886 (push (if (> (length tagsmatcher) 1)
13887 (cons 'and tagsmatcher)
13888 (car tagsmatcher))
13889 orlist)
13890 (setq tagsmatcher nil))
13891 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13892 (setq tagsmatcher
13893 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13895 ;; Make the todo matcher
13896 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13897 (setq todomatcher t)
13898 (setq orterms (org-split-string todomatch "|") orlist nil)
13899 (while (setq term (pop orterms))
13900 (while (string-match re term)
13901 (setq minus (and (match-end 1)
13902 (equal (match-string 1 term) "-"))
13903 kwd (match-string 2 term)
13904 re-p (equal (string-to-char kwd) ?{)
13905 term (substring term (match-end 0))
13906 mm (if re-p
13907 `(string-match ,(substring kwd 1 -1) todo)
13908 (list 'equal 'todo kwd))
13909 mm (if minus (list 'not mm) mm))
13910 (push mm todomatcher))
13911 (push (if (> (length todomatcher) 1)
13912 (cons 'and todomatcher)
13913 (car todomatcher))
13914 orlist)
13915 (setq todomatcher nil))
13916 (setq todomatcher (if (> (length orlist) 1)
13917 (cons 'or orlist) (car orlist))))
13919 ;; Return the string and lisp forms of the matcher
13920 (setq matcher (if todomatcher
13921 (list 'and tagsmatcher todomatcher)
13922 tagsmatcher))
13923 (cons match0 matcher)))
13925 (defun org-match-any-p (re list)
13926 "Does re match any element of list?"
13927 (setq list (mapcar (lambda (x) (string-match re x)) list))
13928 (delq nil list))
13930 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13931 (defvar org-tags-overlay (org-make-overlay 1 1))
13932 (org-detach-overlay org-tags-overlay)
13934 (defun org-align-tags-here (to-col)
13935 ;; Assumes that this is a headline
13936 (let ((pos (point)) (col (current-column)) tags)
13937 (beginning-of-line 1)
13938 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13939 (< pos (match-beginning 2)))
13940 (progn
13941 (setq tags (match-string 2))
13942 (goto-char (match-beginning 1))
13943 (insert " ")
13944 (delete-region (point) (1+ (match-end 0)))
13945 (backward-char 1)
13946 (move-to-column
13947 (max (1+ (current-column))
13948 (1+ col)
13949 (if (> to-col 0)
13950 to-col
13951 (- (abs to-col) (length tags))))
13953 (insert tags)
13954 (move-to-column (min (current-column) col) t))
13955 (goto-char pos))))
13957 (defun org-set-tags (&optional arg just-align)
13958 "Set the tags for the current headline.
13959 With prefix ARG, realign all tags in headings in the current buffer."
13960 (interactive "P")
13961 (let* ((re (concat "^" outline-regexp))
13962 (current (org-get-tags-string))
13963 (col (current-column))
13964 (org-setting-tags t)
13965 table current-tags inherited-tags ; computed below when needed
13966 tags p0 c0 c1 rpl)
13967 (if arg
13968 (save-excursion
13969 (goto-char (point-min))
13970 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13971 (while (re-search-forward re nil t)
13972 (org-set-tags nil t)
13973 (end-of-line 1)))
13974 (message "All tags realigned to column %d" org-tags-column))
13975 (if just-align
13976 (setq tags current)
13977 ;; Get a new set of tags from the user
13978 (save-excursion
13979 (setq table (or org-tag-alist (org-get-buffer-tags))
13980 org-last-tags-completion-table table
13981 current-tags (org-split-string current ":")
13982 inherited-tags (nreverse
13983 (nthcdr (length current-tags)
13984 (nreverse (org-get-tags-at))))
13985 tags
13986 (if (or (eq t org-use-fast-tag-selection)
13987 (and org-use-fast-tag-selection
13988 (delq nil (mapcar 'cdr table))))
13989 (org-fast-tag-selection
13990 current-tags inherited-tags table
13991 (if org-fast-tag-selection-include-todo org-todo-key-alist))
13992 (let ((org-add-colon-after-tag-completion t))
13993 (org-trim
13994 (org-without-partial-completion
13995 (completing-read "Tags: " 'org-tags-completion-function
13996 nil nil current 'org-tags-history)))))))
13997 (while (string-match "[-+&]+" tags)
13998 ;; No boolean logic, just a list
13999 (setq tags (replace-match ":" t t tags))))
14001 (if (string-match "\\`[\t ]*\\'" tags)
14002 (setq tags "")
14003 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14004 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14006 ;; Insert new tags at the correct column
14007 (beginning-of-line 1)
14008 (cond
14009 ((and (equal current "") (equal tags "")))
14010 ((re-search-forward
14011 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14012 (point-at-eol) t)
14013 (if (equal tags "")
14014 (setq rpl "")
14015 (goto-char (match-beginning 0))
14016 (setq c0 (current-column) p0 (point)
14017 c1 (max (1+ c0) (if (> org-tags-column 0)
14018 org-tags-column
14019 (- (- org-tags-column) (length tags))))
14020 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14021 (replace-match rpl t t)
14022 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14023 tags)
14024 (t (error "Tags alignment failed")))
14025 (move-to-column col)
14026 (unless just-align
14027 (run-hooks 'org-after-tags-change-hook)))))
14029 (defun org-change-tag-in-region (beg end tag off)
14030 "Add or remove TAG for each entry in the region.
14031 This works in the agenda, and also in an org-mode buffer."
14032 (interactive
14033 (list (region-beginning) (region-end)
14034 (let ((org-last-tags-completion-table
14035 (if (org-mode-p)
14036 (org-get-buffer-tags)
14037 (org-global-tags-completion-table))))
14038 (completing-read
14039 "Tag: " 'org-tags-completion-function nil nil nil
14040 'org-tags-history))
14041 (progn
14042 (message "[s]et or [r]emove? ")
14043 (equal (read-char-exclusive) ?r))))
14044 (if (fboundp 'deactivate-mark) (deactivate-mark))
14045 (let ((agendap (equal major-mode 'org-agenda-mode))
14046 l1 l2 m buf pos newhead (cnt 0))
14047 (goto-char end)
14048 (setq l2 (1- (org-current-line)))
14049 (goto-char beg)
14050 (setq l1 (org-current-line))
14051 (loop for l from l1 to l2 do
14052 (goto-line l)
14053 (setq m (get-text-property (point) 'org-hd-marker))
14054 (when (or (and (org-mode-p) (org-on-heading-p))
14055 (and agendap m))
14056 (setq buf (if agendap (marker-buffer m) (current-buffer))
14057 pos (if agendap m (point)))
14058 (with-current-buffer buf
14059 (save-excursion
14060 (save-restriction
14061 (goto-char pos)
14062 (setq cnt (1+ cnt))
14063 (org-toggle-tag tag (if off 'off 'on))
14064 (setq newhead (org-get-heading)))))
14065 (and agendap (org-agenda-change-all-lines newhead m))))
14066 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14068 (defun org-tags-completion-function (string predicate &optional flag)
14069 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14070 (confirm (lambda (x) (stringp (car x)))))
14071 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14072 (setq s1 (match-string 1 string)
14073 s2 (match-string 2 string))
14074 (setq s1 "" s2 string))
14075 (cond
14076 ((eq flag nil)
14077 ;; try completion
14078 (setq rtn (try-completion s2 ctable confirm))
14079 (if (stringp rtn)
14080 (setq rtn
14081 (concat s1 s2 (substring rtn (length s2))
14082 (if (and org-add-colon-after-tag-completion
14083 (assoc rtn ctable))
14084 ":" ""))))
14085 rtn)
14086 ((eq flag t)
14087 ;; all-completions
14088 (all-completions s2 ctable confirm)
14090 ((eq flag 'lambda)
14091 ;; exact match?
14092 (assoc s2 ctable)))
14095 (defun org-fast-tag-insert (kwd tags face &optional end)
14096 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14097 (insert (format "%-12s" (concat kwd ":"))
14098 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14099 (or end "")))
14101 (defun org-fast-tag-show-exit (flag)
14102 (save-excursion
14103 (goto-line 3)
14104 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14105 (replace-match ""))
14106 (when flag
14107 (end-of-line 1)
14108 (move-to-column (- (window-width) 19) t)
14109 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14111 (defun org-set-current-tags-overlay (current prefix)
14112 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14113 (if (featurep 'xemacs)
14114 (org-overlay-display org-tags-overlay (concat prefix s)
14115 'secondary-selection)
14116 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14117 (org-overlay-display org-tags-overlay (concat prefix s)))))
14119 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14120 "Fast tag selection with single keys.
14121 CURRENT is the current list of tags in the headline, INHERITED is the
14122 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14123 possibly with grouping information. TODO-TABLE is a similar table with
14124 TODO keywords, should these have keys assigned to them.
14125 If the keys are nil, a-z are automatically assigned.
14126 Returns the new tags string, or nil to not change the current settings."
14127 (let* ((fulltable (append table todo-table))
14128 (maxlen (apply 'max (mapcar
14129 (lambda (x)
14130 (if (stringp (car x)) (string-width (car x)) 0))
14131 fulltable)))
14132 (buf (current-buffer))
14133 (expert (eq org-fast-tag-selection-single-key 'expert))
14134 (buffer-tags nil)
14135 (fwidth (+ maxlen 3 1 3))
14136 (ncol (/ (- (window-width) 4) fwidth))
14137 (i-face 'org-done)
14138 (c-face 'org-todo)
14139 tg cnt e c char c1 c2 ntable tbl rtn
14140 ov-start ov-end ov-prefix
14141 (exit-after-next org-fast-tag-selection-single-key)
14142 (done-keywords org-done-keywords)
14143 groups ingroup)
14144 (save-excursion
14145 (beginning-of-line 1)
14146 (if (looking-at
14147 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14148 (setq ov-start (match-beginning 1)
14149 ov-end (match-end 1)
14150 ov-prefix "")
14151 (setq ov-start (1- (point-at-eol))
14152 ov-end (1+ ov-start))
14153 (skip-chars-forward "^\n\r")
14154 (setq ov-prefix
14155 (concat
14156 (buffer-substring (1- (point)) (point))
14157 (if (> (current-column) org-tags-column)
14159 (make-string (- org-tags-column (current-column)) ?\ ))))))
14160 (org-move-overlay org-tags-overlay ov-start ov-end)
14161 (save-window-excursion
14162 (if expert
14163 (set-buffer (get-buffer-create " *Org tags*"))
14164 (delete-other-windows)
14165 (split-window-vertically)
14166 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14167 (erase-buffer)
14168 (org-set-local 'org-done-keywords done-keywords)
14169 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14170 (org-fast-tag-insert "Current" current c-face "\n\n")
14171 (org-fast-tag-show-exit exit-after-next)
14172 (org-set-current-tags-overlay current ov-prefix)
14173 (setq tbl fulltable char ?a cnt 0)
14174 (while (setq e (pop tbl))
14175 (cond
14176 ((equal e '(:startgroup))
14177 (push '() groups) (setq ingroup t)
14178 (when (not (= cnt 0))
14179 (setq cnt 0)
14180 (insert "\n"))
14181 (insert "{ "))
14182 ((equal e '(:endgroup))
14183 (setq ingroup nil cnt 0)
14184 (insert "}\n"))
14186 (setq tg (car e) c2 nil)
14187 (if (cdr e)
14188 (setq c (cdr e))
14189 ;; automatically assign a character.
14190 (setq c1 (string-to-char
14191 (downcase (substring
14192 tg (if (= (string-to-char tg) ?@) 1 0)))))
14193 (if (or (rassoc c1 ntable) (rassoc c1 table))
14194 (while (or (rassoc char ntable) (rassoc char table))
14195 (setq char (1+ char)))
14196 (setq c2 c1))
14197 (setq c (or c2 char)))
14198 (if ingroup (push tg (car groups)))
14199 (setq tg (org-add-props tg nil 'face
14200 (cond
14201 ((not (assoc tg table))
14202 (org-get-todo-face tg))
14203 ((member tg current) c-face)
14204 ((member tg inherited) i-face)
14205 (t nil))))
14206 (if (and (= cnt 0) (not ingroup)) (insert " "))
14207 (insert "[" c "] " tg (make-string
14208 (- fwidth 4 (length tg)) ?\ ))
14209 (push (cons tg c) ntable)
14210 (when (= (setq cnt (1+ cnt)) ncol)
14211 (insert "\n")
14212 (if ingroup (insert " "))
14213 (setq cnt 0)))))
14214 (setq ntable (nreverse ntable))
14215 (insert "\n")
14216 (goto-char (point-min))
14217 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14218 (fit-window-to-buffer))
14219 (setq rtn
14220 (catch 'exit
14221 (while t
14222 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14223 (if groups " [!] no groups" " [!]groups")
14224 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14225 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14226 (cond
14227 ((= c ?\r) (throw 'exit t))
14228 ((= c ?!)
14229 (setq groups (not groups))
14230 (goto-char (point-min))
14231 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14232 ((= c ?\C-c)
14233 (if (not expert)
14234 (org-fast-tag-show-exit
14235 (setq exit-after-next (not exit-after-next)))
14236 (setq expert nil)
14237 (delete-other-windows)
14238 (split-window-vertically)
14239 (org-switch-to-buffer-other-window " *Org tags*")
14240 (and (fboundp 'fit-window-to-buffer)
14241 (fit-window-to-buffer))))
14242 ((or (= c ?\C-g)
14243 (and (= c ?q) (not (rassoc c ntable))))
14244 (org-detach-overlay org-tags-overlay)
14245 (setq quit-flag t))
14246 ((= c ?\ )
14247 (setq current nil)
14248 (if exit-after-next (setq exit-after-next 'now)))
14249 ((= c ?\t)
14250 (condition-case nil
14251 (setq tg (completing-read
14252 "Tag: "
14253 (or buffer-tags
14254 (with-current-buffer buf
14255 (org-get-buffer-tags)))))
14256 (quit (setq tg "")))
14257 (when (string-match "\\S-" tg)
14258 (add-to-list 'buffer-tags (list tg))
14259 (if (member tg current)
14260 (setq current (delete tg current))
14261 (push tg current)))
14262 (if exit-after-next (setq exit-after-next 'now)))
14263 ((setq e (rassoc c todo-table) tg (car e))
14264 (with-current-buffer buf
14265 (save-excursion (org-todo tg)))
14266 (if exit-after-next (setq exit-after-next 'now)))
14267 ((setq e (rassoc c ntable) tg (car e))
14268 (if (member tg current)
14269 (setq current (delete tg current))
14270 (loop for g in groups do
14271 (if (member tg g)
14272 (mapcar (lambda (x)
14273 (setq current (delete x current)))
14274 g)))
14275 (push tg current))
14276 (if exit-after-next (setq exit-after-next 'now))))
14278 ;; Create a sorted list
14279 (setq current
14280 (sort current
14281 (lambda (a b)
14282 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14283 (if (eq exit-after-next 'now) (throw 'exit t))
14284 (goto-char (point-min))
14285 (beginning-of-line 2)
14286 (delete-region (point) (point-at-eol))
14287 (org-fast-tag-insert "Current" current c-face)
14288 (org-set-current-tags-overlay current ov-prefix)
14289 (while (re-search-forward
14290 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14291 (setq tg (match-string 1))
14292 (add-text-properties
14293 (match-beginning 1) (match-end 1)
14294 (list 'face
14295 (cond
14296 ((member tg current) c-face)
14297 ((member tg inherited) i-face)
14298 (t (get-text-property (match-beginning 1) 'face))))))
14299 (goto-char (point-min)))))
14300 (org-detach-overlay org-tags-overlay)
14301 (if rtn
14302 (mapconcat 'identity current ":")
14303 nil))))
14305 (defun org-get-tags-string ()
14306 "Get the TAGS string in the current headline."
14307 (unless (org-on-heading-p t)
14308 (error "Not on a heading"))
14309 (save-excursion
14310 (beginning-of-line 1)
14311 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14312 (org-match-string-no-properties 1)
14313 "")))
14315 (defun org-get-tags ()
14316 "Get the list of tags specified in the current headline."
14317 (org-split-string (org-get-tags-string) ":"))
14319 (defun org-get-buffer-tags ()
14320 "Get a table of all tags used in the buffer, for completion."
14321 (let (tags)
14322 (save-excursion
14323 (goto-char (point-min))
14324 (while (re-search-forward
14325 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14326 (when (equal (char-after (point-at-bol 0)) ?*)
14327 (mapc (lambda (x) (add-to-list 'tags x))
14328 (org-split-string (org-match-string-no-properties 1) ":")))))
14329 (mapcar 'list tags)))
14332 ;;;; Properties
14334 ;;; Setting and retrieving properties
14336 (defconst org-special-properties
14337 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14338 "The special properties valid in Org-mode.
14340 These are properties that are not defined in the property drawer,
14341 but in some other way.")
14343 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14344 "Regular expression matching the first line of a property drawer.")
14346 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14347 "Regular expression matching the first line of a property drawer.")
14349 (defun org-property-action ()
14350 "Do an action on properties."
14351 (interactive)
14352 (let (c prop)
14353 (org-at-property-p)
14354 (setq prop (match-string 2))
14355 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14356 (setq c (read-char-exclusive))
14357 (cond
14358 ((equal c ?s)
14359 (call-interactively 'org-set-property))
14360 ((equal c ?d)
14361 (call-interactively 'org-delete-property))
14362 ((equal c ?D)
14363 (call-interactively 'org-delete-property-globally))
14364 ((equal c ?c)
14365 (call-interactively 'org-compute-property-at-point))
14366 (t (error "No such property action %c" c)))))
14368 (defun org-at-property-p ()
14369 "Is the cursor in a property line?"
14370 ;; FIXME: Does not check if we are actually in the drawer.
14371 ;; FIXME: also returns true on any drawers.....
14372 ;; This is used by C-c C-c for property action.
14373 (save-excursion
14374 (beginning-of-line 1)
14375 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14377 (defmacro org-with-point-at (pom &rest body)
14378 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14379 (declare (indent 1) (debug t))
14380 `(save-excursion
14381 (if (markerp pom) (set-buffer (marker-buffer pom)))
14382 (save-excursion
14383 (goto-char (or pom (point)))
14384 ,@body)))
14386 (defun org-get-property-block (&optional beg end force)
14387 "Return the (beg . end) range of the body of the property drawer.
14388 BEG and END can be beginning and end of subtree, if not given
14389 they will be found.
14390 If the drawer does not exist and FORCE is non-nil, create the drawer."
14391 (catch 'exit
14392 (save-excursion
14393 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14394 (end (or end (progn (outline-next-heading) (point)))))
14395 (goto-char beg)
14396 (if (re-search-forward org-property-start-re end t)
14397 (setq beg (1+ (match-end 0)))
14398 (if force
14399 (save-excursion
14400 (org-insert-property-drawer)
14401 (setq end (progn (outline-next-heading) (point))))
14402 (throw 'exit nil))
14403 (goto-char beg)
14404 (if (re-search-forward org-property-start-re end t)
14405 (setq beg (1+ (match-end 0)))))
14406 (if (re-search-forward org-property-end-re end t)
14407 (setq end (match-beginning 0))
14408 (or force (throw 'exit nil))
14409 (goto-char beg)
14410 (setq end beg)
14411 (org-indent-line-function)
14412 (insert ":END:\n"))
14413 (cons beg end)))))
14415 (defun org-entry-properties (&optional pom which)
14416 "Get all properties of the entry at point-or-marker POM.
14417 This includes the TODO keyword, the tags, time strings for deadline,
14418 scheduled, and clocking, and any additional properties defined in the
14419 entry. The return value is an alist, keys may occur multiple times
14420 if the property key was used several times.
14421 POM may also be nil, in which case the current entry is used.
14422 If WHICH is nil or `all', get all properties. If WHICH is
14423 `special' or `standard', only get that subclass."
14424 (setq which (or which 'all))
14425 (org-with-point-at pom
14426 (let ((clockstr (substring org-clock-string 0 -1))
14427 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14428 beg end range props sum-props key value)
14429 (save-excursion
14430 (when (condition-case nil (org-back-to-heading t) (error nil))
14431 (setq beg (point))
14432 (setq sum-props (get-text-property (point) 'org-summaries))
14433 (outline-next-heading)
14434 (setq end (point))
14435 (when (memq which '(all special))
14436 ;; Get the special properties, like TODO and tags
14437 (goto-char beg)
14438 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14439 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14440 (when (looking-at org-priority-regexp)
14441 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14442 (when (and (setq value (org-get-tags-string))
14443 (string-match "\\S-" value))
14444 (push (cons "TAGS" value) props))
14445 (when (setq value (org-get-tags-at))
14446 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14447 props))
14448 (while (re-search-forward org-keyword-time-regexp end t)
14449 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14450 (unless (member key excluded) (push key excluded))
14451 (push (cons key
14452 (if (equal key clockstr)
14453 (org-no-properties
14454 (org-trim
14455 (buffer-substring
14456 (match-beginning 2) (point-at-eol))))
14457 (org-match-string-no-properties 2)))
14458 props)))
14459 (when (memq which '(all standard))
14460 ;; Get the standard properties, like :PORP: ...
14461 (setq range (org-get-property-block beg end))
14462 (when range
14463 (goto-char (car range))
14464 (while (re-search-forward
14465 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14466 (cdr range) t)
14467 (setq key (org-match-string-no-properties 1)
14468 value (org-trim (or (org-match-string-no-properties 2) "")))
14469 (unless (member key excluded)
14470 (push (cons key (or value "")) props)))))
14471 (append sum-props (nreverse props)))))))
14473 (defun org-entry-get (pom property &optional inherit)
14474 "Get value of PROPERTY for entry at point-or-marker POM.
14475 If INHERIT is non-nil and the entry does not have the property,
14476 then also check higher levels of the hierarchy.
14477 If the property is present but empty, the return value is the empty string.
14478 If the property is not present at all, nil is returned."
14479 (org-with-point-at pom
14480 (if inherit
14481 (org-entry-get-with-inheritance property)
14482 (if (member property org-special-properties)
14483 ;; We need a special property. Use brute force, get all properties.
14484 (cdr (assoc property (org-entry-properties nil 'special)))
14485 (let ((range (org-get-property-block)))
14486 (if (and range
14487 (goto-char (car range))
14488 (re-search-forward
14489 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14490 (cdr range) t))
14491 ;; Found the property, return it.
14492 (if (match-end 1)
14493 (org-match-string-no-properties 1)
14494 "")))))))
14496 (defun org-entry-delete (pom property)
14497 "Delete the property PROPERTY from entry at point-or-marker POM."
14498 (org-with-point-at pom
14499 (if (member property org-special-properties)
14500 nil ; cannot delete these properties.
14501 (let ((range (org-get-property-block)))
14502 (if (and range
14503 (goto-char (car range))
14504 (re-search-forward
14505 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14506 (cdr range) t))
14507 (progn
14508 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14510 nil)))))
14512 (defvar org-entry-property-inherited-from (make-marker))
14514 (defun org-entry-get-with-inheritance (property)
14515 "Get entry property, and search higher levels if not present."
14516 (let (tmp)
14517 (save-excursion
14518 (catch 'ex
14519 (while t
14520 (when (setq tmp (org-entry-get nil property))
14521 (org-back-to-heading t)
14522 (move-marker org-entry-property-inherited-from (point))
14523 (throw 'ex tmp))
14524 (or (org-up-heading-safe) (throw 'ex nil)))))
14525 (or tmp (cdr (assoc property org-local-properties))
14526 (cdr (assoc property org-global-properties)))))
14528 (defun org-entry-put (pom property value)
14529 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14530 (org-with-point-at pom
14531 (org-back-to-heading t)
14532 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14533 range)
14534 (cond
14535 ((equal property "TODO")
14536 (when (and (stringp value) (string-match "\\S-" value)
14537 (not (member value org-todo-keywords-1)))
14538 (error "\"%s\" is not a valid TODO state" value))
14539 (if (or (not value)
14540 (not (string-match "\\S-" value)))
14541 (setq value 'none))
14542 (org-todo value)
14543 (org-set-tags nil 'align))
14544 ((equal property "PRIORITY")
14545 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14546 (string-to-char value) ?\ ))
14547 (org-set-tags nil 'align))
14548 ((equal property "SCHEDULED")
14549 (if (re-search-forward org-scheduled-time-regexp end t)
14550 (cond
14551 ((eq value 'earlier) (org-timestamp-change -1 'day))
14552 ((eq value 'later) (org-timestamp-change 1 'day))
14553 (t (call-interactively 'org-schedule)))
14554 (call-interactively 'org-schedule)))
14555 ((equal property "DEADLINE")
14556 (if (re-search-forward org-deadline-time-regexp end t)
14557 (cond
14558 ((eq value 'earlier) (org-timestamp-change -1 'day))
14559 ((eq value 'later) (org-timestamp-change 1 'day))
14560 (t (call-interactively 'org-deadline)))
14561 (call-interactively 'org-deadline)))
14562 ((member property org-special-properties)
14563 (error "The %s property can not yet be set with `org-entry-put'"
14564 property))
14565 (t ; a non-special property
14566 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
14567 (setq range (org-get-property-block beg end 'force))
14568 (goto-char (car range))
14569 (if (re-search-forward
14570 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
14571 (progn
14572 (delete-region (match-beginning 1) (match-end 1))
14573 (goto-char (match-beginning 1)))
14574 (goto-char (cdr range))
14575 (insert "\n")
14576 (backward-char 1)
14577 (org-indent-line-function)
14578 (insert ":" property ":"))
14579 (and value (insert " " value))
14580 (org-indent-line-function)))))))
14582 (defun org-buffer-property-keys (&optional include-specials include-defaults)
14583 "Get all property keys in the current buffer.
14584 With INCLUDE-SPECIALS, also list the special properties that relect things
14585 like tags and TODO state.
14586 With INCLUDE-DEFAULTS, also include properties that has special meaning
14587 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
14588 (let (rtn range)
14589 (save-excursion
14590 (save-restriction
14591 (widen)
14592 (goto-char (point-min))
14593 (while (re-search-forward org-property-start-re nil t)
14594 (setq range (org-get-property-block))
14595 (goto-char (car range))
14596 (while (re-search-forward
14597 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
14598 (cdr range) t)
14599 (add-to-list 'rtn (org-match-string-no-properties 1)))
14600 (outline-next-heading))))
14601 (when include-specials
14602 (setq rtn (append org-special-properties rtn)))
14603 (when include-defaults
14604 (add-to-list rtn "CATEGORY")
14605 (add-to-list rtn "ARCHIVE"))
14606 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14608 (defun org-insert-property-drawer ()
14609 "Insert a property drawer into the current entry."
14610 (interactive)
14611 (org-back-to-heading t)
14612 (let ((beg (point))
14613 (re (concat "^[ \t]*" org-keyword-time-regexp))
14614 end hiddenp)
14615 (outline-next-heading)
14616 (setq end (point))
14617 (goto-char beg)
14618 (while (re-search-forward re end t))
14619 (setq hiddenp (org-invisible-p))
14620 (end-of-line 1)
14621 (and (= (char-after) ?\n) (forward-char 1))
14622 (org-skip-over-state-notes)
14623 (end-of-line 0)
14624 (insert "\n:PROPERTIES:\n:END:")
14625 (beginning-of-line 0)
14626 (org-indent-line-function)
14627 (beginning-of-line 2)
14628 (org-indent-line-function)
14629 (beginning-of-line 0)
14630 (if hiddenp
14631 (save-excursion
14632 (org-back-to-heading t)
14633 (hide-entry))
14634 (org-flag-drawer t))))
14636 (defun org-set-property (property value)
14637 "In the current entry, set PROPERTY to VALUE."
14638 (interactive
14639 (let* ((prop (completing-read "Property: "
14640 (mapcar 'list (org-buffer-property-keys))))
14641 (cur (org-entry-get nil prop))
14642 (allowed (org-property-get-allowed-values nil prop 'table))
14643 (val (if allowed
14644 (completing-read "Value: " allowed nil 'req-match)
14645 (read-string
14646 (concat "Value" (if (and cur (string-match "\\S-" cur))
14647 (concat "[" cur "]") "")
14648 ": ")
14649 "" cur))))
14650 (list prop (if (equal val "") cur val))))
14651 (unless (equal (org-entry-get nil property) value)
14652 (org-entry-put nil property value)))
14654 (defun org-delete-property (property)
14655 "In the current entry, delete PROPERTY."
14656 (interactive
14657 (let* ((prop (completing-read
14658 "Property: " (org-entry-properties nil 'standard))))
14659 (list prop)))
14660 (message (concat "Property " property
14661 (if (org-entry-delete nil property)
14662 " deleted"
14663 " was not present in the entry"))))
14665 (defun org-delete-property-globally (property)
14666 "Remove PROPERTY globally, from all entries."
14667 (interactive
14668 (let* ((prop (completing-read
14669 "Globally remove property: "
14670 (mapcar 'list (org-buffer-property-keys)))))
14671 (list prop)))
14672 (save-excursion
14673 (save-restriction
14674 (widen)
14675 (goto-char (point-min))
14676 (let ((cnt 0))
14677 (while (re-search-forward
14678 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14679 nil t)
14680 (setq cnt (1+ cnt))
14681 (replace-match ""))
14682 (message "Property \"%s\" removed from %d entries" property cnt)))))
14684 (defvar org-columns-current-fmt-compiled) ; defined below
14686 (defun org-compute-property-at-point ()
14687 "Compute the property at point.
14688 This looks for an enclosing column format, extracts the operator and
14689 then applies it to the proerty in the column format's scope."
14690 (interactive)
14691 (unless (org-at-property-p)
14692 (error "Not at a property"))
14693 (let ((prop (org-match-string-no-properties 2)))
14694 (org-columns-get-format-and-top-level)
14695 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14696 (error "No operator defined for property %s" prop))
14697 (org-columns-compute prop)))
14699 (defun org-property-get-allowed-values (pom property &optional table)
14700 "Get allowed values for the property PROPERTY.
14701 When TABLE is non-nil, return an alist that can directly be used for
14702 completion."
14703 (let (vals)
14704 (cond
14705 ((equal property "TODO")
14706 (setq vals (org-with-point-at pom
14707 (append org-todo-keywords-1 '("")))))
14708 ((equal property "PRIORITY")
14709 (let ((n org-lowest-priority))
14710 (while (>= n org-highest-priority)
14711 (push (char-to-string n) vals)
14712 (setq n (1- n)))))
14713 ((member property org-special-properties))
14715 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14717 (when (and vals (string-match "\\S-" vals))
14718 (setq vals (car (read-from-string (concat "(" vals ")"))))
14719 (setq vals (mapcar (lambda (x)
14720 (cond ((stringp x) x)
14721 ((numberp x) (number-to-string x))
14722 ((symbolp x) (symbol-name x))
14723 (t "???")))
14724 vals)))))
14725 (if table (mapcar 'list vals) vals)))
14727 (defun org-property-previous-allowed-value (&optional previous)
14728 "Switch to the next allowed value for this property."
14729 (interactive)
14730 (org-property-next-allowed-value t))
14732 (defun org-property-next-allowed-value (&optional previous)
14733 "Switch to the next allowed value for this property."
14734 (interactive)
14735 (unless (org-at-property-p)
14736 (error "Not at a property"))
14737 (let* ((key (match-string 2))
14738 (value (match-string 3))
14739 (allowed (or (org-property-get-allowed-values (point) key)
14740 (and (member value '("[ ]" "[-]" "[X]"))
14741 '("[ ]" "[X]"))))
14742 nval)
14743 (unless allowed
14744 (error "Allowed values for this property have not been defined"))
14745 (if previous (setq allowed (reverse allowed)))
14746 (if (member value allowed)
14747 (setq nval (car (cdr (member value allowed)))))
14748 (setq nval (or nval (car allowed)))
14749 (if (equal nval value)
14750 (error "Only one allowed value for this property"))
14751 (org-at-property-p)
14752 (replace-match (concat " :" key ": " nval) t t)
14753 (org-indent-line-function)
14754 (beginning-of-line 1)
14755 (skip-chars-forward " \t")))
14757 ;;; Column View
14759 (defvar org-columns-overlays nil
14760 "Holds the list of current column overlays.")
14762 (defvar org-columns-current-fmt nil
14763 "Local variable, holds the currently active column format.")
14764 (defvar org-columns-current-fmt-compiled nil
14765 "Local variable, holds the currently active column format.
14766 This is the compiled version of the format.")
14767 (defvar org-columns-current-maxwidths nil
14768 "Loval variable, holds the currently active maximum column widths.")
14769 (defvar org-columns-begin-marker (make-marker)
14770 "Points to the position where last a column creation command was called.")
14771 (defvar org-columns-top-level-marker (make-marker)
14772 "Points to the position where current columns region starts.")
14774 (defvar org-columns-map (make-sparse-keymap)
14775 "The keymap valid in column display.")
14777 (defun org-columns-content ()
14778 "Switch to contents view while in columns view."
14779 (interactive)
14780 (org-overview)
14781 (org-content))
14783 (org-defkey org-columns-map "c" 'org-columns-content)
14784 (org-defkey org-columns-map "o" 'org-overview)
14785 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14786 (org-defkey org-columns-map "v" 'org-columns-show-value)
14787 (org-defkey org-columns-map "q" 'org-columns-quit)
14788 (org-defkey org-columns-map "r" 'org-columns-redo)
14789 (org-defkey org-columns-map [left] 'backward-char)
14790 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14791 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14792 (org-defkey org-columns-map [right] 'forward-char)
14793 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14794 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14795 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14796 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14797 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14798 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14799 (org-defkey org-columns-map "<" 'org-columns-narrow)
14800 (org-defkey org-columns-map ">" 'org-columns-widen)
14801 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14802 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14803 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14804 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14806 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14807 '("Column"
14808 ["Edit property" org-columns-edit-value t]
14809 ["Next allowed value" org-columns-next-allowed-value t]
14810 ["Previous allowed value" org-columns-previous-allowed-value t]
14811 ["Show full value" org-columns-show-value t]
14812 ["Edit allowed" org-columns-edit-allowed t]
14813 "--"
14814 ["Edit column attributes" org-columns-edit-attributes t]
14815 ["Increase column width" org-columns-widen t]
14816 ["Decrease column width" org-columns-narrow t]
14817 "--"
14818 ["Move column right" org-columns-move-right t]
14819 ["Move column left" org-columns-move-left t]
14820 ["Add column" org-columns-new t]
14821 ["Delete column" org-columns-delete t]
14822 "--"
14823 ["CONTENTS" org-columns-content t]
14824 ["OVERVIEW" org-overview t]
14825 ["Refresh columns display" org-columns-redo t]
14826 "--"
14827 ["Quit" org-columns-quit t]))
14829 (defun org-columns-new-overlay (beg end &optional string face)
14830 "Create a new column overlay and add it to the list."
14831 (let ((ov (org-make-overlay beg end)))
14832 (org-overlay-put ov 'face (or face 'secondary-selection))
14833 (org-overlay-display ov string face)
14834 (push ov org-columns-overlays)
14835 ov))
14837 (defun org-columns-display-here (&optional props)
14838 "Overlay the current line with column display."
14839 (interactive)
14840 (let* ((fmt org-columns-current-fmt-compiled)
14841 (beg (point-at-bol))
14842 (level-face (save-excursion
14843 (beginning-of-line 1)
14844 (and (looking-at "\\(\\**\\)\\(\\* \\)")
14845 (org-get-level-face 2))))
14846 (color (list :foreground
14847 (face-attribute (or level-face 'default) :foreground)))
14848 props pom property ass width f string ov column)
14849 ;; Check if the entry is in another buffer.
14850 (unless props
14851 (if (eq major-mode 'org-agenda-mode)
14852 (setq pom (or (get-text-property (point) 'org-hd-marker)
14853 (get-text-property (point) 'org-marker))
14854 props (if pom (org-entry-properties pom) nil))
14855 (setq props (org-entry-properties nil))))
14856 ;; Walk the format
14857 (while (setq column (pop fmt))
14858 (setq property (car column)
14859 ass (if (equal property "ITEM")
14860 (cons "ITEM"
14861 (save-match-data
14862 (org-no-properties
14863 (org-remove-tabs
14864 (buffer-substring-no-properties
14865 (point-at-bol) (point-at-eol))))))
14866 (assoc property props))
14867 width (or (cdr (assoc property org-columns-current-maxwidths))
14868 (nth 2 column))
14869 f (format "%%-%d.%ds | " width width)
14870 string (format f (or (cdr ass) "")))
14871 ;; Create the overlay
14872 (org-unmodified
14873 (setq ov (org-columns-new-overlay
14874 beg (setq beg (1+ beg)) string
14875 (list color 'org-column)))
14876 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14877 (org-overlay-put ov 'keymap org-columns-map)
14878 (org-overlay-put ov 'org-columns-key property)
14879 (org-overlay-put ov 'org-columns-value (cdr ass))
14880 (org-overlay-put ov 'org-columns-pom pom)
14881 (org-overlay-put ov 'org-columns-format f))
14882 (if (or (not (char-after beg))
14883 (equal (char-after beg) ?\n))
14884 (let ((inhibit-read-only t))
14885 (save-excursion
14886 (goto-char beg)
14887 (insert " ")))))
14888 ;; Make the rest of the line disappear.
14889 (org-unmodified
14890 (setq ov (org-columns-new-overlay beg (point-at-eol)))
14891 (org-overlay-put ov 'invisible t)
14892 (org-overlay-put ov 'keymap org-columns-map)
14893 (org-overlay-put ov 'intangible t)
14894 (push ov org-columns-overlays)
14895 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
14896 (org-overlay-put ov 'keymap org-columns-map)
14897 (push ov org-columns-overlays)
14898 (let ((inhibit-read-only t))
14899 (put-text-property (max (point-min) (1- (point-at-bol)))
14900 (min (point-max) (1+ (point-at-eol)))
14901 'read-only "Type `e' to edit property")))))
14903 (defvar org-previous-header-line-format nil
14904 "The header line format before column view was turned on.")
14905 (defvar org-columns-inhibit-recalculation nil
14906 "Inhibit recomputing of columns on column view startup.")
14908 (defvar header-line-format)
14909 (defun org-columns-display-here-title ()
14910 "Overlay the newline before the current line with the table title."
14911 (interactive)
14912 (let ((fmt org-columns-current-fmt-compiled)
14913 string (title "")
14914 property width f column str)
14915 (while (setq column (pop fmt))
14916 (setq property (car column)
14917 str (or (nth 1 column) property)
14918 width (or (cdr (assoc property org-columns-current-maxwidths))
14919 (nth 2 column))
14920 f (format "%%-%d.%ds | " width width)
14921 string (format f str)
14922 title (concat title string)))
14923 (setq title (concat
14924 (org-add-props " " nil 'display '(space :align-to 0))
14925 (org-add-props title nil 'face '(:weight bold :underline t))))
14926 (org-set-local 'org-previous-header-line-format header-line-format)
14927 (setq header-line-format title)))
14929 (defun org-columns-remove-overlays ()
14930 "Remove all currently active column overlays."
14931 (interactive)
14932 (when (marker-buffer org-columns-begin-marker)
14933 (with-current-buffer (marker-buffer org-columns-begin-marker)
14934 (when (local-variable-p 'org-previous-header-line-format)
14935 (setq header-line-format org-previous-header-line-format)
14936 (kill-local-variable 'org-previous-header-line-format))
14937 (move-marker org-columns-begin-marker nil)
14938 (move-marker org-columns-top-level-marker nil)
14939 (org-unmodified
14940 (mapc 'org-delete-overlay org-columns-overlays)
14941 (setq org-columns-overlays nil)
14942 (let ((inhibit-read-only t))
14943 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
14945 (defun org-columns-show-value ()
14946 "Show the full value of the property."
14947 (interactive)
14948 (let ((value (get-char-property (point) 'org-columns-value)))
14949 (message "Value is: %s" (or value ""))))
14951 (defun org-columns-quit ()
14952 "Remove the column overlays and in this way exit column editing."
14953 (interactive)
14954 (org-unmodified
14955 (org-columns-remove-overlays)
14956 (let ((inhibit-read-only t))
14957 (remove-text-properties (point-min) (point-max) '(read-only t))))
14958 (when (eq major-mode 'org-agenda-mode)
14959 (message
14960 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
14962 (defun org-columns-check-computed ()
14963 "Check if this column value is computed.
14964 If yes, throw an error indicating that changing it does not make sense."
14965 (let ((val (get-char-property (point) 'org-columns-value)))
14966 (when (and (stringp val)
14967 (get-char-property 0 'org-computed val))
14968 (error "This value is computed from the entry's children"))))
14970 (defun org-columns-edit-value ()
14971 "Edit the value of the property at point in column view.
14972 Where possible, use the standard interface for changing this line."
14973 (interactive)
14974 (org-columns-check-computed)
14975 (let* ((col (current-column))
14976 (key (get-char-property (point) 'org-columns-key))
14977 (value (get-char-property (point) 'org-columns-value))
14978 (bol (point-at-bol)) (eol (point-at-eol))
14979 (pom (or (get-text-property bol 'org-hd-marker)
14980 (point))) ; keep despite of compiler waring
14981 (line-overlays
14982 (delq nil (mapcar (lambda (x)
14983 (and (eq (overlay-buffer x) (current-buffer))
14984 (>= (overlay-start x) bol)
14985 (<= (overlay-start x) eol)
14987 org-columns-overlays)))
14988 nval eval allowed)
14989 (when (equal key "ITEM")
14990 (error "Cannot edit item headline from here"))
14992 (cond
14993 ((equal key "TODO")
14994 (setq eval '(org-with-point-at pom
14995 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14996 ((equal key "PRIORITY")
14997 (setq eval '(org-with-point-at pom
14998 (call-interactively 'org-priority))))
14999 ((equal key "TAGS")
15000 (setq eval '(org-with-point-at pom
15001 (let ((org-fast-tag-selection-single-key
15002 (if (eq org-fast-tag-selection-single-key 'expert)
15003 t org-fast-tag-selection-single-key)))
15004 (call-interactively 'org-set-tags)))))
15005 ((equal key "DEADLINE")
15006 (setq eval '(org-with-point-at pom
15007 (call-interactively 'org-deadline))))
15008 ((equal key "SCHEDULED")
15009 (setq eval '(org-with-point-at pom
15010 (call-interactively 'org-schedule))))
15012 (setq allowed (org-property-get-allowed-values pom key 'table))
15013 (if allowed
15014 (setq nval (completing-read "Value: " allowed nil t))
15015 (setq nval (read-string "Edit: " value)))
15016 (setq nval (org-trim nval))
15017 (when (not (equal nval value))
15018 (setq eval '(org-entry-put pom key nval)))))
15019 (when eval
15020 (let ((inhibit-read-only t))
15021 (remove-text-properties (1- bol) eol '(read-only t))
15022 (unwind-protect
15023 (progn
15024 (setq org-columns-overlays
15025 (org-delete-all line-overlays org-columns-overlays))
15026 (mapc 'org-delete-overlay line-overlays)
15027 (org-columns-eval eval))
15028 (org-columns-display-here))))
15029 (move-to-column col)
15030 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15031 (org-columns-update key))))
15033 (defun org-columns-edit-allowed ()
15034 "Edit the list of allowed values for the current property."
15035 (interactive)
15036 (let* ((col (current-column))
15037 (key (get-char-property (point) 'org-columns-key))
15038 (key1 (concat key "_ALL"))
15039 (value (get-char-property (point) 'org-columns-value))
15040 (allowed (org-entry-get (point) key1 t))
15041 nval)
15042 (setq nval (read-string "Allowed: " allowed))
15043 (org-entry-put
15044 (cond ((marker-position org-entry-property-inherited-from)
15045 org-entry-property-inherited-from)
15046 ((marker-position org-columns-top-level-marker)
15047 org-columns-top-level-marker))
15048 key1 nval)))
15050 (defun org-columns-eval (form)
15051 (let (hidep)
15052 (save-excursion
15053 (beginning-of-line 1)
15054 (next-line 1)
15055 (setq hidep (org-on-heading-p 1)))
15056 (eval form)
15057 (and hidep (hide-entry))))
15059 (defun org-columns-previous-allowed-value ()
15060 "Switch to the previous allowed value for this column."
15061 (interactive)
15062 (org-columns-next-allowed-value t))
15064 (defun org-columns-next-allowed-value (&optional previous)
15065 "Switch to the next allowed value for this column."
15066 (interactive)
15067 (org-columns-check-computed)
15068 (let* ((col (current-column))
15069 (key (get-char-property (point) 'org-columns-key))
15070 (value (get-char-property (point) 'org-columns-value))
15071 (bol (point-at-bol)) (eol (point-at-eol))
15072 (pom (or (get-text-property bol 'org-hd-marker)
15073 (point))) ; keep despite of compiler waring
15074 (line-overlays
15075 (delq nil (mapcar (lambda (x)
15076 (and (eq (overlay-buffer x) (current-buffer))
15077 (>= (overlay-start x) bol)
15078 (<= (overlay-start x) eol)
15080 org-columns-overlays)))
15081 (allowed (or (org-property-get-allowed-values pom key)
15082 (and (equal
15083 (nth 4 (assoc key org-columns-current-fmt-compiled))
15084 'checkbox) '("[ ]" "[X]"))))
15085 nval)
15086 (when (equal key "ITEM")
15087 (error "Cannot edit item headline from here"))
15088 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15089 (error "Allowed values for this property have not been defined"))
15090 (if (member key '("SCHEDULED" "DEADLINE"))
15091 (setq nval (if previous 'earlier 'later))
15092 (if previous (setq allowed (reverse allowed)))
15093 (if (member value allowed)
15094 (setq nval (car (cdr (member value allowed)))))
15095 (setq nval (or nval (car allowed)))
15096 (if (equal nval value)
15097 (error "Only one allowed value for this property")))
15098 (let ((inhibit-read-only t))
15099 (remove-text-properties (1- bol) eol '(read-only t))
15100 (unwind-protect
15101 (progn
15102 (setq org-columns-overlays
15103 (org-delete-all line-overlays org-columns-overlays))
15104 (mapc 'org-delete-overlay line-overlays)
15105 (org-columns-eval '(org-entry-put pom key nval)))
15106 (org-columns-display-here)))
15107 (move-to-column col)
15108 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15109 (org-columns-update key))))
15111 (defun org-verify-version (task)
15112 (cond
15113 ((eq task 'columns)
15114 (if (or (featurep 'xemacs)
15115 (< emacs-major-version 22))
15116 (error "Emacs 22 is required for the columns feature")))))
15118 (defun org-columns-get-format-and-top-level ()
15119 (let (fmt)
15120 (when (condition-case nil (org-back-to-heading) (error nil))
15121 (move-marker org-entry-property-inherited-from nil)
15122 (setq fmt (org-entry-get nil "COLUMNS" t)))
15123 (setq fmt (or fmt org-columns-default-format))
15124 (org-set-local 'org-columns-current-fmt fmt)
15125 (org-columns-compile-format fmt)
15126 (if (marker-position org-entry-property-inherited-from)
15127 (move-marker org-columns-top-level-marker
15128 org-entry-property-inherited-from)
15129 (move-marker org-columns-top-level-marker (point)))
15130 fmt))
15132 (defun org-columns ()
15133 "Turn on column view on an org-mode file."
15134 (interactive)
15135 (org-verify-version 'columns)
15136 (org-columns-remove-overlays)
15137 (move-marker org-columns-begin-marker (point))
15138 (let (beg end fmt cache maxwidths)
15139 (setq fmt (org-columns-get-format-and-top-level))
15140 (save-excursion
15141 (goto-char org-columns-top-level-marker)
15142 (setq beg (point))
15143 (unless org-columns-inhibit-recalculation
15144 (org-columns-compute-all))
15145 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15146 (point-max)))
15147 (goto-char beg)
15148 ;; Get and cache the properties
15149 (while (re-search-forward (concat "^" outline-regexp) end t)
15150 (push (cons (org-current-line) (org-entry-properties)) cache))
15151 (when cache
15152 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15153 (org-set-local 'org-columns-current-maxwidths maxwidths)
15154 (org-columns-display-here-title)
15155 (mapc (lambda (x)
15156 (goto-line (car x))
15157 (org-columns-display-here (cdr x)))
15158 cache)))))
15160 (defun org-columns-new (&optional prop title width op fmt)
15161 "Insert a new column, to the leeft o the current column."
15162 (interactive)
15163 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15164 cell)
15165 (setq prop (completing-read
15166 "Property: " (mapcar 'list (org-buffer-property-keys t))
15167 nil nil prop))
15168 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15169 (setq width (read-string "Column width: " (if width (number-to-string width))))
15170 (if (string-match "\\S-" width)
15171 (setq width (string-to-number width))
15172 (setq width nil))
15173 (setq fmt (completing-read "Summary [none]: "
15174 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15175 nil t))
15176 (if (string-match "\\S-" fmt)
15177 (setq fmt (intern fmt))
15178 (setq fmt nil))
15179 (if (eq fmt 'none) (setq fmt nil))
15180 (if editp
15181 (progn
15182 (setcar editp prop)
15183 (setcdr editp (list title width nil fmt)))
15184 (setq cell (nthcdr (1- (current-column))
15185 org-columns-current-fmt-compiled))
15186 (setcdr cell (cons (list prop title width nil fmt)
15187 (cdr cell))))
15188 (org-columns-store-format)
15189 (org-columns-redo)))
15191 (defun org-columns-delete ()
15192 "Delete the column at point from columns view."
15193 (interactive)
15194 (let* ((n (current-column))
15195 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15196 (when (y-or-n-p
15197 (format "Are you sure you want to remove column \"%s\"? " title))
15198 (setq org-columns-current-fmt-compiled
15199 (delq (nth n org-columns-current-fmt-compiled)
15200 org-columns-current-fmt-compiled))
15201 (org-columns-store-format)
15202 (org-columns-redo)
15203 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15204 (backward-char 1)))))
15206 (defun org-columns-edit-attributes ()
15207 "Edit the attributes of the current column."
15208 (interactive)
15209 (let* ((n (current-column))
15210 (info (nth n org-columns-current-fmt-compiled)))
15211 (apply 'org-columns-new info)))
15213 (defun org-columns-widen (arg)
15214 "Make the column wider by ARG characters."
15215 (interactive "p")
15216 (let* ((n (current-column))
15217 (entry (nth n org-columns-current-fmt-compiled))
15218 (width (or (nth 2 entry)
15219 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15220 (setq width (max 1 (+ width arg)))
15221 (setcar (nthcdr 2 entry) width)
15222 (org-columns-store-format)
15223 (org-columns-redo)))
15225 (defun org-columns-narrow (arg)
15226 "Make the column nrrower by ARG characters."
15227 (interactive "p")
15228 (org-columns-widen (- arg)))
15230 (defun org-columns-move-right ()
15231 "Swap this column with the one to the right."
15232 (interactive)
15233 (let* ((n (current-column))
15234 (cell (nthcdr n org-columns-current-fmt-compiled))
15236 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15237 (error "Cannot shift this column further to the right"))
15238 (setq e (car cell))
15239 (setcar cell (car (cdr cell)))
15240 (setcdr cell (cons e (cdr (cdr cell))))
15241 (org-columns-store-format)
15242 (org-columns-redo)
15243 (forward-char 1)))
15245 (defun org-columns-move-left ()
15246 "Swap this column with the one to the left."
15247 (interactive)
15248 (let* ((n (current-column)))
15249 (when (= n 0)
15250 (error "Cannot shift this column further to the left"))
15251 (backward-char 1)
15252 (org-columns-move-right)
15253 (backward-char 1)))
15255 (defun org-columns-store-format ()
15256 "Store the text version of the current columns format in appropriate place.
15257 This is either in the COLUMNS property of the node starting the current column
15258 display, or in the #+COLUMNS line of the current buffer."
15259 (let (fmt)
15260 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15261 (if (marker-position org-columns-top-level-marker)
15262 (save-excursion
15263 (goto-char org-columns-top-level-marker)
15264 (if (org-entry-get nil "COLUMNS")
15265 (org-entry-put nil "COLUMNS" fmt)
15266 (goto-char (point-min))
15267 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15268 (replace-match (concat "#+COLUMNS: " fmt t t)))))
15269 (setq org-columns-current-fmt fmt))))
15271 (defvar org-overriding-columns-format nil
15272 "When set, overrides any other definition.")
15273 (defvar org-agenda-view-columns-initially nil
15274 "When set, switch to columns view immediately after creating the agenda.")
15276 (defun org-agenda-columns ()
15277 "Turn on column view in the agenda."
15278 (interactive)
15279 (org-verify-version 'columns)
15280 (org-columns-remove-overlays)
15281 (move-marker org-columns-begin-marker (point))
15282 (let (fmt cache maxwidths m)
15283 (cond
15284 ((and (local-variable-p 'org-overriding-columns-format)
15285 org-overriding-columns-format)
15286 (setq fmt org-overriding-columns-format))
15287 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15288 (setq fmt (org-entry-get m "COLUMNS" t)))
15289 ((and (boundp 'org-columns-current-fmt)
15290 (local-variable-p 'org-columns-current-fmt)
15291 org-columns-current-fmt)
15292 (setq fmt org-columns-current-fmt))
15293 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15294 (setq m (get-text-property m 'org-hd-marker))
15295 (setq fmt (org-entry-get m "COLUMNS" t))))
15296 (setq fmt (or fmt org-columns-default-format))
15297 (org-set-local 'org-columns-current-fmt fmt)
15298 (org-columns-compile-format fmt)
15299 (save-excursion
15300 ;; Get and cache the properties
15301 (goto-char (point-min))
15302 (while (not (eobp))
15303 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15304 (get-text-property (point) 'org-marker)))
15305 (push (cons (org-current-line) (org-entry-properties m)) cache))
15306 (beginning-of-line 2))
15307 (when cache
15308 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15309 (org-set-local 'org-columns-current-maxwidths maxwidths)
15310 (org-columns-display-here-title)
15311 (mapc (lambda (x)
15312 (goto-line (car x))
15313 (org-columns-display-here (cdr x)))
15314 cache)))))
15316 (defun org-columns-get-autowidth-alist (s cache)
15317 "Derive the maximum column widths from the format and the cache."
15318 (let ((start 0) rtn)
15319 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15320 (push (cons (match-string 1 s) 1) rtn)
15321 (setq start (match-end 0)))
15322 (mapc (lambda (x)
15323 (setcdr x (apply 'max
15324 (mapcar
15325 (lambda (y)
15326 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15327 cache))))
15328 rtn)
15329 rtn))
15331 (defun org-columns-compute-all ()
15332 "Compute all columns that have operators defined."
15333 (org-unmodified
15334 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15335 (let ((columns org-columns-current-fmt-compiled) col)
15336 (while (setq col (pop columns))
15337 (when (nth 3 col)
15338 (save-excursion
15339 (org-columns-compute (car col)))))))
15341 (defun org-columns-update (property)
15342 "Recompute PROPERTY, and update the columns display for it."
15343 (org-columns-compute property)
15344 (let (fmt val pos)
15345 (save-excursion
15346 (mapc (lambda (ov)
15347 (when (equal (org-overlay-get ov 'org-columns-key) property)
15348 (setq pos (org-overlay-start ov))
15349 (goto-char pos)
15350 (when (setq val (cdr (assoc property
15351 (get-text-property
15352 (point-at-bol) 'org-summaries))))
15353 (setq fmt (org-overlay-get ov 'org-columns-format))
15354 (org-overlay-put ov 'org-columns-value val)
15355 (org-overlay-put ov 'display (format fmt val)))))
15356 org-columns-overlays))))
15358 (defun org-columns-compute (property)
15359 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15360 (interactive)
15361 (let* ((re (concat "^" outline-regexp))
15362 (lmax 30) ; Does anyone use deeper levels???
15363 (lsum (make-vector lmax 0))
15364 (lflag (make-vector lmax nil))
15365 (level 0)
15366 (ass (assoc property org-columns-current-fmt-compiled))
15367 (format (nth 4 ass))
15368 (beg org-columns-top-level-marker)
15369 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15370 (save-excursion
15371 ;; Find the region to compute
15372 (goto-char beg)
15373 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15374 (goto-char end)
15375 ;; Walk the tree from the back and do the computations
15376 (while (re-search-backward re beg t)
15377 (setq sumpos (match-beginning 0)
15378 last-level level
15379 level (org-outline-level)
15380 val (org-entry-get nil property)
15381 valflag (and val (string-match "\\S-" val)))
15382 (cond
15383 ((< level last-level)
15384 ;; put the sum of lower levels here as a property
15385 (setq sum (aref lsum last-level) ; current sum
15386 flag (aref lflag last-level) ; any valid entries from children?
15387 str (org-column-number-to-string sum format)
15388 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15389 useval (if flag str1 (if valflag val ""))
15390 sum-alist (get-text-property sumpos 'org-summaries))
15391 (if (assoc property sum-alist)
15392 (setcdr (assoc property sum-alist) useval)
15393 (push (cons property useval) sum-alist)
15394 (org-unmodified
15395 (add-text-properties sumpos (1+ sumpos)
15396 (list 'org-summaries sum-alist))))
15397 (when val
15398 (org-entry-put nil property (if flag str val)))
15399 ;; add current to current level accumulator
15400 (when (or flag valflag)
15401 ;; FIXME: is this ok?????????
15402 (aset lsum level (+ (aref lsum level)
15403 (if flag sum (org-column-string-to-number
15404 (if flag str val) format))))
15405 (aset lflag level t))
15406 ;; clear accumulators for deeper levels
15407 (loop for l from (1+ level) to (1- lmax) do
15408 (aset lsum l 0)
15409 (aset lflag l nil)))
15410 ((>= level last-level)
15411 ;; add what we have here to the accumulator for this level
15412 (aset lsum level (+ (aref lsum level)
15413 (org-column-string-to-number (or val "0") format)))
15414 (and valflag (aset lflag level t)))
15415 (t (error "This should not happen")))))))
15417 (defun org-columns-redo ()
15418 "Construct the column display again."
15419 (interactive)
15420 (message "Recomputing columns...")
15421 (save-excursion
15422 (if (marker-position org-columns-begin-marker)
15423 (goto-char org-columns-begin-marker))
15424 (org-columns-remove-overlays)
15425 (if (org-mode-p)
15426 (call-interactively 'org-columns)
15427 (call-interactively 'org-agenda-columns)))
15428 (message "Recomputing columns...done"))
15430 (defun org-columns-not-in-agenda ()
15431 (if (eq major-mode 'org-agenda-mode)
15432 (error "This command is only allowed in Org-mode buffers")))
15435 (defun org-string-to-number (s)
15436 "Convert string to number, and interpret hh:mm:ss."
15437 (if (not (string-match ":" s))
15438 (string-to-number s)
15439 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15440 (while l
15441 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15442 sum)))
15444 (defun org-column-number-to-string (n fmt)
15445 "Convert a computed column number to a string value, according to FMT."
15446 (cond
15447 ((eq fmt 'add_times)
15448 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
15449 (format "%d:%02d" h m)))
15450 ((eq fmt 'checkbox)
15451 (cond ((= n (floor n)) "[X]")
15452 ((> n 1.) "[-]")
15453 (t "[ ]")))
15454 (t (number-to-string n))))
15456 (defun org-column-string-to-number (s fmt)
15457 "Convert a column value to a number that can be used for column computing."
15458 (cond
15459 ((string-match ":" s)
15460 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15461 (while l
15462 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
15463 sum))
15464 ((eq fmt 'checkbox)
15465 (if (equal s "[X]") 1. 0.000001))
15466 (t (string-to-number s))))
15468 (defun org-columns-uncompile-format (cfmt)
15469 "Turn the compiled columns format back into a string representation."
15470 (let ((rtn "") e s prop title op width fmt)
15471 (while (setq e (pop cfmt))
15472 (setq prop (car e)
15473 title (nth 1 e)
15474 width (nth 2 e)
15475 op (nth 3 e)
15476 fmt (nth 4 e))
15477 (cond
15478 ((eq fmt 'add_times) (setq op ":"))
15479 ((eq fmt 'checkbox) (setq op "X"))
15480 ((eq fmt 'add_numbers) (setq op "+")))
15481 (if (equal title prop) (setq title nil))
15482 (setq s (concat "%" (if width (number-to-string width))
15483 prop
15484 (if title (concat "(" title ")"))
15485 (if op (concat "{" op "}"))))
15486 (setq rtn (concat rtn " " s)))
15487 (org-trim rtn)))
15489 (defun org-columns-compile-format (fmt)
15490 "Turn a column format string into an alist of specifications.
15491 The alist has one entry for each column in the format. The elements of
15492 that list are:
15493 property the property
15494 title the title field for the columns
15495 width the column width in characters, can be nil for automatic
15496 operator the operator if any
15497 format the output format for computed results, derived from operator"
15498 (let ((start 0) width prop title op f)
15499 (setq org-columns-current-fmt-compiled nil)
15500 (while (string-match
15501 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
15502 fmt start)
15503 (setq start (match-end 0)
15504 width (match-string 1 fmt)
15505 prop (match-string 2 fmt)
15506 title (or (match-string 3 fmt) prop)
15507 op (match-string 4 fmt)
15508 f nil)
15509 (if width (setq width (string-to-number width)))
15510 (cond
15511 ((equal op "+") (setq f 'add_numbers))
15512 ((equal op ":") (setq f 'add_times))
15513 ((equal op "X") (setq f 'checkbox)))
15514 (push (list prop title width op f) org-columns-current-fmt-compiled))
15515 (setq org-columns-current-fmt-compiled
15516 (nreverse org-columns-current-fmt-compiled))))
15518 ;;;; Timestamps
15520 (defvar org-last-changed-timestamp nil)
15521 (defvar org-time-was-given) ; dynamically scoped parameter
15522 (defvar org-end-time-was-given) ; dynamically scoped parameter
15523 (defvar org-ts-what) ; dynamically scoped parameter
15525 (defun org-time-stamp (arg)
15526 "Prompt for a date/time and insert a time stamp.
15527 If the user specifies a time like HH:MM, or if this command is called
15528 with a prefix argument, the time stamp will contain date and time.
15529 Otherwise, only the date will be included. All parts of a date not
15530 specified by the user will be filled in from the current date/time.
15531 So if you press just return without typing anything, the time stamp
15532 will represent the current date/time. If there is already a timestamp
15533 at the cursor, it will be modified."
15534 (interactive "P")
15535 (let ((default-time
15536 ;; Default time is either today, or, when entering a range,
15537 ;; the range start.
15538 (if (or (org-at-timestamp-p t)
15539 (save-excursion
15540 (re-search-backward
15541 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15542 (- (point) 20) t)))
15543 (apply 'encode-time (org-parse-time-string (match-string 1)))
15544 (current-time)))
15545 org-time-was-given org-end-time-was-given time)
15546 (cond
15547 ((and (org-at-timestamp-p)
15548 (eq last-command 'org-time-stamp)
15549 (eq this-command 'org-time-stamp))
15550 (insert "--")
15551 (setq time (let ((this-command this-command))
15552 (org-read-date arg 'totime nil nil default-time)))
15553 (org-insert-time-stamp time (or org-time-was-given arg)))
15554 ((org-at-timestamp-p)
15555 (setq time (let ((this-command this-command))
15556 (org-read-date arg 'totime nil nil default-time)))
15557 (when (org-at-timestamp-p) ; just to get the match data
15558 (replace-match "")
15559 (setq org-last-changed-timestamp
15560 (org-insert-time-stamp
15561 time (or org-time-was-given arg)
15562 nil nil nil (list org-end-time-was-given))))
15563 (message "Timestamp updated"))
15565 (setq time (let ((this-command this-command))
15566 (org-read-date arg 'totime nil nil default-time)))
15567 (org-insert-time-stamp time (or org-time-was-given arg)
15568 nil nil nil (list org-end-time-was-given))))))
15570 (defun org-time-stamp-inactive (&optional arg)
15571 "Insert an inactive time stamp.
15572 An inactive time stamp is enclosed in square brackets instead of angle
15573 brackets. It is inactive in the sense that it does not trigger agenda entries,
15574 does not link to the calendar and cannot be changed with the S-cursor keys.
15575 So these are more for recording a certain time/date."
15576 (interactive "P")
15577 (let (org-time-was-given org-end-time-was-given time)
15578 (setq time (org-read-date arg 'totime))
15579 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
15580 nil nil (list org-end-time-was-given))))
15582 (defvar org-date-ovl (org-make-overlay 1 1))
15583 (org-overlay-put org-date-ovl 'face 'org-warning)
15584 (org-detach-overlay org-date-ovl)
15586 (defvar org-ans1) ; dynamically scoped parameter
15587 (defvar org-ans2) ; dynamically scoped parameter
15589 (defvar org-plain-time-of-day-regexp) ; defined below
15590 (defun org-read-date (&optional with-time to-time from-string prompt
15591 default-time)
15592 "Read a date and make things smooth for the user.
15593 The prompt will suggest to enter an ISO date, but you can also enter anything
15594 which will at least partially be understood by `parse-time-string'.
15595 Unrecognized parts of the date will default to the current day, month, year,
15596 hour and minute. If this command is called to replace a timestamp at point,
15597 of to enter the second timestamp of a range, the default time is taken from the
15598 existing stamp. For example,
15599 3-2-5 --> 2003-02-05
15600 feb 15 --> currentyear-02-15
15601 sep 12 9 --> 2009-09-12
15602 12:45 --> today 12:45
15603 22 sept 0:34 --> currentyear-09-22 0:34
15604 12 --> currentyear-currentmonth-12
15605 Fri --> nearest Friday (today or later)
15606 +4 --> four days from today (only if +N is the only thing given)
15607 etc.
15608 The function understands only English month and weekday abbreviations,
15609 but this can be configured with the variables `parse-time-months' and
15610 `parse-time-weekdays'.
15612 While prompting, a calendar is popped up - you can also select the
15613 date with the mouse (button 1). The calendar shows a period of three
15614 months. To scroll it to other months, use the keys `>' and `<'.
15615 If you don't like the calendar, turn it off with
15616 \(setq org-popup-calendar-for-date-prompt nil)
15618 With optional argument TO-TIME, the date will immediately be converted
15619 to an internal time.
15620 With an optional argument WITH-TIME, the prompt will suggest to also
15621 insert a time. Note that when WITH-TIME is not set, you can still
15622 enter a time, and this function will inform the calling routine about
15623 this change. The calling routine may then choose to change the format
15624 used to insert the time stamp into the buffer to include the time.
15625 With optional argument FROM-STRING, read fomr this string instead from
15626 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
15627 the time/date that is used for everything that is not specified by the
15628 user."
15629 (require 'parse-time)
15630 (let* ((org-time-stamp-rounding-minutes
15631 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
15632 (ct (org-current-time))
15633 (def (or default-time ct))
15634 (calendar-move-hook nil)
15635 (view-diary-entries-initially nil)
15636 (view-calendar-holidays-initially nil)
15637 (timestr (format-time-string
15638 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
15639 (prompt (concat (if prompt (concat prompt " ") "")
15640 (format "Date and/or time (default [%s]): " timestr)))
15641 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
15642 second minute hour day month year tl wday wday1 pm h2 m2)
15644 (cond
15645 (from-string (setq ans from-string))
15646 (org-popup-calendar-for-date-prompt
15647 (save-excursion
15648 (save-window-excursion
15649 (calendar)
15650 (calendar-forward-day (- (time-to-days def)
15651 (calendar-absolute-from-gregorian
15652 (calendar-current-date))))
15653 (org-eval-in-calendar nil t)
15654 (let* ((old-map (current-local-map))
15655 (map (copy-keymap calendar-mode-map))
15656 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15657 (org-defkey map (kbd "RET") 'org-calendar-select)
15658 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15659 'org-calendar-select-mouse)
15660 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15661 'org-calendar-select-mouse)
15662 (org-defkey minibuffer-local-map [(meta shift left)]
15663 (lambda () (interactive)
15664 (org-eval-in-calendar '(calendar-backward-month 1))))
15665 (org-defkey minibuffer-local-map [(meta shift right)]
15666 (lambda () (interactive)
15667 (org-eval-in-calendar '(calendar-forward-month 1))))
15668 (org-defkey minibuffer-local-map [(shift up)]
15669 (lambda () (interactive)
15670 (org-eval-in-calendar '(calendar-backward-week 1))))
15671 (org-defkey minibuffer-local-map [(shift down)]
15672 (lambda () (interactive)
15673 (org-eval-in-calendar '(calendar-forward-week 1))))
15674 (org-defkey minibuffer-local-map [(shift left)]
15675 (lambda () (interactive)
15676 (org-eval-in-calendar '(calendar-backward-day 1))))
15677 (org-defkey minibuffer-local-map [(shift right)]
15678 (lambda () (interactive)
15679 (org-eval-in-calendar '(calendar-forward-day 1))))
15680 (org-defkey minibuffer-local-map ">"
15681 (lambda () (interactive)
15682 (org-eval-in-calendar '(scroll-calendar-left 1))))
15683 (org-defkey minibuffer-local-map "<"
15684 (lambda () (interactive)
15685 (org-eval-in-calendar '(scroll-calendar-right 1))))
15686 (unwind-protect
15687 (progn
15688 (use-local-map map)
15689 (setq org-ans0 (read-string prompt "" nil nil))
15690 ;; org-ans0: from prompt
15691 ;; org-ans1: from mouse click
15692 ;; org-ans2: from calendar motion
15693 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15694 (use-local-map old-map))))))
15695 (t ; Naked prompt only
15696 (setq ans (read-string prompt "" nil timestr))))
15697 (org-detach-overlay org-date-ovl)
15699 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
15700 (setq deltadays (string-to-number ans) ans ""))
15702 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15703 (when (string-match
15704 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15705 (setq year (if (match-end 2)
15706 (string-to-number (match-string 2 ans))
15707 (string-to-number (format-time-string "%Y")))
15708 month (string-to-number (match-string 3 ans))
15709 day (string-to-number (match-string 4 ans)))
15710 (if (< year 100) (setq year (+ 2000 year)))
15711 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15712 t nil ans)))
15713 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15714 ;; If there is a time with am/pm, and *no* time without it, we convert
15715 ;; so that matching will be successful.
15716 (loop for i from 1 to 2 do ; twice, for end time as well
15717 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15718 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15719 (setq hour (string-to-number (match-string 1 ans))
15720 minute (if (match-end 3)
15721 (string-to-number (match-string 3 ans))
15723 pm (equal ?p
15724 (string-to-char (downcase (match-string 4 ans)))))
15725 (if (and (= hour 12) (not pm))
15726 (setq hour 0)
15727 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15728 (setq ans (replace-match (format "%02d:%02d" hour minute)
15729 t t ans))))
15731 ;; Check if a time range is given as a duration
15732 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
15733 (setq hour (string-to-number (match-string 1 ans))
15734 h2 (+ hour (string-to-number (match-string 3 ans)))
15735 minute (string-to-number (match-string 2 ans))
15736 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
15737 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
15739 ;; Check if there is a time range
15740 (when (and (boundp 'org-end-time-was-given)
15741 (string-match org-plain-time-of-day-regexp ans)
15742 (match-end 8))
15743 (setq org-end-time-was-given (match-string 8 ans))
15744 (setq ans (concat (substring ans 0 (match-beginning 7))
15745 (substring ans (match-end 7)))))
15747 (setq tl (parse-time-string ans)
15748 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
15749 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
15750 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
15751 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
15752 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
15753 second (or (nth 0 tl) 0)
15754 wday (nth 6 tl))
15755 (setq day (+ day deltadays))
15756 (when (and wday (not (nth 3 tl)))
15757 ;; Weekday was given, but no day, so pick that day in the week
15758 ;; on or after the derived date.
15759 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15760 (unless (equal wday wday1)
15761 (setq day (+ day (% (- wday wday1 -7) 7)))))
15762 (if (and (boundp 'org-time-was-given)
15763 (nth 2 tl))
15764 (setq org-time-was-given t))
15765 (if (< year 100) (setq year (+ 2000 year)))
15766 (if to-time
15767 (encode-time second minute hour day month year)
15768 (if (or (nth 1 tl) (nth 2 tl))
15769 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15770 (format "%04d-%02d-%02d" year month day)))))
15772 (defun org-eval-in-calendar (form &optional keepdate)
15773 "Eval FORM in the calendar window and return to current window.
15774 Also, store the cursor date in variable org-ans2."
15775 (let ((sw (selected-window)))
15776 (select-window (get-buffer-window "*Calendar*"))
15777 (eval form)
15778 (when (and (not keepdate) (calendar-cursor-to-date))
15779 (let* ((date (calendar-cursor-to-date))
15780 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15781 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15782 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15783 (select-window sw)
15784 ;; Update the prompt to show new default date
15785 (save-excursion
15786 (goto-char (point-min))
15787 (when (and org-ans2
15788 (re-search-forward "\\[[-0-9]+\\]" nil t)
15789 (get-text-property (match-end 0) 'field))
15790 (let ((inhibit-read-only t))
15791 (replace-match (concat "[" org-ans2 "]") t t)
15792 (add-text-properties (point-min) (1+ (match-end 0))
15793 (text-properties-at (1+ (point-min)))))))))
15795 (defun org-calendar-select ()
15796 "Return to `org-read-date' with the date currently selected.
15797 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15798 (interactive)
15799 (when (calendar-cursor-to-date)
15800 (let* ((date (calendar-cursor-to-date))
15801 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15802 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15803 (if (active-minibuffer-window) (exit-minibuffer))))
15805 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15806 "Insert a date stamp for the date given by the internal TIME.
15807 WITH-HM means, use the stamp format that includes the time of the day.
15808 INACTIVE means use square brackets instead of angular ones, so that the
15809 stamp will not contribute to the agenda.
15810 PRE and POST are optional strings to be inserted before and after the
15811 stamp.
15812 The command returns the inserted time stamp."
15813 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15814 stamp)
15815 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15816 (insert (or pre ""))
15817 (insert (setq stamp (format-time-string fmt time)))
15818 (when (listp extra)
15819 (setq extra (car extra))
15820 (if (and (stringp extra)
15821 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15822 (setq extra (format "-%02d:%02d"
15823 (string-to-number (match-string 1 extra))
15824 (string-to-number (match-string 2 extra))))
15825 (setq extra nil)))
15826 (when extra
15827 (backward-char 1)
15828 (insert extra)
15829 (forward-char 1))
15830 (insert (or post ""))
15831 stamp))
15833 (defun org-toggle-time-stamp-overlays ()
15834 "Toggle the use of custom time stamp formats."
15835 (interactive)
15836 (setq org-display-custom-times (not org-display-custom-times))
15837 (unless org-display-custom-times
15838 (let ((p (point-min)) (bmp (buffer-modified-p)))
15839 (while (setq p (next-single-property-change p 'display))
15840 (if (and (get-text-property p 'display)
15841 (eq (get-text-property p 'face) 'org-date))
15842 (remove-text-properties
15843 p (setq p (next-single-property-change p 'display))
15844 '(display t))))
15845 (set-buffer-modified-p bmp)))
15846 (if (featurep 'xemacs)
15847 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15848 (org-restart-font-lock)
15849 (setq org-table-may-need-update t)
15850 (if org-display-custom-times
15851 (message "Time stamps are overlayed with custom format")
15852 (message "Time stamp overlays removed")))
15854 (defun org-display-custom-time (beg end)
15855 "Overlay modified time stamp format over timestamp between BED and END."
15856 (let* ((ts (buffer-substring beg end))
15857 t1 w1 with-hm tf time str w2 (off 0))
15858 (save-match-data
15859 (setq t1 (org-parse-time-string ts t))
15860 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
15861 (setq off (- (match-end 0) (match-beginning 0)))))
15862 (setq end (- end off))
15863 (setq w1 (- end beg)
15864 with-hm (and (nth 1 t1) (nth 2 t1))
15865 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15866 time (org-fix-decoded-time t1)
15867 str (org-add-props
15868 (format-time-string
15869 (substring tf 1 -1) (apply 'encode-time time))
15870 nil 'mouse-face 'highlight)
15871 w2 (length str))
15872 (if (not (= w2 w1))
15873 (add-text-properties (1+ beg) (+ 2 beg)
15874 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15875 (if (featurep 'xemacs)
15876 (progn
15877 (put-text-property beg end 'invisible t)
15878 (put-text-property beg end 'end-glyph (make-glyph str)))
15879 (put-text-property beg end 'display str))))
15881 (defun org-translate-time (string)
15882 "Translate all timestamps in STRING to custom format.
15883 But do this only if the variable `org-display-custom-times' is set."
15884 (when org-display-custom-times
15885 (save-match-data
15886 (let* ((start 0)
15887 (re org-ts-regexp-both)
15888 t1 with-hm inactive tf time str beg end)
15889 (while (setq start (string-match re string start))
15890 (setq beg (match-beginning 0)
15891 end (match-end 0)
15892 t1 (save-match-data
15893 (org-parse-time-string (substring string beg end) t))
15894 with-hm (and (nth 1 t1) (nth 2 t1))
15895 inactive (equal (substring string beg (1+ beg)) "[")
15896 tf (funcall (if with-hm 'cdr 'car)
15897 org-time-stamp-custom-formats)
15898 time (org-fix-decoded-time t1)
15899 str (format-time-string
15900 (concat
15901 (if inactive "[" "<") (substring tf 1 -1)
15902 (if inactive "]" ">"))
15903 (apply 'encode-time time))
15904 string (replace-match str t t string)
15905 start (+ start (length str)))))))
15906 string)
15908 (defun org-fix-decoded-time (time)
15909 "Set 0 instead of nil for the first 6 elements of time.
15910 Don't touch the rest."
15911 (let ((n 0))
15912 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15914 (defun org-days-to-time (timestamp-string)
15915 "Difference between TIMESTAMP-STRING and now in days."
15916 (- (time-to-days (org-time-string-to-time timestamp-string))
15917 (time-to-days (current-time))))
15919 (defun org-deadline-close (timestamp-string &optional ndays)
15920 "Is the time in TIMESTAMP-STRING close to the current date?"
15921 (setq ndays (or ndays (org-get-wdays timestamp-string)))
15922 (and (< (org-days-to-time timestamp-string) ndays)
15923 (not (org-entry-is-done-p))))
15925 (defun org-get-wdays (ts)
15926 "Get the deadline lead time appropriate for timestring TS."
15927 (cond
15928 ((<= org-deadline-warning-days 0)
15929 ;; 0 or negative, enforce this value no matter what
15930 (- org-deadline-warning-days))
15931 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
15932 ;; lead time is specified.
15933 (floor (* (string-to-number (match-string 1 ts))
15934 (cdr (assoc (match-string 2 ts)
15935 '(("d" . 1) ("w" . 7)
15936 ("m" . 30.4) ("y" . 365.25)))))))
15937 ;; go for the default.
15938 (t org-deadline-warning-days)))
15940 (defun org-calendar-select-mouse (ev)
15941 "Return to `org-read-date' with the date currently selected.
15942 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15943 (interactive "e")
15944 (mouse-set-point ev)
15945 (when (calendar-cursor-to-date)
15946 (let* ((date (calendar-cursor-to-date))
15947 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15948 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15949 (if (active-minibuffer-window) (exit-minibuffer))))
15951 (defun org-check-deadlines (ndays)
15952 "Check if there are any deadlines due or past due.
15953 A deadline is considered due if it happens within `org-deadline-warning-days'
15954 days from today's date. If the deadline appears in an entry marked DONE,
15955 it is not shown. The prefix arg NDAYS can be used to test that many
15956 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15957 (interactive "P")
15958 (let* ((org-warn-days
15959 (cond
15960 ((equal ndays '(4)) 100000)
15961 (ndays (prefix-numeric-value ndays))
15962 (t (abs org-deadline-warning-days))))
15963 (case-fold-search nil)
15964 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15965 (callback
15966 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15968 (message "%d deadlines past-due or due within %d days"
15969 (org-occur regexp nil callback)
15970 org-warn-days)))
15972 (defun org-evaluate-time-range (&optional to-buffer)
15973 "Evaluate a time range by computing the difference between start and end.
15974 Normally the result is just printed in the echo area, but with prefix arg
15975 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15976 If the time range is actually in a table, the result is inserted into the
15977 next column.
15978 For time difference computation, a year is assumed to be exactly 365
15979 days in order to avoid rounding problems."
15980 (interactive "P")
15982 (org-clock-update-time-maybe)
15983 (save-excursion
15984 (unless (org-at-date-range-p t)
15985 (goto-char (point-at-bol))
15986 (re-search-forward org-tr-regexp-both (point-at-eol) t))
15987 (if (not (org-at-date-range-p t))
15988 (error "Not at a time-stamp range, and none found in current line")))
15989 (let* ((ts1 (match-string 1))
15990 (ts2 (match-string 2))
15991 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15992 (match-end (match-end 0))
15993 (time1 (org-time-string-to-time ts1))
15994 (time2 (org-time-string-to-time ts2))
15995 (t1 (time-to-seconds time1))
15996 (t2 (time-to-seconds time2))
15997 (diff (abs (- t2 t1)))
15998 (negative (< (- t2 t1) 0))
15999 ;; (ys (floor (* 365 24 60 60)))
16000 (ds (* 24 60 60))
16001 (hs (* 60 60))
16002 (fy "%dy %dd %02d:%02d")
16003 (fy1 "%dy %dd")
16004 (fd "%dd %02d:%02d")
16005 (fd1 "%dd")
16006 (fh "%02d:%02d")
16007 y d h m align)
16008 (if havetime
16009 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16011 d (floor (/ diff ds)) diff (mod diff ds)
16012 h (floor (/ diff hs)) diff (mod diff hs)
16013 m (floor (/ diff 60)))
16014 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16016 d (floor (+ (/ diff ds) 0.5))
16017 h 0 m 0))
16018 (if (not to-buffer)
16019 (message (org-make-tdiff-string y d h m))
16020 (when (org-at-table-p)
16021 (goto-char match-end)
16022 (setq align t)
16023 (and (looking-at " *|") (goto-char (match-end 0))))
16024 (if (looking-at
16025 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16026 (replace-match ""))
16027 (if negative (insert " -"))
16028 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16029 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16030 (insert " " (format fh h m))))
16031 (if align (org-table-align))
16032 (message "Time difference inserted")))))
16034 (defun org-make-tdiff-string (y d h m)
16035 (let ((fmt "")
16036 (l nil))
16037 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16038 l (push y l)))
16039 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16040 l (push d l)))
16041 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16042 l (push h l)))
16043 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16044 l (push m l)))
16045 (apply 'format fmt (nreverse l))))
16047 (defun org-time-string-to-time (s)
16048 (apply 'encode-time (org-parse-time-string s)))
16050 (defun org-time-string-to-absolute (s &optional daynr)
16051 "Convert a time stamp to an absolute day number.
16052 If there is a specifyer for a cyclic time stamp, get the closest date to
16053 DAYNR."
16054 (cond
16055 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16056 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16057 daynr
16058 (+ daynr 1000)))
16059 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16060 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16061 (time-to-days (current-time))) (match-string 0 s)))
16062 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16064 (defun org-time-from-absolute (d)
16065 "Return the time corresponding to date D.
16066 D may be an absolute day number, or a calendar-type list (month day year)."
16067 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16068 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16070 (defun org-calendar-holiday ()
16071 "List of holidays, for Diary display in Org-mode."
16072 (let ((hl (check-calendar-holidays date)))
16073 (if hl (mapconcat 'identity hl "; "))))
16075 (defun org-diary-sexp-entry (sexp entry date)
16076 "Process a SEXP diary ENTRY for DATE."
16077 (require 'diary-lib)
16078 (let ((result (if calendar-debug-sexp
16079 (let ((stack-trace-on-error t))
16080 (eval (car (read-from-string sexp))))
16081 (condition-case nil
16082 (eval (car (read-from-string sexp)))
16083 (error
16084 (beep)
16085 (message "Bad sexp at line %d in %s: %s"
16086 (org-current-line)
16087 (buffer-file-name) sexp)
16088 (sleep-for 2))))))
16089 (cond ((stringp result) result)
16090 ((and (consp result)
16091 (stringp (cdr result))) (cdr result))
16092 (result entry)
16093 (t nil))))
16095 (defun org-diary-to-ical-string (frombuf)
16096 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16097 This uses the icalendar.el library."
16098 (let* ((tmpdir (if (featurep 'xemacs)
16099 (temp-directory)
16100 temporary-file-directory))
16101 (tmpfile (make-temp-name
16102 (expand-file-name "orgics" tmpdir)))
16103 buf rtn b e)
16104 (save-excursion
16105 (set-buffer frombuf)
16106 (icalendar-export-region (point-min) (point-max) tmpfile)
16107 (setq buf (find-buffer-visiting tmpfile))
16108 (set-buffer buf)
16109 (goto-char (point-min))
16110 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16111 (setq b (match-beginning 0)))
16112 (goto-char (point-max))
16113 (if (re-search-backward "^END:VEVENT" nil t)
16114 (setq e (match-end 0)))
16115 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16116 (kill-buffer buf)
16117 (kill-buffer frombuf)
16118 (delete-file tmpfile)
16119 rtn))
16121 (defun org-closest-date (start current change)
16122 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16123 ;; Make the proper lists from the dates
16124 (catch 'exit
16125 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16126 dn dw sday cday n1 n2
16127 d m y y1 y2 date1 date2 nmonths nm ny m2)
16129 (setq start (org-date-to-gregorian start)
16130 current (org-date-to-gregorian
16131 (if org-agenda-repeating-timestamp-show-all
16132 current
16133 (time-to-days (current-time))))
16134 sday (calendar-absolute-from-gregorian start)
16135 cday (calendar-absolute-from-gregorian current))
16137 (if (<= cday sday) (throw 'exit sday))
16139 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16140 (setq dn (string-to-number (match-string 1 change))
16141 dw (cdr (assoc (match-string 2 change) a1)))
16142 (error "Invalid change specifyer: %s" change))
16143 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16144 (cond
16145 ((eq dw 'day)
16146 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16147 n2 (+ n1 dn)))
16148 ((eq dw 'year)
16149 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16150 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16151 (setq date1 (list m d y1)
16152 n1 (calendar-absolute-from-gregorian date1)
16153 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16154 n2 (calendar-absolute-from-gregorian date2)))
16155 ((eq dw 'month)
16156 ;; approx number of month between the tow dates
16157 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16158 ;; How often does dn fit in there?
16159 (setq d (nth 1 start) m (car start) y (nth 2 start)
16160 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16161 m (+ m nm)
16162 ny (floor (/ m 12))
16163 y (+ y ny)
16164 m (- m (* ny 12)))
16165 (while (> m 12) (setq m (- m 12) y (1+ y)))
16166 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16167 (setq m2 (+ m dn) y2 y)
16168 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16169 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16170 (while (< n2 cday)
16171 (setq n1 n2 m m2 y y2)
16172 (setq m2 (+ m dn) y2 y)
16173 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16174 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16176 (if org-agenda-repeating-timestamp-show-all
16177 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16178 (if (= cday n1) n1 n2)))))
16180 (defun org-date-to-gregorian (date)
16181 "Turn any specification of DATE into a gregorian date for the calendar."
16182 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16183 ((and (listp date) (= (length date) 3)) date)
16184 ((stringp date)
16185 (setq date (org-parse-time-string date))
16186 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16187 ((listp date)
16188 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16190 (defun org-parse-time-string (s &optional nodefault)
16191 "Parse the standard Org-mode time string.
16192 This should be a lot faster than the normal `parse-time-string'.
16193 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16194 hour and minute fields will be nil if not given."
16195 (if (string-match org-ts-regexp0 s)
16196 (list 0
16197 (if (or (match-beginning 8) (not nodefault))
16198 (string-to-number (or (match-string 8 s) "0")))
16199 (if (or (match-beginning 7) (not nodefault))
16200 (string-to-number (or (match-string 7 s) "0")))
16201 (string-to-number (match-string 4 s))
16202 (string-to-number (match-string 3 s))
16203 (string-to-number (match-string 2 s))
16204 nil nil nil)
16205 (make-list 9 0)))
16207 (defun org-timestamp-up (&optional arg)
16208 "Increase the date item at the cursor by one.
16209 If the cursor is on the year, change the year. If it is on the month or
16210 the day, change that.
16211 With prefix ARG, change by that many units."
16212 (interactive "p")
16213 (org-timestamp-change (prefix-numeric-value arg)))
16215 (defun org-timestamp-down (&optional arg)
16216 "Decrease the date item at the cursor by one.
16217 If the cursor is on the year, change the year. If it is on the month or
16218 the day, change that.
16219 With prefix ARG, change by that many units."
16220 (interactive "p")
16221 (org-timestamp-change (- (prefix-numeric-value arg))))
16223 (defun org-timestamp-up-day (&optional arg)
16224 "Increase the date in the time stamp by one day.
16225 With prefix ARG, change that many days."
16226 (interactive "p")
16227 (if (and (not (org-at-timestamp-p t))
16228 (org-on-heading-p))
16229 (org-todo 'up)
16230 (org-timestamp-change (prefix-numeric-value arg) 'day)))
16232 (defun org-timestamp-down-day (&optional arg)
16233 "Decrease the date in the time stamp by one day.
16234 With prefix ARG, change that many days."
16235 (interactive "p")
16236 (if (and (not (org-at-timestamp-p t))
16237 (org-on-heading-p))
16238 (org-todo 'down)
16239 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
16241 (defsubst org-pos-in-match-range (pos n)
16242 (and (match-beginning n)
16243 (<= (match-beginning n) pos)
16244 (>= (match-end n) pos)))
16246 (defun org-at-timestamp-p (&optional inactive-ok)
16247 "Determine if the cursor is in or at a timestamp."
16248 (interactive)
16249 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16250 (pos (point))
16251 (ans (or (looking-at tsr)
16252 (save-excursion
16253 (skip-chars-backward "^[<\n\r\t")
16254 (if (> (point) (point-min)) (backward-char 1))
16255 (and (looking-at tsr)
16256 (> (- (match-end 0) pos) -1))))))
16257 (and (boundp 'org-ts-what)
16258 (setq org-ts-what
16259 (cond
16260 ((org-pos-in-match-range pos 2) 'year)
16261 ((org-pos-in-match-range pos 3) 'month)
16262 ((org-pos-in-match-range pos 7) 'hour)
16263 ((org-pos-in-match-range pos 8) 'minute)
16264 ((or (org-pos-in-match-range pos 4)
16265 (org-pos-in-match-range pos 5)) 'day)
16266 ((and (> pos (or (match-end 8) (match-end 5)))
16267 (< pos (match-end 0)))
16268 (- pos (or (match-end 8) (match-end 5))))
16269 (t 'day))))
16270 ans))
16272 (defun org-timestamp-change (n &optional what)
16273 "Change the date in the time stamp at point.
16274 The date will be changed by N times WHAT. WHAT can be `day', `month',
16275 `year', `minute', `second'. If WHAT is not given, the cursor position
16276 in the timestamp determines what will be changed."
16277 (let ((pos (point))
16278 with-hm inactive
16279 org-ts-what
16280 extra
16281 ts time time0)
16282 (if (not (org-at-timestamp-p t))
16283 (error "Not at a timestamp"))
16284 (if (and (not what) (not (eq org-ts-what 'day))
16285 org-display-custom-times
16286 (get-text-property (point) 'display)
16287 (not (get-text-property (1- (point)) 'display)))
16288 (setq org-ts-what 'day))
16289 (setq org-ts-what (or what org-ts-what)
16290 inactive (= (char-after (match-beginning 0)) ?\[)
16291 ts (match-string 0))
16292 (replace-match "")
16293 (if (string-match
16294 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
16296 (setq extra (match-string 1 ts)))
16297 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
16298 (setq with-hm t))
16299 (setq time0 (org-parse-time-string ts))
16300 (setq time
16301 (apply 'encode-time
16302 (append
16303 (list (or (car time0) 0))
16304 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
16305 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
16306 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
16307 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
16308 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
16309 (nthcdr 6 time0))))
16310 (when (integerp org-ts-what)
16311 (setq extra (org-modify-ts-extra extra org-ts-what n)))
16312 (if (eq what 'calendar)
16313 (let ((cal-date
16314 (save-excursion
16315 (save-match-data
16316 (set-buffer "*Calendar*")
16317 (calendar-cursor-to-date)))))
16318 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
16319 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
16320 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
16321 (setcar time0 (or (car time0) 0))
16322 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
16323 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
16324 (setq time (apply 'encode-time time0))))
16325 (setq org-last-changed-timestamp
16326 (org-insert-time-stamp time with-hm inactive nil nil extra))
16327 (org-clock-update-time-maybe)
16328 (goto-char pos)
16329 ;; Try to recenter the calendar window, if any
16330 (if (and org-calendar-follow-timestamp-change
16331 (get-buffer-window "*Calendar*" t)
16332 (memq org-ts-what '(day month year)))
16333 (org-recenter-calendar (time-to-days time)))))
16335 ;; FIXME: does not yet work for lead times
16336 (defun org-modify-ts-extra (s pos n)
16337 "Change the different parts of the lead-time and repeat fields in timestamp."
16338 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
16339 ng h m new)
16340 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
16341 (cond
16342 ((or (org-pos-in-match-range pos 2)
16343 (org-pos-in-match-range pos 3))
16344 (setq m (string-to-number (match-string 3 s))
16345 h (string-to-number (match-string 2 s)))
16346 (if (org-pos-in-match-range pos 2)
16347 (setq h (+ h n))
16348 (setq m (+ m n)))
16349 (if (< m 0) (setq m (+ m 60) h (1- h)))
16350 (if (> m 59) (setq m (- m 60) h (1+ h)))
16351 (setq h (min 24 (max 0 h)))
16352 (setq ng 1 new (format "-%02d:%02d" h m)))
16353 ((org-pos-in-match-range pos 6)
16354 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
16355 ((org-pos-in-match-range pos 5)
16356 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
16358 (when ng
16359 (setq s (concat
16360 (substring s 0 (match-beginning ng))
16362 (substring s (match-end ng))))))
16365 (defun org-recenter-calendar (date)
16366 "If the calendar is visible, recenter it to DATE."
16367 (let* ((win (selected-window))
16368 (cwin (get-buffer-window "*Calendar*" t))
16369 (calendar-move-hook nil))
16370 (when cwin
16371 (select-window cwin)
16372 (calendar-goto-date (if (listp date) date
16373 (calendar-gregorian-from-absolute date)))
16374 (select-window win))))
16376 (defun org-goto-calendar (&optional arg)
16377 "Go to the Emacs calendar at the current date.
16378 If there is a time stamp in the current line, go to that date.
16379 A prefix ARG can be used to force the current date."
16380 (interactive "P")
16381 (let ((tsr org-ts-regexp) diff
16382 (calendar-move-hook nil)
16383 (view-calendar-holidays-initially nil)
16384 (view-diary-entries-initially nil))
16385 (if (or (org-at-timestamp-p)
16386 (save-excursion
16387 (beginning-of-line 1)
16388 (looking-at (concat ".*" tsr))))
16389 (let ((d1 (time-to-days (current-time)))
16390 (d2 (time-to-days
16391 (org-time-string-to-time (match-string 1)))))
16392 (setq diff (- d2 d1))))
16393 (calendar)
16394 (calendar-goto-today)
16395 (if (and diff (not arg)) (calendar-forward-day diff))))
16397 (defun org-date-from-calendar ()
16398 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
16399 If there is already a time stamp at the cursor position, update it."
16400 (interactive)
16401 (org-timestamp-change 0 'calendar))
16403 ;; Make appt aware of appointments from the agenda
16404 (defun org-agenda-to-appt (&optional filter)
16405 "Activate appointments found in `org-agenda-files'.
16406 When prefixed, prompt for a regular expression and use it as a
16407 filter: only add entries if they match this regular expression.
16409 FILTER can be a string. In this case, use this string as a
16410 regular expression to filter results.
16412 FILTER can also be an alist, with the car of each cell being
16413 either 'headline or 'category. For example:
16415 '((headline \"IMPORTANT\")
16416 (category \"Work\"))
16418 will only add headlines containing IMPORTANT or headlines
16419 belonging to the category \"Work\"."
16420 (interactive "P")
16421 (require 'org)
16422 (if (equal filter '(4))
16423 (setq filter (read-from-minibuffer "Regexp filter: ")))
16424 (let* ((today (org-date-to-gregorian
16425 (time-to-days (current-time))))
16426 (files org-agenda-files) entries file)
16427 (while (setq file (pop files))
16428 (setq entries (append entries (org-agenda-get-day-entries
16429 file today :timestamp))))
16430 (setq entries (delq nil entries))
16431 (mapc
16432 (lambda(x)
16433 (let* ((evt (org-trim (get-text-property 1 'txt x)))
16434 (cat (get-text-property 1 'org-category x))
16435 (tod (get-text-property 1 'time-of-day x))
16436 (ok (or (and (stringp filter) (string-match filter evt))
16437 (and (not (null filter)) (listp filter)
16438 (or (string-match
16439 (cadr (assoc 'category filter)) cat)
16440 (string-match
16441 (cadr (assoc 'headline filter)) evt))))))
16442 ;; (setq evt (set-text-properties 0 (length event) nil evt))
16443 (when (and ok tod)
16444 (setq tod (number-to-string tod)
16445 tod (when (string-match
16446 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
16447 (concat (match-string 1 tod) ":"
16448 (match-string 2 tod))))
16449 (appt-add tod evt)))) entries)
16450 nil))
16452 ;;; The clock for measuring work time.
16454 (defvar org-mode-line-string "")
16455 (put 'org-mode-line-string 'risky-local-variable t)
16457 (defvar org-mode-line-timer nil)
16458 (defvar org-clock-heading "")
16459 (defvar org-clock-start-time "")
16461 (defun org-update-mode-line ()
16462 (let* ((delta (- (time-to-seconds (current-time))
16463 (time-to-seconds org-clock-start-time)))
16464 (h (floor delta 3600))
16465 (m (floor (- delta (* 3600 h)) 60)))
16466 (setq org-mode-line-string
16467 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
16468 'help-echo "Org-mode clock is running"))
16469 (force-mode-line-update)))
16471 (defvar org-clock-marker (make-marker)
16472 "Marker recording the last clock-in.")
16473 (defvar org-clock-mode-line-entry nil
16474 "Information for the modeline about the running clock.")
16476 (defun org-clock-in ()
16477 "Start the clock on the current item.
16478 If necessary, clock-out of the currently active clock."
16479 (interactive)
16480 (org-clock-out t)
16481 (let (ts)
16482 (save-excursion
16483 (org-back-to-heading t)
16484 (if (looking-at org-todo-line-regexp)
16485 (setq org-clock-heading (match-string 3))
16486 (setq org-clock-heading "???"))
16487 (setq org-clock-heading (propertize org-clock-heading 'face nil))
16488 (org-clock-find-position)
16490 (insert "\n") (backward-char 1)
16491 (indent-relative)
16492 (insert org-clock-string " ")
16493 (setq org-clock-start-time (current-time))
16494 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16495 (move-marker org-clock-marker (point) (buffer-base-buffer))
16496 (or global-mode-string (setq global-mode-string '("")))
16497 (or (memq 'org-mode-line-string global-mode-string)
16498 (setq global-mode-string
16499 (append global-mode-string '(org-mode-line-string))))
16500 (org-update-mode-line)
16501 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
16502 (message "Clock started at %s" ts))))
16504 (defun org-clock-find-position ()
16505 "Find the location where the next clock line should be inserted."
16506 (org-back-to-heading t)
16507 (catch 'exit
16508 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
16509 (re (concat "^[ \t]*" org-clock-string))
16510 (cnt 0)
16511 first last)
16512 (goto-char beg)
16513 (when (eobp) (newline) (setq end (max (point) end)))
16514 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
16515 ;; we seem to have a CLOCK drawer, so go there.
16516 (beginning-of-line 2)
16517 (throw 'exit t))
16518 ;; Lets count the CLOCK lines
16519 (goto-char beg)
16520 (while (re-search-forward re end t)
16521 (setq first (or first (match-beginning 0))
16522 last (match-beginning 0)
16523 cnt (1+ cnt)))
16524 (when (and (integerp org-clock-into-drawer)
16525 (>= (1+ cnt) org-clock-into-drawer))
16526 ;; Wrap current entries into a new drawer
16527 (goto-char last)
16528 (beginning-of-line 2)
16529 (if (org-at-item-p) (org-end-of-item))
16530 (insert ":END:\n")
16531 (beginning-of-line 0)
16532 (org-indent-line-function)
16533 (goto-char first)
16534 (insert ":CLOCK:\n")
16535 (beginning-of-line 0)
16536 (org-indent-line-function)
16537 (org-flag-drawer t)
16538 (beginning-of-line 2)
16539 (throw 'exit nil))
16541 (goto-char beg)
16542 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16543 (not (equal (match-string 1) org-clock-string)))
16544 ;; Planning info, skip to after it
16545 (beginning-of-line 2)
16546 (or (bolp) (newline)))
16547 (when (eq t org-clock-into-drawer)
16548 (insert ":CLOCK:\n:END:\n")
16549 (beginning-of-line -1)
16550 (org-indent-line-function)
16551 (org-flag-drawer t)
16552 (beginning-of-line 2)
16553 (org-indent-line-function)))))
16555 (defun org-clock-out (&optional fail-quietly)
16556 "Stop the currently running clock.
16557 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
16558 (interactive)
16559 (catch 'exit
16560 (if (not (marker-buffer org-clock-marker))
16561 (if fail-quietly (throw 'exit t) (error "No active clock")))
16562 (let (ts te s h m)
16563 (save-excursion
16564 (set-buffer (marker-buffer org-clock-marker))
16565 (goto-char org-clock-marker)
16566 (beginning-of-line 1)
16567 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
16568 (equal (match-string 1) org-clock-string))
16569 (setq ts (match-string 2))
16570 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
16571 (goto-char (match-end 0))
16572 (delete-region (point) (point-at-eol))
16573 (insert "--")
16574 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
16575 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
16576 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
16577 h (floor (/ s 3600))
16578 s (- s (* 3600 h))
16579 m (floor (/ s 60))
16580 s (- s (* 60 s)))
16581 (insert " => " (format "%2d:%02d" h m))
16582 (move-marker org-clock-marker nil)
16583 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
16584 (org-log-done (org-parse-local-options logging 'org-log-done))
16585 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
16586 (org-add-log-maybe 'clock-out))
16587 (when org-mode-line-timer
16588 (cancel-timer org-mode-line-timer)
16589 (setq org-mode-line-timer nil))
16590 (setq global-mode-string
16591 (delq 'org-mode-line-string global-mode-string))
16592 (force-mode-line-update)
16593 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
16595 (defun org-clock-cancel ()
16596 "Cancel the running clock be removing the start timestamp."
16597 (interactive)
16598 (if (not (marker-buffer org-clock-marker))
16599 (error "No active clock"))
16600 (save-excursion
16601 (set-buffer (marker-buffer org-clock-marker))
16602 (goto-char org-clock-marker)
16603 (delete-region (1- (point-at-bol)) (point-at-eol)))
16604 (message "Clock canceled"))
16606 (defun org-clock-goto (&optional delete-windows)
16607 "Go to the currently clocked-in entry."
16608 (interactive "P")
16609 (if (not (marker-buffer org-clock-marker))
16610 (error "No active clock"))
16611 (switch-to-buffer-other-window
16612 (marker-buffer org-clock-marker))
16613 (if delete-windows (delete-other-windows))
16614 (goto-char org-clock-marker)
16615 (org-show-entry)
16616 (org-back-to-heading)
16617 (recenter))
16619 (defvar org-clock-file-total-minutes nil
16620 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
16621 (make-variable-buffer-local 'org-clock-file-total-minutes)
16623 (defun org-clock-sum (&optional tstart tend)
16624 "Sum the times for each subtree.
16625 Puts the resulting times in minutes as a text property on each headline."
16626 (interactive)
16627 (let* ((bmp (buffer-modified-p))
16628 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
16629 org-clock-string
16630 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
16631 (lmax 30)
16632 (ltimes (make-vector lmax 0))
16633 (t1 0)
16634 (level 0)
16635 ts te dt
16636 time)
16637 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
16638 (save-excursion
16639 (goto-char (point-max))
16640 (while (re-search-backward re nil t)
16641 (cond
16642 ((match-end 2)
16643 ;; Two time stamps
16644 (setq ts (match-string 2)
16645 te (match-string 3)
16646 ts (time-to-seconds
16647 (apply 'encode-time (org-parse-time-string ts)))
16648 te (time-to-seconds
16649 (apply 'encode-time (org-parse-time-string te)))
16650 ts (if tstart (max ts tstart) ts)
16651 te (if tend (min te tend) te)
16652 dt (- te ts)
16653 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
16654 ((match-end 4)
16655 ;; A naket time
16656 (setq t1 (+ t1 (string-to-number (match-string 5))
16657 (* 60 (string-to-number (match-string 4))))))
16658 (t ;; A headline
16659 (setq level (- (match-end 1) (match-beginning 1)))
16660 (when (or (> t1 0) (> (aref ltimes level) 0))
16661 (loop for l from 0 to level do
16662 (aset ltimes l (+ (aref ltimes l) t1)))
16663 (setq t1 0 time (aref ltimes level))
16664 (loop for l from level to (1- lmax) do
16665 (aset ltimes l 0))
16666 (goto-char (match-beginning 0))
16667 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
16668 (setq org-clock-file-total-minutes (aref ltimes 0)))
16669 (set-buffer-modified-p bmp)))
16671 (defun org-clock-display (&optional total-only)
16672 "Show subtree times in the entire buffer.
16673 If TOTAL-ONLY is non-nil, only show the total time for the entire file
16674 in the echo area."
16675 (interactive)
16676 (org-remove-clock-overlays)
16677 (let (time h m p)
16678 (org-clock-sum)
16679 (unless total-only
16680 (save-excursion
16681 (goto-char (point-min))
16682 (while (or (and (equal (setq p (point)) (point-min))
16683 (get-text-property p :org-clock-minutes))
16684 (setq p (next-single-property-change
16685 (point) :org-clock-minutes)))
16686 (goto-char p)
16687 (when (setq time (get-text-property p :org-clock-minutes))
16688 (org-put-clock-overlay time (funcall outline-level))))
16689 (setq h (/ org-clock-file-total-minutes 60)
16690 m (- org-clock-file-total-minutes (* 60 h)))
16691 ;; Arrange to remove the overlays upon next change.
16692 (when org-remove-highlights-with-change
16693 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
16694 nil 'local))))
16695 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
16697 (defvar org-clock-overlays nil)
16698 (make-variable-buffer-local 'org-clock-overlays)
16700 (defun org-put-clock-overlay (time &optional level)
16701 "Put an overlays on the current line, displaying TIME.
16702 If LEVEL is given, prefix time with a corresponding number of stars.
16703 This creates a new overlay and stores it in `org-clock-overlays', so that it
16704 will be easy to remove."
16705 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
16706 (l (if level (org-get-legal-level level 0) 0))
16707 (off 0)
16708 ov tx)
16709 (move-to-column c)
16710 (unless (eolp) (skip-chars-backward "^ \t"))
16711 (skip-chars-backward " \t")
16712 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
16713 tx (concat (buffer-substring (1- (point)) (point))
16714 (make-string (+ off (max 0 (- c (current-column)))) ?.)
16715 (org-add-props (format "%s %2d:%02d%s"
16716 (make-string l ?*) h m
16717 (make-string (- 10 l) ?\ ))
16718 '(face secondary-selection))
16719 ""))
16720 (if (not (featurep 'xemacs))
16721 (org-overlay-put ov 'display tx)
16722 (org-overlay-put ov 'invisible t)
16723 (org-overlay-put ov 'end-glyph (make-glyph tx)))
16724 (push ov org-clock-overlays)))
16726 (defun org-remove-clock-overlays (&optional beg end noremove)
16727 "Remove the occur highlights from the buffer.
16728 BEG and END are ignored. If NOREMOVE is nil, remove this function
16729 from the `before-change-functions' in the current buffer."
16730 (interactive)
16731 (unless org-inhibit-highlight-removal
16732 (mapc 'org-delete-overlay org-clock-overlays)
16733 (setq org-clock-overlays nil)
16734 (unless noremove
16735 (remove-hook 'before-change-functions
16736 'org-remove-clock-overlays 'local))))
16738 (defun org-clock-out-if-current ()
16739 "Clock out if the current entry contains the running clock.
16740 This is used to stop the clock after a TODO entry is marked DONE,
16741 and is only done if the variable `org-clock-out-when-done' is not nil."
16742 (when (and org-clock-out-when-done
16743 (member state org-done-keywords)
16744 (equal (marker-buffer org-clock-marker) (current-buffer))
16745 (< (point) org-clock-marker)
16746 (> (save-excursion (outline-next-heading) (point))
16747 org-clock-marker))
16748 ;; Clock out, but don't accept a logging message for this.
16749 (let ((org-log-done (if (and (listp org-log-done)
16750 (member 'clock-out org-log-done))
16751 '(done)
16752 org-log-done)))
16753 (org-clock-out))))
16755 (add-hook 'org-after-todo-state-change-hook
16756 'org-clock-out-if-current)
16758 (defun org-check-running-clock ()
16759 "Check if the current buffer contains the running clock.
16760 If yes, offer to stop it and to save the buffer with the changes."
16761 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
16762 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
16763 (buffer-name))))
16764 (org-clock-out)
16765 (when (y-or-n-p "Save changed buffer?")
16766 (save-buffer))))
16768 (defun org-clock-report (&optional arg)
16769 "Create a table containing a report about clocked time.
16770 If the cursor is inside an existing clocktable block, then the table
16771 will be updated. If not, a new clocktable will be inserted.
16772 When called with a prefix argument, move to the first clock table in the
16773 buffer and update it."
16774 (interactive "P")
16775 (org-remove-clock-overlays)
16776 (when arg (org-find-dblock "clocktable"))
16777 (if (org-in-clocktable-p)
16778 (goto-char (org-in-clocktable-p))
16779 (org-create-dblock (list :name "clocktable"
16780 :maxlevel 2 :scope 'file)))
16781 (org-update-dblock))
16783 (defun org-in-clocktable-p ()
16784 "Check if the cursor is in a clocktable."
16785 (let ((pos (point)) start)
16786 (save-excursion
16787 (end-of-line 1)
16788 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
16789 (setq start (match-beginning 0))
16790 (re-search-forward "^#\\+END:.*" nil t)
16791 (>= (match-end 0) pos)
16792 start))))
16794 (defun org-clock-update-time-maybe ()
16795 "If this is a CLOCK line, update it and return t.
16796 Otherwise, return nil."
16797 (interactive)
16798 (save-excursion
16799 (beginning-of-line 1)
16800 (skip-chars-forward " \t")
16801 (when (looking-at org-clock-string)
16802 (let ((re (concat "[ \t]*" org-clock-string
16803 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16804 "\\([ \t]*=>.*\\)?"))
16805 ts te h m s)
16806 (if (not (looking-at re))
16808 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16809 (end-of-line 1)
16810 (setq ts (match-string 1)
16811 te (match-string 2))
16812 (setq s (- (time-to-seconds
16813 (apply 'encode-time (org-parse-time-string te)))
16814 (time-to-seconds
16815 (apply 'encode-time (org-parse-time-string ts))))
16816 h (floor (/ s 3600))
16817 s (- s (* 3600 h))
16818 m (floor (/ s 60))
16819 s (- s (* 60 s)))
16820 (insert " => " (format "%2d:%02d" h m))
16821 t)))))
16823 (defun org-clock-special-range (key &optional time as-strings)
16824 "Return two times bordering a special time range.
16825 Key is a symbol specifying the range and can be one of `today', `yesterday',
16826 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16827 A week starts Monday 0:00 and ends Sunday 24:00.
16828 The range is determined relative to TIME. TIME defaults to the current time.
16829 The return value is a cons cell with two internal times like the ones
16830 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16831 the returned times will be formatted strings."
16832 (let* ((tm (decode-time (or time (current-time))))
16833 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16834 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16835 (dow (nth 6 tm))
16836 s1 m1 h1 d1 month1 y1 diff ts te fm)
16837 (cond
16838 ((eq key 'today)
16839 (setq h 0 m 0 h1 24 m1 0))
16840 ((eq key 'yesterday)
16841 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16842 ((eq key 'thisweek)
16843 (setq diff (if (= dow 0) 6 (1- dow))
16844 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16845 ((eq key 'lastweek)
16846 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16847 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16848 ((eq key 'thismonth)
16849 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16850 ((eq key 'lastmonth)
16851 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16852 ((eq key 'thisyear)
16853 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16854 ((eq key 'lastyear)
16855 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
16856 (t (error "No such time block %s" key)))
16857 (setq ts (encode-time s m h d month y)
16858 te (encode-time (or s1 s) (or m1 m) (or h1 h)
16859 (or d1 d) (or month1 month) (or y1 y)))
16860 (setq fm (cdr org-time-stamp-formats))
16861 (if as-strings
16862 (cons (format-time-string fm ts) (format-time-string fm te))
16863 (cons ts te))))
16865 (defun org-dblock-write:clocktable (params)
16866 "Write the standard clocktable."
16867 (let ((hlchars '((1 . "*") (2 . "/")))
16868 (emph nil)
16869 (ins (make-marker))
16870 (total-time nil)
16871 ipos time h m p level hlc hdl maxlevel
16872 ts te cc block beg end pos scope tbl tostring multifile)
16873 (setq scope (plist-get params :scope)
16874 tostring (plist-get params :tostring)
16875 multifile (plist-get params :multifile)
16876 maxlevel (or (plist-get params :maxlevel) 3)
16877 emph (plist-get params :emphasize)
16878 ts (plist-get params :tstart)
16879 te (plist-get params :tend)
16880 block (plist-get params :block))
16881 (when block
16882 (setq cc (org-clock-special-range block nil t)
16883 ts (car cc) te (cdr cc)))
16884 (if ts (setq ts (time-to-seconds
16885 (apply 'encode-time (org-parse-time-string ts)))))
16886 (if te (setq te (time-to-seconds
16887 (apply 'encode-time (org-parse-time-string te)))))
16888 (move-marker ins (point))
16889 (setq ipos (point))
16891 ;; Get the right scope
16892 (setq pos (point))
16893 (save-restriction
16894 (cond
16895 ((not scope))
16896 ((eq scope 'file) (widen))
16897 ((eq scope 'subtree) (org-narrow-to-subtree))
16898 ((eq scope 'tree)
16899 (while (org-up-heading-safe))
16900 (org-narrow-to-subtree))
16901 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
16902 (symbol-name scope)))
16903 (setq level (string-to-number (match-string 1 (symbol-name scope))))
16904 (catch 'exit
16905 (while (org-up-heading-safe)
16906 (looking-at outline-regexp)
16907 (if (<= (org-reduced-level (funcall outline-level)) level)
16908 (throw 'exit nil))))
16909 (org-narrow-to-subtree))
16910 ((or (listp scope) (eq scope 'agenda))
16911 (let* ((files (if (listp scope) scope (org-agenda-files)))
16912 (scope 'agenda)
16913 (p1 (copy-sequence params))
16914 file)
16915 (plist-put p1 :tostring t)
16916 (plist-put p1 :multifile t)
16917 (plist-put p1 :scope 'file)
16918 (org-prepare-agenda-buffers files)
16919 (while (setq file (pop files))
16920 (with-current-buffer (find-buffer-visiting file)
16921 (push (org-clocktable-add-file
16922 file (org-dblock-write:clocktable p1)) tbl)
16923 (setq total-time (+ (or total-time 0)
16924 org-clock-file-total-minutes)))))))
16925 (goto-char pos)
16927 (unless (eq scope 'agenda)
16928 (org-clock-sum ts te)
16929 (goto-char (point-min))
16930 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16931 (goto-char p)
16932 (when (setq time (get-text-property p :org-clock-minutes))
16933 (save-excursion
16934 (beginning-of-line 1)
16935 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
16936 (setq level (org-reduced-level
16937 (- (match-end 1) (match-beginning 1))))
16938 (<= level maxlevel))
16939 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
16940 hdl (match-string 2)
16941 h (/ time 60)
16942 m (- time (* 60 h)))
16943 (if (and (not multifile) (= level 1)) (push "|-" tbl))
16944 (push (concat
16945 "| " (int-to-string level) "|" hlc hdl hlc " |"
16946 (make-string (1- level) ?|)
16947 hlc (format "%d:%02d" h m) hlc
16948 " |") tbl))))))
16949 (setq tbl (nreverse tbl))
16950 (if tostring
16951 (if tbl (mapconcat 'identity tbl "\n") nil)
16952 (goto-char ins)
16953 (insert-before-markers
16954 "Clock summary at ["
16955 (substring
16956 (format-time-string (cdr org-time-stamp-formats))
16957 1 -1)
16958 "]."
16959 (if block
16960 (format " Considered range is /%s/." block)
16962 "\n\n"
16963 (if (eq scope 'agenda) "|File" "")
16964 "|L|Headline|Time|\n")
16965 (setq total-time (or total-time org-clock-file-total-minutes)
16966 h (/ total-time 60)
16967 m (- total-time (* 60 h)))
16968 (insert-before-markers
16969 "|-\n|"
16970 (if (eq scope 'agenda) "|" "")
16971 "|"
16972 "*Total time*| "
16973 (format "*%d:%02d*" h m)
16974 "|\n|-\n")
16975 (setq tbl (delq nil tbl))
16976 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
16977 (equal (substring (car tbl) 0 2) "|-"))
16978 (pop tbl))
16979 (insert-before-markers (mapconcat
16980 'identity (delq nil tbl)
16981 (if (eq scope 'agenda) "\n|-\n" "\n")))
16982 (backward-delete-char 1)
16983 (goto-char ipos)
16984 (skip-chars-forward "^|")
16985 (org-table-align)))))
16987 (defun org-clocktable-add-file (file table)
16988 (if table
16989 (let ((lines (org-split-string table "\n"))
16990 (ff (file-name-nondirectory file)))
16991 (mapconcat 'identity
16992 (mapcar (lambda (x)
16993 (if (string-match org-table-dataline-regexp x)
16994 (concat "|" ff x)
16996 lines)
16997 "\n"))))
16999 ;; FIXME: I don't think anybody uses this, ask David
17000 (defun org-collect-clock-time-entries ()
17001 "Return an internal list with clocking information.
17002 This list has one entry for each CLOCK interval.
17003 FIXME: describe the elements."
17004 (interactive)
17005 (let ((re (concat "^[ \t]*" org-clock-string
17006 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17007 rtn beg end next cont level title total closedp leafp
17008 clockpos titlepos h m donep)
17009 (save-excursion
17010 (org-clock-sum)
17011 (goto-char (point-min))
17012 (while (re-search-forward re nil t)
17013 (setq clockpos (match-beginning 0)
17014 beg (match-string 1) end (match-string 2)
17015 cont (match-end 0))
17016 (setq beg (apply 'encode-time (org-parse-time-string beg))
17017 end (apply 'encode-time (org-parse-time-string end)))
17018 (org-back-to-heading t)
17019 (setq donep (org-entry-is-done-p))
17020 (setq titlepos (point)
17021 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17022 h (/ total 60) m (- total (* 60 h))
17023 total (cons h m))
17024 (looking-at "\\(\\*+\\) +\\(.*\\)")
17025 (setq level (- (match-end 1) (match-beginning 1))
17026 title (org-match-string-no-properties 2))
17027 (save-excursion (outline-next-heading) (setq next (point)))
17028 (setq closedp (re-search-forward org-closed-time-regexp next t))
17029 (goto-char next)
17030 (setq leafp (and (looking-at "^\\*+ ")
17031 (<= (- (match-end 0) (point)) level)))
17032 (push (list beg end clockpos closedp donep
17033 total title titlepos level leafp)
17034 rtn)
17035 (goto-char cont)))
17036 (nreverse rtn)))
17038 ;;;; Agenda, and Diary Integration
17040 ;;; Define the Org-agenda-mode
17042 (defvar org-agenda-mode-map (make-sparse-keymap)
17043 "Keymap for `org-agenda-mode'.")
17045 (defvar org-agenda-menu) ; defined later in this file.
17046 (defvar org-agenda-follow-mode nil)
17047 (defvar org-agenda-show-log nil)
17048 (defvar org-agenda-redo-command nil)
17049 (defvar org-agenda-mode-hook nil)
17050 (defvar org-agenda-type nil)
17051 (defvar org-agenda-force-single-file nil)
17053 (defun org-agenda-mode ()
17054 "Mode for time-sorted view on action items in Org-mode files.
17056 The following commands are available:
17058 \\{org-agenda-mode-map}"
17059 (interactive)
17060 (kill-all-local-variables)
17061 (setq org-agenda-undo-list nil
17062 org-agenda-pending-undo-list nil)
17063 (setq major-mode 'org-agenda-mode)
17064 ;; Keep global-font-lock-mode from turning on font-lock-mode
17065 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17066 (setq mode-name "Org-Agenda")
17067 (use-local-map org-agenda-mode-map)
17068 (easy-menu-add org-agenda-menu)
17069 (if org-startup-truncated (setq truncate-lines t))
17070 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17071 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17072 ;; Make sure properties are removed when copying text
17073 (when (boundp 'buffer-substring-filters)
17074 (org-set-local 'buffer-substring-filters
17075 (cons (lambda (x)
17076 (set-text-properties 0 (length x) nil x) x)
17077 buffer-substring-filters)))
17078 (unless org-agenda-keep-modes
17079 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17080 org-agenda-show-log nil))
17081 (easy-menu-change
17082 '("Agenda") "Agenda Files"
17083 (append
17084 (list
17085 (vector
17086 (if (get 'org-agenda-files 'org-restrict)
17087 "Restricted to single file"
17088 "Edit File List")
17089 '(org-edit-agenda-file-list)
17090 (not (get 'org-agenda-files 'org-restrict)))
17091 "--")
17092 (mapcar 'org-file-menu-entry (org-agenda-files))))
17093 (org-agenda-set-mode-name)
17094 (apply
17095 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17096 (list 'org-agenda-mode-hook)))
17098 (substitute-key-definition 'undo 'org-agenda-undo
17099 org-agenda-mode-map global-map)
17100 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17101 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17102 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17103 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17104 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17105 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17106 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17107 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17108 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17109 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17110 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17111 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17112 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17113 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17114 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17115 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17116 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17117 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17118 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17119 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17120 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17121 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17122 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17123 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17124 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17125 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17126 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17127 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17128 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17130 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17131 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17132 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17133 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17134 (while l (org-defkey org-agenda-mode-map
17135 (int-to-string (pop l)) 'digit-argument)))
17137 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17138 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17139 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17140 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17141 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17142 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17143 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17144 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17145 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17146 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17147 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17148 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17149 (org-defkey org-agenda-mode-map "n" 'next-line)
17150 (org-defkey org-agenda-mode-map "p" 'previous-line)
17151 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17152 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17153 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17154 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17155 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17156 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17157 (eval-after-load "calendar"
17158 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17159 'org-calendar-goto-agenda))
17160 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17161 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17162 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17163 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17164 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17165 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17166 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17167 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17168 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17169 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17170 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17171 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17172 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17173 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17174 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17175 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17176 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17177 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17178 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17179 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17180 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17181 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17183 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17184 "Local keymap for agenda entries from Org-mode.")
17186 (org-defkey org-agenda-keymap
17187 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17188 (org-defkey org-agenda-keymap
17189 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17190 (when org-agenda-mouse-1-follows-link
17191 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17192 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17193 '("Agenda"
17194 ("Agenda Files")
17195 "--"
17196 ["Show" org-agenda-show t]
17197 ["Go To (other window)" org-agenda-goto t]
17198 ["Go To (this window)" org-agenda-switch-to t]
17199 ["Follow Mode" org-agenda-follow-mode
17200 :style toggle :selected org-agenda-follow-mode :active t]
17201 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
17202 "--"
17203 ["Cycle TODO" org-agenda-todo t]
17204 ["Archive subtree" org-agenda-archive t]
17205 ["Delete subtree" org-agenda-kill t]
17206 "--"
17207 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
17208 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
17209 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
17210 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
17211 "--"
17212 ("Tags and Properties"
17213 ["Show all Tags" org-agenda-show-tags t]
17214 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
17215 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
17216 "--"
17217 ["Column View" org-columns t])
17218 ("Date/Schedule"
17219 ["Schedule" org-agenda-schedule t]
17220 ["Set Deadline" org-agenda-deadline t]
17221 "--"
17222 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
17223 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
17224 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
17225 ("Clock"
17226 ["Clock in" org-agenda-clock-in t]
17227 ["Clock out" org-agenda-clock-out t]
17228 ["Clock cancel" org-agenda-clock-cancel t]
17229 ["Goto running clock" org-clock-goto t])
17230 ("Priority"
17231 ["Set Priority" org-agenda-priority t]
17232 ["Increase Priority" org-agenda-priority-up t]
17233 ["Decrease Priority" org-agenda-priority-down t]
17234 ["Show Priority" org-agenda-show-priority t])
17235 ("Calendar/Diary"
17236 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
17237 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
17238 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
17239 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
17240 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
17241 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
17242 "--"
17243 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
17244 "--"
17245 ("View"
17246 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
17247 :style radio :selected (equal org-agenda-ndays 1)]
17248 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
17249 :style radio :selected (equal org-agenda-ndays 7)]
17250 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
17251 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
17252 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
17253 :style radio :selected (member org-agenda-ndays '(365 366))]
17254 "--"
17255 ["Show Logbook entries" org-agenda-log-mode
17256 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
17257 ["Include Diary" org-agenda-toggle-diary
17258 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
17259 ["Use Time Grid" org-agenda-toggle-time-grid
17260 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
17261 ["Write view to file" org-write-agenda t]
17262 ["Rebuild buffer" org-agenda-redo t]
17263 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
17264 "--"
17265 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
17266 "--"
17267 ["Quit" org-agenda-quit t]
17268 ["Exit and Release Buffers" org-agenda-exit t]
17271 ;;; Agenda undo
17273 (defvar org-agenda-allow-remote-undo t
17274 "Non-nil means, allow remote undo from the agenda buffer.")
17275 (defvar org-agenda-undo-list nil
17276 "List of undoable operations in the agenda since last refresh.")
17277 (defvar org-agenda-undo-has-started-in nil
17278 "Buffers that have already seen `undo-start' in the current undo sequence.")
17279 (defvar org-agenda-pending-undo-list nil
17280 "In a series of undo commands, this is the list of remaning undo items.")
17282 (defmacro org-if-unprotected (&rest body)
17283 "Execute BODY if there is no `org-protected' text property at point."
17284 (declare (debug t))
17285 `(unless (get-text-property (point) 'org-protected)
17286 ,@body))
17288 (defmacro org-with-remote-undo (_buffer &rest _body)
17289 "Execute BODY while recording undo information in two buffers."
17290 (declare (indent 1) (debug t))
17291 `(let ((_cline (org-current-line))
17292 (_cmd this-command)
17293 (_buf1 (current-buffer))
17294 (_buf2 ,_buffer)
17295 (_undo1 buffer-undo-list)
17296 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
17297 _c1 _c2)
17298 ,@_body
17299 (when org-agenda-allow-remote-undo
17300 (setq _c1 (org-verify-change-for-undo
17301 _undo1 (with-current-buffer _buf1 buffer-undo-list))
17302 _c2 (org-verify-change-for-undo
17303 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
17304 (when (or _c1 _c2)
17305 ;; make sure there are undo boundaries
17306 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
17307 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
17308 ;; remember which buffer to undo
17309 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
17310 org-agenda-undo-list)))))
17312 (defun org-agenda-undo ()
17313 "Undo a remote editing step in the agenda.
17314 This undoes changes both in the agenda buffer and in the remote buffer
17315 that have been changed along."
17316 (interactive)
17317 (or org-agenda-allow-remote-undo
17318 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
17319 (if (not (eq this-command last-command))
17320 (setq org-agenda-undo-has-started-in nil
17321 org-agenda-pending-undo-list org-agenda-undo-list))
17322 (if (not org-agenda-pending-undo-list)
17323 (error "No further undo information"))
17324 (let* ((entry (pop org-agenda-pending-undo-list))
17325 buf line cmd rembuf)
17326 (setq cmd (pop entry) line (pop entry))
17327 (setq rembuf (nth 2 entry))
17328 (org-with-remote-undo rembuf
17329 (while (bufferp (setq buf (pop entry)))
17330 (if (pop entry)
17331 (with-current-buffer buf
17332 (let ((last-undo-buffer buf)
17333 (inhibit-read-only t))
17334 (unless (memq buf org-agenda-undo-has-started-in)
17335 (push buf org-agenda-undo-has-started-in)
17336 (make-local-variable 'pending-undo-list)
17337 (undo-start))
17338 (while (and pending-undo-list
17339 (listp pending-undo-list)
17340 (not (car pending-undo-list)))
17341 (pop pending-undo-list))
17342 (undo-more 1))))))
17343 (goto-line line)
17344 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
17346 (defun org-verify-change-for-undo (l1 l2)
17347 "Verify that a real change occurred between the undo lists L1 and L2."
17348 (while (and l1 (listp l1) (null (car l1))) (pop l1))
17349 (while (and l2 (listp l2) (null (car l2))) (pop l2))
17350 (not (eq l1 l2)))
17352 ;;; Agenda dispatch
17354 (defvar org-agenda-restrict nil)
17355 (defvar org-agenda-restrict-begin (make-marker))
17356 (defvar org-agenda-restrict-end (make-marker))
17357 (defvar org-agenda-last-dispatch-buffer nil)
17359 ;;;###autoload
17360 (defun org-agenda (arg)
17361 "Dispatch agenda commands to collect entries to the agenda buffer.
17362 Prompts for a character to select a command. Any prefix arg will be passed
17363 on to the selected command. The default selections are:
17365 a Call `org-agenda-list' to display the agenda for current day or week.
17366 t Call `org-todo-list' to display the global todo list.
17367 T Call `org-todo-list' to display the global todo list, select only
17368 entries with a specific TODO keyword (the user gets a prompt).
17369 m Call `org-tags-view' to display headlines with tags matching
17370 a condition (the user is prompted for the condition).
17371 M Like `m', but select only TODO entries, no ordinary headlines.
17372 L Create a timeline for the current buffer.
17373 e Export views to associated files.
17375 More commands can be added by configuring the variable
17376 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
17377 searches can be pre-defined in this way.
17379 If the current buffer is in Org-mode and visiting a file, you can also
17380 first press `1' to indicate that the agenda should be temporarily (until the
17381 next use of \\[org-agenda]) restricted to the current file."
17382 (interactive "P")
17383 (catch 'exit
17384 (let* ((buf (current-buffer))
17385 (bfn (buffer-file-name (buffer-base-buffer)))
17386 (restrict-ok (and bfn (org-mode-p)))
17387 (custom org-agenda-custom-commands)
17388 c entry key type match lprops)
17389 ;; Turn off restriction
17390 (put 'org-agenda-files 'org-restrict nil)
17391 (setq org-agenda-restrict nil)
17392 (move-marker org-agenda-restrict-begin nil)
17393 (move-marker org-agenda-restrict-end nil)
17394 ;; Delete old local properties
17395 (put 'org-agenda-redo-command 'org-lprops nil)
17396 ;; Remember where this call originated
17397 (setq org-agenda-last-dispatch-buffer (current-buffer))
17398 (save-window-excursion
17399 (delete-other-windows)
17400 (org-switch-to-buffer-other-window " *Agenda Commands*")
17401 (erase-buffer)
17402 (insert (eval-when-compile
17403 (let ((header
17404 "Press key for an agenda command:
17405 -------------------------------- C Configure custom agenda commands
17406 a Agenda for current week or day e Export agenda views
17407 t List of all TODO entries T Entries with special TODO kwd
17408 m Match a TAGS query M Like m, but only TODO entries
17409 L Timeline for current buffer # List stuck projects (!=configure)
17411 (start 0))
17412 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
17413 (setq start (match-end 0))
17414 (add-text-properties (match-beginning 2) (match-end 2)
17415 '(face bold) header))
17416 header)))
17417 (while (setq entry (pop custom))
17418 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
17419 (insert (format "\n%-4s%-14s: %s"
17420 (org-add-props (copy-sequence key)
17421 '(face bold))
17422 (cond
17423 ((stringp type) type)
17424 ((eq type 'agenda) "Agenda for current week or day")
17425 ((eq type 'alltodo) "List of all TODO entries")
17426 ((eq type 'stuck) "List of stuck projects")
17427 ((eq type 'todo) "TODO keyword")
17428 ((eq type 'tags) "Tags query")
17429 ((eq type 'tags-todo) "Tags (TODO)")
17430 ((eq type 'tags-tree) "Tags tree")
17431 ((eq type 'todo-tree) "TODO kwd tree")
17432 ((eq type 'occur-tree) "Occur tree")
17433 ((functionp type) (symbol-name type))
17434 (t "???"))
17435 (if (stringp match)
17436 (org-add-props match nil 'face 'org-warning)
17437 (format "set of %d commands" (length match))))))
17438 (if restrict-ok
17439 (insert "\n"
17440 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
17441 (goto-char (point-min))
17442 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
17443 (message "Press key for agenda command%s"
17444 (if restrict-ok ", or [1] or [0] to restrict" ""))
17445 (setq c (read-char-exclusive))
17446 (message "")
17447 (when (memq c '(?L ?1 ?0))
17448 (if restrict-ok
17449 (put 'org-agenda-files 'org-restrict (list bfn))
17450 (error "Cannot restrict agenda to current buffer"))
17451 (with-current-buffer " *Agenda Commands*"
17452 (goto-char (point-max))
17453 (delete-region (point-at-bol) (point))
17454 (goto-char (point-min)))
17455 (when (eq c ?0)
17456 (setq org-agenda-restrict t)
17457 (with-current-buffer buf
17458 (if (org-region-active-p)
17459 (progn
17460 (move-marker org-agenda-restrict-begin (region-beginning))
17461 (move-marker org-agenda-restrict-end (region-end)))
17462 (save-excursion
17463 (org-back-to-heading t)
17464 (move-marker org-agenda-restrict-begin (point))
17465 (move-marker org-agenda-restrict-end
17466 (progn (org-end-of-subtree t)))))))
17467 (unless (eq c ?L)
17468 (message "Press key for agenda command%s"
17469 (if restrict-ok " (restricted to current file)" ""))
17470 (setq c (read-char-exclusive)))
17471 (message "")))
17472 (require 'calendar) ; FIXME: can we avoid this for some commands?
17473 ;; For example the todo list should not need it (but does...)
17474 (cond
17475 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
17476 (if (symbolp (nth 1 entry))
17477 (progn
17478 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
17479 lprops (nth 3 entry))
17480 (put 'org-agenda-redo-command 'org-lprops lprops)
17481 (cond
17482 ((eq type 'agenda)
17483 (org-let lprops '(org-agenda-list current-prefix-arg)))
17484 ((eq type 'alltodo)
17485 (org-let lprops '(org-todo-list current-prefix-arg)))
17486 ((eq type 'stuck)
17487 (org-let lprops '(org-agenda-list-stuck-projects
17488 current-prefix-arg)))
17489 ((eq type 'tags)
17490 (org-let lprops '(org-tags-view current-prefix-arg match)))
17491 ((eq type 'tags-todo)
17492 (org-let lprops '(org-tags-view '(4) match)))
17493 ((eq type 'todo)
17494 (org-let lprops '(org-todo-list match)))
17495 ((eq type 'tags-tree)
17496 (org-check-for-org-mode)
17497 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
17498 ((eq type 'todo-tree)
17499 (org-check-for-org-mode)
17500 (org-let lprops
17501 '(org-occur (concat "^" outline-regexp "[ \t]*"
17502 (regexp-quote match) "\\>"))))
17503 ((eq type 'occur-tree)
17504 (org-check-for-org-mode)
17505 (org-let lprops '(org-occur match)))
17506 ((fboundp type)
17507 (org-let lprops '(funcall type match)))
17508 (t (error "Invalid custom agenda command type %s" type))))
17509 (org-run-agenda-series (nth 1 entry) (cddr entry))))
17510 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
17511 ((equal c ?a) (call-interactively 'org-agenda-list))
17512 ((equal c ?t) (call-interactively 'org-todo-list))
17513 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
17514 ((equal c ?m) (call-interactively 'org-tags-view))
17515 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
17516 ((equal c ?e) (call-interactively 'org-store-agenda-views))
17517 ((equal c ?L)
17518 (unless restrict-ok
17519 (error "This is not an Org-mode file"))
17520 (org-call-with-arg 'org-timeline arg))
17521 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
17522 ((equal c ?!) (customize-variable 'org-stuck-projects))
17523 (t (error "Invalid key"))))))
17525 (defun org-run-agenda-series (name series)
17526 (org-prepare-agenda name)
17527 (let* ((org-agenda-multi t)
17528 (redo (list 'org-run-agenda-series name (list 'quote series)))
17529 (cmds (car series))
17530 (gprops (nth 1 series))
17531 match ;; The byte compiler incorrectly complains about this. Keep it!
17532 cmd type lprops)
17533 (while (setq cmd (pop cmds))
17534 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
17535 (cond
17536 ((eq type 'agenda)
17537 (org-let2 gprops lprops
17538 '(call-interactively 'org-agenda-list)))
17539 ((eq type 'alltodo)
17540 (org-let2 gprops lprops
17541 '(call-interactively 'org-todo-list)))
17542 ((eq type 'stuck)
17543 (org-let2 gprops lprops
17544 '(call-interactively 'org-agenda-list-stuck-projects)))
17545 ((eq type 'tags)
17546 (org-let2 gprops lprops
17547 '(org-tags-view current-prefix-arg match)))
17548 ((eq type 'tags-todo)
17549 (org-let2 gprops lprops
17550 '(org-tags-view '(4) match)))
17551 ((eq type 'todo)
17552 (org-let2 gprops lprops
17553 '(org-todo-list match)))
17554 ((fboundp type)
17555 (org-let2 gprops lprops
17556 '(funcall type match)))
17557 (t (error "Invalid type in command series"))))
17558 (widen)
17559 (setq org-agenda-redo-command redo)
17560 (goto-char (point-min)))
17561 (org-finalize-agenda))
17563 ;;;###autoload
17564 (defmacro org-batch-agenda (cmd-key &rest parameters)
17565 "Run an agenda command in batch mode and send the result to STDOUT.
17566 If CMD-KEY is a string of length 1, it is used as a key in
17567 `org-agenda-custom-commands' and triggers this command. If it is a
17568 longer string is is used as a tags/todo match string.
17569 Paramters are alternating variable names and values that will be bound
17570 before running the agenda command."
17571 (let (pars)
17572 (while parameters
17573 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17574 (if (> (length cmd-key) 1)
17575 (eval (list 'let (nreverse pars)
17576 (list 'org-tags-view nil cmd-key)))
17577 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17578 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17579 (set-buffer org-agenda-buffer-name)
17580 (princ (org-encode-for-stdout (buffer-string)))))
17582 (defun org-encode-for-stdout (string)
17583 (if (fboundp 'encode-coding-string)
17584 (encode-coding-string string buffer-file-coding-system)
17585 string))
17587 (defvar org-agenda-info nil)
17589 ;;;###autoload
17590 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
17591 "Run an agenda command in batch mode and send the result to STDOUT.
17592 If CMD-KEY is a string of length 1, it is used as a key in
17593 `org-agenda-custom-commands' and triggers this command. If it is a
17594 longer string is is used as a tags/todo match string.
17595 Paramters are alternating variable names and values that will be bound
17596 before running the agenda command.
17598 The output gives a line for each selected agenda item. Each
17599 item is a list of comma-separated values, like this:
17601 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
17603 category The category of the item
17604 head The headline, without TODO kwd, TAGS and PRIORITY
17605 type The type of the agenda entry, can be
17606 todo selected in TODO match
17607 tagsmatch selected in tags match
17608 diary imported from diary
17609 deadline a deadline on given date
17610 scheduled scheduled on given date
17611 timestamp entry has timestamp on given date
17612 closed entry was closed on given date
17613 upcoming-deadline warning about deadline
17614 past-scheduled forwarded scheduled item
17615 block entry has date block including g. date
17616 todo The todo keyword, if any
17617 tags All tags including inherited ones, separated by colons
17618 date The relevant date, like 2007-2-14
17619 time The time, like 15:00-16:50
17620 extra Sting with extra planning info
17621 priority-l The priority letter if any was given
17622 priority-n The computed numerical priority
17623 agenda-day The day in the agenda where this is listed"
17625 (let (pars)
17626 (while parameters
17627 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17628 (push (list 'org-agenda-remove-tags t) pars)
17629 (if (> (length cmd-key) 1)
17630 (eval (list 'let (nreverse pars)
17631 (list 'org-tags-view nil cmd-key)))
17632 (flet ((read-char-exclusive () (string-to-char cmd-key)))
17633 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
17634 (set-buffer org-agenda-buffer-name)
17635 (let* ((lines (org-split-string (buffer-string) "\n"))
17636 line)
17637 (while (setq line (pop lines))
17638 (catch 'next
17639 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
17640 (setq org-agenda-info
17641 (org-fix-agenda-info (text-properties-at 0 line)))
17642 (princ
17643 (org-encode-for-stdout
17644 (mapconcat 'org-agenda-export-csv-mapper
17645 '(org-category txt type todo tags date time-of-day extra
17646 priority-letter priority agenda-day)
17647 ",")))
17648 (princ "\n"))))))
17650 (defun org-fix-agenda-info (props)
17651 "Make sure all properties on an agenda item have a canonical form,
17652 so the the export commands caneasily use it."
17653 (let (tmp re)
17654 (when (setq tmp (plist-get props 'tags))
17655 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
17656 (when (setq tmp (plist-get props 'date))
17657 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17658 (let ((calendar-date-display-form '(year "-" month "-" day)))
17659 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
17661 (setq tmp (calendar-date-string tmp)))
17662 (setq props (plist-put props 'date tmp)))
17663 (when (setq tmp (plist-get props 'day))
17664 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
17665 (let ((calendar-date-display-form '(year "-" month "-" day)))
17666 (setq tmp (calendar-date-string tmp)))
17667 (setq props (plist-put props 'day tmp))
17668 (setq props (plist-put props 'agenda-day tmp)))
17669 (when (setq tmp (plist-get props 'txt))
17670 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
17671 (plist-put props 'priority-letter (match-string 1 tmp))
17672 (setq tmp (replace-match "" t t tmp)))
17673 (when (and (setq re (plist-get props 'org-todo-regexp))
17674 (setq re (concat "\\`\\.*" re " ?"))
17675 (string-match re tmp))
17676 (plist-put props 'todo (match-string 1 tmp))
17677 (setq tmp (replace-match "" t t tmp)))
17678 (plist-put props 'txt tmp)))
17679 props)
17681 (defun org-agenda-export-csv-mapper (prop)
17682 (let ((res (plist-get org-agenda-info prop)))
17683 (setq res
17684 (cond
17685 ((not res) "")
17686 ((stringp res) res)
17687 (t (prin1-to-string res))))
17688 (while (string-match "," res)
17689 (setq res (replace-match ";" t t res)))
17690 (org-trim res)))
17693 ;;;###autoload
17694 (defun org-store-agenda-views (&rest parameters)
17695 (interactive)
17696 (eval (list 'org-batch-store-agenda-views)))
17698 ;; FIXME, why is this a macro?????
17699 ;;;###autoload
17700 (defmacro org-batch-store-agenda-views (&rest parameters)
17701 "Run all custom agenda commands that have a file argument."
17702 (let ((cmds org-agenda-custom-commands)
17703 (pop-up-frames nil)
17704 (dir default-directory)
17705 pars cmd thiscmdkey files opts)
17706 (while parameters
17707 (push (list (pop parameters) (if parameters (pop parameters))) pars))
17708 (setq pars (reverse pars))
17709 (save-window-excursion
17710 (while cmds
17711 (setq cmd (pop cmds)
17712 thiscmdkey (car cmd)
17713 opts (nth 3 cmd)
17714 files (nth 4 cmd))
17715 (if (stringp files) (setq files (list files)))
17716 (when files
17717 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
17718 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17719 '(org-agenda nil))))
17720 (set-buffer org-agenda-buffer-name)
17721 (while files
17722 (eval (list 'let (append org-agenda-exporter-settings opts pars)
17723 (list 'org-write-agenda
17724 (expand-file-name (pop files) dir) t))))
17725 (and (get-buffer org-agenda-buffer-name)
17726 (kill-buffer org-agenda-buffer-name)))))))
17728 (defun org-write-agenda (file &optional nosettings)
17729 "Write the current buffer (an agenda view) as a file.
17730 Depending on the extension of the file name, plain text (.txt),
17731 HTML (.html or .htm) or Postscript (.ps) is produced.
17732 If NOSETTINGS is given, do not scope the settings of
17733 `org-agenda-exporter-settings' into the export commands. This is used when
17734 the settings have already been scoped and we do not wish to overrule other,
17735 higher priority settings."
17736 (interactive "FWrite agenda to file: ")
17737 (if (not (file-writable-p file))
17738 (error "Cannot write agenda to file %s" file))
17739 (cond
17740 ((string-match "\\.html?\\'" file) (require 'htmlize))
17741 ((string-match "\\.ps\\'" file) (require 'ps-print)))
17742 (org-let (if nosettings nil org-agenda-exporter-settings)
17743 '(save-excursion
17744 (save-window-excursion
17745 (cond
17746 ((string-match "\\.html?\\'" file)
17747 (set-buffer (htmlize-buffer (current-buffer)))
17749 (when (and org-agenda-export-html-style
17750 (string-match "<style>" org-agenda-export-html-style))
17751 ;; replace <style> section with org-agenda-export-html-style
17752 (goto-char (point-min))
17753 (kill-region (- (search-forward "<style") 6)
17754 (search-forward "</style>"))
17755 (insert org-agenda-export-html-style))
17756 (write-file file)
17757 (kill-buffer (current-buffer))
17758 (message "HTML written to %s" file))
17759 ((string-match "\\.ps\\'" file)
17760 (ps-print-buffer-with-faces file)
17761 (message "Postscript written to %s" file))
17763 (let ((bs (buffer-string)))
17764 (find-file file)
17765 (insert bs)
17766 (save-buffer 0)
17767 (kill-buffer (current-buffer))
17768 (message "Plain text written to %s" file))))))
17769 (set-buffer org-agenda-buffer-name)))
17771 (defmacro org-no-read-only (&rest body)
17772 "Inhibit read-only for BODY."
17773 `(let ((inhibit-read-only t)) ,@body))
17775 (defun org-check-for-org-mode ()
17776 "Make sure current buffer is in org-mode. Error if not."
17777 (or (org-mode-p)
17778 (error "Cannot execute org-mode agenda command on buffer in %s."
17779 major-mode)))
17781 (defun org-fit-agenda-window ()
17782 "Fit the window to the buffer size."
17783 (and (memq org-agenda-window-setup '(reorganize-frame))
17784 (fboundp 'fit-window-to-buffer)
17785 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
17786 (/ (frame-height) 2))))
17788 ;;; Agenda file list
17790 (defun org-agenda-files (&optional unrestricted)
17791 "Get the list of agenda files.
17792 Optional UNRESTRICTED means return the full list even if a restriction
17793 is currently in place."
17794 (let ((files
17795 (cond
17796 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17797 ((stringp org-agenda-files) (org-read-agenda-file-list))
17798 ((listp org-agenda-files) org-agenda-files)
17799 (t (error "Invalid value of `org-agenda-files'")))))
17800 (if org-agenda-skip-unavailable-files
17801 (delq nil
17802 (mapcar (function
17803 (lambda (file)
17804 (and (file-readable-p file) file)))
17805 files))
17806 files))) ; `org-check-agenda-file' will remove them from the list
17808 (defun org-edit-agenda-file-list ()
17809 "Edit the list of agenda files.
17810 Depending on setup, this either uses customize to edit the variable
17811 `org-agenda-files', or it visits the file that is holding the list. In the
17812 latter case, the buffer is set up in a way that saving it automatically kills
17813 the buffer and restores the previous window configuration."
17814 (interactive)
17815 (if (stringp org-agenda-files)
17816 (let ((cw (current-window-configuration)))
17817 (find-file org-agenda-files)
17818 (org-set-local 'org-window-configuration cw)
17819 (org-add-hook 'after-save-hook
17820 (lambda ()
17821 (set-window-configuration
17822 (prog1 org-window-configuration
17823 (kill-buffer (current-buffer))))
17824 (org-install-agenda-files-menu)
17825 (message "New agenda file list installed"))
17826 nil 'local)
17827 (message (substitute-command-keys
17828 "Edit list and finish with \\[save-buffer]")))
17829 (customize-variable 'org-agenda-files)))
17831 (defun org-store-new-agenda-file-list (list)
17832 "Set new value for the agenda file list and save it correcly."
17833 (if (stringp org-agenda-files)
17834 (let ((f org-agenda-files) b)
17835 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
17836 (with-temp-file f
17837 (insert (mapconcat 'identity list "\n") "\n")))
17838 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
17839 (setq org-agenda-files list)
17840 (customize-save-variable 'org-agenda-files org-agenda-files))))
17842 (defun org-read-agenda-file-list ()
17843 "Read the list of agenda files from a file."
17844 (when (stringp org-agenda-files)
17845 (with-temp-buffer
17846 (insert-file-contents org-agenda-files)
17847 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
17850 ;;;###autoload
17851 (defun org-cycle-agenda-files ()
17852 "Cycle through the files in `org-agenda-files'.
17853 If the current buffer visits an agenda file, find the next one in the list.
17854 If the current buffer does not, find the first agenda file."
17855 (interactive)
17856 (let* ((fs (org-agenda-files t))
17857 (files (append fs (list (car fs))))
17858 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17859 file)
17860 (unless files (error "No agenda files"))
17861 (catch 'exit
17862 (while (setq file (pop files))
17863 (if (equal (file-truename file) tcf)
17864 (when (car files)
17865 (find-file (car files))
17866 (throw 'exit t))))
17867 (find-file (car fs)))
17868 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
17870 (defun org-agenda-file-to-front (&optional to-end)
17871 "Move/add the current file to the top of the agenda file list.
17872 If the file is not present in the list, it is added to the front. If it is
17873 present, it is moved there. With optional argument TO-END, add/move to the
17874 end of the list."
17875 (interactive "P")
17876 (let ((org-agenda-skip-unavailable-files nil)
17877 (file-alist (mapcar (lambda (x)
17878 (cons (file-truename x) x))
17879 (org-agenda-files t)))
17880 (ctf (file-truename buffer-file-name))
17881 x had)
17882 (setq x (assoc ctf file-alist) had x)
17884 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17885 (if to-end
17886 (setq file-alist (append (delq x file-alist) (list x)))
17887 (setq file-alist (cons x (delq x file-alist))))
17888 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17889 (org-install-agenda-files-menu)
17890 (message "File %s to %s of agenda file list"
17891 (if had "moved" "added") (if to-end "end" "front"))))
17893 (defun org-remove-file (&optional file)
17894 "Remove current file from the list of files in variable `org-agenda-files'.
17895 These are the files which are being checked for agenda entries.
17896 Optional argument FILE means, use this file instead of the current."
17897 (interactive)
17898 (let* ((org-agenda-skip-unavailable-files nil)
17899 (file (or file buffer-file-name))
17900 (true-file (file-truename file))
17901 (afile (abbreviate-file-name file))
17902 (files (delq nil (mapcar
17903 (lambda (x)
17904 (if (equal true-file
17905 (file-truename x))
17906 nil x))
17907 (org-agenda-files t)))))
17908 (if (not (= (length files) (length (org-agenda-files t))))
17909 (progn
17910 (org-store-new-agenda-file-list files)
17911 (org-install-agenda-files-menu)
17912 (message "Removed file: %s" afile))
17913 (message "File was not in list: %s" afile))))
17915 (defun org-file-menu-entry (file)
17916 (vector file (list 'find-file file) t))
17918 (defun org-check-agenda-file (file)
17919 "Make sure FILE exists. If not, ask user what to do."
17920 (when (not (file-exists-p file))
17921 (message "non-existent file %s. [R]emove from list or [A]bort?"
17922 (abbreviate-file-name file))
17923 (let ((r (downcase (read-char-exclusive))))
17924 (cond
17925 ((equal r ?r)
17926 (org-remove-file file)
17927 (throw 'nextfile t))
17928 (t (error "Abort"))))))
17930 ;;; Agenda prepare and finalize
17932 (defvar org-agenda-multi nil) ; dynammically scoped
17933 (defvar org-agenda-buffer-name "*Org Agenda*")
17934 (defvar org-pre-agenda-window-conf nil)
17935 (defvar org-agenda-name nil)
17936 (defun org-prepare-agenda (&optional name)
17937 (setq org-todo-keywords-for-agenda nil)
17938 (setq org-done-keywords-for-agenda nil)
17939 (if org-agenda-multi
17940 (progn
17941 (setq buffer-read-only nil)
17942 (goto-char (point-max))
17943 (unless (or (bobp) org-agenda-compact-blocks)
17944 (insert "\n" (make-string (window-width) ?=) "\n"))
17945 (narrow-to-region (point) (point-max)))
17946 (org-agenda-maybe-reset-markers 'force)
17947 (org-prepare-agenda-buffers (org-agenda-files))
17948 (setq org-todo-keywords-for-agenda
17949 (org-uniquify org-todo-keywords-for-agenda))
17950 (setq org-done-keywords-for-agenda
17951 (org-uniquify org-done-keywords-for-agenda))
17952 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
17953 (awin (get-buffer-window abuf)))
17954 (cond
17955 ((equal (current-buffer) abuf) nil)
17956 (awin (select-window awin))
17957 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
17958 ((equal org-agenda-window-setup 'current-window)
17959 (switch-to-buffer abuf))
17960 ((equal org-agenda-window-setup 'other-window)
17961 (org-switch-to-buffer-other-window abuf))
17962 ((equal org-agenda-window-setup 'other-frame)
17963 (switch-to-buffer-other-frame abuf))
17964 ((equal org-agenda-window-setup 'reorganize-frame)
17965 (delete-other-windows)
17966 (org-switch-to-buffer-other-window abuf))))
17967 (setq buffer-read-only nil)
17968 (erase-buffer)
17969 (org-agenda-mode)
17970 (and name (not org-agenda-name)
17971 (org-set-local 'org-agenda-name name)))
17972 (setq buffer-read-only nil))
17974 (defun org-finalize-agenda ()
17975 "Finishing touch for the agenda buffer, called just before displaying it."
17976 (unless org-agenda-multi
17977 (save-excursion
17978 (let ((inhibit-read-only t))
17979 (goto-char (point-min))
17980 (while (org-activate-bracket-links (point-max))
17981 (add-text-properties (match-beginning 0) (match-end 0)
17982 '(face org-link)))
17983 (org-agenda-align-tags)
17984 (unless org-agenda-with-colors
17985 (remove-text-properties (point-min) (point-max) '(face nil))))
17986 (if (and (boundp 'org-overriding-columns-format)
17987 org-overriding-columns-format)
17988 (org-set-local 'org-overriding-columns-format
17989 org-overriding-columns-format))
17990 (if (and (boundp 'org-agenda-view-columns-initially)
17991 org-agenda-view-columns-initially)
17992 (org-agenda-columns))
17993 (run-hooks 'org-finalize-agenda-hook))))
17995 (defun org-prepare-agenda-buffers (files)
17996 "Create buffers for all agenda files, protect archived trees and comments."
17997 (interactive)
17998 (let ((pa '(:org-archived t))
17999 (pc '(:org-comment t))
18000 (pall '(:org-archived t :org-comment t))
18001 (inhibit-read-only t)
18002 (rea (concat ":" org-archive-tag ":"))
18003 bmp file re)
18004 (save-excursion
18005 (save-restriction
18006 (while (setq file (pop files))
18007 (org-check-agenda-file file)
18008 (set-buffer (org-get-agenda-file-buffer file))
18009 (widen)
18010 (setq bmp (buffer-modified-p))
18011 (org-refresh-category-properties)
18012 (setq org-todo-keywords-for-agenda
18013 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18014 (setq org-done-keywords-for-agenda
18015 (append org-done-keywords-for-agenda org-done-keywords))
18016 (save-excursion
18017 (remove-text-properties (point-min) (point-max) pall)
18018 (when org-agenda-skip-archived-trees
18019 (goto-char (point-min))
18020 (while (re-search-forward rea nil t)
18021 (if (org-on-heading-p t)
18022 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18023 (goto-char (point-min))
18024 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18025 (while (re-search-forward re nil t)
18026 (add-text-properties
18027 (match-beginning 0) (org-end-of-subtree t) pc)))
18028 (set-buffer-modified-p bmp))))))
18030 (defvar org-agenda-skip-function nil
18031 "Function to be called at each match during agenda construction.
18032 If this function returns nil, the current match should not be skipped.
18033 Otherwise, the function must return a position from where the search
18034 should be continued.
18035 This may also be a Lisp form, it will be evaluated.
18036 Never set this variable using `setq' or so, because then it will apply
18037 to all future agenda commands. Instead, bind it with `let' to scope
18038 it dynamically into the agenda-constructing command. A good way to set
18039 it is through options in org-agenda-custom-commands.")
18041 (defun org-agenda-skip ()
18042 "Throw to `:skip' in places that should be skipped.
18043 Also moves point to the end of the skipped region, so that search can
18044 continue from there."
18045 (let ((p (point-at-bol)) to fp)
18046 (and org-agenda-skip-archived-trees
18047 (get-text-property p :org-archived)
18048 (org-end-of-subtree t)
18049 (throw :skip t))
18050 (and (get-text-property p :org-comment)
18051 (org-end-of-subtree t)
18052 (throw :skip t))
18053 (if (equal (char-after p) ?#) (throw :skip t))
18054 (when (and (or (setq fp (functionp org-agenda-skip-function))
18055 (consp org-agenda-skip-function))
18056 (setq to (save-excursion
18057 (save-match-data
18058 (if fp
18059 (funcall org-agenda-skip-function)
18060 (eval org-agenda-skip-function))))))
18061 (goto-char to)
18062 (throw :skip t))))
18064 (defvar org-agenda-markers nil
18065 "List of all currently active markers created by `org-agenda'.")
18066 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
18067 "Creation time of the last agenda marker.")
18069 (defun org-agenda-new-marker (&optional pos)
18070 "Return a new agenda marker.
18071 Org-mode keeps a list of these markers and resets them when they are
18072 no longer in use."
18073 (let ((m (copy-marker (or pos (point)))))
18074 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
18075 (push m org-agenda-markers)
18078 (defun org-agenda-maybe-reset-markers (&optional force)
18079 "Reset markers created by `org-agenda'. But only if they are old enough."
18080 (if (or (and force (not org-agenda-multi))
18081 (> (- (time-to-seconds (current-time))
18082 org-agenda-last-marker-time)
18084 (while org-agenda-markers
18085 (move-marker (pop org-agenda-markers) nil))))
18087 (defvar org-agenda-new-buffers nil
18088 "Buffers created to visit agenda files.")
18090 (defun org-get-agenda-file-buffer (file)
18091 "Get a buffer visiting FILE. If the buffer needs to be created, add
18092 it to the list of buffers which might be released later."
18093 (let ((buf (org-find-base-buffer-visiting file)))
18094 (if buf
18095 buf ; just return it
18096 ;; Make a new buffer and remember it
18097 (setq buf (find-file-noselect file))
18098 (if buf (push buf org-agenda-new-buffers))
18099 buf)))
18101 (defun org-release-buffers (blist)
18102 "Release all buffers in list, asking the user for confirmation when needed.
18103 When a buffer is unmodified, it is just killed. When modified, it is saved
18104 \(if the user agrees) and then killed."
18105 (let (buf file)
18106 (while (setq buf (pop blist))
18107 (setq file (buffer-file-name buf))
18108 (when (and (buffer-modified-p buf)
18109 file
18110 (y-or-n-p (format "Save file %s? " file)))
18111 (with-current-buffer buf (save-buffer)))
18112 (kill-buffer buf))))
18114 (defun org-get-category (&optional pos)
18115 "Get the category applying to position POS."
18116 (get-text-property (or pos (point)) 'org-category))
18118 ;;; Agenda timeline
18120 (defun org-timeline (&optional include-all)
18121 "Show a time-sorted view of the entries in the current org file.
18122 Only entries with a time stamp of today or later will be listed. With
18123 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
18124 under the current date.
18125 If the buffer contains an active region, only check the region for
18126 dates."
18127 (interactive "P")
18128 (require 'calendar)
18129 (org-compile-prefix-format 'timeline)
18130 (org-set-sorting-strategy 'timeline)
18131 (let* ((dopast t)
18132 (dotodo include-all)
18133 (doclosed org-agenda-show-log)
18134 (entry buffer-file-name)
18135 (date (calendar-current-date))
18136 (beg (if (org-region-active-p) (region-beginning) (point-min)))
18137 (end (if (org-region-active-p) (region-end) (point-max)))
18138 (day-numbers (org-get-all-dates beg end 'no-ranges
18139 t doclosed ; always include today
18140 org-timeline-show-empty-dates))
18141 (today (time-to-days (current-time)))
18142 (past t)
18143 args
18144 s e rtn d emptyp)
18145 (setq org-agenda-redo-command
18146 (list 'progn
18147 (list 'org-switch-to-buffer-other-window (current-buffer))
18148 (list 'org-timeline (list 'quote include-all))))
18149 (if (not dopast)
18150 ;; Remove past dates from the list of dates.
18151 (setq day-numbers (delq nil (mapcar (lambda(x)
18152 (if (>= x today) x nil))
18153 day-numbers))))
18154 (org-prepare-agenda (concat "Timeline "
18155 (file-name-nondirectory buffer-file-name)))
18156 (if doclosed (push :closed args))
18157 (push :timestamp args)
18158 (push :sexp args)
18159 (if dotodo (push :todo args))
18160 (while (setq d (pop day-numbers))
18161 (if (and (listp d) (eq (car d) :omitted))
18162 (progn
18163 (setq s (point))
18164 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
18165 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
18166 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
18167 (if (and (>= d today)
18168 dopast
18169 past)
18170 (progn
18171 (setq past nil)
18172 (insert (make-string 79 ?-) "\n")))
18173 (setq date (calendar-gregorian-from-absolute d))
18174 (setq s (point))
18175 (setq rtn (and (not emptyp)
18176 (apply 'org-agenda-get-day-entries entry
18177 date args)))
18178 (if (or rtn (equal d today) org-timeline-show-empty-dates)
18179 (progn
18180 (insert
18181 (if (stringp org-agenda-format-date)
18182 (format-time-string org-agenda-format-date
18183 (org-time-from-absolute date))
18184 (funcall org-agenda-format-date date))
18185 "\n")
18186 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18187 (put-text-property s (1- (point)) 'org-date-line t)
18188 (if (equal d today)
18189 (put-text-property s (1- (point)) 'org-today t))
18190 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
18191 (put-text-property s (1- (point)) 'day d)))))
18192 (goto-char (point-min))
18193 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
18194 (point-min)))
18195 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
18196 (org-finalize-agenda)
18197 (setq buffer-read-only t)))
18199 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
18200 "Return a list of all relevant day numbers from BEG to END buffer positions.
18201 If NO-RANGES is non-nil, include only the start and end dates of a range,
18202 not every single day in the range. If FORCE-TODAY is non-nil, make
18203 sure that TODAY is included in the list. If INACTIVE is non-nil, also
18204 inactive time stamps (those in square brackets) are included.
18205 When EMPTY is non-nil, also include days without any entries."
18206 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
18207 dates dates1 date day day1 day2 ts1 ts2)
18208 (if force-today
18209 (setq dates (list (time-to-days (current-time)))))
18210 (save-excursion
18211 (goto-char beg)
18212 (while (re-search-forward re end t)
18213 (setq day (time-to-days (org-time-string-to-time
18214 (substring (match-string 1) 0 10))))
18215 (or (memq day dates) (push day dates)))
18216 (unless no-ranges
18217 (goto-char beg)
18218 (while (re-search-forward org-tr-regexp end t)
18219 (setq ts1 (substring (match-string 1) 0 10)
18220 ts2 (substring (match-string 2) 0 10)
18221 day1 (time-to-days (org-time-string-to-time ts1))
18222 day2 (time-to-days (org-time-string-to-time ts2)))
18223 (while (< (setq day1 (1+ day1)) day2)
18224 (or (memq day1 dates) (push day1 dates)))))
18225 (setq dates (sort dates '<))
18226 (when empty
18227 (while (setq day (pop dates))
18228 (setq day2 (car dates))
18229 (push day dates1)
18230 (when (and day2 empty)
18231 (if (or (eq empty t)
18232 (and (numberp empty) (<= (- day2 day) empty)))
18233 (while (< (setq day (1+ day)) day2)
18234 (push (list day) dates1))
18235 (push (cons :omitted (- day2 day)) dates1))))
18236 (setq dates (nreverse dates1)))
18237 dates)))
18239 ;;; Agenda Daily/Weekly
18241 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
18242 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
18243 (defvar org-agenda-last-arguments nil
18244 "The arguments of the previous call to org-agenda")
18245 (defvar org-starting-day nil) ; local variable in the agenda buffer
18246 (defvar org-agenda-span nil) ; local variable in the agenda buffer
18247 (defvar org-include-all-loc nil) ; local variable
18248 (defvar org-agenda-remove-date nil) ; dynamically scoped
18250 ;;;###autoload
18251 (defun org-agenda-list (&optional include-all start-day ndays)
18252 "Produce a weekly view from all files in variable `org-agenda-files'.
18253 The view will be for the current week, but from the overview buffer you
18254 will be able to go to other weeks.
18255 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
18256 also be shown, under the current date.
18257 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
18258 on the days are also shown. See the variable `org-log-done' for how
18259 to turn on logging.
18260 START-DAY defaults to TODAY, or to the most recent match for the weekday
18261 given in `org-agenda-start-on-weekday'.
18262 NDAYS defaults to `org-agenda-ndays'."
18263 (interactive "P")
18264 (setq ndays (or ndays org-agenda-ndays)
18265 start-day (or start-day org-agenda-start-day))
18266 (if org-agenda-overriding-arguments
18267 (setq include-all (car org-agenda-overriding-arguments)
18268 start-day (nth 1 org-agenda-overriding-arguments)
18269 ndays (nth 2 org-agenda-overriding-arguments)))
18270 (if (stringp start-day)
18271 ;; Convert to an absolute day number
18272 (setq start-day (time-to-days (org-read-date nil t start-day))))
18273 (setq org-agenda-last-arguments (list include-all start-day ndays))
18274 (org-compile-prefix-format 'agenda)
18275 (org-set-sorting-strategy 'agenda)
18276 (require 'calendar)
18277 (let* ((org-agenda-start-on-weekday
18278 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
18279 org-agenda-start-on-weekday nil))
18280 (thefiles (org-agenda-files))
18281 (files thefiles)
18282 (today (time-to-days (current-time)))
18283 (sd (or start-day today))
18284 (start (if (or (null org-agenda-start-on-weekday)
18285 (< org-agenda-ndays 7))
18287 (let* ((nt (calendar-day-of-week
18288 (calendar-gregorian-from-absolute sd)))
18289 (n1 org-agenda-start-on-weekday)
18290 (d (- nt n1)))
18291 (- sd (+ (if (< d 0) 7 0) d)))))
18292 (day-numbers (list start))
18293 (inhibit-redisplay (not debug-on-error))
18294 s e rtn rtnall file date d start-pos end-pos todayp nd)
18295 (setq org-agenda-redo-command
18296 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
18297 ;; Make the list of days
18298 (setq ndays (or ndays org-agenda-ndays)
18299 nd ndays)
18300 (while (> ndays 1)
18301 (push (1+ (car day-numbers)) day-numbers)
18302 (setq ndays (1- ndays)))
18303 (setq day-numbers (nreverse day-numbers))
18304 (org-prepare-agenda "Day/Week")
18305 (org-set-local 'org-starting-day (car day-numbers))
18306 (org-set-local 'org-include-all-loc include-all)
18307 (org-set-local 'org-agenda-span
18308 (org-agenda-ndays-to-span nd))
18309 (when (and (or include-all org-agenda-include-all-todo)
18310 (member today day-numbers))
18311 (setq files thefiles
18312 rtnall nil)
18313 (while (setq file (pop files))
18314 (catch 'nextfile
18315 (org-check-agenda-file file)
18316 (setq date (calendar-gregorian-from-absolute today)
18317 rtn (org-agenda-get-day-entries
18318 file date :todo))
18319 (setq rtnall (append rtnall rtn))))
18320 (when rtnall
18321 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
18322 (add-text-properties (point-min) (1- (point))
18323 (list 'face 'org-agenda-structure))
18324 (insert (org-finalize-agenda-entries rtnall) "\n")))
18325 (unless org-agenda-compact-blocks
18326 (setq s (point))
18327 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
18328 "-agenda:\n")
18329 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
18330 'org-date-line t)))
18331 (while (setq d (pop day-numbers))
18332 (setq date (calendar-gregorian-from-absolute d)
18333 s (point))
18334 (if (or (setq todayp (= d today))
18335 (and (not start-pos) (= d sd)))
18336 (setq start-pos (point))
18337 (if (and start-pos (not end-pos))
18338 (setq end-pos (point))))
18339 (setq files thefiles
18340 rtnall nil)
18341 (while (setq file (pop files))
18342 (catch 'nextfile
18343 (org-check-agenda-file file)
18344 (if org-agenda-show-log
18345 (setq rtn (org-agenda-get-day-entries
18346 file date
18347 :deadline :scheduled :timestamp :sexp :closed))
18348 (setq rtn (org-agenda-get-day-entries
18349 file date
18350 :deadline :scheduled :sexp :timestamp)))
18351 (setq rtnall (append rtnall rtn))))
18352 (if org-agenda-include-diary
18353 (progn
18354 (require 'diary-lib)
18355 (setq rtn (org-get-entries-from-diary date))
18356 (setq rtnall (append rtnall rtn))))
18357 (if (or rtnall org-agenda-show-all-dates)
18358 (progn
18359 (insert
18360 (if (stringp org-agenda-format-date)
18361 (format-time-string org-agenda-format-date
18362 (org-time-from-absolute date))
18363 (funcall org-agenda-format-date date))
18364 "\n")
18365 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
18366 (put-text-property s (1- (point)) 'org-date-line t)
18367 (if todayp (put-text-property s (1- (point)) 'org-today t))
18368 (if rtnall (insert
18369 (org-finalize-agenda-entries
18370 (org-agenda-add-time-grid-maybe
18371 rtnall nd todayp))
18372 "\n"))
18373 (put-text-property s (1- (point)) 'day d))))
18374 (goto-char (point-min))
18375 (org-fit-agenda-window)
18376 (unless (and (pos-visible-in-window-p (point-min))
18377 (pos-visible-in-window-p (point-max)))
18378 (goto-char (1- (point-max)))
18379 (recenter -1)
18380 (if (not (pos-visible-in-window-p (or start-pos 1)))
18381 (progn
18382 (goto-char (or start-pos 1))
18383 (recenter 1))))
18384 (goto-char (or start-pos 1))
18385 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
18386 (org-finalize-agenda)
18387 (setq buffer-read-only t)
18388 (message "")))
18390 (defun org-agenda-ndays-to-span (n)
18391 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
18393 ;;; Agenda TODO list
18395 (defvar org-select-this-todo-keyword nil)
18396 (defvar org-last-arg nil)
18398 ;;;###autoload
18399 (defun org-todo-list (arg)
18400 "Show all TODO entries from all agenda file in a single list.
18401 The prefix arg can be used to select a specific TODO keyword and limit
18402 the list to these. When using \\[universal-argument], you will be prompted
18403 for a keyword. A numeric prefix directly selects the Nth keyword in
18404 `org-todo-keywords-1'."
18405 (interactive "P")
18406 (require 'calendar)
18407 (org-compile-prefix-format 'todo)
18408 (org-set-sorting-strategy 'todo)
18409 (org-prepare-agenda "TODO")
18410 (let* ((today (time-to-days (current-time)))
18411 (date (calendar-gregorian-from-absolute today))
18412 (kwds org-todo-keywords-for-agenda)
18413 (completion-ignore-case t)
18414 (org-select-this-todo-keyword
18415 (if (stringp arg) arg
18416 (and arg (integerp arg) (> arg 0)
18417 (nth (1- arg) kwds))))
18418 rtn rtnall files file pos)
18419 (when (equal arg '(4))
18420 (setq org-select-this-todo-keyword
18421 (completing-read "Keyword (or KWD1|K2D2|...): "
18422 (mapcar 'list kwds) nil nil)))
18423 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
18424 (org-set-local 'org-last-arg arg)
18425 (setq org-agenda-redo-command
18426 '(org-todo-list (or current-prefix-arg org-last-arg)))
18427 (setq files (org-agenda-files)
18428 rtnall nil)
18429 (while (setq file (pop files))
18430 (catch 'nextfile
18431 (org-check-agenda-file file)
18432 (setq rtn (org-agenda-get-day-entries file date :todo))
18433 (setq rtnall (append rtnall rtn))))
18434 (if org-agenda-overriding-header
18435 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18436 nil 'face 'org-agenda-structure) "\n")
18437 (insert "Global list of TODO items of type: ")
18438 (add-text-properties (point-min) (1- (point))
18439 (list 'face 'org-agenda-structure))
18440 (setq pos (point))
18441 (insert (or org-select-this-todo-keyword "ALL") "\n")
18442 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18443 (setq pos (point))
18444 (unless org-agenda-multi
18445 (insert "Available with `N r': (0)ALL")
18446 (let ((n 0) s)
18447 (mapc (lambda (x)
18448 (setq s (format "(%d)%s" (setq n (1+ n)) x))
18449 (if (> (+ (current-column) (string-width s) 1) (frame-width))
18450 (insert "\n "))
18451 (insert " " s))
18452 kwds))
18453 (insert "\n"))
18454 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18455 (when rtnall
18456 (insert (org-finalize-agenda-entries rtnall) "\n"))
18457 (goto-char (point-min))
18458 (org-fit-agenda-window)
18459 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
18460 (org-finalize-agenda)
18461 (setq buffer-read-only t)))
18463 ;;; Agenda tags match
18465 ;;;###autoload
18466 (defun org-tags-view (&optional todo-only match)
18467 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
18468 The prefix arg TODO-ONLY limits the search to TODO entries."
18469 (interactive "P")
18470 (org-compile-prefix-format 'tags)
18471 (org-set-sorting-strategy 'tags)
18472 (let* ((org-tags-match-list-sublevels
18473 (if todo-only t org-tags-match-list-sublevels))
18474 (completion-ignore-case t)
18475 rtn rtnall files file pos matcher
18476 buffer)
18477 (setq matcher (org-make-tags-matcher match)
18478 match (car matcher) matcher (cdr matcher))
18479 (org-prepare-agenda (concat "TAGS " match))
18480 (setq org-agenda-redo-command
18481 (list 'org-tags-view (list 'quote todo-only)
18482 (list 'if 'current-prefix-arg nil match)))
18483 (setq files (org-agenda-files)
18484 rtnall nil)
18485 (while (setq file (pop files))
18486 (catch 'nextfile
18487 (org-check-agenda-file file)
18488 (setq buffer (if (file-exists-p file)
18489 (org-get-agenda-file-buffer file)
18490 (error "No such file %s" file)))
18491 (if (not buffer)
18492 ;; If file does not exist, merror message to agenda
18493 (setq rtn (list
18494 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
18495 rtnall (append rtnall rtn))
18496 (with-current-buffer buffer
18497 (unless (org-mode-p)
18498 (error "Agenda file %s is not in `org-mode'" file))
18499 (save-excursion
18500 (save-restriction
18501 (if org-agenda-restrict
18502 (narrow-to-region org-agenda-restrict-begin
18503 org-agenda-restrict-end)
18504 (widen))
18505 (setq rtn (org-scan-tags 'agenda matcher todo-only))
18506 (setq rtnall (append rtnall rtn))))))))
18507 (if org-agenda-overriding-header
18508 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
18509 nil 'face 'org-agenda-structure) "\n")
18510 (insert "Headlines with TAGS match: ")
18511 (add-text-properties (point-min) (1- (point))
18512 (list 'face 'org-agenda-structure))
18513 (setq pos (point))
18514 (insert match "\n")
18515 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
18516 (setq pos (point))
18517 (unless org-agenda-multi
18518 (insert "Press `C-u r' to search again with new search string\n"))
18519 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
18520 (when rtnall
18521 (insert (org-finalize-agenda-entries rtnall) "\n"))
18522 (goto-char (point-min))
18523 (org-fit-agenda-window)
18524 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
18525 (org-finalize-agenda)
18526 (setq buffer-read-only t)))
18528 ;;; Agenda Finding stuck projects
18530 (defvar org-agenda-skip-regexp nil
18531 "Regular expression used in skipping subtrees for the agenda.
18532 This is basically a temporary global variable that can be set and then
18533 used by user-defined selections using `org-agenda-skip-function'.")
18535 (defvar org-agenda-overriding-header nil
18536 "When this is set during todo and tags searches, will replace header.")
18538 (defun org-agenda-skip-subtree-when-regexp-matches ()
18539 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
18540 If yes, it returns the end position of this tree, causing agenda commands
18541 to skip this subtree. This is a function that can be put into
18542 `org-agenda-skip-function' for the duration of a command."
18543 (let ((end (save-excursion (org-end-of-subtree t)))
18544 skip)
18545 (save-excursion
18546 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
18547 (and skip end)))
18549 (defun org-agenda-skip-entry-if (&rest conditions)
18550 "Skip entry if any of CONDITIONS is true.
18551 See `org-agenda-skip-if for details."
18552 (org-agenda-skip-if nil conditions))
18553 (defun org-agenda-skip-subtree-if (&rest conditions)
18554 "Skip entry if any of CONDITIONS is true.
18555 See `org-agenda-skip-if for details."
18556 (org-agenda-skip-if t conditions))
18558 (defun org-agenda-skip-if (subtree conditions)
18559 "Checks current entity for CONDITIONS.
18560 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
18561 the entry, i.e. the text before the next heading is checked.
18563 CONDITIONS is a list of symbols, boolean OR is used to combine the results
18564 from different tests. Valid conditions are:
18566 scheduled Check if there is a scheduled cookie
18567 notscheduled Check if there is no scheduled cookie
18568 deadline Check if there is a deadline
18569 notdeadline Check if there is no deadline
18570 regexp Check if regexp matches
18571 notregexp Check if regexp does not match.
18573 The regexp is taken from the conditions list, it must com right after the
18574 `regexp' of `notregexp' element.
18576 If any of these conditions is met, this function returns the end point of
18577 the entity, causing the search to continue from there. This is a function
18578 that can be put into `org-agenda-skip-function' for the duration of a command."
18579 (let (beg end m r)
18580 (org-back-to-heading t)
18581 (setq beg (point)
18582 end (if subtree
18583 (progn (org-end-of-subtree t) (point))
18584 (progn (outline-next-heading) (1- (point)))))
18585 (goto-char beg)
18586 (and
18588 (and (memq 'scheduled conditions)
18589 (re-search-forward org-scheduled-time-regexp end t))
18590 (and (memq 'notscheduled conditions)
18591 (not (re-search-forward org-scheduled-time-regexp end t)))
18592 (and (memq 'deadline conditions)
18593 (re-search-forward org-deadline-time-regexp end t))
18594 (and (memq 'notdeadline conditions)
18595 (not (re-search-forward org-deadline-time-regexp end t)))
18596 (and (setq m (memq 'regexp conditions))
18597 (stringp (setq r (nth 1 m)))
18598 (re-search-forward (nth 1 m) end t))
18599 (and (setq m (memq 'notregexp conditions))
18600 (stringp (setq r (nth 1 m)))
18601 (not (re-search-forward (nth 1 m) end t))))
18602 end)))
18604 (defun org-agenda-list-stuck-projects (&rest ignore)
18605 "Create agenda view for projects that are stuck.
18606 Stuck projects are project that have no next actions. For the definitions
18607 of what a project is and how to check if it stuck, customize the variable
18608 `org-stuck-projects'.
18609 MATCH is being ignored."
18610 (interactive)
18611 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
18612 ;; FIXME: we could have used org-agenda-skip-if here.
18613 (org-agenda-overriding-header "List of stuck projects: ")
18614 (matcher (nth 0 org-stuck-projects))
18615 (todo (nth 1 org-stuck-projects))
18616 (todo-wds (if (member "*" todo)
18617 (progn
18618 (org-prepare-agenda-buffers (org-agenda-files))
18619 (org-delete-all
18620 org-done-keywords-for-agenda
18621 (copy-sequence org-todo-keywords-for-agenda)))
18622 todo))
18623 (todo-re (concat "^\\*+[ \t]+\\("
18624 (mapconcat 'identity todo-wds "\\|")
18625 "\\)\\>"))
18626 (tags (nth 2 org-stuck-projects))
18627 (tags-re (if (member "*" tags)
18628 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
18629 (concat "^\\*+ .*:\\("
18630 (mapconcat 'identity tags "\\|")
18631 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
18632 (gen-re (nth 3 org-stuck-projects))
18633 (re-list
18634 (delq nil
18635 (list
18636 (if todo todo-re)
18637 (if tags tags-re)
18638 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
18639 gen-re)))))
18640 (setq org-agenda-skip-regexp
18641 (if re-list
18642 (mapconcat 'identity re-list "\\|")
18643 (error "No information how to identify unstuck projects")))
18644 (org-tags-view nil matcher)
18645 (with-current-buffer org-agenda-buffer-name
18646 (setq org-agenda-redo-command
18647 '(org-agenda-list-stuck-projects
18648 (or current-prefix-arg org-last-arg))))))
18650 ;;; Diary integration
18652 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
18654 (defun org-get-entries-from-diary (date)
18655 "Get the (Emacs Calendar) diary entries for DATE."
18656 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
18657 (diary-display-hook '(fancy-diary-display))
18658 (pop-up-frames nil)
18659 (list-diary-entries-hook
18660 (cons 'org-diary-default-entry list-diary-entries-hook))
18661 (diary-file-name-prefix-function nil) ; turn this feature off
18662 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
18663 entries
18664 (org-disable-agenda-to-diary t))
18665 (save-excursion
18666 (save-window-excursion
18667 (funcall (if (fboundp 'diary-list-entries)
18668 'diary-list-entries 'list-diary-entries)
18669 date 1)))
18670 (if (not (get-buffer fancy-diary-buffer))
18671 (setq entries nil)
18672 (with-current-buffer fancy-diary-buffer
18673 (setq buffer-read-only nil)
18674 (if (zerop (buffer-size))
18675 ;; No entries
18676 (setq entries nil)
18677 ;; Omit the date and other unnecessary stuff
18678 (org-agenda-cleanup-fancy-diary)
18679 ;; Add prefix to each line and extend the text properties
18680 (if (zerop (buffer-size))
18681 (setq entries nil)
18682 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
18683 (set-buffer-modified-p nil)
18684 (kill-buffer fancy-diary-buffer)))
18685 (when entries
18686 (setq entries (org-split-string entries "\n"))
18687 (setq entries
18688 (mapcar
18689 (lambda (x)
18690 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
18691 ;; Extend the text properties to the beginning of the line
18692 (org-add-props x (text-properties-at (1- (length x)) x)
18693 'type "diary" 'date date))
18694 entries)))))
18696 (defun org-agenda-cleanup-fancy-diary ()
18697 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
18698 This gets rid of the date, the underline under the date, and
18699 the dummy entry installed by `org-mode' to ensure non-empty diary for each
18700 date. It also removes lines that contain only whitespace."
18701 (goto-char (point-min))
18702 (if (looking-at ".*?:[ \t]*")
18703 (progn
18704 (replace-match "")
18705 (re-search-forward "\n=+$" nil t)
18706 (replace-match "")
18707 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
18708 (re-search-forward "\n=+$" nil t)
18709 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
18710 (goto-char (point-min))
18711 (while (re-search-forward "^ +\n" nil t)
18712 (replace-match ""))
18713 (goto-char (point-min))
18714 (if (re-search-forward "^Org-mode dummy\n?" nil t)
18715 (replace-match "")))
18717 ;; Make sure entries from the diary have the right text properties.
18718 (eval-after-load "diary-lib"
18719 '(if (boundp 'diary-modify-entry-list-string-function)
18720 ;; We can rely on the hook, nothing to do
18722 ;; Hook not avaiable, must use advice to make this work
18723 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
18724 "Make the position visible."
18725 (if (and org-disable-agenda-to-diary ;; called from org-agenda
18726 (stringp string)
18727 buffer-file-name)
18728 (setq string (org-modify-diary-entry-string string))))))
18730 (defun org-modify-diary-entry-string (string)
18731 "Add text properties to string, allowing org-mode to act on it."
18732 (org-add-props string nil
18733 'mouse-face 'highlight
18734 'keymap org-agenda-keymap
18735 'help-echo (if buffer-file-name
18736 (format "mouse-2 or RET jump to diary file %s"
18737 (abbreviate-file-name buffer-file-name))
18739 'org-agenda-diary-link t
18740 'org-marker (org-agenda-new-marker (point-at-bol))))
18742 (defun org-diary-default-entry ()
18743 "Add a dummy entry to the diary.
18744 Needed to avoid empty dates which mess up holiday display."
18745 ;; Catch the error if dealing with the new add-to-diary-alist
18746 (when org-disable-agenda-to-diary
18747 (condition-case nil
18748 (add-to-diary-list original-date "Org-mode dummy" "")
18749 (error
18750 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
18752 ;;;###autoload
18753 (defun org-diary (&rest args)
18754 "Return diary information from org-files.
18755 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
18756 It accesses org files and extracts information from those files to be
18757 listed in the diary. The function accepts arguments specifying what
18758 items should be listed. The following arguments are allowed:
18760 :timestamp List the headlines of items containing a date stamp or
18761 date range matching the selected date. Deadlines will
18762 also be listed, on the expiration day.
18764 :sexp List entries resulting from diary-like sexps.
18766 :deadline List any deadlines past due, or due within
18767 `org-deadline-warning-days'. The listing occurs only
18768 in the diary for *today*, not at any other date. If
18769 an entry is marked DONE, it is no longer listed.
18771 :scheduled List all items which are scheduled for the given date.
18772 The diary for *today* also contains items which were
18773 scheduled earlier and are not yet marked DONE.
18775 :todo List all TODO items from the org-file. This may be a
18776 long list - so this is not turned on by default.
18777 Like deadlines, these entries only show up in the
18778 diary for *today*, not at any other date.
18780 The call in the diary file should look like this:
18782 &%%(org-diary) ~/path/to/some/orgfile.org
18784 Use a separate line for each org file to check. Or, if you omit the file name,
18785 all files listed in `org-agenda-files' will be checked automatically:
18787 &%%(org-diary)
18789 If you don't give any arguments (as in the example above), the default
18790 arguments (:deadline :scheduled :timestamp :sexp) are used.
18791 So the example above may also be written as
18793 &%%(org-diary :deadline :timestamp :sexp :scheduled)
18795 The function expects the lisp variables `entry' and `date' to be provided
18796 by the caller, because this is how the calendar works. Don't use this
18797 function from a program - use `org-agenda-get-day-entries' instead."
18798 (org-agenda-maybe-reset-markers)
18799 (org-compile-prefix-format 'agenda)
18800 (org-set-sorting-strategy 'agenda)
18801 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18802 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
18803 (list entry)
18804 (org-agenda-files t)))
18805 file rtn results)
18806 (org-prepare-agenda-buffers files)
18807 ;; If this is called during org-agenda, don't return any entries to
18808 ;; the calendar. Org Agenda will list these entries itself.
18809 (if org-disable-agenda-to-diary (setq files nil))
18810 (while (setq file (pop files))
18811 (setq rtn (apply 'org-agenda-get-day-entries file date args))
18812 (setq results (append results rtn)))
18813 (if results
18814 (concat (org-finalize-agenda-entries results) "\n"))))
18816 ;;; Agenda entry finders
18818 (defun org-agenda-get-day-entries (file date &rest args)
18819 "Does the work for `org-diary' and `org-agenda'.
18820 FILE is the path to a file to be checked for entries. DATE is date like
18821 the one returned by `calendar-current-date'. ARGS are symbols indicating
18822 which kind of entries should be extracted. For details about these, see
18823 the documentation of `org-diary'."
18824 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18825 (let* ((org-startup-folded nil)
18826 (org-startup-align-all-tables nil)
18827 (buffer (if (file-exists-p file)
18828 (org-get-agenda-file-buffer file)
18829 (error "No such file %s" file)))
18830 arg results rtn)
18831 (if (not buffer)
18832 ;; If file does not exist, make sure an error message ends up in diary
18833 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
18834 (with-current-buffer buffer
18835 (unless (org-mode-p)
18836 (error "Agenda file %s is not in `org-mode'" file))
18837 (let ((case-fold-search nil))
18838 (save-excursion
18839 (save-restriction
18840 (if org-agenda-restrict
18841 (narrow-to-region org-agenda-restrict-begin
18842 org-agenda-restrict-end)
18843 (widen))
18844 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
18845 (while (setq arg (pop args))
18846 (cond
18847 ((and (eq arg :todo)
18848 (equal date (calendar-current-date)))
18849 (setq rtn (org-agenda-get-todos))
18850 (setq results (append results rtn)))
18851 ((eq arg :timestamp)
18852 (setq rtn (org-agenda-get-blocks))
18853 (setq results (append results rtn))
18854 (setq rtn (org-agenda-get-timestamps))
18855 (setq results (append results rtn)))
18856 ((eq arg :sexp)
18857 (setq rtn (org-agenda-get-sexps))
18858 (setq results (append results rtn)))
18859 ((eq arg :scheduled)
18860 (setq rtn (org-agenda-get-scheduled))
18861 (setq results (append results rtn)))
18862 ((eq arg :closed)
18863 (setq rtn (org-agenda-get-closed))
18864 (setq results (append results rtn)))
18865 ((eq arg :deadline)
18866 (setq rtn (org-agenda-get-deadlines))
18867 (setq results (append results rtn))))))))
18868 results))))
18870 ;; FIXME: this works only if the cursor is *not* at the
18871 ;; beginning of the entry
18872 (defun org-entry-is-done-p ()
18873 "Is the current entry marked DONE?"
18874 (save-excursion
18875 (and (re-search-backward "[\r\n]\\*+ " nil t)
18876 (looking-at org-nl-done-regexp))))
18878 (defun org-at-date-range-p (&optional inactive-ok)
18879 "Is the cursor inside a date range?"
18880 (interactive)
18881 (save-excursion
18882 (catch 'exit
18883 (let ((pos (point)))
18884 (skip-chars-backward "^[<\r\n")
18885 (skip-chars-backward "<[")
18886 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18887 (>= (match-end 0) pos)
18888 (throw 'exit t))
18889 (skip-chars-backward "^<[\r\n")
18890 (skip-chars-backward "<[")
18891 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18892 (>= (match-end 0) pos)
18893 (throw 'exit t)))
18894 nil)))
18896 (defun org-agenda-get-todos ()
18897 "Return the TODO information for agenda display."
18898 (let* ((props (list 'face nil
18899 'done-face 'org-done
18900 'org-not-done-regexp org-not-done-regexp
18901 'org-todo-regexp org-todo-regexp
18902 'mouse-face 'highlight
18903 'keymap org-agenda-keymap
18904 'help-echo
18905 (format "mouse-2 or RET jump to org file %s"
18906 (abbreviate-file-name buffer-file-name))))
18907 ;; FIXME: get rid of the \n at some point but watch out
18908 (regexp (concat "^\\*+[ \t]+\\("
18909 (if org-select-this-todo-keyword
18910 (if (equal org-select-this-todo-keyword "*")
18911 org-todo-regexp
18912 (concat "\\<\\("
18913 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
18914 "\\)\\>"))
18915 org-not-done-regexp)
18916 "[^\n\r]*\\)"))
18917 marker priority category tags
18918 ee txt beg end)
18919 (goto-char (point-min))
18920 (while (re-search-forward regexp nil t)
18921 (catch :skip
18922 (save-match-data
18923 (beginning-of-line)
18924 (setq beg (point) end (progn (outline-next-heading) (point)))
18925 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
18926 (re-search-forward org-scheduled-time-regexp end t))
18927 (and org-agenda-todo-ignore-deadlines (goto-char beg)
18928 (re-search-forward org-deadline-time-regexp end t)
18929 (org-deadline-close (match-string 1))))
18930 (goto-char (1+ beg))
18931 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
18932 (throw :skip nil)))
18933 (goto-char beg)
18934 (org-agenda-skip)
18935 (goto-char (match-beginning 1))
18936 (setq marker (org-agenda-new-marker (match-beginning 0))
18937 category (org-get-category)
18938 tags (org-get-tags-at (point))
18939 txt (org-format-agenda-item "" (match-string 1) category tags)
18940 priority (1+ (org-get-priority txt)))
18941 (org-add-props txt props
18942 'org-marker marker 'org-hd-marker marker
18943 'priority priority 'org-category category
18944 'type "todo")
18945 (push txt ee)
18946 (if org-agenda-todo-list-sublevels
18947 (goto-char (match-end 1))
18948 (org-end-of-subtree 'invisible))))
18949 (nreverse ee)))
18951 (defconst org-agenda-no-heading-message
18952 "No heading for this item in buffer or region.")
18954 (defun org-agenda-get-timestamps ()
18955 "Return the date stamp information for agenda display."
18956 (let* ((props (list 'face nil
18957 'org-not-done-regexp org-not-done-regexp
18958 'org-todo-regexp org-todo-regexp
18959 'mouse-face 'highlight
18960 'keymap org-agenda-keymap
18961 'help-echo
18962 (format "mouse-2 or RET jump to org file %s"
18963 (abbreviate-file-name buffer-file-name))))
18964 (d1 (calendar-absolute-from-gregorian date))
18965 (remove-re
18966 (concat
18967 (regexp-quote
18968 (format-time-string
18969 "<%Y-%m-%d"
18970 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18971 ".*?>"))
18972 (regexp
18973 (concat
18974 (regexp-quote
18975 (substring
18976 (format-time-string
18977 (car org-time-stamp-formats)
18978 (apply 'encode-time ; DATE bound by calendar
18979 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18980 0 11))
18981 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
18982 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
18983 marker hdmarker deadlinep scheduledp donep tmp priority category
18984 ee txt timestr tags b0 b3 e3)
18985 (goto-char (point-min))
18986 (while (re-search-forward regexp nil t)
18987 (setq b0 (match-beginning 0)
18988 b3 (match-beginning 3) e3 (match-end 3))
18989 (catch :skip
18990 (and (org-at-date-range-p) (throw :skip nil))
18991 (org-agenda-skip)
18992 (if (and (match-end 1)
18993 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
18994 (throw :skip nil))
18995 (if (and e3
18996 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
18997 (throw :skip nil))
18998 (setq marker (org-agenda-new-marker b0)
18999 category (org-get-category b0)
19000 tmp (buffer-substring (max (point-min)
19001 (- b0 org-ds-keyword-length))
19003 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19004 deadlinep (string-match org-deadline-regexp tmp)
19005 scheduledp (string-match org-scheduled-regexp tmp)
19006 donep (org-entry-is-done-p))
19007 (if (or scheduledp deadlinep) (throw :skip t))
19008 (if (string-match ">" timestr)
19009 ;; substring should only run to end of time stamp
19010 (setq timestr (substring timestr 0 (match-end 0))))
19011 (save-excursion
19012 (if (re-search-backward "^\\*+ " nil t)
19013 (progn
19014 (goto-char (match-beginning 0))
19015 (setq hdmarker (org-agenda-new-marker)
19016 tags (org-get-tags-at))
19017 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19018 (setq txt (org-format-agenda-item
19019 nil (match-string 1) category tags timestr nil
19020 remove-re)))
19021 (setq txt org-agenda-no-heading-message))
19022 (setq priority (org-get-priority txt))
19023 (org-add-props txt props
19024 'org-marker marker 'org-hd-marker hdmarker)
19025 (org-add-props txt nil 'priority priority
19026 'org-category category 'date date
19027 'type "timestamp")
19028 (push txt ee))
19029 (outline-next-heading)))
19030 (nreverse ee)))
19032 (defun org-agenda-get-sexps ()
19033 "Return the sexp information for agenda display."
19034 (require 'diary-lib)
19035 (let* ((props (list 'face nil
19036 'mouse-face 'highlight
19037 'keymap org-agenda-keymap
19038 'help-echo
19039 (format "mouse-2 or RET jump to org file %s"
19040 (abbreviate-file-name buffer-file-name))))
19041 (regexp "^&?%%(")
19042 marker category ee txt tags entry result beg b sexp sexp-entry)
19043 (goto-char (point-min))
19044 (while (re-search-forward regexp nil t)
19045 (catch :skip
19046 (org-agenda-skip)
19047 (setq beg (match-beginning 0))
19048 (goto-char (1- (match-end 0)))
19049 (setq b (point))
19050 (forward-sexp 1)
19051 (setq sexp (buffer-substring b (point)))
19052 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
19053 (org-trim (match-string 1))
19054 ""))
19055 (setq result (org-diary-sexp-entry sexp sexp-entry date))
19056 (when result
19057 (setq marker (org-agenda-new-marker beg)
19058 category (org-get-category beg))
19060 (if (string-match "\\S-" result)
19061 (setq txt result)
19062 (setq txt "SEXP entry returned empty string"))
19064 (setq txt (org-format-agenda-item
19065 "" txt category tags 'time))
19066 (org-add-props txt props 'org-marker marker)
19067 (org-add-props txt nil
19068 'org-category category 'date date
19069 'type "sexp")
19070 (push txt ee))))
19071 (nreverse ee)))
19073 (defun org-agenda-get-closed ()
19074 "Return the logged TODO entries for agenda display."
19075 (let* ((props (list 'mouse-face 'highlight
19076 'org-not-done-regexp org-not-done-regexp
19077 'org-todo-regexp org-todo-regexp
19078 'keymap org-agenda-keymap
19079 'help-echo
19080 (format "mouse-2 or RET jump to org file %s"
19081 (abbreviate-file-name buffer-file-name))))
19082 (regexp (concat
19083 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
19084 (regexp-quote
19085 (substring
19086 (format-time-string
19087 (car org-time-stamp-formats)
19088 (apply 'encode-time ; DATE bound by calendar
19089 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19090 1 11))))
19091 marker hdmarker priority category tags closedp
19092 ee txt timestr)
19093 (goto-char (point-min))
19094 (while (re-search-forward regexp nil t)
19095 (catch :skip
19096 (org-agenda-skip)
19097 (setq marker (org-agenda-new-marker (match-beginning 0))
19098 closedp (equal (match-string 1) org-closed-string)
19099 category (org-get-category (match-beginning 0))
19100 timestr (buffer-substring (match-beginning 0) (point-at-eol))
19101 ;; donep (org-entry-is-done-p)
19103 (if (string-match "\\]" timestr)
19104 ;; substring should only run to end of time stamp
19105 (setq timestr (substring timestr 0 (match-end 0))))
19106 (save-excursion
19107 (if (re-search-backward "^\\*+ " nil t)
19108 (progn
19109 (goto-char (match-beginning 0))
19110 (setq hdmarker (org-agenda-new-marker)
19111 tags (org-get-tags-at))
19112 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19113 (setq txt (org-format-agenda-item
19114 (if closedp "Closed: " "Clocked: ")
19115 (match-string 1) category tags timestr)))
19116 (setq txt org-agenda-no-heading-message))
19117 (setq priority 100000)
19118 (org-add-props txt props
19119 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
19120 'priority priority 'org-category category
19121 'type "closed" 'date date
19122 'undone-face 'org-warning 'done-face 'org-done)
19123 (push txt ee))
19124 (outline-next-heading)))
19125 (nreverse ee)))
19127 (defun org-agenda-get-deadlines ()
19128 "Return the deadline information for agenda display."
19129 (let* ((props (list 'mouse-face 'highlight
19130 'org-not-done-regexp org-not-done-regexp
19131 'org-todo-regexp org-todo-regexp
19132 'keymap org-agenda-keymap
19133 'help-echo
19134 (format "mouse-2 or RET jump to org file %s"
19135 (abbreviate-file-name buffer-file-name))))
19136 (regexp org-deadline-time-regexp)
19137 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19138 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19139 d2 diff dfrac wdays pos pos1 category tags
19140 ee txt head face s upcomingp donep timestr)
19141 (goto-char (point-min))
19142 (while (re-search-forward regexp nil t)
19143 (catch :skip
19144 (org-agenda-skip)
19145 (setq s (match-string 1)
19146 pos (1- (match-beginning 1))
19147 d2 (org-time-string-to-absolute (match-string 1) d1)
19148 diff (- d2 d1)
19149 wdays (org-get-wdays s)
19150 dfrac (/ (* 1.0 (- wdays diff)) wdays)
19151 upcomingp (and todayp (> diff 0)))
19152 ;; When to show a deadline in the calendar:
19153 ;; If the expiration is within wdays warning time.
19154 ;; Past-due deadlines are only shown on the current date
19155 (if (or (and (<= diff wdays) todayp)
19156 (= diff 0))
19157 (save-excursion
19158 (setq category (org-get-category))
19159 (if (re-search-backward "^\\*+[ \t]+" nil t)
19160 (progn
19161 (goto-char (match-end 0))
19162 (setq pos1 (match-beginning 0))
19163 (setq tags (org-get-tags-at pos1))
19164 (setq head (buffer-substring-no-properties
19165 (point)
19166 (progn (skip-chars-forward "^\r\n")
19167 (point))))
19168 (setq donep (string-match org-looking-at-done-regexp head))
19169 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19170 (setq timestr
19171 (concat (substring s (match-beginning 1)) " "))
19172 (setq timestr 'time))
19173 (if (and donep
19174 (or org-agenda-skip-deadline-if-done
19175 (not (= diff 0))))
19176 (setq txt nil)
19177 (setq txt (org-format-agenda-item
19178 (if (= diff 0)
19179 "Deadline: "
19180 (format "In %3d d.: " diff))
19181 head category tags timestr))))
19182 (setq txt org-agenda-no-heading-message))
19183 (when txt
19184 (setq face (org-agenda-deadline-face dfrac))
19185 (org-add-props txt props
19186 'org-marker (org-agenda-new-marker pos)
19187 'org-hd-marker (org-agenda-new-marker pos1)
19188 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
19189 (org-get-priority txt))
19190 'org-category category
19191 'type (if upcomingp "upcoming-deadline" "deadline")
19192 'date (if upcomingp date d2)
19193 'face (if donep 'org-done face)
19194 'undone-face face 'done-face 'org-done)
19195 (push txt ee))))))
19196 (nreverse ee)))
19198 (defun org-agenda-deadline-face (fraction)
19199 "Return the face to displaying a deadline item.
19200 FRACTION is what fraction of the head-warning time has passed."
19201 (let ((faces org-agenda-deadline-faces) f)
19202 (catch 'exit
19203 (while (setq f (pop faces))
19204 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
19206 (defun org-agenda-get-scheduled ()
19207 "Return the scheduled information for agenda display."
19208 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
19209 'org-todo-regexp org-todo-regexp
19210 'done-face 'org-done
19211 'mouse-face 'highlight
19212 'keymap org-agenda-keymap
19213 'help-echo
19214 (format "mouse-2 or RET jump to org file %s"
19215 (abbreviate-file-name buffer-file-name))))
19216 (regexp org-scheduled-time-regexp)
19217 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
19218 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
19219 d2 diff pos pos1 category tags
19220 ee txt head pastschedp donep face timestr s)
19221 (goto-char (point-min))
19222 (while (re-search-forward regexp nil t)
19223 (catch :skip
19224 (org-agenda-skip)
19225 (setq s (match-string 1)
19226 pos (1- (match-beginning 1))
19227 d2 (org-time-string-to-absolute (match-string 1) d1)
19228 diff (- d2 d1))
19229 (setq pastschedp (and todayp (< diff 0)))
19230 ;; When to show a scheduled item in the calendar:
19231 ;; If it is on or past the date.
19232 (if (or (and (< diff 0) todayp)
19233 (= diff 0))
19234 (save-excursion
19235 (setq category (org-get-category))
19236 (if (re-search-backward "^\\*+[ \t]+" nil t)
19237 (progn
19238 (goto-char (match-end 0))
19239 (setq pos1 (match-beginning 0))
19240 (setq tags (org-get-tags-at))
19241 (setq head (buffer-substring-no-properties
19242 (point)
19243 (progn (skip-chars-forward "^\r\n") (point))))
19244 (setq donep (string-match org-looking-at-done-regexp head))
19245 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
19246 (setq timestr
19247 (concat (substring s (match-beginning 1)) " "))
19248 (setq timestr 'time))
19249 (if (and donep
19250 (or org-agenda-skip-scheduled-if-done
19251 (not (= diff 0))))
19252 (setq txt nil)
19253 (setq txt (org-format-agenda-item
19254 (if (= diff 0)
19255 "Scheduled: "
19256 (format "Sched.%2dx: " (- 1 diff)))
19257 head category tags timestr))))
19258 (setq txt org-agenda-no-heading-message))
19259 (when txt
19260 (setq face (if pastschedp
19261 'org-scheduled-previously
19262 'org-scheduled-today))
19263 (org-add-props txt props
19264 'undone-face face
19265 'face (if donep 'org-done face)
19266 'org-marker (org-agenda-new-marker pos)
19267 'org-hd-marker (org-agenda-new-marker pos1)
19268 'type (if pastschedp "past-scheduled" "scheduled")
19269 'date (if pastschedp d2 date)
19270 'priority (+ 94 (- 5 diff) (org-get-priority txt))
19271 'org-category category)
19272 (push txt ee))))))
19273 (nreverse ee)))
19275 (defun org-agenda-get-blocks ()
19276 "Return the date-range information for agenda display."
19277 (let* ((props (list 'face nil
19278 'org-not-done-regexp org-not-done-regexp
19279 'org-todo-regexp org-todo-regexp
19280 'mouse-face 'highlight
19281 'keymap org-agenda-keymap
19282 'help-echo
19283 (format "mouse-2 or RET jump to org file %s"
19284 (abbreviate-file-name buffer-file-name))))
19285 (regexp org-tr-regexp)
19286 (d0 (calendar-absolute-from-gregorian date))
19287 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
19288 (goto-char (point-min))
19289 (while (re-search-forward regexp nil t)
19290 (catch :skip
19291 (org-agenda-skip)
19292 (setq pos (point))
19293 (setq timestr (match-string 0)
19294 s1 (match-string 1)
19295 s2 (match-string 2)
19296 d1 (time-to-days (org-time-string-to-time s1))
19297 d2 (time-to-days (org-time-string-to-time s2)))
19298 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
19299 ;; Only allow days between the limits, because the normal
19300 ;; date stamps will catch the limits.
19301 (save-excursion
19302 (setq marker (org-agenda-new-marker (point)))
19303 (setq category (org-get-category))
19304 (if (re-search-backward "^\\*+ " nil t)
19305 (progn
19306 (goto-char (match-beginning 0))
19307 (setq hdmarker (org-agenda-new-marker (point)))
19308 (setq tags (org-get-tags-at))
19309 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19310 (setq txt (org-format-agenda-item
19311 (format (if (= d1 d2) "" "(%d/%d): ")
19312 (1+ (- d0 d1)) (1+ (- d2 d1)))
19313 (match-string 1) category tags
19314 (if (= d0 d1) timestr))))
19315 (setq txt org-agenda-no-heading-message))
19316 (org-add-props txt props
19317 'org-marker marker 'org-hd-marker hdmarker
19318 'type "block" 'date date
19319 'priority (org-get-priority txt) 'org-category category)
19320 (push txt ee)))
19321 (goto-char pos)))
19322 ;; Sort the entries by expiration date.
19323 (nreverse ee)))
19325 ;;; Agenda presentation and sorting
19327 (defconst org-plain-time-of-day-regexp
19328 (concat
19329 "\\(\\<[012]?[0-9]"
19330 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19331 "\\(--?"
19332 "\\(\\<[012]?[0-9]"
19333 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19334 "\\)?")
19335 "Regular expression to match a plain time or time range.
19336 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19337 groups carry important information:
19338 0 the full match
19339 1 the first time, range or not
19340 8 the second time, if it is a range.")
19342 (defconst org-plain-time-extension-regexp
19343 (concat
19344 "\\(\\<[012]?[0-9]"
19345 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
19346 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
19347 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
19348 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
19349 groups carry important information:
19350 0 the full match
19351 7 hours of duration
19352 9 minutes of duration")
19354 (defconst org-stamp-time-of-day-regexp
19355 (concat
19356 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
19357 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
19358 "\\(--?"
19359 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
19360 "Regular expression to match a timestamp time or time range.
19361 After a match, the following groups carry important information:
19362 0 the full match
19363 1 date plus weekday, for backreferencing to make sure both times on same day
19364 2 the first time, range or not
19365 4 the second time, if it is a range.")
19367 (defvar org-prefix-has-time nil
19368 "A flag, set by `org-compile-prefix-format'.
19369 The flag is set if the currently compiled format contains a `%t'.")
19370 (defvar org-prefix-has-tag nil
19371 "A flag, set by `org-compile-prefix-format'.
19372 The flag is set if the currently compiled format contains a `%T'.")
19374 (defun org-format-agenda-item (extra txt &optional category tags dotime
19375 noprefix remove-re)
19376 "Format TXT to be inserted into the agenda buffer.
19377 In particular, it adds the prefix and corresponding text properties. EXTRA
19378 must be a string and replaces the `%s' specifier in the prefix format.
19379 CATEGORY (string, symbol or nil) may be used to overrule the default
19380 category taken from local variable or file name. It will replace the `%c'
19381 specifier in the format. DOTIME, when non-nil, indicates that a
19382 time-of-day should be extracted from TXT for sorting of this entry, and for
19383 the `%t' specifier in the format. When DOTIME is a string, this string is
19384 searched for a time before TXT is. NOPREFIX is a flag and indicates that
19385 only the correctly processes TXT should be returned - this is used by
19386 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
19387 Any match of REMOVE-RE will be removed from TXT."
19388 (save-match-data
19389 ;; Diary entries sometimes have extra whitespace at the beginning
19390 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
19391 (let* ((category (or category
19392 org-category
19393 (if buffer-file-name
19394 (file-name-sans-extension
19395 (file-name-nondirectory buffer-file-name))
19396 "")))
19397 (tag (if tags (nth (1- (length tags)) tags) ""))
19398 time ; time and tag are needed for the eval of the prefix format
19399 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
19400 (time-of-day (and dotime (org-get-time-of-day ts)))
19401 stamp plain s0 s1 s2 rtn srp)
19402 (when (and dotime time-of-day org-prefix-has-time)
19403 ;; Extract starting and ending time and move them to prefix
19404 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
19405 (setq plain (string-match org-plain-time-of-day-regexp ts)))
19406 (setq s0 (match-string 0 ts)
19407 srp (and stamp (match-end 3))
19408 s1 (match-string (if plain 1 2) ts)
19409 s2 (match-string (if plain 8 (if srp 4 6)) ts))
19411 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
19412 ;; them, we might want to remove them there to avoid duplication.
19413 ;; The user can turn this off with a variable.
19414 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
19415 (string-match (concat (regexp-quote s0) " *") txt)
19416 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
19417 (= (match-beginning 0) 0)
19419 (setq txt (replace-match "" nil nil txt))))
19420 ;; Normalize the time(s) to 24 hour
19421 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
19422 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
19424 (when (and s1 (not s2) org-agenda-default-appointment-duration
19425 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
19426 (let ((m (+ (string-to-number (match-string 2 s1))
19427 (* 60 (string-to-number (match-string 1 s1)))
19428 org-agenda-default-appointment-duration))
19430 (setq h (/ m 60) m (- m (* h 60)))
19431 (setq s2 (format "%02d:%02d" h m))))
19433 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
19434 txt)
19435 ;; Tags are in the string
19436 (if (or (eq org-agenda-remove-tags t)
19437 (and org-agenda-remove-tags
19438 org-prefix-has-tag))
19439 (setq txt (replace-match "" t t txt))
19440 (setq txt (replace-match
19441 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
19442 (match-string 2 txt))
19443 t t txt))))
19445 (when remove-re
19446 (while (string-match remove-re txt)
19447 (setq txt (replace-match "" t t txt))))
19449 ;; Create the final string
19450 (if noprefix
19451 (setq rtn txt)
19452 ;; Prepare the variables needed in the eval of the compiled format
19453 (setq time (cond (s2 (concat s1 "-" s2))
19454 (s1 (concat s1 "......"))
19455 (t ""))
19456 extra (or extra "")
19457 category (if (symbolp category) (symbol-name category) category))
19458 ;; Evaluate the compiled format
19459 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
19461 ;; And finally add the text properties
19462 (org-add-props rtn nil
19463 'org-category (downcase category) 'tags tags
19464 'prefix-length (- (length rtn) (length txt))
19465 'time-of-day time-of-day
19466 'txt txt
19467 'time time
19468 'extra extra
19469 'dotime dotime))))
19471 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
19472 (defvar org-agenda-sorting-strategy-selected nil)
19474 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
19475 (catch 'exit
19476 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
19477 ((and todayp (member 'today (car org-agenda-time-grid))))
19478 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
19479 ((member 'weekly (car org-agenda-time-grid)))
19480 (t (throw 'exit list)))
19481 (let* ((have (delq nil (mapcar
19482 (lambda (x) (get-text-property 1 'time-of-day x))
19483 list)))
19484 (string (nth 1 org-agenda-time-grid))
19485 (gridtimes (nth 2 org-agenda-time-grid))
19486 (req (car org-agenda-time-grid))
19487 (remove (member 'remove-match req))
19488 new time)
19489 (if (and (member 'require-timed req) (not have))
19490 ;; don't show empty grid
19491 (throw 'exit list))
19492 (while (setq time (pop gridtimes))
19493 (unless (and remove (member time have))
19494 (setq time (int-to-string time))
19495 (push (org-format-agenda-item
19496 nil string "" nil
19497 (concat (substring time 0 -2) ":" (substring time -2)))
19498 new)
19499 (put-text-property
19500 1 (length (car new)) 'face 'org-time-grid (car new))))
19501 (if (member 'time-up org-agenda-sorting-strategy-selected)
19502 (append new list)
19503 (append list new)))))
19505 (defun org-compile-prefix-format (key)
19506 "Compile the prefix format into a Lisp form that can be evaluated.
19507 The resulting form is returned and stored in the variable
19508 `org-prefix-format-compiled'."
19509 (setq org-prefix-has-time nil org-prefix-has-tag nil)
19510 (let ((s (cond
19511 ((stringp org-agenda-prefix-format)
19512 org-agenda-prefix-format)
19513 ((assq key org-agenda-prefix-format)
19514 (cdr (assq key org-agenda-prefix-format)))
19515 (t " %-12:c%?-12t% s")))
19516 (start 0)
19517 varform vars var e c f opt)
19518 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
19519 s start)
19520 (setq var (cdr (assoc (match-string 4 s)
19521 '(("c" . category) ("t" . time) ("s" . extra)
19522 ("T" . tag))))
19523 c (or (match-string 3 s) "")
19524 opt (match-beginning 1)
19525 start (1+ (match-beginning 0)))
19526 (if (equal var 'time) (setq org-prefix-has-time t))
19527 (if (equal var 'tag) (setq org-prefix-has-tag t))
19528 (setq f (concat "%" (match-string 2 s) "s"))
19529 (if opt
19530 (setq varform
19531 `(if (equal "" ,var)
19533 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
19534 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
19535 (setq s (replace-match "%s" t nil s))
19536 (push varform vars))
19537 (setq vars (nreverse vars))
19538 (setq org-prefix-format-compiled `(format ,s ,@vars))))
19540 (defun org-set-sorting-strategy (key)
19541 (if (symbolp (car org-agenda-sorting-strategy))
19542 ;; the old format
19543 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
19544 (setq org-agenda-sorting-strategy-selected
19545 (or (cdr (assq key org-agenda-sorting-strategy))
19546 (cdr (assq 'agenda org-agenda-sorting-strategy))
19547 '(time-up category-keep priority-down)))))
19549 (defun org-get-time-of-day (s &optional string mod24)
19550 "Check string S for a time of day.
19551 If found, return it as a military time number between 0 and 2400.
19552 If not found, return nil.
19553 The optional STRING argument forces conversion into a 5 character wide string
19554 HH:MM."
19555 (save-match-data
19556 (when
19558 (string-match
19559 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
19560 (string-match
19561 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
19562 (let* ((h (string-to-number (match-string 1 s)))
19563 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
19564 (ampm (if (match-end 4) (downcase (match-string 4 s))))
19565 (am-p (equal ampm "am"))
19566 (h1 (cond ((not ampm) h)
19567 ((= h 12) (if am-p 0 12))
19568 (t (+ h (if am-p 0 12)))))
19569 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
19570 (mod h1 24) h1))
19571 (t0 (+ (* 100 h2) m))
19572 (t1 (concat (if (>= h1 24) "+" " ")
19573 (if (< t0 100) "0" "")
19574 (if (< t0 10) "0" "")
19575 (int-to-string t0))))
19576 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
19578 (defun org-finalize-agenda-entries (list &optional nosort)
19579 "Sort and concatenate the agenda items."
19580 (setq list (mapcar 'org-agenda-highlight-todo list))
19581 (if nosort
19582 list
19583 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
19585 (defun org-agenda-highlight-todo (x)
19586 (let (re pl)
19587 (if (eq x 'line)
19588 (save-excursion
19589 (beginning-of-line 1)
19590 (setq re (get-text-property (point) 'org-todo-regexp))
19591 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
19592 (and (looking-at (concat "[ \t]*\\.*" re))
19593 (add-text-properties (match-beginning 0) (match-end 0)
19594 (list 'face (org-get-todo-face 0)))))
19595 (setq re (concat (get-text-property 0 'org-todo-regexp x))
19596 pl (get-text-property 0 'prefix-length x))
19597 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
19598 (add-text-properties
19599 (or (match-end 1) (match-end 0)) (match-end 0)
19600 (list 'face (org-get-todo-face (match-string 2 x)))
19602 x)))
19604 (defsubst org-cmp-priority (a b)
19605 "Compare the priorities of string A and B."
19606 (let ((pa (or (get-text-property 1 'priority a) 0))
19607 (pb (or (get-text-property 1 'priority b) 0)))
19608 (cond ((> pa pb) +1)
19609 ((< pa pb) -1)
19610 (t nil))))
19612 (defsubst org-cmp-category (a b)
19613 "Compare the string values of categories of strings A and B."
19614 (let ((ca (or (get-text-property 1 'org-category a) ""))
19615 (cb (or (get-text-property 1 'org-category b) "")))
19616 (cond ((string-lessp ca cb) -1)
19617 ((string-lessp cb ca) +1)
19618 (t nil))))
19620 (defsubst org-cmp-tag (a b)
19621 "Compare the string values of categories of strings A and B."
19622 (let ((ta (car (last (get-text-property 1 'tags a))))
19623 (tb (car (last (get-text-property 1 'tags b)))))
19624 (cond ((not ta) +1)
19625 ((not tb) -1)
19626 ((string-lessp ta tb) -1)
19627 ((string-lessp tb ta) +1)
19628 (t nil))))
19630 (defsubst org-cmp-time (a b)
19631 "Compare the time-of-day values of strings A and B."
19632 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
19633 (ta (or (get-text-property 1 'time-of-day a) def))
19634 (tb (or (get-text-property 1 'time-of-day b) def)))
19635 (cond ((< ta tb) -1)
19636 ((< tb ta) +1)
19637 (t nil))))
19639 (defun org-entries-lessp (a b)
19640 "Predicate for sorting agenda entries."
19641 ;; The following variables will be used when the form is evaluated.
19642 ;; So even though the compiler complains, keep them.
19643 (let* ((time-up (org-cmp-time a b))
19644 (time-down (if time-up (- time-up) nil))
19645 (priority-up (org-cmp-priority a b))
19646 (priority-down (if priority-up (- priority-up) nil))
19647 (category-up (org-cmp-category a b))
19648 (category-down (if category-up (- category-up) nil))
19649 (category-keep (if category-up +1 nil))
19650 (tag-up (org-cmp-tag a b))
19651 (tag-down (if tag-up (- tag-up) nil)))
19652 (cdr (assoc
19653 (eval (cons 'or org-agenda-sorting-strategy-selected))
19654 '((-1 . t) (1 . nil) (nil . nil))))))
19656 ;;; Agenda commands
19658 (defun org-agenda-check-type (error &rest types)
19659 "Check if agenda buffer is of allowed type.
19660 If ERROR is non-nil, throw an error, otherwise just return nil."
19661 (if (memq org-agenda-type types)
19663 (if error
19664 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
19665 nil)))
19667 (defun org-agenda-quit ()
19668 "Exit agenda by removing the window or the buffer."
19669 (interactive)
19670 (let ((buf (current-buffer)))
19671 (if (not (one-window-p)) (delete-window))
19672 (kill-buffer buf)
19673 (org-agenda-maybe-reset-markers 'force)
19674 (org-columns-remove-overlays))
19675 ;; Maybe restore the pre-agenda window configuration.
19676 (and org-agenda-restore-windows-after-quit
19677 (not (eq org-agenda-window-setup 'other-frame))
19678 org-pre-agenda-window-conf
19679 (set-window-configuration org-pre-agenda-window-conf)))
19681 (defun org-agenda-exit ()
19682 "Exit agenda by removing the window or the buffer.
19683 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
19684 Org-mode buffers visited directly by the user will not be touched."
19685 (interactive)
19686 (org-release-buffers org-agenda-new-buffers)
19687 (setq org-agenda-new-buffers nil)
19688 (org-agenda-quit))
19690 (defun org-save-all-org-buffers ()
19691 "Save all Org-mode buffers without user confirmation."
19692 (interactive)
19693 (message "Saving all Org-mode buffers...")
19694 (save-some-buffers t 'org-mode-p)
19695 (message "Saving all Org-mode buffers... done"))
19697 (defun org-agenda-redo ()
19698 "Rebuild Agenda.
19699 When this is the global TODO list, a prefix argument will be interpreted."
19700 (interactive)
19701 (let* ((org-agenda-keep-modes t)
19702 (line (org-current-line))
19703 (window-line (- line (org-current-line (window-start))))
19704 (lprops (get 'org-agenda-redo-command 'org-lprops)))
19705 (message "Rebuilding agenda buffer...")
19706 (org-let lprops '(eval org-agenda-redo-command))
19707 (setq org-agenda-undo-list nil
19708 org-agenda-pending-undo-list nil)
19709 (message "Rebuilding agenda buffer...done")
19710 (goto-line line)
19711 (recenter window-line)))
19713 (defun org-agenda-goto-date (date)
19714 "Jump to DATE in agenda."
19715 (interactive (list (org-read-date)))
19716 (org-agenda-list nil date))
19718 (defun org-agenda-goto-today ()
19719 "Go to today."
19720 (interactive)
19721 (org-agenda-check-type t 'timeline 'agenda)
19722 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
19723 (cond
19724 (tdpos (goto-char tdpos))
19725 ((eq org-agenda-type 'agenda)
19726 (let* ((sd (time-to-days (current-time)))
19727 (comp (org-agenda-compute-time-span sd org-agenda-span))
19728 (org-agenda-overriding-arguments org-agenda-last-arguments))
19729 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
19730 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
19731 (org-agenda-redo)
19732 (org-agenda-find-today-or-agenda)))
19733 (t (error "Cannot find today")))))
19735 (defun org-agenda-find-today-or-agenda ()
19736 (goto-char
19737 (or (text-property-any (point-min) (point-max) 'org-today t)
19738 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
19739 (point-min))))
19741 (defun org-agenda-later (arg)
19742 "Go forward in time by thee current span.
19743 With prefix ARG, go forward that many times the current span."
19744 (interactive "p")
19745 (org-agenda-check-type t 'agenda)
19746 (let* ((span org-agenda-span)
19747 (sd org-starting-day)
19748 (greg (calendar-gregorian-from-absolute sd))
19749 greg2 nd)
19750 (cond
19751 ((eq span 'day)
19752 (setq sd (+ arg sd) nd 1))
19753 ((eq span 'week)
19754 (setq sd (+ (* 7 arg) sd) nd 7))
19755 ((eq span 'month)
19756 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
19757 sd (calendar-absolute-from-gregorian greg2))
19758 (setcar greg2 (1+ (car greg2)))
19759 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
19760 ((eq span 'year)
19761 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
19762 sd (calendar-absolute-from-gregorian greg2))
19763 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
19764 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
19765 (let ((org-agenda-overriding-arguments
19766 (list (car org-agenda-last-arguments) sd nd t)))
19767 (org-agenda-redo)
19768 (org-agenda-find-today-or-agenda))))
19770 (defun org-agenda-earlier (arg)
19771 "Go backward in time by the current span.
19772 With prefix ARG, go backward that many times the current span."
19773 (interactive "p")
19774 (org-agenda-later (- arg)))
19776 (defun org-agenda-day-view ()
19777 "Switch to daily view for agenda."
19778 (interactive)
19779 (setq org-agenda-ndays 1)
19780 (org-agenda-change-time-span 'day))
19781 (defun org-agenda-week-view ()
19782 "Switch to daily view for agenda."
19783 (interactive)
19784 (setq org-agenda-ndays 7)
19785 (org-agenda-change-time-span 'week))
19786 (defun org-agenda-month-view ()
19787 "Switch to daily view for agenda."
19788 (interactive)
19789 (org-agenda-change-time-span 'month))
19790 (defun org-agenda-year-view ()
19791 "Switch to daily view for agenda."
19792 (interactive)
19793 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
19794 (org-agenda-change-time-span 'year)
19795 (error "Abort")))
19797 (defun org-agenda-change-time-span (span)
19798 "Change the agenda view to SPAN.
19799 SPAN may be `day', `week', `month', `year'."
19800 (org-agenda-check-type t 'agenda)
19801 (if (equal org-agenda-span span)
19802 (error "Viewing span is already \"%s\"" span))
19803 (let* ((sd (or (get-text-property (point) 'day)
19804 org-starting-day))
19805 (computed (org-agenda-compute-time-span sd span))
19806 (org-agenda-overriding-arguments
19807 (list (car org-agenda-last-arguments)
19808 (car computed) (cdr computed) t)))
19809 (org-agenda-redo)
19810 (org-agenda-find-today-or-agenda))
19811 (org-agenda-set-mode-name)
19812 (message "Switched to %s view" span))
19814 (defun org-agenda-compute-time-span (sd span)
19815 "Compute starting date and number of days for agenda.
19816 SPAN may be `day', `week', `month', `year'. The return value
19817 is a cons cell with the starting date and the number of days,
19818 so that the date SD will be in that range."
19819 (let* ((greg (calendar-gregorian-from-absolute sd))
19821 (cond
19822 ((eq span 'day)
19823 (setq nd 1))
19824 ((eq span 'week)
19825 (let* ((nt (calendar-day-of-week
19826 (calendar-gregorian-from-absolute sd)))
19827 (d (if org-agenda-start-on-weekday
19828 (- nt org-agenda-start-on-weekday)
19829 0)))
19830 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
19831 (setq nd 7)))
19832 ((eq span 'month)
19833 (setq sd (calendar-absolute-from-gregorian
19834 (list (car greg) 1 (nth 2 greg)))
19835 nd (- (calendar-absolute-from-gregorian
19836 (list (1+ (car greg)) 1 (nth 2 greg)))
19837 sd)))
19838 ((eq span 'year)
19839 (setq sd (calendar-absolute-from-gregorian
19840 (list 1 1 (nth 2 greg)))
19841 nd (- (calendar-absolute-from-gregorian
19842 (list 1 1 (1+ (nth 2 greg))))
19843 sd))))
19844 (cons sd nd)))
19846 ;; FIXME: does not work if user makes date format that starts with a blank
19847 (defun org-agenda-next-date-line (&optional arg)
19848 "Jump to the next line indicating a date in agenda buffer."
19849 (interactive "p")
19850 (org-agenda-check-type t 'agenda 'timeline)
19851 (beginning-of-line 1)
19852 (if (looking-at "^\\S-") (forward-char 1))
19853 (if (not (re-search-forward "^\\S-" nil t arg))
19854 (progn
19855 (backward-char 1)
19856 (error "No next date after this line in this buffer")))
19857 (goto-char (match-beginning 0)))
19859 (defun org-agenda-previous-date-line (&optional arg)
19860 "Jump to the previous line indicating a date in agenda buffer."
19861 (interactive "p")
19862 (org-agenda-check-type t 'agenda 'timeline)
19863 (beginning-of-line 1)
19864 (if (not (re-search-backward "^\\S-" nil t arg))
19865 (error "No previous date before this line in this buffer")))
19867 ;; Initialize the highlight
19868 (defvar org-hl (org-make-overlay 1 1))
19869 (org-overlay-put org-hl 'face 'highlight)
19871 (defun org-highlight (begin end &optional buffer)
19872 "Highlight a region with overlay."
19873 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
19874 org-hl begin end (or buffer (current-buffer))))
19876 (defun org-unhighlight ()
19877 "Detach overlay INDEX."
19878 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
19880 ;; FIXME this is currently not used.
19881 (defun org-highlight-until-next-command (beg end &optional buffer)
19882 (org-highlight beg end buffer)
19883 (add-hook 'pre-command-hook 'org-unhighlight-once))
19884 (defun org-unhighlight-once ()
19885 (remove-hook 'pre-command-hook 'org-unhighlight-once)
19886 (org-unhighlight))
19888 (defun org-agenda-follow-mode ()
19889 "Toggle follow mode in an agenda buffer."
19890 (interactive)
19891 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
19892 (org-agenda-set-mode-name)
19893 (message "Follow mode is %s"
19894 (if org-agenda-follow-mode "on" "off")))
19896 (defun org-agenda-log-mode ()
19897 "Toggle log mode in an agenda buffer."
19898 (interactive)
19899 (org-agenda-check-type t 'agenda 'timeline)
19900 (setq org-agenda-show-log (not org-agenda-show-log))
19901 (org-agenda-set-mode-name)
19902 (org-agenda-redo)
19903 (message "Log mode is %s"
19904 (if org-agenda-show-log "on" "off")))
19906 (defun org-agenda-toggle-diary ()
19907 "Toggle diary inclusion in an agenda buffer."
19908 (interactive)
19909 (org-agenda-check-type t 'agenda)
19910 (setq org-agenda-include-diary (not org-agenda-include-diary))
19911 (org-agenda-redo)
19912 (org-agenda-set-mode-name)
19913 (message "Diary inclusion turned %s"
19914 (if org-agenda-include-diary "on" "off")))
19916 (defun org-agenda-toggle-time-grid ()
19917 "Toggle time grid in an agenda buffer."
19918 (interactive)
19919 (org-agenda-check-type t 'agenda)
19920 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
19921 (org-agenda-redo)
19922 (org-agenda-set-mode-name)
19923 (message "Time-grid turned %s"
19924 (if org-agenda-use-time-grid "on" "off")))
19926 (defun org-agenda-set-mode-name ()
19927 "Set the mode name to indicate all the small mode settings."
19928 (setq mode-name
19929 (concat "Org-Agenda"
19930 (if (equal org-agenda-ndays 1) " Day" "")
19931 (if (equal org-agenda-ndays 7) " Week" "")
19932 (if org-agenda-follow-mode " Follow" "")
19933 (if org-agenda-include-diary " Diary" "")
19934 (if org-agenda-use-time-grid " Grid" "")
19935 (if org-agenda-show-log " Log" "")))
19936 (force-mode-line-update))
19938 (defun org-agenda-post-command-hook ()
19939 (and (eolp) (not (bolp)) (backward-char 1))
19940 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
19941 (if (and org-agenda-follow-mode
19942 (get-text-property (point) 'org-marker))
19943 (org-agenda-show)))
19945 (defun org-agenda-show-priority ()
19946 "Show the priority of the current item.
19947 This priority is composed of the main priority given with the [#A] cookies,
19948 and by additional input from the age of a schedules or deadline entry."
19949 (interactive)
19950 (let* ((pri (get-text-property (point-at-bol) 'priority)))
19951 (message "Priority is %d" (if pri pri -1000))))
19953 (defun org-agenda-show-tags ()
19954 "Show the tags applicable to the current item."
19955 (interactive)
19956 (let* ((tags (get-text-property (point-at-bol) 'tags)))
19957 (if tags
19958 (message "Tags are :%s:"
19959 (org-no-properties (mapconcat 'identity tags ":")))
19960 (message "No tags associated with this line"))))
19962 (defun org-agenda-goto (&optional highlight)
19963 "Go to the Org-mode file which contains the item at point."
19964 (interactive)
19965 (let* ((marker (or (get-text-property (point) 'org-marker)
19966 (org-agenda-error)))
19967 (buffer (marker-buffer marker))
19968 (pos (marker-position marker)))
19969 (switch-to-buffer-other-window buffer)
19970 (widen)
19971 (goto-char pos)
19972 (when (org-mode-p)
19973 (org-show-context 'agenda)
19974 (save-excursion
19975 (and (outline-next-heading)
19976 (org-flag-heading nil)))) ; show the next heading
19977 (run-hooks 'org-agenda-after-show-hook)
19978 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
19980 (defvar org-agenda-after-show-hook nil
19981 "Normal hook run after an item has been shown from the agenda.
19982 Point is in the buffer where the item originated.")
19984 (defun org-agenda-kill ()
19985 "Kill the entry or subtree belonging to the current agenda entry."
19986 (interactive)
19987 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19988 (let* ((marker (or (get-text-property (point) 'org-marker)
19989 (org-agenda-error)))
19990 (buffer (marker-buffer marker))
19991 (pos (marker-position marker))
19992 (type (get-text-property (point) 'type))
19993 dbeg dend (n 0) conf)
19994 (org-with-remote-undo buffer
19995 (with-current-buffer buffer
19996 (save-excursion
19997 (goto-char pos)
19998 (if (and (org-mode-p) (not (member type '("sexp"))))
19999 (setq dbeg (progn (org-back-to-heading t) (point))
20000 dend (org-end-of-subtree t t))
20001 (setq dbeg (point-at-bol)
20002 dend (min (point-max) (1+ (point-at-eol)))))
20003 (goto-char dbeg)
20004 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20005 (setq conf (or (eq t org-agenda-confirm-kill)
20006 (and (numberp org-agenda-confirm-kill)
20007 (> n org-agenda-confirm-kill))))
20008 (and conf
20009 (not (y-or-n-p
20010 (format "Delete entry with %d lines in buffer \"%s\"? "
20011 n (buffer-name buffer))))
20012 (error "Abort"))
20013 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20014 (with-current-buffer buffer (delete-region dbeg dend))
20015 (message "Agenda item and source killed"))))
20017 (defun org-agenda-archive ()
20018 "Kill the entry or subtree belonging to the current agenda entry."
20019 (interactive)
20020 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20021 (let* ((marker (or (get-text-property (point) 'org-marker)
20022 (org-agenda-error)))
20023 (buffer (marker-buffer marker))
20024 (pos (marker-position marker)))
20025 (org-with-remote-undo buffer
20026 (with-current-buffer buffer
20027 (if (org-mode-p)
20028 (save-excursion
20029 (goto-char pos)
20030 (org-remove-subtree-entries-from-agenda)
20031 (org-back-to-heading t)
20032 (org-archive-subtree))
20033 (error "Archiving works only in Org-mode files"))))))
20035 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
20036 "Remove all lines in the agenda that correspond to a given subtree.
20037 The subtree is the one in buffer BUF, starting at BEG and ending at END.
20038 If this information is not given, the function uses the tree at point."
20039 (let ((buf (or buf (current-buffer))) m p)
20040 (save-excursion
20041 (unless (and beg end)
20042 (org-back-to-heading t)
20043 (setq beg (point))
20044 (org-end-of-subtree t)
20045 (setq end (point)))
20046 (set-buffer (get-buffer org-agenda-buffer-name))
20047 (save-excursion
20048 (goto-char (point-max))
20049 (beginning-of-line 1)
20050 (while (not (bobp))
20051 (when (and (setq m (get-text-property (point) 'org-marker))
20052 (equal buf (marker-buffer m))
20053 (setq p (marker-position m))
20054 (>= p beg)
20055 (<= p end))
20056 (let ((inhibit-read-only t))
20057 (delete-region (point-at-bol) (1+ (point-at-eol)))))
20058 (beginning-of-line 0))))))
20060 (defun org-agenda-open-link ()
20061 "Follow the link in the current line, if any."
20062 (interactive)
20063 (let ((eol (point-at-eol)))
20064 (save-excursion
20065 (if (or (re-search-forward org-bracket-link-regexp eol t)
20066 (re-search-forward org-angle-link-re eol t)
20067 (re-search-forward org-plain-link-re eol t))
20068 (call-interactively 'org-open-at-point)
20069 (error "No link in current line")))))
20071 (defun org-agenda-switch-to (&optional delete-other-windows)
20072 "Go to the Org-mode file which contains the item at point."
20073 (interactive)
20074 (let* ((marker (or (get-text-property (point) 'org-marker)
20075 (org-agenda-error)))
20076 (buffer (marker-buffer marker))
20077 (pos (marker-position marker)))
20078 (switch-to-buffer buffer)
20079 (and delete-other-windows (delete-other-windows))
20080 (widen)
20081 (goto-char pos)
20082 (when (org-mode-p)
20083 (org-show-context 'agenda)
20084 (save-excursion
20085 (and (outline-next-heading)
20086 (org-flag-heading nil)))))) ; show the next heading
20088 (defun org-agenda-goto-mouse (ev)
20089 "Go to the Org-mode file which contains the item at the mouse click."
20090 (interactive "e")
20091 (mouse-set-point ev)
20092 (org-agenda-goto))
20094 (defun org-agenda-show ()
20095 "Display the Org-mode file which contains the item at point."
20096 (interactive)
20097 (let ((win (selected-window)))
20098 (org-agenda-goto t)
20099 (select-window win)))
20101 (defun org-agenda-recenter (arg)
20102 "Display the Org-mode file which contains the item at point and recenter."
20103 (interactive "P")
20104 (let ((win (selected-window)))
20105 (org-agenda-goto t)
20106 (recenter arg)
20107 (select-window win)))
20109 (defun org-agenda-show-mouse (ev)
20110 "Display the Org-mode file which contains the item at the mouse click."
20111 (interactive "e")
20112 (mouse-set-point ev)
20113 (org-agenda-show))
20115 (defun org-agenda-check-no-diary ()
20116 "Check if the entry is a diary link and abort if yes."
20117 (if (get-text-property (point) 'org-agenda-diary-link)
20118 (org-agenda-error)))
20120 (defun org-agenda-error ()
20121 (error "Command not allowed in this line"))
20123 (defun org-agenda-tree-to-indirect-buffer ()
20124 "Show the subtree corresponding to the current entry in an indirect buffer.
20125 This calls the command `org-tree-to-indirect-buffer' from the original
20126 Org-mode buffer.
20127 With numerical prefix arg ARG, go up to this level and then take that tree.
20128 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
20129 dedicated frame)."
20130 (interactive)
20131 (org-agenda-check-no-diary)
20132 (let* ((marker (or (get-text-property (point) 'org-marker)
20133 (org-agenda-error)))
20134 (buffer (marker-buffer marker))
20135 (pos (marker-position marker)))
20136 (with-current-buffer buffer
20137 (save-excursion
20138 (goto-char pos)
20139 (call-interactively 'org-tree-to-indirect-buffer)))))
20141 (defvar org-last-heading-marker (make-marker)
20142 "Marker pointing to the headline that last changed its TODO state
20143 by a remote command from the agenda.")
20145 (defun org-agenda-todo-nextset ()
20146 "Switch TODO entry to next sequence."
20147 (interactive)
20148 (org-agenda-todo 'nextset))
20150 (defun org-agenda-todo-previousset ()
20151 "Switch TODO entry to previous sequence."
20152 (interactive)
20153 (org-agenda-todo 'previousset))
20155 (defun org-agenda-todo (&optional arg)
20156 "Cycle TODO state of line at point, also in Org-mode file.
20157 This changes the line at point, all other lines in the agenda referring to
20158 the same tree node, and the headline of the tree node in the Org-mode file."
20159 (interactive "P")
20160 (org-agenda-check-no-diary)
20161 (let* ((col (current-column))
20162 (marker (or (get-text-property (point) 'org-marker)
20163 (org-agenda-error)))
20164 (buffer (marker-buffer marker))
20165 (pos (marker-position marker))
20166 (hdmarker (get-text-property (point) 'org-hd-marker))
20167 (inhibit-read-only t)
20168 newhead)
20169 (org-with-remote-undo buffer
20170 (with-current-buffer buffer
20171 (widen)
20172 (goto-char pos)
20173 (org-show-context 'agenda)
20174 (save-excursion
20175 (and (outline-next-heading)
20176 (org-flag-heading nil))) ; show the next heading
20177 (org-todo arg)
20178 (and (bolp) (forward-char 1))
20179 (setq newhead (org-get-heading))
20180 (save-excursion
20181 (org-back-to-heading)
20182 (move-marker org-last-heading-marker (point))))
20183 (beginning-of-line 1)
20184 (save-excursion
20185 (org-agenda-change-all-lines newhead hdmarker 'fixface))
20186 (move-to-column col))))
20188 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
20189 "Change all lines in the agenda buffer which match HDMARKER.
20190 The new content of the line will be NEWHEAD (as modified by
20191 `org-format-agenda-item'). HDMARKER is checked with
20192 `equal' against all `org-hd-marker' text properties in the file.
20193 If FIXFACE is non-nil, the face of each item is modified acording to
20194 the new TODO state."
20195 (let* ((inhibit-read-only t)
20196 props m pl undone-face done-face finish new dotime cat tags)
20197 (save-excursion
20198 (goto-char (point-max))
20199 (beginning-of-line 1)
20200 (while (not finish)
20201 (setq finish (bobp))
20202 (when (and (setq m (get-text-property (point) 'org-hd-marker))
20203 (equal m hdmarker))
20204 (setq props (text-properties-at (point))
20205 dotime (get-text-property (point) 'dotime)
20206 cat (get-text-property (point) 'org-category)
20207 tags (get-text-property (point) 'tags)
20208 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
20209 pl (get-text-property (point) 'prefix-length)
20210 undone-face (get-text-property (point) 'undone-face)
20211 done-face (get-text-property (point) 'done-face))
20212 (move-to-column pl)
20213 (cond
20214 ((equal new "")
20215 (beginning-of-line 1)
20216 (and (looking-at ".*\n?") (replace-match "")))
20217 ((looking-at ".*")
20218 (replace-match new t t)
20219 (beginning-of-line 1)
20220 (add-text-properties (point-at-bol) (point-at-eol) props)
20221 (when fixface
20222 (add-text-properties
20223 (point-at-bol) (point-at-eol)
20224 (list 'face
20225 (if org-last-todo-state-is-todo
20226 undone-face done-face))))
20227 (org-agenda-highlight-todo 'line)
20228 (beginning-of-line 1))
20229 (t (error "Line update did not work"))))
20230 (beginning-of-line 0)))
20231 (org-finalize-agenda)))
20233 (defun org-agenda-align-tags (&optional line)
20234 "Align all tags in agenda items to `org-agenda-tags-column'."
20235 (let ((inhibit-read-only t) l c)
20236 (save-excursion
20237 (goto-char (if line (point-at-bol) (point-min)))
20238 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20239 (if line (point-at-eol) nil) t)
20240 (add-text-properties
20241 (match-beginning 2) (match-end 2)
20242 (list 'face (list 'org-tag (get-text-property
20243 (match-beginning 2) 'face))))
20244 (setq l (- (match-end 2) (match-beginning 2))
20245 c (if (< org-agenda-tags-column 0)
20246 (- (abs org-agenda-tags-column) l)
20247 org-agenda-tags-column))
20248 (delete-region (match-beginning 1) (match-end 1))
20249 (goto-char (match-beginning 1))
20250 (insert (org-add-props
20251 (make-string (max 1 (- c (current-column))) ?\ )
20252 (text-properties-at (point))))))))
20254 (defun org-agenda-priority-up ()
20255 "Increase the priority of line at point, also in Org-mode file."
20256 (interactive)
20257 (org-agenda-priority 'up))
20259 (defun org-agenda-priority-down ()
20260 "Decrease the priority of line at point, also in Org-mode file."
20261 (interactive)
20262 (org-agenda-priority 'down))
20264 (defun org-agenda-priority (&optional force-direction)
20265 "Set the priority of line at point, also in Org-mode file.
20266 This changes the line at point, all other lines in the agenda referring to
20267 the same tree node, and the headline of the tree node in the Org-mode file."
20268 (interactive)
20269 (org-agenda-check-no-diary)
20270 (let* ((marker (or (get-text-property (point) 'org-marker)
20271 (org-agenda-error)))
20272 (hdmarker (get-text-property (point) 'org-hd-marker))
20273 (buffer (marker-buffer hdmarker))
20274 (pos (marker-position hdmarker))
20275 (inhibit-read-only t)
20276 newhead)
20277 (org-with-remote-undo buffer
20278 (with-current-buffer buffer
20279 (widen)
20280 (goto-char pos)
20281 (org-show-context 'agenda)
20282 (save-excursion
20283 (and (outline-next-heading)
20284 (org-flag-heading nil))) ; show the next heading
20285 (funcall 'org-priority force-direction)
20286 (end-of-line 1)
20287 (setq newhead (org-get-heading)))
20288 (org-agenda-change-all-lines newhead hdmarker)
20289 (beginning-of-line 1))))
20291 (defun org-get-tags-at (&optional pos)
20292 "Get a list of all headline tags applicable at POS.
20293 POS defaults to point. If tags are inherited, the list contains
20294 the targets in the same sequence as the headlines appear, i.e.
20295 the tags of the current headline come last."
20296 (interactive)
20297 (let (tags lastpos)
20298 (save-excursion
20299 (save-restriction
20300 (widen)
20301 (goto-char (or pos (point)))
20302 (save-match-data
20303 (org-back-to-heading t)
20304 (condition-case nil
20305 (while (not (equal lastpos (point)))
20306 (setq lastpos (point))
20307 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
20308 (setq tags (append (org-split-string
20309 (org-match-string-no-properties 1) ":")
20310 tags)))
20311 (or org-use-tag-inheritance (error ""))
20312 (org-up-heading-all 1))
20313 (error nil))))
20314 tags)))
20316 ;; FIXME: should fix the tags property of the agenda line.
20317 (defun org-agenda-set-tags ()
20318 "Set tags for the current headline."
20319 (interactive)
20320 (org-agenda-check-no-diary)
20321 (if (and (org-region-active-p) (interactive-p))
20322 (call-interactively 'org-change-tag-in-region)
20323 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20324 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20325 (org-agenda-error)))
20326 (buffer (marker-buffer hdmarker))
20327 (pos (marker-position hdmarker))
20328 (inhibit-read-only t)
20329 newhead)
20330 (org-with-remote-undo buffer
20331 (with-current-buffer buffer
20332 (widen)
20333 (goto-char pos)
20334 (save-excursion
20335 (org-show-context 'agenda))
20336 (save-excursion
20337 (and (outline-next-heading)
20338 (org-flag-heading nil))) ; show the next heading
20339 (goto-char pos)
20340 (call-interactively 'org-set-tags)
20341 (end-of-line 1)
20342 (setq newhead (org-get-heading)))
20343 (org-agenda-change-all-lines newhead hdmarker)
20344 (beginning-of-line 1)))))
20346 (defun org-agenda-toggle-archive-tag ()
20347 "Toggle the archive tag for the current entry."
20348 (interactive)
20349 (org-agenda-check-no-diary)
20350 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
20351 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
20352 (org-agenda-error)))
20353 (buffer (marker-buffer hdmarker))
20354 (pos (marker-position hdmarker))
20355 (inhibit-read-only t)
20356 newhead)
20357 (org-with-remote-undo buffer
20358 (with-current-buffer buffer
20359 (widen)
20360 (goto-char pos)
20361 (org-show-context 'agenda)
20362 (save-excursion
20363 (and (outline-next-heading)
20364 (org-flag-heading nil))) ; show the next heading
20365 (call-interactively 'org-toggle-archive-tag)
20366 (end-of-line 1)
20367 (setq newhead (org-get-heading)))
20368 (org-agenda-change-all-lines newhead hdmarker)
20369 (beginning-of-line 1))))
20371 (defun org-agenda-date-later (arg &optional what)
20372 "Change the date of this item to one day later."
20373 (interactive "p")
20374 (org-agenda-check-type t 'agenda 'timeline)
20375 (org-agenda-check-no-diary)
20376 (let* ((marker (or (get-text-property (point) 'org-marker)
20377 (org-agenda-error)))
20378 (buffer (marker-buffer marker))
20379 (pos (marker-position marker)))
20380 (org-with-remote-undo buffer
20381 (with-current-buffer buffer
20382 (widen)
20383 (goto-char pos)
20384 (if (not (org-at-timestamp-p))
20385 (error "Cannot find time stamp"))
20386 (org-timestamp-change arg (or what 'day)))
20387 (org-agenda-show-new-time marker org-last-changed-timestamp))
20388 (message "Time stamp changed to %s" org-last-changed-timestamp)))
20390 (defun org-agenda-date-earlier (arg &optional what)
20391 "Change the date of this item to one day earlier."
20392 (interactive "p")
20393 (org-agenda-date-later (- arg) what))
20395 (defun org-agenda-show-new-time (marker stamp &optional prefix)
20396 "Show new date stamp via text properties."
20397 ;; We use text properties to make this undoable
20398 (let ((inhibit-read-only t))
20399 (setq stamp (concat " " prefix " => " stamp))
20400 (save-excursion
20401 (goto-char (point-max))
20402 (while (not (bobp))
20403 (when (equal marker (get-text-property (point) 'org-marker))
20404 (move-to-column (- (window-width) (length stamp)) t)
20405 (if (featurep 'xemacs)
20406 ;; Use `duplicable' property to trigger undo recording
20407 (let ((ex (make-extent nil nil))
20408 (gl (make-glyph stamp)))
20409 (set-glyph-face gl 'secondary-selection)
20410 (set-extent-properties
20411 ex (list 'invisible t 'end-glyph gl 'duplicable t))
20412 (insert-extent ex (1- (point)) (point-at-eol)))
20413 (add-text-properties
20414 (1- (point)) (point-at-eol)
20415 (list 'display (org-add-props stamp nil
20416 'face 'secondary-selection))))
20417 (beginning-of-line 1))
20418 (beginning-of-line 0)))))
20420 (defun org-agenda-date-prompt (arg)
20421 "Change the date of this item. Date is prompted for, with default today.
20422 The prefix ARG is passed to the `org-time-stamp' command and can therefore
20423 be used to request time specification in the time stamp."
20424 (interactive "P")
20425 (org-agenda-check-type t 'agenda 'timeline)
20426 (org-agenda-check-no-diary)
20427 (let* ((marker (or (get-text-property (point) 'org-marker)
20428 (org-agenda-error)))
20429 (buffer (marker-buffer marker))
20430 (pos (marker-position marker)))
20431 (org-with-remote-undo buffer
20432 (with-current-buffer buffer
20433 (widen)
20434 (goto-char pos)
20435 (if (not (org-at-timestamp-p))
20436 (error "Cannot find time stamp"))
20437 (org-time-stamp arg)
20438 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
20440 (defun org-agenda-schedule (arg)
20441 "Schedule the item at point."
20442 (interactive "P")
20443 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20444 (org-agenda-check-no-diary)
20445 (let* ((marker (or (get-text-property (point) 'org-marker)
20446 (org-agenda-error)))
20447 (buffer (marker-buffer marker))
20448 (pos (marker-position marker))
20449 (org-insert-labeled-timestamps-at-point nil)
20451 (org-with-remote-undo buffer
20452 (with-current-buffer buffer
20453 (widen)
20454 (goto-char pos)
20455 (setq ts (org-schedule arg)))
20456 (org-agenda-show-new-time marker ts "S"))
20457 (message "Item scheduled for %s" ts)))
20459 (defun org-agenda-deadline (arg)
20460 "Schedule the item at point."
20461 (interactive "P")
20462 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
20463 (org-agenda-check-no-diary)
20464 (let* ((marker (or (get-text-property (point) 'org-marker)
20465 (org-agenda-error)))
20466 (buffer (marker-buffer marker))
20467 (pos (marker-position marker))
20468 (org-insert-labeled-timestamps-at-point nil)
20470 (org-with-remote-undo buffer
20471 (with-current-buffer buffer
20472 (widen)
20473 (goto-char pos)
20474 (setq ts (org-deadline arg)))
20475 (org-agenda-show-new-time marker ts "S"))
20476 (message "Deadline for this item set to %s" ts)))
20478 (defun org-get-heading (&optional no-tags)
20479 "Return the heading of the current entry, without the stars."
20480 (save-excursion
20481 (org-back-to-heading t)
20482 (if (looking-at
20483 (if no-tags
20484 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
20485 "\\*+[ \t]+\\([^\r\n]*\\)"))
20486 (match-string 1) "")))
20488 (defun org-agenda-clock-in (&optional arg)
20489 "Start the clock on the currently selected item."
20490 (interactive "P")
20491 (org-agenda-check-no-diary)
20492 (let* ((marker (or (get-text-property (point) 'org-marker)
20493 (org-agenda-error)))
20494 (pos (marker-position marker)))
20495 (org-with-remote-undo (marker-buffer marker)
20496 (with-current-buffer (marker-buffer marker)
20497 (widen)
20498 (goto-char pos)
20499 (org-clock-in)))))
20501 (defun org-agenda-clock-out (&optional arg)
20502 "Stop the currently running clock."
20503 (interactive "P")
20504 (unless (marker-buffer org-clock-marker)
20505 (error "No running clock"))
20506 (org-with-remote-undo (marker-buffer org-clock-marker)
20507 (org-clock-out)))
20509 (defun org-agenda-clock-cancel (&optional arg)
20510 "Cancel the currently running clock."
20511 (interactive "P")
20512 (unless (marker-buffer org-clock-marker)
20513 (error "No running clock"))
20514 (org-with-remote-undo (marker-buffer org-clock-marker)
20515 (org-clock-cancel)))
20517 (defun org-agenda-diary-entry ()
20518 "Make a diary entry, like the `i' command from the calendar.
20519 All the standard commands work: block, weekly etc."
20520 (interactive)
20521 (org-agenda-check-type t 'agenda 'timeline)
20522 (require 'diary-lib)
20523 (let* ((char (progn
20524 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
20525 (read-char-exclusive)))
20526 (cmd (cdr (assoc char
20527 '((?d . insert-diary-entry)
20528 (?w . insert-weekly-diary-entry)
20529 (?m . insert-monthly-diary-entry)
20530 (?y . insert-yearly-diary-entry)
20531 (?a . insert-anniversary-diary-entry)
20532 (?b . insert-block-diary-entry)
20533 (?c . insert-cyclic-diary-entry)))))
20534 (oldf (symbol-function 'calendar-cursor-to-date))
20535 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
20536 (point (point))
20537 (mark (or (mark t) (point))))
20538 (unless cmd
20539 (error "No command associated with <%c>" char))
20540 (unless (and (get-text-property point 'day)
20541 (or (not (equal ?b char))
20542 (get-text-property mark 'day)))
20543 (error "Don't know which date to use for diary entry"))
20544 ;; We implement this by hacking the `calendar-cursor-to-date' function
20545 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
20546 (let ((calendar-mark-ring
20547 (list (calendar-gregorian-from-absolute
20548 (or (get-text-property mark 'day)
20549 (get-text-property point 'day))))))
20550 (unwind-protect
20551 (progn
20552 (fset 'calendar-cursor-to-date
20553 (lambda (&optional error)
20554 (calendar-gregorian-from-absolute
20555 (get-text-property point 'day))))
20556 (call-interactively cmd))
20557 (fset 'calendar-cursor-to-date oldf)))))
20560 (defun org-agenda-execute-calendar-command (cmd)
20561 "Execute a calendar command from the agenda, with the date associated to
20562 the cursor position."
20563 (org-agenda-check-type t 'agenda 'timeline)
20564 (require 'diary-lib)
20565 (unless (get-text-property (point) 'day)
20566 (error "Don't know which date to use for calendar command"))
20567 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
20568 (point (point))
20569 (date (calendar-gregorian-from-absolute
20570 (get-text-property point 'day)))
20571 ;; the following 3 vars are needed in the calendar
20572 (displayed-day (extract-calendar-day date))
20573 (displayed-month (extract-calendar-month date))
20574 (displayed-year (extract-calendar-year date)))
20575 (unwind-protect
20576 (progn
20577 (fset 'calendar-cursor-to-date
20578 (lambda (&optional error)
20579 (calendar-gregorian-from-absolute
20580 (get-text-property point 'day))))
20581 (call-interactively cmd))
20582 (fset 'calendar-cursor-to-date oldf))))
20584 (defun org-agenda-phases-of-moon ()
20585 "Display the phases of the moon for the 3 months around the cursor date."
20586 (interactive)
20587 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
20589 (defun org-agenda-holidays ()
20590 "Display the holidays for the 3 months around the cursor date."
20591 (interactive)
20592 (org-agenda-execute-calendar-command 'list-calendar-holidays))
20594 (defun org-agenda-sunrise-sunset (arg)
20595 "Display sunrise and sunset for the cursor date.
20596 Latitude and longitude can be specified with the variables
20597 `calendar-latitude' and `calendar-longitude'. When called with prefix
20598 argument, latitude and longitude will be prompted for."
20599 (interactive "P")
20600 (let ((calendar-longitude (if arg nil calendar-longitude))
20601 (calendar-latitude (if arg nil calendar-latitude))
20602 (calendar-location-name
20603 (if arg "the given coordinates" calendar-location-name)))
20604 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
20606 (defun org-agenda-goto-calendar ()
20607 "Open the Emacs calendar with the date at the cursor."
20608 (interactive)
20609 (org-agenda-check-type t 'agenda 'timeline)
20610 (let* ((day (or (get-text-property (point) 'day)
20611 (error "Don't know which date to open in calendar")))
20612 (date (calendar-gregorian-from-absolute day))
20613 (calendar-move-hook nil)
20614 (view-calendar-holidays-initially nil)
20615 (view-diary-entries-initially nil))
20616 (calendar)
20617 (calendar-goto-date date)))
20619 (defun org-calendar-goto-agenda ()
20620 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
20621 This is a command that has to be installed in `calendar-mode-map'."
20622 (interactive)
20623 (org-agenda-list nil (calendar-absolute-from-gregorian
20624 (calendar-cursor-to-date))
20625 nil))
20627 (defun org-agenda-convert-date ()
20628 (interactive)
20629 (org-agenda-check-type t 'agenda 'timeline)
20630 (let ((day (get-text-property (point) 'day))
20631 date s)
20632 (unless day
20633 (error "Don't know which date to convert"))
20634 (setq date (calendar-gregorian-from-absolute day))
20635 (setq s (concat
20636 "Gregorian: " (calendar-date-string date) "\n"
20637 "ISO: " (calendar-iso-date-string date) "\n"
20638 "Day of Yr: " (calendar-day-of-year-string date) "\n"
20639 "Julian: " (calendar-julian-date-string date) "\n"
20640 "Astron. JD: " (calendar-astro-date-string date)
20641 " (Julian date number at noon UTC)\n"
20642 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
20643 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
20644 "French: " (calendar-french-date-string date) "\n"
20645 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
20646 "Mayan: " (calendar-mayan-date-string date) "\n"
20647 "Coptic: " (calendar-coptic-date-string date) "\n"
20648 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
20649 "Persian: " (calendar-persian-date-string date) "\n"
20650 "Chinese: " (calendar-chinese-date-string date) "\n"))
20651 (with-output-to-temp-buffer "*Dates*"
20652 (princ s))
20653 (if (fboundp 'fit-window-to-buffer)
20654 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
20657 ;;;; Embedded LaTeX
20659 (defvar org-cdlatex-mode-map (make-sparse-keymap)
20660 "Keymap for the minor `org-cdlatex-mode'.")
20662 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
20663 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
20664 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
20665 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
20666 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
20668 (defvar org-cdlatex-texmathp-advice-is-done nil
20669 "Flag remembering if we have applied the advice to texmathp already.")
20671 (define-minor-mode org-cdlatex-mode
20672 "Toggle the minor `org-cdlatex-mode'.
20673 This mode supports entering LaTeX environment and math in LaTeX fragments
20674 in Org-mode.
20675 \\{org-cdlatex-mode-map}"
20676 nil " OCDL" nil
20677 (when org-cdlatex-mode (require 'cdlatex))
20678 (unless org-cdlatex-texmathp-advice-is-done
20679 (setq org-cdlatex-texmathp-advice-is-done t)
20680 (defadvice texmathp (around org-math-always-on activate)
20681 "Always return t in org-mode buffers.
20682 This is because we want to insert math symbols without dollars even outside
20683 the LaTeX math segments. If Orgmode thinks that point is actually inside
20684 en embedded LaTeX fragement, let texmathp do its job.
20685 \\[org-cdlatex-mode-map]"
20686 (interactive)
20687 (let (p)
20688 (cond
20689 ((not (org-mode-p)) ad-do-it)
20690 ((eq this-command 'cdlatex-math-symbol)
20691 (setq ad-return-value t
20692 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
20694 (let ((p (org-inside-LaTeX-fragment-p)))
20695 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
20696 (setq ad-return-value t
20697 texmathp-why '("Org-mode embedded math" . 0))
20698 (if p ad-do-it)))))))))
20700 (defun turn-on-org-cdlatex ()
20701 "Unconditionally turn on `org-cdlatex-mode'."
20702 (org-cdlatex-mode 1))
20704 (defun org-inside-LaTeX-fragment-p ()
20705 "Test if point is inside a LaTeX fragment.
20706 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
20707 sequence appearing also before point.
20708 Even though the matchers for math are configurable, this function assumes
20709 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
20710 delimiters are skipped when they have been removed by customization.
20711 The return value is nil, or a cons cell with the delimiter and
20712 and the position of this delimiter.
20714 This function does a reasonably good job, but can locally be fooled by
20715 for example currency specifications. For example it will assume being in
20716 inline math after \"$22.34\". The LaTeX fragment formatter will only format
20717 fragments that are properly closed, but during editing, we have to live
20718 with the uncertainty caused by missing closing delimiters. This function
20719 looks only before point, not after."
20720 (catch 'exit
20721 (let ((pos (point))
20722 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
20723 (lim (progn
20724 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
20725 (point)))
20726 dd-on str (start 0) m re)
20727 (goto-char pos)
20728 (when dodollar
20729 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
20730 re (nth 1 (assoc "$" org-latex-regexps)))
20731 (while (string-match re str start)
20732 (cond
20733 ((= (match-end 0) (length str))
20734 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
20735 ((= (match-end 0) (- (length str) 5))
20736 (throw 'exit nil))
20737 (t (setq start (match-end 0))))))
20738 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
20739 (goto-char pos)
20740 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
20741 (and (match-beginning 2) (throw 'exit nil))
20742 ;; count $$
20743 (while (re-search-backward "\\$\\$" lim t)
20744 (setq dd-on (not dd-on)))
20745 (goto-char pos)
20746 (if dd-on (cons "$$" m))))))
20749 (defun org-try-cdlatex-tab ()
20750 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
20751 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
20752 - inside a LaTeX fragment, or
20753 - after the first word in a line, where an abbreviation expansion could
20754 insert a LaTeX environment."
20755 (when org-cdlatex-mode
20756 (cond
20757 ((save-excursion
20758 (skip-chars-backward "a-zA-Z0-9*")
20759 (skip-chars-backward " \t")
20760 (bolp))
20761 (cdlatex-tab) t)
20762 ((org-inside-LaTeX-fragment-p)
20763 (cdlatex-tab) t)
20764 (t nil))))
20766 (defun org-cdlatex-underscore-caret (&optional arg)
20767 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
20768 Revert to the normal definition outside of these fragments."
20769 (interactive "P")
20770 (if (org-inside-LaTeX-fragment-p)
20771 (call-interactively 'cdlatex-sub-superscript)
20772 (let (org-cdlatex-mode)
20773 (call-interactively (key-binding (vector last-input-event))))))
20775 (defun org-cdlatex-math-modify (&optional arg)
20776 "Execute `cdlatex-math-modify' in LaTeX fragments.
20777 Revert to the normal definition outside of these fragments."
20778 (interactive "P")
20779 (if (org-inside-LaTeX-fragment-p)
20780 (call-interactively 'cdlatex-math-modify)
20781 (let (org-cdlatex-mode)
20782 (call-interactively (key-binding (vector last-input-event))))))
20784 (defvar org-latex-fragment-image-overlays nil
20785 "List of overlays carrying the images of latex fragments.")
20786 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
20788 (defun org-remove-latex-fragment-image-overlays ()
20789 "Remove all overlays with LaTeX fragment images in current buffer."
20790 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
20791 (setq org-latex-fragment-image-overlays nil))
20793 (defun org-preview-latex-fragment (&optional subtree)
20794 "Preview the LaTeX fragment at point, or all locally or globally.
20795 If the cursor is in a LaTeX fragment, create the image and overlay
20796 it over the source code. If there is no fragment at point, display
20797 all fragments in the current text, from one headline to the next. With
20798 prefix SUBTREE, display all fragments in the current subtree. With a
20799 double prefix `C-u C-u', or when the cursor is before the first headline,
20800 display all fragments in the buffer.
20801 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
20802 (interactive "P")
20803 (org-remove-latex-fragment-image-overlays)
20804 (save-excursion
20805 (save-restriction
20806 (let (beg end at msg)
20807 (cond
20808 ((or (equal subtree '(16))
20809 (not (save-excursion
20810 (re-search-backward (concat "^" outline-regexp) nil t))))
20811 (setq beg (point-min) end (point-max)
20812 msg "Creating images for buffer...%s"))
20813 ((equal subtree '(4))
20814 (org-back-to-heading)
20815 (setq beg (point) end (org-end-of-subtree t)
20816 msg "Creating images for subtree...%s"))
20818 (if (setq at (org-inside-LaTeX-fragment-p))
20819 (goto-char (max (point-min) (- (cdr at) 2)))
20820 (org-back-to-heading))
20821 (setq beg (point) end (progn (outline-next-heading) (point))
20822 msg (if at "Creating image...%s"
20823 "Creating images for entry...%s"))))
20824 (message msg "")
20825 (narrow-to-region beg end)
20826 (goto-char beg)
20827 (org-format-latex
20828 (concat "ltxpng/" (file-name-sans-extension
20829 (file-name-nondirectory
20830 buffer-file-name)))
20831 default-directory 'overlays msg at 'forbuffer)
20832 (message msg "done. Use `C-c C-c' to remove images.")))))
20834 (defvar org-latex-regexps
20835 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
20836 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
20837 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
20838 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
20839 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
20840 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
20841 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
20842 "Regular expressions for matching embedded LaTeX.")
20844 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
20845 "Replace LaTeX fragments with links to an image, and produce images."
20846 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
20847 (let* ((prefixnodir (file-name-nondirectory prefix))
20848 (absprefix (expand-file-name prefix dir))
20849 (todir (file-name-directory absprefix))
20850 (opt org-format-latex-options)
20851 (matchers (plist-get opt :matchers))
20852 (re-list org-latex-regexps)
20853 (cnt 0) txt link beg end re e checkdir
20854 m n block linkfile movefile ov)
20855 ;; Check if there are old images files with this prefix, and remove them
20856 (when (file-directory-p todir)
20857 (mapc 'delete-file
20858 (directory-files
20859 todir 'full
20860 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
20861 ;; Check the different regular expressions
20862 (while (setq e (pop re-list))
20863 (setq m (car e) re (nth 1 e) n (nth 2 e)
20864 block (if (nth 3 e) "\n\n" ""))
20865 (when (member m matchers)
20866 (goto-char (point-min))
20867 (while (re-search-forward re nil t)
20868 (when (or (not at) (equal (cdr at) (match-beginning n)))
20869 (setq txt (match-string n)
20870 beg (match-beginning n) end (match-end n)
20871 cnt (1+ cnt)
20872 linkfile (format "%s_%04d.png" prefix cnt)
20873 movefile (format "%s_%04d.png" absprefix cnt)
20874 link (concat block "[[file:" linkfile "]]" block))
20875 (if msg (message msg cnt))
20876 (goto-char beg)
20877 (unless checkdir ; make sure the directory exists
20878 (setq checkdir t)
20879 (or (file-directory-p todir) (make-directory todir)))
20880 (org-create-formula-image
20881 txt movefile opt forbuffer)
20882 (if overlays
20883 (progn
20884 (setq ov (org-make-overlay beg end))
20885 (if (featurep 'xemacs)
20886 (progn
20887 (org-overlay-put ov 'invisible t)
20888 (org-overlay-put
20889 ov 'end-glyph
20890 (make-glyph (vector 'png :file movefile))))
20891 (org-overlay-put
20892 ov 'display
20893 (list 'image :type 'png :file movefile :ascent 'center)))
20894 (push ov org-latex-fragment-image-overlays)
20895 (goto-char end))
20896 (delete-region beg end)
20897 (insert link))))))))
20899 ;; This function borrows from Ganesh Swami's latex2png.el
20900 (defun org-create-formula-image (string tofile options buffer)
20901 (let* ((tmpdir (if (featurep 'xemacs)
20902 (temp-directory)
20903 temporary-file-directory))
20904 (texfilebase (make-temp-name
20905 (expand-file-name "orgtex" tmpdir)))
20906 (texfile (concat texfilebase ".tex"))
20907 (dvifile (concat texfilebase ".dvi"))
20908 (pngfile (concat texfilebase ".png"))
20909 (fnh (face-attribute 'default :height nil))
20910 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
20911 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
20912 (fg (or (plist-get options (if buffer :foreground :html-foreground))
20913 "Black"))
20914 (bg (or (plist-get options (if buffer :background :html-background))
20915 "Transparent")))
20916 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
20917 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
20918 (with-temp-file texfile
20919 (insert org-format-latex-header
20920 "\n\\begin{document}\n" string "\n\\end{document}\n"))
20921 (let ((dir default-directory))
20922 (condition-case nil
20923 (progn
20924 (cd tmpdir)
20925 (call-process "latex" nil nil nil texfile))
20926 (error nil))
20927 (cd dir))
20928 (if (not (file-exists-p dvifile))
20929 (progn (message "Failed to create dvi file from %s" texfile) nil)
20930 (call-process "dvipng" nil nil nil
20931 "-E" "-fg" fg "-bg" bg
20932 "-D" dpi
20933 ;;"-x" scale "-y" scale
20934 "-T" "tight"
20935 "-o" pngfile
20936 dvifile)
20937 (if (not (file-exists-p pngfile))
20938 (progn (message "Failed to create png file from %s" texfile) nil)
20939 ;; Use the requested file name and clean up
20940 (copy-file pngfile tofile 'replace)
20941 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
20942 (delete-file (concat texfilebase e)))
20943 pngfile))))
20945 (defun org-dvipng-color (attr)
20946 "Return an rgb color specification for dvipng."
20947 (apply 'format "rgb %s %s %s"
20948 (mapcar 'org-normalize-color
20949 (color-values (face-attribute 'default attr nil)))))
20951 (defun org-normalize-color (value)
20952 "Return string to be used as color value for an RGB component."
20953 (format "%g" (/ value 65535.0)))
20955 ;;;; Exporting
20957 ;;; Variables, constants, and parameter plists
20959 (defconst org-level-max 20)
20961 (defvar org-export-html-preamble nil
20962 "Preamble, to be inserted just after <body>. Set by publishing functions.")
20963 (defvar org-export-html-postamble nil
20964 "Preamble, to be inserted just before </body>. Set by publishing functions.")
20965 (defvar org-export-html-auto-preamble t
20966 "Should default preamble be inserted? Set by publishing functions.")
20967 (defvar org-export-html-auto-postamble t
20968 "Should default postamble be inserted? Set by publishing functions.")
20969 (defvar org-current-export-file nil) ; dynamically scoped parameter
20970 (defvar org-current-export-dir nil) ; dynamically scoped parameter
20973 (defconst org-export-plist-vars
20974 '((:language . org-export-default-language)
20975 (:customtime . org-display-custom-times)
20976 (:headline-levels . org-export-headline-levels)
20977 (:section-numbers . org-export-with-section-numbers)
20978 (:table-of-contents . org-export-with-toc)
20979 (:preserve-breaks . org-export-preserve-breaks)
20980 (:archived-trees . org-export-with-archived-trees)
20981 (:emphasize . org-export-with-emphasize)
20982 (:sub-superscript . org-export-with-sub-superscripts)
20983 (:footnotes . org-export-with-footnotes)
20984 (:property-drawer . org-export-with-property-drawer)
20985 (:TeX-macros . org-export-with-TeX-macros)
20986 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
20987 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
20988 (:fixed-width . org-export-with-fixed-width)
20989 (:timestamps . org-export-with-timestamps)
20990 (:author-info . org-export-author-info)
20991 (:time-stamp-file . org-export-time-stamp-file)
20992 (:tables . org-export-with-tables)
20993 (:table-auto-headline . org-export-highlight-first-table-line)
20994 (:style . org-export-html-style)
20995 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
20996 (:convert-org-links . org-export-html-link-org-files-as-html)
20997 (:inline-images . org-export-html-inline-images)
20998 (:html-extension . org-export-html-extension)
20999 (:expand-quoted-html . org-export-html-expand)
21000 (:timestamp . org-export-html-with-timestamp)
21001 (:publishing-directory . org-export-publishing-directory)
21002 (:preamble . org-export-html-preamble)
21003 (:postamble . org-export-html-postamble)
21004 (:auto-preamble . org-export-html-auto-preamble)
21005 (:auto-postamble . org-export-html-auto-postamble)
21006 (:author . user-full-name)
21007 (:email . user-mail-address)))
21009 (defun org-default-export-plist ()
21010 "Return the property list with default settings for the export variables."
21011 (let ((l org-export-plist-vars) rtn e)
21012 (while (setq e (pop l))
21013 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21014 rtn))
21016 (defun org-infile-export-plist ()
21017 "Return the property list with file-local settings for export."
21018 (save-excursion
21019 (goto-char 0)
21020 (let ((re (org-make-options-regexp
21021 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
21022 p key val text options)
21023 (while (re-search-forward re nil t)
21024 (setq key (org-match-string-no-properties 1)
21025 val (org-match-string-no-properties 2))
21026 (cond
21027 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
21028 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
21029 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
21030 ((string-equal key "DATE") (setq p (plist-put p :date val)))
21031 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
21032 ((string-equal key "TEXT")
21033 (setq text (if text (concat text "\n" val) val)))
21034 ((string-equal key "OPTIONS") (setq options val))))
21035 (setq p (plist-put p :text text))
21036 (when options
21037 (let ((op '(("H" . :headline-levels)
21038 ("num" . :section-numbers)
21039 ("toc" . :table-of-contents)
21040 ("\\n" . :preserve-breaks)
21041 ("@" . :expand-quoted-html)
21042 (":" . :fixed-width)
21043 ("|" . :tables)
21044 ("^" . :sub-superscript)
21045 ("f" . :footnotes)
21046 ("p" . :property-drawer)
21047 ("*" . :emphasize)
21048 ("TeX" . :TeX-macros)
21049 ("LaTeX" . :LaTeX-fragments)
21050 ("skip" . :skip-before-1st-heading)
21051 ("author" . :author-info)
21052 ("timestamp" . :time-stamp-file)))
21054 (while (setq o (pop op))
21055 (if (string-match (concat (regexp-quote (car o))
21056 ":\\([^ \t\n\r;,.]*\\)")
21057 options)
21058 (setq p (plist-put p (cdr o)
21059 (car (read-from-string
21060 (match-string 1 options)))))))))
21061 p)))
21063 (defun org-export-directory (type plist)
21064 (let* ((val (plist-get plist :publishing-directory))
21065 (dir (if (listp val)
21066 (or (cdr (assoc type val)) ".")
21067 val)))
21068 dir))
21070 (defun org-skip-comments (lines)
21071 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
21072 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
21073 (re2 "^\\(\\*+\\)[ \t\n\r]")
21074 (case-fold-search nil)
21075 rtn line level)
21076 (while (setq line (pop lines))
21077 (cond
21078 ((and (string-match re1 line)
21079 (setq level (- (match-end 1) (match-beginning 1))))
21080 ;; Beginning of a COMMENT subtree. Skip it.
21081 (while (and (setq line (pop lines))
21082 (or (not (string-match re2 line))
21083 (> (- (match-end 1) (match-beginning 1)) level))))
21084 (setq lines (cons line lines)))
21085 ((string-match "^#" line)
21086 ;; an ordinary comment line
21088 ((and org-export-table-remove-special-lines
21089 (string-match "^[ \t]*|" line)
21090 (or (string-match "^[ \t]*| *[!_^] *|" line)
21091 (and (string-match "| *<[0-9]+> *|" line)
21092 (not (string-match "| *[^ <|]" line)))))
21093 ;; a special table line that should be removed
21095 (t (setq rtn (cons line rtn)))))
21096 (nreverse rtn)))
21098 (defun org-export (&optional arg)
21099 (interactive)
21100 (let ((help "[t] insert the export option template
21101 \[v] limit export to visible part of outline tree
21103 \[a] export as ASCII
21105 \[h] export as HTML
21106 \[H] export as HTML to temporary buffer
21107 \[R] export region as HTML
21108 \[b] export as HTML and browse immediately
21109 \[x] export as XOXO
21111 \[l] export as LaTeX
21112 \[L] export as LaTeX to temporary buffer
21114 \[i] export current file as iCalendar file
21115 \[I] export all agenda files as iCalendar files
21116 \[c] export agenda files into combined iCalendar file
21118 \[F] publish current file
21119 \[P] publish current project
21120 \[X] publish... (project will be prompted for)
21121 \[A] publish all projects")
21122 (cmds
21123 '((?t . org-insert-export-options-template)
21124 (?v . org-export-visible)
21125 (?a . org-export-as-ascii)
21126 (?h . org-export-as-html)
21127 (?b . org-export-as-html-and-open)
21128 (?H . org-export-as-html-to-buffer)
21129 (?R . org-export-region-as-html)
21130 (?x . org-export-as-xoxo)
21131 (?l . org-export-as-latex)
21132 (?L . org-export-as-latex-to-buffer)
21133 (?i . org-export-icalendar-this-file)
21134 (?I . org-export-icalendar-all-agenda-files)
21135 (?c . org-export-icalendar-combine-agenda-files)
21136 (?F . org-publish-current-file)
21137 (?P . org-publish-current-project)
21138 (?X . org-publish)
21139 (?A . org-publish-all)))
21140 r1 r2 ass)
21141 (save-window-excursion
21142 (delete-other-windows)
21143 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
21144 (princ help))
21145 (message "Select command: ")
21146 (setq r1 (read-char-exclusive)))
21147 (setq r2 (if (< r1 27) (+ r1 96) r1))
21148 (if (setq ass (assq r2 cmds))
21149 (call-interactively (cdr ass))
21150 (error "No command associated with key %c" r1))))
21152 (defconst org-html-entities
21153 '(("nbsp")
21154 ("iexcl")
21155 ("cent")
21156 ("pound")
21157 ("curren")
21158 ("yen")
21159 ("brvbar")
21160 ("vert" . "&#124;")
21161 ("sect")
21162 ("uml")
21163 ("copy")
21164 ("ordf")
21165 ("laquo")
21166 ("not")
21167 ("shy")
21168 ("reg")
21169 ("macr")
21170 ("deg")
21171 ("plusmn")
21172 ("sup2")
21173 ("sup3")
21174 ("acute")
21175 ("micro")
21176 ("para")
21177 ("middot")
21178 ("odot"."o")
21179 ("star"."*")
21180 ("cedil")
21181 ("sup1")
21182 ("ordm")
21183 ("raquo")
21184 ("frac14")
21185 ("frac12")
21186 ("frac34")
21187 ("iquest")
21188 ("Agrave")
21189 ("Aacute")
21190 ("Acirc")
21191 ("Atilde")
21192 ("Auml")
21193 ("Aring") ("AA"."&Aring;")
21194 ("AElig")
21195 ("Ccedil")
21196 ("Egrave")
21197 ("Eacute")
21198 ("Ecirc")
21199 ("Euml")
21200 ("Igrave")
21201 ("Iacute")
21202 ("Icirc")
21203 ("Iuml")
21204 ("ETH")
21205 ("Ntilde")
21206 ("Ograve")
21207 ("Oacute")
21208 ("Ocirc")
21209 ("Otilde")
21210 ("Ouml")
21211 ("times")
21212 ("Oslash")
21213 ("Ugrave")
21214 ("Uacute")
21215 ("Ucirc")
21216 ("Uuml")
21217 ("Yacute")
21218 ("THORN")
21219 ("szlig")
21220 ("agrave")
21221 ("aacute")
21222 ("acirc")
21223 ("atilde")
21224 ("auml")
21225 ("aring")
21226 ("aelig")
21227 ("ccedil")
21228 ("egrave")
21229 ("eacute")
21230 ("ecirc")
21231 ("euml")
21232 ("igrave")
21233 ("iacute")
21234 ("icirc")
21235 ("iuml")
21236 ("eth")
21237 ("ntilde")
21238 ("ograve")
21239 ("oacute")
21240 ("ocirc")
21241 ("otilde")
21242 ("ouml")
21243 ("divide")
21244 ("oslash")
21245 ("ugrave")
21246 ("uacute")
21247 ("ucirc")
21248 ("uuml")
21249 ("yacute")
21250 ("thorn")
21251 ("yuml")
21252 ("fnof")
21253 ("Alpha")
21254 ("Beta")
21255 ("Gamma")
21256 ("Delta")
21257 ("Epsilon")
21258 ("Zeta")
21259 ("Eta")
21260 ("Theta")
21261 ("Iota")
21262 ("Kappa")
21263 ("Lambda")
21264 ("Mu")
21265 ("Nu")
21266 ("Xi")
21267 ("Omicron")
21268 ("Pi")
21269 ("Rho")
21270 ("Sigma")
21271 ("Tau")
21272 ("Upsilon")
21273 ("Phi")
21274 ("Chi")
21275 ("Psi")
21276 ("Omega")
21277 ("alpha")
21278 ("beta")
21279 ("gamma")
21280 ("delta")
21281 ("epsilon")
21282 ("varepsilon"."&epsilon;")
21283 ("zeta")
21284 ("eta")
21285 ("theta")
21286 ("iota")
21287 ("kappa")
21288 ("lambda")
21289 ("mu")
21290 ("nu")
21291 ("xi")
21292 ("omicron")
21293 ("pi")
21294 ("rho")
21295 ("sigmaf") ("varsigma"."&sigmaf;")
21296 ("sigma")
21297 ("tau")
21298 ("upsilon")
21299 ("phi")
21300 ("chi")
21301 ("psi")
21302 ("omega")
21303 ("thetasym") ("vartheta"."&thetasym;")
21304 ("upsih")
21305 ("piv")
21306 ("bull") ("bullet"."&bull;")
21307 ("hellip") ("dots"."&hellip;")
21308 ("prime")
21309 ("Prime")
21310 ("oline")
21311 ("frasl")
21312 ("weierp")
21313 ("image")
21314 ("real")
21315 ("trade")
21316 ("alefsym")
21317 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
21318 ("uarr") ("uparrow"."&uarr;")
21319 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
21320 ("darr")("downarrow"."&darr;")
21321 ("harr") ("leftrightarrow"."&harr;")
21322 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
21323 ("lArr") ("Leftarrow"."&lArr;")
21324 ("uArr") ("Uparrow"."&uArr;")
21325 ("rArr") ("Rightarrow"."&rArr;")
21326 ("dArr") ("Downarrow"."&dArr;")
21327 ("hArr") ("Leftrightarrow"."&hArr;")
21328 ("forall")
21329 ("part") ("partial"."&part;")
21330 ("exist") ("exists"."&exist;")
21331 ("empty") ("emptyset"."&empty;")
21332 ("nabla")
21333 ("isin") ("in"."&isin;")
21334 ("notin")
21335 ("ni")
21336 ("prod")
21337 ("sum")
21338 ("minus")
21339 ("lowast") ("ast"."&lowast;")
21340 ("radic")
21341 ("prop") ("proptp"."&prop;")
21342 ("infin") ("infty"."&infin;")
21343 ("ang") ("angle"."&ang;")
21344 ("and") ("vee"."&and;")
21345 ("or") ("wedge"."&or;")
21346 ("cap")
21347 ("cup")
21348 ("int")
21349 ("there4")
21350 ("sim")
21351 ("cong") ("simeq"."&cong;")
21352 ("asymp")("approx"."&asymp;")
21353 ("ne") ("neq"."&ne;")
21354 ("equiv")
21355 ("le")
21356 ("ge")
21357 ("sub") ("subset"."&sub;")
21358 ("sup") ("supset"."&sup;")
21359 ("nsub")
21360 ("sube")
21361 ("supe")
21362 ("oplus")
21363 ("otimes")
21364 ("perp")
21365 ("sdot") ("cdot"."&sdot;")
21366 ("lceil")
21367 ("rceil")
21368 ("lfloor")
21369 ("rfloor")
21370 ("lang")
21371 ("rang")
21372 ("loz") ("Diamond"."&loz;")
21373 ("spades") ("spadesuit"."&spades;")
21374 ("clubs") ("clubsuit"."&clubs;")
21375 ("hearts") ("diamondsuit"."&hearts;")
21376 ("diams") ("diamondsuit"."&diams;")
21377 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
21378 ("quot")
21379 ("amp")
21380 ("lt")
21381 ("gt")
21382 ("OElig")
21383 ("oelig")
21384 ("Scaron")
21385 ("scaron")
21386 ("Yuml")
21387 ("circ")
21388 ("tilde")
21389 ("ensp")
21390 ("emsp")
21391 ("thinsp")
21392 ("zwnj")
21393 ("zwj")
21394 ("lrm")
21395 ("rlm")
21396 ("ndash")
21397 ("mdash")
21398 ("lsquo")
21399 ("rsquo")
21400 ("sbquo")
21401 ("ldquo")
21402 ("rdquo")
21403 ("bdquo")
21404 ("dagger")
21405 ("Dagger")
21406 ("permil")
21407 ("lsaquo")
21408 ("rsaquo")
21409 ("euro")
21411 ("arccos"."arccos")
21412 ("arcsin"."arcsin")
21413 ("arctan"."arctan")
21414 ("arg"."arg")
21415 ("cos"."cos")
21416 ("cosh"."cosh")
21417 ("cot"."cot")
21418 ("coth"."coth")
21419 ("csc"."csc")
21420 ("deg"."deg")
21421 ("det"."det")
21422 ("dim"."dim")
21423 ("exp"."exp")
21424 ("gcd"."gcd")
21425 ("hom"."hom")
21426 ("inf"."inf")
21427 ("ker"."ker")
21428 ("lg"."lg")
21429 ("lim"."lim")
21430 ("liminf"."liminf")
21431 ("limsup"."limsup")
21432 ("ln"."ln")
21433 ("log"."log")
21434 ("max"."max")
21435 ("min"."min")
21436 ("Pr"."Pr")
21437 ("sec"."sec")
21438 ("sin"."sin")
21439 ("sinh"."sinh")
21440 ("sup"."sup")
21441 ("tan"."tan")
21442 ("tanh"."tanh")
21444 "Entities for TeX->HTML translation.
21445 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
21446 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
21447 In that case, \"\\ent\" will be translated to \"&other;\".
21448 The list contains HTML entities for Latin-1, Greek and other symbols.
21449 It is supplemented by a number of commonly used TeX macros with appropriate
21450 translations. There is currently no way for users to extend this.")
21452 ;;; General functions for all backends
21454 (defun org-cleaned-string-for-export (string &rest parameters)
21455 "Cleanup a buffer STRING so that links can be created safely."
21456 (interactive)
21457 (let* ((re-radio (and org-target-link-regexp
21458 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
21459 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
21460 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
21461 (re-archive (concat ":" org-archive-tag ":"))
21462 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
21463 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
21464 (htmlp (plist-get parameters :for-html))
21465 (asciip (plist-get parameters :for-ascii))
21466 (latexp (plist-get parameters :for-LaTeX))
21467 (commentsp (plist-get parameters :comments))
21468 (archived-trees (plist-get parameters :archived-trees))
21469 (inhibit-read-only t)
21470 (outline-regexp "\\*+ ")
21471 a b xx
21472 rtn p)
21473 (with-current-buffer (get-buffer-create " org-mode-tmp")
21474 (erase-buffer)
21475 (insert string)
21476 ;; Remove license-to-kill stuff
21477 (while (setq p (text-property-any (point-min) (point-max)
21478 :org-license-to-kill t))
21479 (delete-region p (next-single-property-change p :org-license-to-kill)))
21481 (let ((org-inhibit-startup t)) (org-mode))
21482 (untabify (point-min) (point-max))
21484 ;; Get the correct stuff before the first headline
21485 (when (plist-get parameters :skip-before-1st-heading)
21486 (goto-char (point-min))
21487 (when (re-search-forward "^\\*+[ \t]" nil t)
21488 (delete-region (point-min) (match-beginning 0))
21489 (goto-char (point-min))
21490 (insert "\n")))
21491 (when (plist-get parameters :add-text)
21492 (goto-char (point-min))
21493 (insert (plist-get parameters :add-text) "\n"))
21495 ;; Get rid of archived trees
21496 (when (not (eq archived-trees t))
21497 (goto-char (point-min))
21498 (while (re-search-forward re-archive nil t)
21499 (if (not (org-on-heading-p t))
21500 (org-end-of-subtree t)
21501 (beginning-of-line 1)
21502 (setq a (if archived-trees
21503 (1+ (point-at-eol)) (point))
21504 b (org-end-of-subtree t))
21505 (if (> b a) (delete-region a b)))))
21507 ;; Get rid of property drawers
21508 (unless org-export-with-property-drawer
21509 (goto-char (point-min))
21510 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
21511 (replace-match "")))
21513 ;; Find targets in comments and move them out of comments,
21514 ;; but mark them as targets that should be invisible
21515 (goto-char (point-min))
21516 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
21517 (replace-match "\\1(INVISIBLE)"))
21519 ;; Protect backend specific stuff, throw away the others.
21520 (goto-char (point-min))
21521 (let ((formatters
21522 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
21523 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
21524 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
21525 fmt)
21526 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
21527 (add-text-properties (match-beginning 0) (match-end 0)
21528 '(org-protected t)))
21529 (while formatters
21530 (setq fmt (pop formatters))
21531 (when (car fmt)
21532 (goto-char (point-min))
21533 (while (re-search-forward (concat "^#\\+" (cadr fmt)
21534 ":[ \t]*\\(.*\\)") nil t)
21535 (replace-match "\\1" t)
21536 (add-text-properties
21537 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
21538 '(org-protected t))))
21539 (goto-char (point-min))
21540 (while (re-search-forward
21541 (concat "^#\\+"
21542 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
21543 (cadddr fmt) "\\>.*\n?") nil t)
21544 (if (car fmt)
21545 (add-text-properties (match-beginning 1) (1+ (match-end 1))
21546 '(org-protected t))
21547 (delete-region (match-beginning 0) (match-end 0))))))
21549 ;; Protect quoted subtrees
21550 (goto-char (point-min))
21551 (while (re-search-forward re-quote nil t)
21552 (goto-char (match-beginning 0))
21553 (end-of-line 1)
21554 (add-text-properties (point) (org-end-of-subtree t)
21555 '(org-protected t)))
21557 ;; Remove subtrees that are commented
21558 (goto-char (point-min))
21559 (while (re-search-forward re-commented nil t)
21560 (goto-char (match-beginning 0))
21561 (delete-region (point) (org-end-of-subtree t)))
21563 ;; Remove special table lines
21564 (when org-export-table-remove-special-lines
21565 (goto-char (point-min))
21566 (while (re-search-forward "^[ \t]*|" nil t)
21567 (beginning-of-line 1)
21568 (if (or (looking-at "[ \t]*| *[!_^] *|")
21569 (and (looking-at ".*?| *<[0-9]+> *|")
21570 (not (looking-at ".*?| *[^ <|]"))))
21571 (delete-region (max (point-min) (1- (point-at-bol)))
21572 (point-at-eol))
21573 (end-of-line 1))))
21575 ;; Specific LaTeX stuff
21576 (when latexp
21577 (require 'org-export-latex nil)
21578 (org-export-latex-cleaned-string))
21580 ;; Specific HTML stuff
21581 (when htmlp
21582 ;; Convert LaTeX fragments to images
21583 (when (plist-get parameters :LaTeX-fragments)
21584 (org-format-latex
21585 (concat "ltxpng/" (file-name-sans-extension
21586 (file-name-nondirectory
21587 org-current-export-file)))
21588 org-current-export-dir nil "Creating LaTeX image %s"))
21589 (message "Exporting..."))
21591 ;; Remove or replace comments
21592 (goto-char (point-min))
21593 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
21594 (if commentsp
21595 (progn (add-text-properties
21596 (match-beginning 0) (match-end 0) '(org-protected t))
21597 (replace-match (format commentsp (match-string 1)) t t))
21598 (replace-match "")))
21600 ;; Find matches for radio targets and turn them into internal links
21601 (goto-char (point-min))
21602 (when re-radio
21603 (while (re-search-forward re-radio nil t)
21604 (org-if-unprotected
21605 (replace-match "\\1[[\\2]]"))))
21607 ;; Find all links that contain a newline and put them into a single line
21608 (goto-char (point-min))
21609 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
21610 (org-if-unprotected
21611 (replace-match "\\1 \\3")
21612 (goto-char (match-beginning 0))))
21615 ;; Normalize links: Convert angle and plain links into bracket links
21616 ;; Expand link abbreviations
21617 (goto-char (point-min))
21618 (while (re-search-forward re-plain-link nil t)
21619 (goto-char (1- (match-end 0)))
21620 (org-if-unprotected
21621 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21622 ":" (match-string 3) "]]")))
21623 ;; added 'org-link face to links
21624 (put-text-property 0 (length s) 'face 'org-link s)
21625 (replace-match s t t))))
21626 (goto-char (point-min))
21627 (while (re-search-forward re-angle-link nil t)
21628 (goto-char (1- (match-end 0)))
21629 (org-if-unprotected
21630 (let* ((s (concat (match-string 1) "[[" (match-string 2)
21631 ":" (match-string 3) "]]")))
21632 (put-text-property 0 (length s) 'face 'org-link s)
21633 (replace-match s t t))))
21634 (goto-char (point-min))
21635 (while (re-search-forward org-bracket-link-regexp nil t)
21636 (org-if-unprotected
21637 (let* ((s (concat "[[" (setq xx (save-match-data
21638 (org-link-expand-abbrev (match-string 1))))
21640 (if (match-end 3)
21641 (match-string 2)
21642 (concat "[" xx "]"))
21643 "]")))
21644 (put-text-property 0 (length s) 'face 'org-link s)
21645 (replace-match s t t))))
21647 ;; Find multiline emphasis and put them into single line
21648 (when (plist-get parameters :emph-multiline)
21649 (goto-char (point-min))
21650 (while (re-search-forward org-emph-re nil t)
21651 (if (not (= (char-after (match-beginning 3))
21652 (char-after (match-beginning 4))))
21653 (org-if-unprotected
21654 (subst-char-in-region (match-beginning 0) (match-end 0)
21655 ?\n ?\ t)
21656 (goto-char (1- (match-end 0))))
21657 (goto-char (1+ (match-beginning 0))))))
21659 (setq rtn (buffer-string)))
21660 (kill-buffer " org-mode-tmp")
21661 rtn))
21663 (defun org-export-grab-title-from-buffer ()
21664 "Get a title for the current document, from looking at the buffer."
21665 (let ((inhibit-read-only t))
21666 (save-excursion
21667 (goto-char (point-min))
21668 (let ((end (save-excursion (outline-next-heading) (point))))
21669 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
21670 ;; Mark the line so that it will not be exported as normal text.
21671 (org-unmodified
21672 (add-text-properties (match-beginning 0) (match-end 0)
21673 (list :org-license-to-kill t)))
21674 ;; Return the title string
21675 (org-trim (match-string 0)))))))
21677 (defun org-export-get-title-from-subtree ()
21678 "Return subtree title and exclude it from export."
21679 (let (title (m (mark)))
21680 (save-excursion
21681 (goto-char (region-beginning))
21682 (when (and (org-at-heading-p)
21683 (>= (org-end-of-subtree t t) (region-end)))
21684 ;; This is a subtree, we take the title from the first heading
21685 (goto-char (region-beginning))
21686 (looking-at org-todo-line-regexp)
21687 (setq title (match-string 3))
21688 (org-unmodified
21689 (add-text-properties (point) (1+ (point-at-eol))
21690 (list :org-license-to-kill t)))))
21691 title))
21693 (defun org-solidify-link-text (s &optional alist)
21694 "Take link text and make a safe target out of it."
21695 (save-match-data
21696 (let* ((rtn
21697 (mapconcat
21698 'identity
21699 (org-split-string s "[ \t\r\n]+") "--"))
21700 (a (assoc rtn alist)))
21701 (or (cdr a) rtn))))
21703 (defun org-get-min-level (lines)
21704 "Get the minimum level in LINES."
21705 (let ((re "^\\(\\*+\\) ") l min)
21706 (catch 'exit
21707 (while (setq l (pop lines))
21708 (if (string-match re l)
21709 (throw 'exit (org-tr-level (length (match-string 1 l))))))
21710 1)))
21712 ;; Variable holding the vector with section numbers
21713 (defvar org-section-numbers (make-vector org-level-max 0))
21715 (defun org-init-section-numbers ()
21716 "Initialize the vector for the section numbers."
21717 (let* ((level -1)
21718 (numbers (nreverse (org-split-string "" "\\.")))
21719 (depth (1- (length org-section-numbers)))
21720 (i depth) number-string)
21721 (while (>= i 0)
21722 (if (> i level)
21723 (aset org-section-numbers i 0)
21724 (setq number-string (or (car numbers) "0"))
21725 (if (string-match "\\`[A-Z]\\'" number-string)
21726 (aset org-section-numbers i
21727 (- (string-to-char number-string) ?A -1))
21728 (aset org-section-numbers i (string-to-number number-string)))
21729 (pop numbers))
21730 (setq i (1- i)))))
21732 (defun org-section-number (&optional level)
21733 "Return a string with the current section number.
21734 When LEVEL is non-nil, increase section numbers on that level."
21735 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
21736 (when level
21737 (when (> level -1)
21738 (aset org-section-numbers
21739 level (1+ (aref org-section-numbers level))))
21740 (setq idx (1+ level))
21741 (while (<= idx depth)
21742 (if (not (= idx 1))
21743 (aset org-section-numbers idx 0))
21744 (setq idx (1+ idx))))
21745 (setq idx 0)
21746 (while (<= idx depth)
21747 (setq n (aref org-section-numbers idx))
21748 (setq string (concat string (if (not (string= string "")) "." "")
21749 (int-to-string n)))
21750 (setq idx (1+ idx)))
21751 (save-match-data
21752 (if (string-match "\\`\\([@0]\\.\\)+" string)
21753 (setq string (replace-match "" t nil string)))
21754 (if (string-match "\\(\\.0\\)+\\'" string)
21755 (setq string (replace-match "" t nil string))))
21756 string))
21758 ;;; ASCII export
21760 (defvar org-last-level nil) ; dynamically scoped variable
21761 (defvar org-min-level nil) ; dynamically scoped variable
21762 (defvar org-levels-open nil) ; dynamically scoped parameter
21763 (defvar org-ascii-current-indentation nil) ; For communication
21765 (defun org-export-as-ascii (arg)
21766 "Export the outline as a pretty ASCII file.
21767 If there is an active region, export only the region.
21768 The prefix ARG specifies how many levels of the outline should become
21769 underlined headlines. The default is 3."
21770 (interactive "P")
21771 (setq-default org-todo-line-regexp org-todo-line-regexp)
21772 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21773 (org-infile-export-plist)))
21774 (region-p (org-region-active-p))
21775 (subtree-p
21776 (when region-p
21777 (save-excursion
21778 (goto-char (region-beginning))
21779 (and (org-at-heading-p)
21780 (>= (org-end-of-subtree t t) (region-end))))))
21781 (custom-times org-display-custom-times)
21782 (org-ascii-current-indentation '(0 . 0))
21783 (level 0) line txt
21784 (umax nil)
21785 (umax-toc nil)
21786 (case-fold-search nil)
21787 (filename (concat (file-name-as-directory
21788 (org-export-directory :ascii opt-plist))
21789 (file-name-sans-extension
21790 (or (and subtree-p
21791 (org-entry-get (region-beginning)
21792 "EXPORT_FILE_NAME" t))
21793 (file-name-nondirectory buffer-file-name)))
21794 ".txt"))
21795 (filename (if (equal (file-truename filename)
21796 (file-truename buffer-file-name))
21797 (concat filename ".txt")
21798 filename))
21799 (buffer (find-file-noselect filename))
21800 (org-levels-open (make-vector org-level-max nil))
21801 (odd org-odd-levels-only)
21802 (date (plist-get opt-plist :date))
21803 (author (plist-get opt-plist :author))
21804 (title (or (and subtree-p (org-export-get-title-from-subtree))
21805 (plist-get opt-plist :title)
21806 (and (not
21807 (plist-get opt-plist :skip-before-1st-heading))
21808 (org-export-grab-title-from-buffer))
21809 (file-name-sans-extension
21810 (file-name-nondirectory buffer-file-name))))
21811 (email (plist-get opt-plist :email))
21812 (language (plist-get opt-plist :language))
21813 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21814 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
21815 (todo nil)
21816 (lang-words nil)
21817 (region
21818 (buffer-substring
21819 (if (org-region-active-p) (region-beginning) (point-min))
21820 (if (org-region-active-p) (region-end) (point-max))))
21821 (lines (org-split-string
21822 (org-cleaned-string-for-export
21823 region
21824 :for-ascii t
21825 :skip-before-1st-heading
21826 (plist-get opt-plist :skip-before-1st-heading)
21827 :archived-trees
21828 (plist-get opt-plist :archived-trees)
21829 :add-text (plist-get opt-plist :text))
21830 "\n"))
21831 thetoc have-headings first-heading-pos
21832 table-open table-buffer)
21834 (let ((inhibit-read-only t))
21835 (org-unmodified
21836 (remove-text-properties (point-min) (point-max)
21837 '(:org-license-to-kill t))))
21839 (setq org-min-level (org-get-min-level lines))
21840 (setq org-last-level org-min-level)
21841 (org-init-section-numbers)
21843 (find-file-noselect filename)
21845 (setq lang-words (or (assoc language org-export-language-setup)
21846 (assoc "en" org-export-language-setup)))
21847 (switch-to-buffer-other-window buffer)
21848 (erase-buffer)
21849 (fundamental-mode)
21850 ;; create local variables for all options, to make sure all called
21851 ;; functions get the correct information
21852 (mapcar (lambda (x)
21853 (set (make-local-variable (cdr x))
21854 (plist-get opt-plist (car x))))
21855 org-export-plist-vars)
21856 (org-set-local 'org-odd-levels-only odd)
21857 (setq umax (if arg (prefix-numeric-value arg)
21858 org-export-headline-levels))
21859 (setq umax-toc (if (integerp org-export-with-toc)
21860 (min org-export-with-toc umax)
21861 umax))
21863 ;; File header
21864 (if title (org-insert-centered title ?=))
21865 (insert "\n")
21866 (if (and (or author email)
21867 org-export-author-info)
21868 (insert (concat (nth 1 lang-words) ": " (or author "")
21869 (if email (concat " <" email ">") "")
21870 "\n")))
21872 (cond
21873 ((and date (string-match "%" date))
21874 (setq date (format-time-string date (current-time))))
21875 (date)
21876 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
21878 (if (and date org-export-time-stamp-file)
21879 (insert (concat (nth 2 lang-words) ": " date"\n")))
21881 (insert "\n\n")
21883 (if org-export-with-toc
21884 (progn
21885 (push (concat (nth 3 lang-words) "\n") thetoc)
21886 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
21887 (mapcar '(lambda (line)
21888 (if (string-match org-todo-line-regexp
21889 line)
21890 ;; This is a headline
21891 (progn
21892 (setq have-headings t)
21893 (setq level (- (match-end 1) (match-beginning 1))
21894 level (org-tr-level level)
21895 txt (match-string 3 line)
21896 todo
21897 (or (and org-export-mark-todo-in-toc
21898 (match-beginning 2)
21899 (not (member (match-string 2 line)
21900 org-done-keywords)))
21901 ; TODO, not DONE
21902 (and org-export-mark-todo-in-toc
21903 (= level umax-toc)
21904 (org-search-todo-below
21905 line lines level))))
21906 (setq txt (org-html-expand-for-ascii txt))
21908 (if (and (memq org-export-with-tags '(not-in-toc nil))
21909 (string-match
21910 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21911 txt))
21912 (setq txt (replace-match "" t t txt)))
21913 (if (string-match quote-re0 txt)
21914 (setq txt (replace-match "" t t txt)))
21916 (if org-export-with-section-numbers
21917 (setq txt (concat (org-section-number level)
21918 " " txt)))
21919 (if (<= level umax-toc)
21920 (progn
21921 (push
21922 (concat
21923 (make-string
21924 (* (max 0 (- level org-min-level)) 4) ?\ )
21925 (format (if todo "%s (*)\n" "%s\n") txt))
21926 thetoc)
21927 (setq org-last-level level))
21928 ))))
21929 lines)
21930 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21932 (org-init-section-numbers)
21933 (while (setq line (pop lines))
21934 ;; Remove the quoted HTML tags.
21935 (setq line (org-html-expand-for-ascii line))
21936 ;; Remove targets
21937 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
21938 (setq line (replace-match "" t t line)))
21939 ;; Replace internal links
21940 (while (string-match org-bracket-link-regexp line)
21941 (setq line (replace-match
21942 (if (match-end 3) "[\\3]" "[\\1]")
21943 t nil line)))
21944 (when custom-times
21945 (setq line (org-translate-time line)))
21946 (cond
21947 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21948 ;; a Headline
21949 (setq first-heading-pos (or first-heading-pos (point)))
21950 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21951 txt (match-string 2 line))
21952 (org-ascii-level-start level txt umax lines))
21954 ((and org-export-with-tables
21955 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21956 (if (not table-open)
21957 ;; New table starts
21958 (setq table-open t table-buffer nil))
21959 ;; Accumulate lines
21960 (setq table-buffer (cons line table-buffer))
21961 (when (or (not lines)
21962 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21963 (car lines))))
21964 (setq table-open nil
21965 table-buffer (nreverse table-buffer))
21966 (insert (mapconcat
21967 (lambda (x)
21968 (org-fix-indentation x org-ascii-current-indentation))
21969 (org-format-table-ascii table-buffer)
21970 "\n") "\n")))
21972 (setq line (org-fix-indentation line org-ascii-current-indentation))
21973 (if (and org-export-with-fixed-width
21974 (string-match "^\\([ \t]*\\)\\(:\\)" line))
21975 (setq line (replace-match "\\1" nil nil line)))
21976 (insert line "\n"))))
21978 (normal-mode)
21980 ;; insert the table of contents
21981 (when thetoc
21982 (goto-char (point-min))
21983 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
21984 (progn
21985 (goto-char (match-beginning 0))
21986 (replace-match ""))
21987 (goto-char first-heading-pos))
21988 (mapc 'insert thetoc)
21989 (or (looking-at "[ \t]*\n[ \t]*\n")
21990 (insert "\n\n")))
21992 (save-buffer)
21993 ;; remove display and invisible chars
21994 (let (beg end)
21995 (goto-char (point-min))
21996 (while (setq beg (next-single-property-change (point) 'display))
21997 (setq end (next-single-property-change beg 'display))
21998 (delete-region beg end)
21999 (goto-char beg)
22000 (insert "=>"))
22001 (goto-char (point-min))
22002 (while (setq beg (next-single-property-change (point) 'org-cwidth))
22003 (setq end (next-single-property-change beg 'org-cwidth))
22004 (delete-region beg end)
22005 (goto-char beg)))
22006 (goto-char (point-min))))
22008 (defun org-search-todo-below (line lines level)
22009 "Search the subtree below LINE for any TODO entries."
22010 (let ((rest (cdr (memq line lines)))
22011 (re org-todo-line-regexp)
22012 line lv todo)
22013 (catch 'exit
22014 (while (setq line (pop rest))
22015 (if (string-match re line)
22016 (progn
22017 (setq lv (- (match-end 1) (match-beginning 1))
22018 todo (and (match-beginning 2)
22019 (not (member (match-string 2 line)
22020 org-done-keywords))))
22021 ; TODO, not DONE
22022 (if (<= lv level) (throw 'exit nil))
22023 (if todo (throw 'exit t))))))))
22025 (defun org-html-expand-for-ascii (line)
22026 "Handle quoted HTML for ASCII export."
22027 (if org-export-html-expand
22028 (while (string-match "@<[^<>\n]*>" line)
22029 ;; We just remove the tags for now.
22030 (setq line (replace-match "" nil nil line))))
22031 line)
22033 (defun org-insert-centered (s &optional underline)
22034 "Insert the string S centered and underline it with character UNDERLINE."
22035 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
22036 (insert (make-string ind ?\ ) s "\n")
22037 (if underline
22038 (insert (make-string ind ?\ )
22039 (make-string (string-width s) underline)
22040 "\n"))))
22042 (defun org-ascii-level-start (level title umax &optional lines)
22043 "Insert a new level in ASCII export."
22044 (let (char (n (- level umax 1)) (ind 0))
22045 (if (> level umax)
22046 (progn
22047 (insert (make-string (* 2 n) ?\ )
22048 (char-to-string (nth (% n (length org-export-ascii-bullets))
22049 org-export-ascii-bullets))
22050 " " title "\n")
22051 ;; find the indentation of the next non-empty line
22052 (catch 'stop
22053 (while lines
22054 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
22055 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
22056 (throw 'stop (setq ind (org-get-indentation (car lines)))))
22057 (pop lines)))
22058 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
22059 (if (or (not (equal (char-before) ?\n))
22060 (not (equal (char-before (1- (point))) ?\n)))
22061 (insert "\n"))
22062 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
22063 (unless org-export-with-tags
22064 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22065 (setq title (replace-match "" t t title))))
22066 (if org-export-with-section-numbers
22067 (setq title (concat (org-section-number level) " " title)))
22068 (insert title "\n" (make-string (string-width title) char) "\n")
22069 (setq org-ascii-current-indentation '(0 . 0)))))
22071 (defun org-export-visible (type arg)
22072 "Create a copy of the visible part of the current buffer, and export it.
22073 The copy is created in a temporary buffer and removed after use.
22074 TYPE is the final key (as a string) that also select the export command in
22075 the `C-c C-e' export dispatcher.
22076 As a special case, if the you type SPC at the prompt, the temporary
22077 org-mode file will not be removed but presented to you so that you can
22078 continue to use it. The prefix arg ARG is passed through to the exporting
22079 command."
22080 (interactive
22081 (list (progn
22082 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
22083 (read-char-exclusive))
22084 current-prefix-arg))
22085 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
22086 (error "Invalid export key"))
22087 (let* ((binding (cdr (assoc type
22088 '((?a . org-export-as-ascii)
22089 (?\C-a . org-export-as-ascii)
22090 (?b . org-export-as-html-and-open)
22091 (?\C-b . org-export-as-html-and-open)
22092 (?h . org-export-as-html)
22093 (?H . org-export-as-html-to-buffer)
22094 (?R . org-export-region-as-html)
22095 (?x . org-export-as-xoxo)))))
22096 (keepp (equal type ?\ ))
22097 (file buffer-file-name)
22098 (buffer (get-buffer-create "*Org Export Visible*"))
22099 s e)
22100 ;; Need to hack the drawers here.
22101 (save-excursion
22102 (goto-char (point-min))
22103 (while (re-search-forward org-drawer-regexp nil t)
22104 (goto-char (match-beginning 1))
22105 (or (org-invisible-p) (org-flag-drawer nil))))
22106 (with-current-buffer buffer (erase-buffer))
22107 (save-excursion
22108 (setq s (goto-char (point-min)))
22109 (while (not (= (point) (point-max)))
22110 (goto-char (org-find-invisible))
22111 (append-to-buffer buffer s (point))
22112 (setq s (goto-char (org-find-visible))))
22113 (org-cycle-hide-drawers 'all)
22114 (goto-char (point-min))
22115 (unless keepp
22116 ;; Copy all comment lines to the end, to make sure #+ settings are
22117 ;; still available for the second export step. Kind of a hack, but
22118 ;; does do the trick.
22119 (if (looking-at "#[^\r\n]*")
22120 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
22121 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
22122 (append-to-buffer buffer (1+ (match-beginning 0))
22123 (min (point-max) (1+ (match-end 0))))))
22124 (set-buffer buffer)
22125 (let ((buffer-file-name file)
22126 (org-inhibit-startup t))
22127 (org-mode)
22128 (show-all)
22129 (unless keepp (funcall binding arg))))
22130 (if (not keepp)
22131 (kill-buffer buffer)
22132 (switch-to-buffer-other-window buffer)
22133 (goto-char (point-min)))))
22135 (defun org-find-visible ()
22136 (let ((s (point)))
22137 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22138 (get-char-property s 'invisible)))
22140 (defun org-find-invisible ()
22141 (let ((s (point)))
22142 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
22143 (not (get-char-property s 'invisible))))
22146 ;;; HTML export
22148 (defun org-get-current-options ()
22149 "Return a string with current options as keyword options.
22150 Does include HTML export options as well as TODO and CATEGORY stuff."
22151 (format
22152 "#+TITLE: %s
22153 #+AUTHOR: %s
22154 #+EMAIL: %s
22155 #+LANGUAGE: %s
22156 #+TEXT: Some descriptive text to be emitted. Several lines OK.
22157 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
22158 #+CATEGORY: %s
22159 #+SEQ_TODO: %s
22160 #+TYP_TODO: %s
22161 #+PRIORITIES: %c %c %c
22162 #+STARTUP: %s %s %s %s %s
22163 #+TAGS: %s
22164 #+ARCHIVE: %s
22165 #+LINK: %s
22167 (buffer-name) (user-full-name) user-mail-address org-export-default-language
22168 org-export-headline-levels
22169 org-export-with-section-numbers
22170 org-export-with-toc
22171 org-export-preserve-breaks
22172 org-export-html-expand
22173 org-export-with-fixed-width
22174 org-export-with-tables
22175 org-export-with-sub-superscripts
22176 org-export-with-footnotes
22177 org-export-with-emphasize
22178 org-export-with-TeX-macros
22179 org-export-with-LaTeX-fragments
22180 org-export-skip-text-before-1st-heading
22181 org-export-with-property-drawer
22182 (file-name-nondirectory buffer-file-name)
22183 "TODO FEEDBACK VERIFY DONE"
22184 "Me Jason Marie DONE"
22185 org-highest-priority org-lowest-priority org-default-priority
22186 (cdr (assoc org-startup-folded
22187 '((nil . "showall") (t . "overview") (content . "content"))))
22188 (if org-odd-levels-only "odd" "oddeven")
22189 (if org-hide-leading-stars "hidestars" "showstars")
22190 (if org-startup-align-all-tables "align" "noalign")
22191 (cond ((eq t org-log-done) "logdone")
22192 ((not org-log-done) "nologging")
22193 ((listp org-log-done)
22194 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
22195 org-log-done " ")))
22196 (or (mapconcat (lambda (x)
22197 (cond
22198 ((equal '(:startgroup) x) "{")
22199 ((equal '(:endgroup) x) "}")
22200 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
22201 (t (car x))))
22202 (or org-tag-alist (org-get-buffer-tags)) " ") "")
22203 org-archive-location
22204 "org file:~/org/%s.org"
22207 (defun org-insert-export-options-template ()
22208 "Insert into the buffer a template with information for exporting."
22209 (interactive)
22210 (if (not (bolp)) (newline))
22211 (let ((s (org-get-current-options)))
22212 (and (string-match "#\\+CATEGORY" s)
22213 (setq s (substring s 0 (match-beginning 0))))
22214 (insert s)))
22216 (defun org-toggle-fixed-width-section (arg)
22217 "Toggle the fixed-width export.
22218 If there is no active region, the QUOTE keyword at the current headline is
22219 inserted or removed. When present, it causes the text between this headline
22220 and the next to be exported as fixed-width text, and unmodified.
22221 If there is an active region, this command adds or removes a colon as the
22222 first character of this line. If the first character of a line is a colon,
22223 this line is also exported in fixed-width font."
22224 (interactive "P")
22225 (let* ((cc 0)
22226 (regionp (org-region-active-p))
22227 (beg (if regionp (region-beginning) (point)))
22228 (end (if regionp (region-end)))
22229 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
22230 (re "[ \t]*\\(:\\)")
22231 off)
22232 (if regionp
22233 (save-excursion
22234 (goto-char beg)
22235 (setq cc (current-column))
22236 (beginning-of-line 1)
22237 (setq off (looking-at re))
22238 (while (> nlines 0)
22239 (setq nlines (1- nlines))
22240 (beginning-of-line 1)
22241 (cond
22242 (arg
22243 (move-to-column cc t)
22244 (insert ":\n")
22245 (forward-line -1))
22246 ((and off (looking-at re))
22247 (replace-match "" t t nil 1))
22248 ((not off) (move-to-column cc t) (insert ":")))
22249 (forward-line 1)))
22250 (save-excursion
22251 (org-back-to-heading)
22252 (if (looking-at (concat outline-regexp
22253 "\\( *\\<" org-quote-string "\\>\\)"))
22254 (replace-match "" t t nil 1)
22255 (if (looking-at outline-regexp)
22256 (progn
22257 (goto-char (match-end 0))
22258 (insert org-quote-string " "))))))))
22260 (defun org-export-as-html-and-open (arg)
22261 "Export the outline as HTML and immediately open it with a browser.
22262 If there is an active region, export only the region.
22263 The prefix ARG specifies how many levels of the outline should become
22264 headlines. The default is 3. Lower levels will become bulleted lists."
22265 (interactive "P")
22266 (org-export-as-html arg 'hidden)
22267 (org-open-file buffer-file-name))
22269 (defun org-export-as-html-batch ()
22270 "Call `org-export-as-html', may be used in batch processing as
22271 emacs --batch
22272 --load=$HOME/lib/emacs/org.el
22273 --eval \"(setq org-export-headline-levels 2)\"
22274 --visit=MyFile --funcall org-export-as-html-batch"
22275 (org-export-as-html org-export-headline-levels 'hidden))
22277 (defun org-export-as-html-to-buffer (arg)
22278 "Call `org-exort-as-html` with output to a temporary buffer.
22279 No file is created. The prefix ARG is passed through to `org-export-as-html'."
22280 (interactive "P")
22281 (org-export-as-html arg nil nil "*Org HTML Export*")
22282 (switch-to-buffer-other-window "*Org HTML Export*"))
22284 (defun org-replace-region-by-html (beg end)
22285 "Assume the current region has org-mode syntax, and convert it to HTML.
22286 This can be used in any buffer. For example, you could write an
22287 itemized list in org-mode syntax in an HTML buffer and then use this
22288 command to convert it."
22289 (interactive "r")
22290 (let (reg html buf pop-up-frames)
22291 (save-window-excursion
22292 (if (org-mode-p)
22293 (setq html (org-export-region-as-html
22294 beg end t 'string))
22295 (setq reg (buffer-substring beg end)
22296 buf (get-buffer-create "*Org tmp*"))
22297 (with-current-buffer buf
22298 (erase-buffer)
22299 (insert reg)
22300 (org-mode)
22301 (setq html (org-export-region-as-html
22302 (point-min) (point-max) t 'string)))
22303 (kill-buffer buf)))
22304 (delete-region beg end)
22305 (insert html)))
22307 (defun org-export-region-as-html (beg end &optional body-only buffer)
22308 "Convert region from BEG to END in org-mode buffer to HTML.
22309 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
22310 contents, and only produce the region of converted text, useful for
22311 cut-and-paste operations.
22312 If BUFFER is a buffer or a string, use/create that buffer as a target
22313 of the converted HTML. If BUFFER is the symbol `string', return the
22314 produced HTML as a string and leave not buffer behind. For example,
22315 a Lisp program could call this function in the following way:
22317 (setq html (org-export-region-as-html beg end t 'string))
22319 When called interactively, the output buffer is selected, and shown
22320 in a window. A non-interactive call will only retunr the buffer."
22321 (interactive "r\nP")
22322 (when (interactive-p)
22323 (setq buffer "*Org HTML Export*"))
22324 (let ((transient-mark-mode t) (zmacs-regions t)
22325 rtn)
22326 (goto-char end)
22327 (set-mark (point)) ;; to activate the region
22328 (goto-char beg)
22329 (setq rtn (org-export-as-html
22330 nil nil nil
22331 buffer body-only))
22332 (if (fboundp 'deactivate-mark) (deactivate-mark))
22333 (if (and (interactive-p) (bufferp rtn))
22334 (switch-to-buffer-other-window rtn)
22335 rtn)))
22337 (defun org-export-as-html (arg &optional hidden ext-plist
22338 to-buffer body-only)
22339 "Export the outline as a pretty HTML file.
22340 If there is an active region, export only the region. The prefix
22341 ARG specifies how many levels of the outline should become
22342 headlines. The default is 3. Lower levels will become bulleted
22343 lists. When HIDDEN is non-nil, don't display the HTML buffer.
22344 EXT-PLIST is a property list with external parameters overriding
22345 org-mode's default settings, but still inferior to file-local
22346 settings. When TO-BUFFER is non-nil, create a buffer with that
22347 name and export to that buffer. If TO-BUFFER is the symbol `string',
22348 don't leave any buffer behind but just return the resulting HTML as
22349 a string. When BODY-ONLY is set, don't produce the file header and footer,
22350 simply return the content of <body>...</body>, without even
22351 the body tags themselves."
22352 (interactive "P")
22354 ;; Make sure we have a file name when we need it.
22355 (when (and (not (or to-buffer body-only))
22356 (not buffer-file-name))
22357 (if (buffer-base-buffer)
22358 (org-set-local 'buffer-file-name
22359 (with-current-buffer (buffer-base-buffer)
22360 buffer-file-name))
22361 (error "Need a file name to be able to export.")))
22363 (message "Exporting...")
22364 (setq-default org-todo-line-regexp org-todo-line-regexp)
22365 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
22366 (setq-default org-done-keywords org-done-keywords)
22367 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
22368 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22369 ext-plist
22370 (org-infile-export-plist)))
22372 (style (plist-get opt-plist :style))
22373 (link-validate (plist-get opt-plist :link-validation-function))
22374 valid thetoc have-headings first-heading-pos
22375 (odd org-odd-levels-only)
22376 (region-p (org-region-active-p))
22377 (subtree-p
22378 (when region-p
22379 (save-excursion
22380 (goto-char (region-beginning))
22381 (and (org-at-heading-p)
22382 (>= (org-end-of-subtree t t) (region-end))))))
22383 ;; The following two are dynamically scoped into other
22384 ;; routines below.
22385 (org-current-export-dir (org-export-directory :html opt-plist))
22386 (org-current-export-file buffer-file-name)
22387 (level 0) (line "") (origline "") txt todo
22388 (umax nil)
22389 (umax-toc nil)
22390 (filename (if to-buffer nil
22391 (concat (file-name-as-directory
22392 (org-export-directory :html opt-plist))
22393 (file-name-sans-extension
22394 (or (and subtree-p
22395 (org-entry-get (region-beginning)
22396 "EXPORT_FILE_NAME" t))
22397 (file-name-nondirectory buffer-file-name)))
22398 "." org-export-html-extension)))
22399 (current-dir (if buffer-file-name
22400 (file-name-directory buffer-file-name)
22401 default-directory))
22402 (buffer (if to-buffer
22403 (cond
22404 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
22405 (t (get-buffer-create to-buffer)))
22406 (find-file-noselect filename)))
22407 (org-levels-open (make-vector org-level-max nil))
22408 (date (plist-get opt-plist :date))
22409 (author (plist-get opt-plist :author))
22410 (title (or (and subtree-p (org-export-get-title-from-subtree))
22411 (plist-get opt-plist :title)
22412 (and (not
22413 (plist-get opt-plist :skip-before-1st-heading))
22414 (org-export-grab-title-from-buffer))
22415 (and buffer-file-name
22416 (file-name-sans-extension
22417 (file-name-nondirectory buffer-file-name)))
22418 "UNTITLED"))
22419 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22420 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
22421 (inquote nil)
22422 (infixed nil)
22423 (in-local-list nil)
22424 (local-list-num nil)
22425 (local-list-indent nil)
22426 (llt org-plain-list-ordered-item-terminator)
22427 (email (plist-get opt-plist :email))
22428 (language (plist-get opt-plist :language))
22429 (lang-words nil)
22430 (target-alist nil) tg
22431 (head-count 0) cnt
22432 (start 0)
22433 (coding-system (and (boundp 'buffer-file-coding-system)
22434 buffer-file-coding-system))
22435 (coding-system-for-write (or org-export-html-coding-system
22436 coding-system))
22437 (save-buffer-coding-system (or org-export-html-coding-system
22438 coding-system))
22439 (charset (and coding-system-for-write
22440 (fboundp 'coding-system-get)
22441 (coding-system-get coding-system-for-write
22442 'mime-charset)))
22443 (region
22444 (buffer-substring
22445 (if region-p (region-beginning) (point-min))
22446 (if region-p (region-end) (point-max))))
22447 (lines
22448 (org-split-string
22449 (org-cleaned-string-for-export
22450 region
22451 :emph-multiline t
22452 :for-html t
22453 :skip-before-1st-heading
22454 (plist-get opt-plist :skip-before-1st-heading)
22455 :archived-trees
22456 (plist-get opt-plist :archived-trees)
22457 :add-text
22458 (plist-get opt-plist :text)
22459 :LaTeX-fragments
22460 (plist-get opt-plist :LaTeX-fragments))
22461 "[\r\n]"))
22462 table-open type
22463 table-buffer table-orig-buffer
22464 ind start-is-num starter didclose
22465 rpl path desc descp desc1 desc2 link
22468 (let ((inhibit-read-only t))
22469 (org-unmodified
22470 (remove-text-properties (point-min) (point-max)
22471 '(:org-license-to-kill t))))
22473 (message "Exporting...")
22475 (setq org-min-level (org-get-min-level lines))
22476 (setq org-last-level org-min-level)
22477 (org-init-section-numbers)
22479 (cond
22480 ((and date (string-match "%" date))
22481 (setq date (format-time-string date (current-time))))
22482 (date)
22483 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22485 ;; Get the language-dependent settings
22486 (setq lang-words (or (assoc language org-export-language-setup)
22487 (assoc "en" org-export-language-setup)))
22489 ;; Switch to the output buffer
22490 (set-buffer buffer)
22491 (erase-buffer)
22492 (fundamental-mode)
22494 (and (fboundp 'set-buffer-file-coding-system)
22495 (set-buffer-file-coding-system coding-system-for-write))
22497 (let ((case-fold-search nil)
22498 (org-odd-levels-only odd))
22499 ;; create local variables for all options, to make sure all called
22500 ;; functions get the correct information
22501 (mapcar (lambda (x)
22502 (set (make-local-variable (cdr x))
22503 (plist-get opt-plist (car x))))
22504 org-export-plist-vars)
22505 (setq umax (if arg (prefix-numeric-value arg)
22506 org-export-headline-levels))
22507 (setq umax-toc (if (integerp org-export-with-toc)
22508 (min org-export-with-toc umax)
22509 umax))
22510 (unless body-only
22511 ;; File header
22512 (insert (format
22513 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
22514 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
22515 <html xmlns=\"http://www.w3.org/1999/xhtml\"
22516 lang=\"%s\" xml:lang=\"%s\">
22517 <head>
22518 <title>%s</title>
22519 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
22520 <meta name=\"generator\" content=\"Org-mode\"/>
22521 <meta name=\"generated\" content=\"%s\"/>
22522 <meta name=\"author\" content=\"%s\"/>
22524 </head><body>
22526 language language (org-html-expand title)
22527 (or charset "iso-8859-1") date author style))
22529 (insert (or (plist-get opt-plist :preamble) ""))
22531 (when (plist-get opt-plist :auto-preamble)
22532 (if title (insert (format org-export-html-title-format
22533 (org-html-expand title))))))
22535 (if (and org-export-with-toc (not body-only))
22536 (progn
22537 (push (format "<h%d>%s</h%d>\n"
22538 org-export-html-toplevel-hlevel
22539 (nth 3 lang-words)
22540 org-export-html-toplevel-hlevel)
22541 thetoc)
22542 (push "<ul>\n<li>" thetoc)
22543 (setq lines
22544 (mapcar '(lambda (line)
22545 (if (string-match org-todo-line-regexp line)
22546 ;; This is a headline
22547 (progn
22548 (setq have-headings t)
22549 (setq level (- (match-end 1) (match-beginning 1))
22550 level (org-tr-level level)
22551 txt (save-match-data
22552 (org-html-expand
22553 (org-export-cleanup-toc-line
22554 (match-string 3 line))))
22555 todo
22556 (or (and org-export-mark-todo-in-toc
22557 (match-beginning 2)
22558 (not (member (match-string 2 line)
22559 org-done-keywords)))
22560 ; TODO, not DONE
22561 (and org-export-mark-todo-in-toc
22562 (= level umax-toc)
22563 (org-search-todo-below
22564 line lines level))))
22565 (if (and (memq org-export-with-tags '(not-in-toc nil))
22566 (string-match
22567 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22568 txt))
22569 (setq txt (replace-match "" t t txt)))
22570 (if (string-match quote-re0 txt)
22571 (setq txt (replace-match "" t t txt)))
22572 (if org-export-with-section-numbers
22573 (setq txt (concat (org-section-number level)
22574 " " txt)))
22575 (if (<= level (max umax umax-toc))
22576 (setq head-count (+ head-count 1)))
22577 (if (<= level umax-toc)
22578 (progn
22579 (if (> level org-last-level)
22580 (progn
22581 (setq cnt (- level org-last-level))
22582 (while (>= (setq cnt (1- cnt)) 0)
22583 (push "\n<ul>\n<li>" thetoc))
22584 (push "\n" thetoc)))
22585 (if (< level org-last-level)
22586 (progn
22587 (setq cnt (- org-last-level level))
22588 (while (>= (setq cnt (1- cnt)) 0)
22589 (push "</li>\n</ul>" thetoc))
22590 (push "\n" thetoc)))
22591 ;; Check for targets
22592 (while (string-match org-target-regexp line)
22593 (setq tg (match-string 1 line)
22594 line (replace-match
22595 (concat "@<span class=\"target\">" tg "@</span> ")
22596 t t line))
22597 (push (cons (org-solidify-link-text tg)
22598 (format "sec-%d" head-count))
22599 target-alist))
22600 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
22601 (setq txt (replace-match "" t t txt)))
22602 (push
22603 (format
22604 (if todo
22605 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
22606 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
22607 head-count txt) thetoc)
22609 (setq org-last-level level))
22611 line)
22612 lines))
22613 (while (> org-last-level (1- org-min-level))
22614 (setq org-last-level (1- org-last-level))
22615 (push "</li>\n</ul>\n" thetoc))
22616 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22618 (setq head-count 0)
22619 (org-init-section-numbers)
22621 (while (setq line (pop lines) origline line)
22622 (catch 'nextline
22624 ;; end of quote section?
22625 (when (and inquote (string-match "^\\*+ " line))
22626 (insert "</pre>\n")
22627 (setq inquote nil))
22628 ;; inside a quote section?
22629 (when inquote
22630 (insert (org-html-protect line) "\n")
22631 (throw 'nextline nil))
22633 ;; verbatim lines
22634 (when (and org-export-with-fixed-width
22635 (string-match "^[ \t]*:\\(.*\\)" line))
22636 (when (not infixed)
22637 (setq infixed t)
22638 (insert "<pre>\n"))
22639 (insert (org-html-protect (match-string 1 line)) "\n")
22640 (when (and lines
22641 (not (string-match "^[ \t]*\\(:.*\\)"
22642 (car lines))))
22643 (setq infixed nil)
22644 (insert "</pre>\n"))
22645 (throw 'nextline nil))
22647 ;; Protected HTML
22648 (when (get-text-property 0 'org-protected line)
22649 (let (par)
22650 (when (re-search-backward
22651 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
22652 (setq par (match-string 1))
22653 (replace-match "\\2\n"))
22654 (insert line "\n")
22655 (while (and lines
22656 (get-text-property 0 'org-protected (car lines)))
22657 (insert (pop lines) "\n"))
22658 (and par (insert "<p>\n")))
22659 (throw 'nextline nil))
22661 ;; Horizontal line
22662 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
22663 (insert "\n<hr/>\n")
22664 (throw 'nextline nil))
22666 ;; make targets to anchors
22667 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
22668 (cond
22669 ((match-end 2)
22670 (setq line (replace-match
22671 (concat "@<a name=\""
22672 (org-solidify-link-text (match-string 1 line))
22673 "\">\\nbsp@</a>")
22674 t t line)))
22675 ((and org-export-with-toc (equal (string-to-char line) ?*))
22676 (setq line (replace-match
22677 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
22678 ; (concat "@<i>" (match-string 1 line) "@</i> ")
22679 t t line)))
22681 (setq line (replace-match
22682 (concat "@<a name=\""
22683 (org-solidify-link-text (match-string 1 line))
22684 "\" class=\"target\">" (match-string 1 line) "@</a> ")
22685 t t line)))))
22687 (setq line (org-html-handle-time-stamps line))
22689 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
22690 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
22691 ;; Also handle sub_superscripts and checkboxes
22692 (setq line (org-html-expand line))
22694 ;; Format the links
22695 (setq start 0)
22696 (while (string-match org-bracket-link-analytic-regexp line start)
22697 (setq start (match-beginning 0))
22698 (setq type (if (match-end 2) (match-string 2 line) "internal"))
22699 (setq path (match-string 3 line))
22700 (setq desc1 (if (match-end 5) (match-string 5 line))
22701 desc2 (if (match-end 2) (concat type ":" path) path)
22702 descp (and desc1 (not (equal desc1 desc2)))
22703 desc (or desc1 desc2))
22704 ;; Make an image out of the description if that is so wanted
22705 (when (and descp (org-file-image-p desc))
22706 (save-match-data
22707 (if (string-match "^file:" desc)
22708 (setq desc (substring desc (match-end 0)))))
22709 (setq desc (concat "<img src=\"" desc "\"/>")))
22710 ;; FIXME: do we need to unescape here somewhere?
22711 (cond
22712 ((equal type "internal")
22713 (setq rpl
22714 (concat
22715 "<a href=\"#"
22716 (org-solidify-link-text
22717 (save-match-data (org-link-unescape path)) target-alist)
22718 "\">" desc "</a>")))
22719 ((member type '("http" "https"))
22720 ;; standard URL, just check if we need to inline an image
22721 (if (and (or (eq t org-export-html-inline-images)
22722 (and org-export-html-inline-images (not descp)))
22723 (org-file-image-p path))
22724 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
22725 (setq link (concat type ":" path))
22726 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
22727 ((member type '("ftp" "mailto" "news"))
22728 ;; standard URL
22729 (setq link (concat type ":" path))
22730 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
22731 ((string= type "file")
22732 ;; FILE link
22733 (let* ((filename path)
22734 (abs-p (file-name-absolute-p filename))
22735 thefile file-is-image-p search)
22736 (save-match-data
22737 (if (string-match "::\\(.*\\)" filename)
22738 (setq search (match-string 1 filename)
22739 filename (replace-match "" t nil filename)))
22740 (setq valid
22741 (if (functionp link-validate)
22742 (funcall link-validate filename current-dir)
22744 (setq file-is-image-p (org-file-image-p filename))
22745 (setq thefile (if abs-p (expand-file-name filename) filename))
22746 (when (and org-export-html-link-org-files-as-html
22747 (string-match "\\.org$" thefile))
22748 (setq thefile (concat (substring thefile 0
22749 (match-beginning 0))
22750 "." org-export-html-extension))
22751 (if (and search
22752 ;; make sure this is can be used as target search
22753 (not (string-match "^[0-9]*$" search))
22754 (not (string-match "^\\*" search))
22755 (not (string-match "^/.*/$" search)))
22756 (setq thefile (concat thefile "#"
22757 (org-solidify-link-text
22758 (org-link-unescape search)))))
22759 (when (string-match "^file:" desc)
22760 (setq desc (replace-match "" t t desc))
22761 (if (string-match "\\.org$" desc)
22762 (setq desc (replace-match "" t t desc))))))
22763 (setq rpl (if (and file-is-image-p
22764 (or (eq t org-export-html-inline-images)
22765 (and org-export-html-inline-images
22766 (not descp))))
22767 (concat "<img src=\"" thefile "\"/>")
22768 (concat "<a href=\"" thefile "\">" desc "</a>")))
22769 (if (not valid) (setq rpl desc))))
22770 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
22771 (setq rpl (concat "<i>&lt;" type ":"
22772 (save-match-data (org-link-unescape path))
22773 "&gt;</i>"))))
22774 (setq line (replace-match rpl t t line)
22775 start (+ start (length rpl))))
22777 ;; TODO items
22778 (if (and (string-match org-todo-line-regexp line)
22779 (match-beginning 2))
22781 (setq line
22782 (concat (substring line 0 (match-beginning 2))
22783 "<span class=\""
22784 (if (member (match-string 2 line)
22785 org-done-keywords)
22786 "done" "todo")
22787 "\">" (match-string 2 line)
22788 "</span>" (substring line (match-end 2)))))
22790 ;; Does this contain a reference to a footnote?
22791 (when org-export-with-footnotes
22792 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
22793 (let ((n (match-string 2 line)))
22794 (setq line
22795 (replace-match
22796 (format
22797 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
22798 (match-string 1 line) n n n)
22799 t t line)))))
22801 (cond
22802 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22803 ;; This is a headline
22804 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22805 txt (match-string 2 line))
22806 (if (string-match quote-re0 txt)
22807 (setq txt (replace-match "" t t txt)))
22808 (if (<= level (max umax umax-toc))
22809 (setq head-count (+ head-count 1)))
22810 (when in-local-list
22811 ;; Close any local lists before inserting a new header line
22812 (while local-list-num
22813 (org-close-li)
22814 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
22815 (pop local-list-num))
22816 (setq local-list-indent nil
22817 in-local-list nil))
22818 (setq first-heading-pos (or first-heading-pos (point)))
22819 (org-html-level-start level txt umax
22820 (and org-export-with-toc (<= level umax))
22821 head-count)
22822 ;; QUOTES
22823 (when (string-match quote-re line)
22824 (insert "<pre>")
22825 (setq inquote t)))
22827 ((and org-export-with-tables
22828 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22829 (if (not table-open)
22830 ;; New table starts
22831 (setq table-open t table-buffer nil table-orig-buffer nil))
22832 ;; Accumulate lines
22833 (setq table-buffer (cons line table-buffer)
22834 table-orig-buffer (cons origline table-orig-buffer))
22835 (when (or (not lines)
22836 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22837 (car lines))))
22838 (setq table-open nil
22839 table-buffer (nreverse table-buffer)
22840 table-orig-buffer (nreverse table-orig-buffer))
22841 (org-close-par-maybe)
22842 (insert (org-format-table-html table-buffer table-orig-buffer))))
22844 ;; Normal lines
22845 (when (string-match
22846 (cond
22847 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22848 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22849 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22850 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
22851 line)
22852 (setq ind (org-get-string-indentation line)
22853 start-is-num (match-beginning 4)
22854 starter (if (match-beginning 2)
22855 (substring (match-string 2 line) 0 -1))
22856 line (substring line (match-beginning 5)))
22857 (unless (string-match "[^ \t]" line)
22858 ;; empty line. Pretend indentation is large.
22859 (setq ind (if org-empty-line-terminates-plain-lists
22861 (1+ (or (car local-list-indent) 1)))))
22862 (setq didclose nil)
22863 (while (and in-local-list
22864 (or (and (= ind (car local-list-indent))
22865 (not starter))
22866 (< ind (car local-list-indent))))
22867 (setq didclose t)
22868 (org-close-li)
22869 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
22870 (pop local-list-num) (pop local-list-indent)
22871 (setq in-local-list local-list-indent))
22872 (cond
22873 ((and starter
22874 (or (not in-local-list)
22875 (> ind (car local-list-indent))))
22876 ;; Start new (level of) list
22877 (org-close-par-maybe)
22878 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
22879 (push start-is-num local-list-num)
22880 (push ind local-list-indent)
22881 (setq in-local-list t))
22882 (starter
22883 ;; continue current list
22884 (org-close-li)
22885 (insert "<li>\n"))
22886 (didclose
22887 ;; we did close a list, normal text follows: need <p>
22888 (org-open-par)))
22889 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
22890 (setq line
22891 (replace-match
22892 (if (equal (match-string 1 line) "X")
22893 "<b>[X]</b>"
22894 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
22895 t t line))))
22897 ;; Empty lines start a new paragraph. If hand-formatted lists
22898 ;; are not fully interpreted, lines starting with "-", "+", "*"
22899 ;; also start a new paragraph.
22900 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
22902 ;; Is this the start of a footnote?
22903 (when org-export-with-footnotes
22904 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
22905 (org-close-par-maybe)
22906 (let ((n (match-string 1 line)))
22907 (setq line (replace-match
22908 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
22910 ;; Check if the line break needs to be conserved
22911 (cond
22912 ((string-match "\\\\\\\\[ \t]*$" line)
22913 (setq line (replace-match "<br/>" t t line)))
22914 (org-export-preserve-breaks
22915 (setq line (concat line "<br/>"))))
22917 (insert line "\n")))))
22919 ;; Properly close all local lists and other lists
22920 (when inquote (insert "</pre>\n"))
22921 (when in-local-list
22922 ;; Close any local lists before inserting a new header line
22923 (while local-list-num
22924 (org-close-li)
22925 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
22926 (pop local-list-num))
22927 (setq local-list-indent nil
22928 in-local-list nil))
22929 (org-html-level-start 1 nil umax
22930 (and org-export-with-toc (<= level umax))
22931 head-count)
22933 (unless body-only
22934 (when (plist-get opt-plist :auto-postamble)
22935 (when (and org-export-author-info author)
22936 (insert "<p class=\"author\"> "
22937 (nth 1 lang-words) ": " author "\n")
22938 (when email
22939 (insert "<a href=\"mailto:" email "\">&lt;"
22940 email "&gt;</a>\n"))
22941 (insert "</p>\n"))
22942 (when (and date org-export-time-stamp-file)
22943 (insert "<p class=\"date\"> "
22944 (nth 2 lang-words) ": "
22945 date "</p>\n")))
22947 (if org-export-html-with-timestamp
22948 (insert org-export-html-html-helper-timestamp))
22949 (insert (or (plist-get opt-plist :postamble) ""))
22950 (insert "</body>\n</html>\n"))
22952 (normal-mode)
22953 (if (eq major-mode default-major-mode) (html-mode))
22955 ;; insert the table of contents
22956 (goto-char (point-min))
22957 (when thetoc
22958 (if (or (re-search-forward
22959 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
22960 (re-search-forward
22961 "\\[TABLE-OF-CONTENTS\\]" nil t))
22962 (progn
22963 (goto-char (match-beginning 0))
22964 (replace-match ""))
22965 (goto-char first-heading-pos)
22966 (when (looking-at "\\s-*</p>")
22967 (goto-char (match-end 0))
22968 (insert "\n")))
22969 (mapc 'insert thetoc))
22970 ;; remove empty paragraphs and lists
22971 (goto-char (point-min))
22972 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
22973 (replace-match ""))
22974 (goto-char (point-min))
22975 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
22976 (replace-match ""))
22977 (or to-buffer (save-buffer))
22978 (goto-char (point-min))
22979 (message "Exporting... done")
22980 (if (eq to-buffer 'string)
22981 (prog1 (buffer-substring (point-min) (point-max))
22982 (kill-buffer (current-buffer)))
22983 (current-buffer)))))
22985 (defvar org-table-colgroup-info nil)
22986 (defun org-format-table-ascii (lines)
22987 "Format a table for ascii export."
22988 (if (stringp lines)
22989 (setq lines (org-split-string lines "\n")))
22990 (if (not (string-match "^[ \t]*|" (car lines)))
22991 ;; Table made by table.el - test for spanning
22992 lines
22994 ;; A normal org table
22995 ;; Get rid of hlines at beginning and end
22996 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22997 (setq lines (nreverse lines))
22998 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22999 (setq lines (nreverse lines))
23000 (when org-export-table-remove-special-lines
23001 ;; Check if the table has a marking column. If yes remove the
23002 ;; column and the special lines
23003 (setq lines (org-table-clean-before-export lines)))
23004 ;; Get rid of the vertical lines except for grouping
23005 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
23006 rtn line vl1 start)
23007 (while (setq line (pop lines))
23008 (if (string-match org-table-hline-regexp line)
23009 (and (string-match "|\\(.*\\)|" line)
23010 (setq line (replace-match " \\1" t nil line)))
23011 (setq start 0 vl1 vl)
23012 (while (string-match "|" line start)
23013 (setq start (match-end 0))
23014 (or (pop vl1) (setq line (replace-match " " t t line)))))
23015 (push line rtn))
23016 (nreverse rtn))))
23018 (defun org-colgroup-info-to-vline-list (info)
23019 (let (vl new last)
23020 (while info
23021 (setq last new new (pop info))
23022 (if (or (memq last '(:end :startend))
23023 (memq new '(:start :startend)))
23024 (push t vl)
23025 (push nil vl)))
23026 (setq vl (nreverse vl))
23027 (and vl (setcar vl nil))
23028 vl))
23030 (defun org-format-table-html (lines olines)
23031 "Find out which HTML converter to use and return the HTML code."
23032 (if (stringp lines)
23033 (setq lines (org-split-string lines "\n")))
23034 (if (string-match "^[ \t]*|" (car lines))
23035 ;; A normal org table
23036 (org-format-org-table-html lines)
23037 ;; Table made by table.el - test for spanning
23038 (let* ((hlines (delq nil (mapcar
23039 (lambda (x)
23040 (if (string-match "^[ \t]*\\+-" x) x
23041 nil))
23042 lines)))
23043 (first (car hlines))
23044 (ll (and (string-match "\\S-+" first)
23045 (match-string 0 first)))
23046 (re (concat "^[ \t]*" (regexp-quote ll)))
23047 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
23048 hlines))))
23049 (if (and (not spanning)
23050 (not org-export-prefer-native-exporter-for-tables))
23051 ;; We can use my own converter with HTML conversions
23052 (org-format-table-table-html lines)
23053 ;; Need to use the code generator in table.el, with the original text.
23054 (org-format-table-table-html-using-table-generate-source olines)))))
23056 (defun org-format-org-table-html (lines &optional splice)
23057 "Format a table into HTML."
23058 ;; Get rid of hlines at beginning and end
23059 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23060 (setq lines (nreverse lines))
23061 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23062 (setq lines (nreverse lines))
23063 (when org-export-table-remove-special-lines
23064 ;; Check if the table has a marking column. If yes remove the
23065 ;; column and the special lines
23066 (setq lines (org-table-clean-before-export lines)))
23068 (let ((head (and org-export-highlight-first-table-line
23069 (delq nil (mapcar
23070 (lambda (x) (string-match "^[ \t]*|-" x))
23071 (cdr lines)))))
23072 (nlines 0) fnum i
23073 tbopen line fields html gr colgropen)
23074 (if splice (setq head nil))
23075 (unless splice (push (if head "<thead>" "<tbody>") html))
23076 (setq tbopen t)
23077 (while (setq line (pop lines))
23078 (catch 'next-line
23079 (if (string-match "^[ \t]*|-" line)
23080 (progn
23081 (unless splice
23082 (push (if head "</thead>" "</tbody>") html)
23083 (if lines (push "<tbody>" html) (setq tbopen nil)))
23084 (setq head nil) ;; head ends here, first time around
23085 ;; ignore this line
23086 (throw 'next-line t)))
23087 ;; Break the line into fields
23088 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23089 (unless fnum (setq fnum (make-vector (length fields) 0)))
23090 (setq nlines (1+ nlines) i -1)
23091 (push (concat "<tr>"
23092 (mapconcat
23093 (lambda (x)
23094 (setq i (1+ i))
23095 (if (and (< i nlines)
23096 (string-match org-table-number-regexp x))
23097 (incf (aref fnum i)))
23098 (if head
23099 (concat (car org-export-table-header-tags) x
23100 (cdr org-export-table-header-tags))
23101 (concat (car org-export-table-data-tags) x
23102 (cdr org-export-table-data-tags))))
23103 fields "")
23104 "</tr>")
23105 html)))
23106 (unless splice (if tbopen (push "</tbody>" html)))
23107 (unless splice (push "</table>\n" html))
23108 (setq html (nreverse html))
23109 (unless splice
23110 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
23111 (push (mapconcat
23112 (lambda (x)
23113 (setq gr (pop org-table-colgroup-info))
23114 (format "%s<COL align=\"%s\"></COL>%s"
23115 (if (memq gr '(:start :startend))
23116 (prog1
23117 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
23118 (setq colgropen t))
23120 (if (> (/ (float x) nlines) org-table-number-fraction)
23121 "right" "left")
23122 (if (memq gr '(:end :startend))
23123 (progn (setq colgropen nil) "</colgroup>")
23124 "")))
23125 fnum "")
23126 html)
23127 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
23128 (push org-export-html-table-tag html))
23129 (concat (mapconcat 'identity html "\n") "\n")))
23131 (defun org-table-clean-before-export (lines)
23132 "Check if the table has a marking column.
23133 If yes remove the column and the special lines."
23134 (setq org-table-colgroup-info nil)
23135 (if (memq nil
23136 (mapcar
23137 (lambda (x) (or (string-match "^[ \t]*|-" x)
23138 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
23139 lines))
23140 (progn
23141 (setq org-table-clean-did-remove-column nil)
23142 (delq nil
23143 (mapcar
23144 (lambda (x)
23145 (cond
23146 ((string-match "^[ \t]*| */ *|" x)
23147 (setq org-table-colgroup-info
23148 (mapcar (lambda (x)
23149 (cond ((member x '("<" "&lt;")) :start)
23150 ((member x '(">" "&gt;")) :end)
23151 ((member x '("<>" "&lt;&gt;")) :startend)
23152 (t nil)))
23153 (org-split-string x "[ \t]*|[ \t]*")))
23154 nil)
23155 (t x)))
23156 lines)))
23157 (setq org-table-clean-did-remove-column t)
23158 (delq nil
23159 (mapcar
23160 (lambda (x)
23161 (cond
23162 ((string-match "^[ \t]*| */ *|" x)
23163 (setq org-table-colgroup-info
23164 (mapcar (lambda (x)
23165 (cond ((member x '("<" "&lt;")) :start)
23166 ((member x '(">" "&gt;")) :end)
23167 ((member x '("<>" "&lt;&gt;")) :startend)
23168 (t nil)))
23169 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
23170 nil)
23171 ((string-match "^[ \t]*| *[!_^/] *|" x)
23172 nil) ; ignore this line
23173 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
23174 (string-match "^\\([ \t]*\\)|[^|]*|" x))
23175 ;; remove the first column
23176 (replace-match "\\1|" t nil x))
23177 (t (error "This should not happen"))))
23178 lines))))
23180 (defun org-format-table-table-html (lines)
23181 "Format a table generated by table.el into HTML.
23182 This conversion does *not* use `table-generate-source' from table.el.
23183 This has the advantage that Org-mode's HTML conversions can be used.
23184 But it has the disadvantage, that no cell- or row-spanning is allowed."
23185 (let (line field-buffer
23186 (head org-export-highlight-first-table-line)
23187 fields html empty)
23188 (setq html (concat org-export-html-table-tag "\n"))
23189 (while (setq line (pop lines))
23190 (setq empty "&nbsp;")
23191 (catch 'next-line
23192 (if (string-match "^[ \t]*\\+-" line)
23193 (progn
23194 (if field-buffer
23195 (progn
23196 (setq
23197 html
23198 (concat
23199 html
23200 "<tr>"
23201 (mapconcat
23202 (lambda (x)
23203 (if (equal x "") (setq x empty))
23204 (if head
23205 (concat (car org-export-table-header-tags) x
23206 (cdr org-export-table-header-tags))
23207 (concat (car org-export-table-data-tags) x
23208 (cdr org-export-table-data-tags))))
23209 field-buffer "\n")
23210 "</tr>\n"))
23211 (setq head nil)
23212 (setq field-buffer nil)))
23213 ;; Ignore this line
23214 (throw 'next-line t)))
23215 ;; Break the line into fields and store the fields
23216 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
23217 (if field-buffer
23218 (setq field-buffer (mapcar
23219 (lambda (x)
23220 (concat x "<br/>" (pop fields)))
23221 field-buffer))
23222 (setq field-buffer fields))))
23223 (setq html (concat html "</table>\n"))
23224 html))
23226 (defun org-format-table-table-html-using-table-generate-source (lines)
23227 "Format a table into html, using `table-generate-source' from table.el.
23228 This has the advantage that cell- or row-spanning is allowed.
23229 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
23230 (require 'table)
23231 (with-current-buffer (get-buffer-create " org-tmp1 ")
23232 (erase-buffer)
23233 (insert (mapconcat 'identity lines "\n"))
23234 (goto-char (point-min))
23235 (if (not (re-search-forward "|[^+]" nil t))
23236 (error "Error processing table"))
23237 (table-recognize-table)
23238 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
23239 (table-generate-source 'html " org-tmp2 ")
23240 (set-buffer " org-tmp2 ")
23241 (buffer-substring (point-min) (point-max))))
23243 (defun org-html-handle-time-stamps (s)
23244 "Format time stamps in string S, or remove them."
23245 (catch 'exit
23246 (let (r b)
23247 (while (string-match org-maybe-keyword-time-regexp s)
23248 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
23249 ;; never export CLOCK
23250 (throw 'exit ""))
23251 (or b (setq b (substring s 0 (match-beginning 0))))
23252 (if (not org-export-with-timestamps)
23253 (setq r (concat r (substring s 0 (match-beginning 0)))
23254 s (substring s (match-end 0)))
23255 (setq r (concat
23256 r (substring s 0 (match-beginning 0))
23257 (if (match-end 1)
23258 (format "@<span class=\"timestamp-kwd\">%s @</span>"
23259 (match-string 1 s)))
23260 (format " @<span class=\"timestamp\">%s@</span>"
23261 (substring
23262 (org-translate-time (match-string 3 s)) 1 -1)))
23263 s (substring s (match-end 0)))))
23264 ;; Line break if line started and ended with time stamp stuff
23265 (if (not r)
23267 (setq r (concat r s))
23268 (unless (string-match "\\S-" (concat b s))
23269 (setq r (concat r "@<br/>")))
23270 r))))
23272 (defun org-html-protect (s)
23273 ;; convert & to &amp;, < to &lt; and > to &gt;
23274 (let ((start 0))
23275 (while (string-match "&" s start)
23276 (setq s (replace-match "&amp;" t t s)
23277 start (1+ (match-beginning 0))))
23278 (while (string-match "<" s)
23279 (setq s (replace-match "&lt;" t t s)))
23280 (while (string-match ">" s)
23281 (setq s (replace-match "&gt;" t t s))))
23284 (defun org-export-cleanup-toc-line (s)
23285 "Remove tags and time staps from lines going into the toc."
23286 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
23287 (setq s (replace-match "" t t s)))
23288 (when org-export-remove-timestamps-from-toc
23289 (while (string-match org-maybe-keyword-time-regexp s)
23290 (setq s (replace-match "" t t s))))
23291 (while (string-match org-bracket-link-regexp s)
23292 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
23293 t t s)))
23296 (defun org-html-expand (string)
23297 "Prepare STRING for HTML export. Applies all active conversions.
23298 If there are links in the string, don't modify these."
23299 (let* (m s l res)
23300 (while (setq m (string-match org-bracket-link-regexp string))
23301 (setq s (substring string 0 m)
23302 l (match-string 0 string)
23303 string (substring string (match-end 0)))
23304 (push (org-html-do-expand s) res)
23305 (push l res))
23306 (push (org-html-do-expand string) res)
23307 (apply 'concat (nreverse res))))
23309 (defun org-html-do-expand (s)
23310 "Apply all active conversions to translate special ASCII to HTML."
23311 (setq s (org-html-protect s))
23312 (if org-export-html-expand
23313 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
23314 (setq s (replace-match "<\\1>" t nil s))))
23315 (if org-export-with-emphasize
23316 (setq s (org-export-html-convert-emphasize s)))
23317 (if org-export-with-sub-superscripts
23318 (setq s (org-export-html-convert-sub-super s)))
23319 (if org-export-with-TeX-macros
23320 (let ((start 0) wd ass)
23321 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
23322 (setq wd (match-string 1 s))
23323 (if (setq ass (assoc wd org-html-entities))
23324 (setq s (replace-match (or (cdr ass)
23325 (concat "&" (car ass) ";"))
23326 t t s))
23327 (setq start (+ start (length wd)))))))
23330 (defun org-create-multibrace-regexp (left right n)
23331 "Create a regular expression which will match a balanced sexp.
23332 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
23333 as single character strings.
23334 The regexp returned will match the entire expression including the
23335 delimiters. It will also define a single group which contains the
23336 match except for the outermost delimiters. The maximum depth of
23337 stacked delimiters is N. Escaping delimiters is not possible."
23338 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
23339 (or "\\|")
23340 (re nothing)
23341 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
23342 (while (> n 1)
23343 (setq n (1- n)
23344 re (concat re or next)
23345 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
23346 (concat left "\\(" re "\\)" right)))
23348 (defvar org-match-substring-regexp
23349 (concat
23350 "\\([^\\]\\)\\([_^]\\)\\("
23351 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
23352 "\\|"
23353 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
23354 "\\|"
23355 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
23356 "The regular expression matching a sub- or superscript.")
23358 ;(let ((s "a\\_b"))
23359 ; (and (string-match org-match-substring-regexp s)
23360 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
23362 (defun org-export-html-convert-sub-super (string)
23363 "Convert sub- and superscripts in STRING to HTML."
23364 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
23365 (while (string-match org-match-substring-regexp string s)
23366 (if (and requireb (match-end 8))
23367 (setq s (match-end 2))
23368 (setq s (match-end 1)
23369 key (if (string= (match-string 2 string) "_") "sub" "sup")
23370 c (or (match-string 8 string)
23371 (match-string 6 string)
23372 (match-string 5 string))
23373 string (replace-match
23374 (concat (match-string 1 string)
23375 "<" key ">" c "</" key ">")
23376 t t string))))
23377 (while (string-match "\\\\\\([_^]\\)" string)
23378 (setq string (replace-match (match-string 1 string) t t string)))
23379 string))
23381 (defun org-export-html-convert-emphasize (string)
23382 "Apply emphasis."
23383 (let ((s 0))
23384 (while (string-match org-emph-re string s)
23385 (if (not (equal
23386 (substring string (match-beginning 3) (1+ (match-beginning 3)))
23387 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
23388 (setq string (replace-match
23389 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
23390 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
23391 "\\5") t nil string))
23392 (setq s (1+ s))))
23393 string))
23395 (defvar org-par-open nil)
23396 (defun org-open-par ()
23397 "Insert <p>, but first close previous paragraph if any."
23398 (org-close-par-maybe)
23399 (insert "\n<p>")
23400 (setq org-par-open t))
23401 (defun org-close-par-maybe ()
23402 "Close paragraph if there is one open."
23403 (when org-par-open
23404 (insert "</p>")
23405 (setq org-par-open nil)))
23406 (defun org-close-li ()
23407 "Close <li> if necessary."
23408 (org-close-par-maybe)
23409 (insert "</li>\n"))
23411 (defvar body-only) ; dynamically scoped into this.
23412 (defun org-html-level-start (level title umax with-toc head-count)
23413 "Insert a new level in HTML export.
23414 When TITLE is nil, just close all open levels."
23415 (org-close-par-maybe)
23416 (let ((l (1+ (max level umax))))
23417 (while (<= l org-level-max)
23418 (if (aref org-levels-open (1- l))
23419 (progn
23420 (org-html-level-close l)
23421 (aset org-levels-open (1- l) nil)))
23422 (setq l (1+ l)))
23423 (when title
23424 ;; If title is nil, this means this function is called to close
23425 ;; all levels, so the rest is done only if title is given
23426 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23427 (setq title (replace-match
23428 (if org-export-with-tags
23429 (save-match-data
23430 (concat
23431 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
23432 (mapconcat 'identity (org-split-string
23433 (match-string 1 title) ":")
23434 "&nbsp;")
23435 "</span>"))
23437 t t title)))
23438 (if (> level umax)
23439 (progn
23440 (if (aref org-levels-open (1- level))
23441 (progn
23442 (org-close-li)
23443 (insert "<li>" title "<br/>\n"))
23444 (aset org-levels-open (1- level) t)
23445 (org-close-par-maybe)
23446 (insert "<ul>\n<li>" title "<br/>\n")))
23447 (if (and org-export-with-section-numbers (not body-only))
23448 (setq title (concat (org-section-number level) " " title)))
23449 (setq level (+ level org-export-html-toplevel-hlevel -1))
23450 (if with-toc
23451 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
23452 level head-count title level))
23453 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
23454 (org-open-par)))))
23456 (defun org-html-level-close (&rest args)
23457 "Terminate one level in HTML export."
23458 (org-close-li)
23459 (insert "</ul>\n"))
23461 ;;; iCalendar export
23463 ;;;###autoload
23464 (defun org-export-icalendar-this-file ()
23465 "Export current file as an iCalendar file.
23466 The iCalendar file will be located in the same directory as the Org-mode
23467 file, but with extension `.ics'."
23468 (interactive)
23469 (org-export-icalendar nil buffer-file-name))
23471 ;;;###autoload
23472 (defun org-export-icalendar-all-agenda-files ()
23473 "Export all files in `org-agenda-files' to iCalendar .ics files.
23474 Each iCalendar file will be located in the same directory as the Org-mode
23475 file, but with extension `.ics'."
23476 (interactive)
23477 (apply 'org-export-icalendar nil (org-agenda-files t)))
23479 ;;;###autoload
23480 (defun org-export-icalendar-combine-agenda-files ()
23481 "Export all files in `org-agenda-files' to a single combined iCalendar file.
23482 The file is stored under the name `org-combined-agenda-icalendar-file'."
23483 (interactive)
23484 (apply 'org-export-icalendar t (org-agenda-files t)))
23486 (defun org-export-icalendar (combine &rest files)
23487 "Create iCalendar files for all elements of FILES.
23488 If COMBINE is non-nil, combine all calendar entries into a single large
23489 file and store it under the name `org-combined-agenda-icalendar-file'."
23490 (save-excursion
23491 (org-prepare-agenda-buffers files)
23492 (let* ((dir (org-export-directory
23493 :ical (list :publishing-directory
23494 org-export-publishing-directory)))
23495 file ical-file ical-buffer category started org-agenda-new-buffers)
23497 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
23498 (when combine
23499 (setq ical-file
23500 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
23501 org-combined-agenda-icalendar-file
23502 (expand-file-name org-combined-agenda-icalendar-file dir))
23503 ical-buffer (org-get-agenda-file-buffer ical-file))
23504 (set-buffer ical-buffer) (erase-buffer))
23505 (while (setq file (pop files))
23506 (catch 'nextfile
23507 (org-check-agenda-file file)
23508 (set-buffer (org-get-agenda-file-buffer file))
23509 (unless combine
23510 (setq ical-file (concat (file-name-as-directory dir)
23511 (file-name-sans-extension
23512 (file-name-nondirectory buffer-file-name))
23513 ".ics"))
23514 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
23515 (with-current-buffer ical-buffer (erase-buffer)))
23516 (setq category (or org-category
23517 (file-name-sans-extension
23518 (file-name-nondirectory buffer-file-name))))
23519 (if (symbolp category) (setq category (symbol-name category)))
23520 (let ((standard-output ical-buffer))
23521 (if combine
23522 (and (not started) (setq started t)
23523 (org-start-icalendar-file org-icalendar-combined-name))
23524 (org-start-icalendar-file category))
23525 (org-print-icalendar-entries combine)
23526 (when (or (and combine (not files)) (not combine))
23527 (org-finish-icalendar-file)
23528 (set-buffer ical-buffer)
23529 (save-buffer)
23530 (run-hooks 'org-after-save-iCalendar-file-hook)))))
23531 (org-release-buffers org-agenda-new-buffers))))
23533 (defvar org-after-save-iCalendar-file-hook nil
23534 "Hook run after an iCalendar file has been saved.
23535 The iCalendar buffer is still current when this hook is run.
23536 A good way to use this is to tell a desktop calenndar application to re-read
23537 the iCalendar file.")
23539 (defun org-print-icalendar-entries (&optional combine)
23540 "Print iCalendar entries for the current Org-mode file to `standard-output'.
23541 When COMBINE is non nil, add the category to each line."
23542 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
23543 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
23544 (dts (org-ical-ts-to-string
23545 (format-time-string (cdr org-time-stamp-formats) (current-time))
23546 "DTSTART"))
23547 hd ts ts2 state status (inc t) pos b sexp rrule
23548 scheduledp deadlinep tmp pri category entry location summary desc
23549 (sexp-buffer (get-buffer-create "*ical-tmp*")))
23550 (org-refresh-category-properties)
23551 (save-excursion
23552 (goto-char (point-min))
23553 (while (re-search-forward re1 nil t)
23554 (catch :skip
23555 (org-agenda-skip)
23556 (setq pos (match-beginning 0)
23557 ts (match-string 0)
23558 inc t
23559 hd (org-get-heading)
23560 summary (org-entry-get nil "SUMMARY")
23561 desc (or (org-entry-get nil "DESCRIPTION")
23562 (org-get-cleaned-entry org-icalendar-include-body))
23563 location (org-entry-get nil "LOCATION")
23564 category (org-get-category))
23565 (if (looking-at re2)
23566 (progn
23567 (goto-char (match-end 0))
23568 (setq ts2 (match-string 1) inc nil))
23569 (setq tmp (buffer-substring (max (point-min)
23570 (- pos org-ds-keyword-length))
23571 pos)
23572 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
23573 (progn
23574 (setq inc nil)
23575 (replace-match "\\1" t nil ts))
23577 deadlinep (string-match org-deadline-regexp tmp)
23578 scheduledp (string-match org-scheduled-regexp tmp)
23579 ;; donep (org-entry-is-done-p)
23581 (if (or (string-match org-tr-regexp hd)
23582 (string-match org-ts-regexp hd))
23583 (setq hd (replace-match "" t t hd)))
23584 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
23585 (setq rrule
23586 (concat "\nRRULE:FREQ="
23587 (cdr (assoc
23588 (match-string 2 ts)
23589 '(("d" . "DAILY")("w" . "WEEKLY")
23590 ("m" . "MONTHLY")("y" . "YEARLY"))))
23591 ";INTERVAL=" (match-string 1 ts)))
23592 (setq rrule ""))
23593 (setq summary (or summary hd))
23594 (if (string-match org-bracket-link-regexp summary)
23595 (setq summary
23596 (replace-match (if (match-end 3)
23597 (match-string 3 summary)
23598 (match-string 1 summary))
23599 t t summary)))
23600 (if deadlinep (setq summary (concat "DL: " summary)))
23601 (if scheduledp (setq summary (concat "S: " summary)))
23602 (if (string-match "\\`<%%" ts)
23603 (with-current-buffer sexp-buffer
23604 (insert (substring ts 1 -1) " " summary "\n"))
23605 (princ (format "BEGIN:VEVENT
23607 %s%s
23608 SUMMARY:%s%s%s
23609 CATEGORIES:%s
23610 END:VEVENT\n"
23611 (org-ical-ts-to-string ts "DTSTART")
23612 (org-ical-ts-to-string ts2 "DTEND" inc)
23613 rrule summary
23614 (if (and desc (string-match "\\S-" desc))
23615 (concat "\nDESCRIPTION: " desc) "")
23616 (if (and location (string-match "\\S-" location))
23617 (concat "\nLOCATION: " location) "")
23618 category)))))
23620 (when (and org-icalendar-include-sexps
23621 (condition-case nil (require 'icalendar) (error nil))
23622 (fboundp 'icalendar-export-region))
23623 ;; Get all the literal sexps
23624 (goto-char (point-min))
23625 (while (re-search-forward "^&?%%(" nil t)
23626 (catch :skip
23627 (org-agenda-skip)
23628 (setq b (match-beginning 0))
23629 (goto-char (1- (match-end 0)))
23630 (forward-sexp 1)
23631 (end-of-line 1)
23632 (setq sexp (buffer-substring b (point)))
23633 (with-current-buffer sexp-buffer
23634 (insert sexp "\n"))
23635 (princ (org-diary-to-ical-string sexp-buffer)))))
23637 (when org-icalendar-include-todo
23638 (goto-char (point-min))
23639 (while (re-search-forward org-todo-line-regexp nil t)
23640 (catch :skip
23641 (org-agenda-skip)
23642 (setq state (match-string 2))
23643 (setq status (if (member state org-done-keywords)
23644 "COMPLETED" "NEEDS-ACTION"))
23645 (when (and state
23646 (or (not (member state org-done-keywords))
23647 (eq org-icalendar-include-todo 'all))
23648 (not (member org-archive-tag (org-get-tags-at)))
23650 (setq hd (match-string 3)
23651 summary (org-entry-get nil "SUMMARY")
23652 desc (or (org-entry-get nil "DESCRIPTION")
23653 (org-get-cleaned-entry org-icalendar-include-body))
23654 location (org-entry-get nil "LOCATION"))
23655 (if (string-match org-bracket-link-regexp hd)
23656 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
23657 (match-string 1 hd))
23658 t t hd)))
23659 (if (string-match org-priority-regexp hd)
23660 (setq pri (string-to-char (match-string 2 hd))
23661 hd (concat (substring hd 0 (match-beginning 1))
23662 (substring hd (match-end 1))))
23663 (setq pri org-default-priority))
23664 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
23665 (- org-lowest-priority org-highest-priority))))))
23667 (princ (format "BEGIN:VTODO
23669 SUMMARY:%s%s%s
23670 CATEGORIES:%s
23671 SEQUENCE:1
23672 PRIORITY:%d
23673 STATUS:%s
23674 END:VTODO\n"
23676 (or summary hd)
23677 (if (and location (string-match "\\S-" location))
23678 (concat "\nLOCATION: " location) "")
23679 (if (and desc (string-match "\\S-" desc))
23680 (concat "\nDESCRIPTION: " desc) "")
23681 category pri status)))))))))
23683 (defun org-get-cleaned-entry (what)
23684 "Clean-up description string."
23685 (when what
23686 (save-excursion
23687 (org-back-to-heading t)
23688 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
23689 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
23690 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
23691 (while (string-match re s) (setq s (replace-match "" t t s)))
23692 (while (string-match re2 s) (setq s (replace-match "" t t s)))
23693 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
23694 (while (string-match "[ \t]*\n[ \t]*" s)
23695 (setq s (replace-match "\\n" t t s)))
23696 (setq s (org-trim s))
23697 (if (and (numberp what)
23698 (> (length s) what))
23699 (substring s 0 what)
23700 s)))))
23702 (defun org-start-icalendar-file (name)
23703 "Start an iCalendar file by inserting the header."
23704 (let ((user user-full-name)
23705 (name (or name "unknown"))
23706 (timezone (cadr (current-time-zone))))
23707 (princ
23708 (format "BEGIN:VCALENDAR
23709 VERSION:2.0
23710 X-WR-CALNAME:%s
23711 PRODID:-//%s//Emacs with Org-mode//EN
23712 X-WR-TIMEZONE:%s
23713 CALSCALE:GREGORIAN\n" name user timezone))))
23715 (defun org-finish-icalendar-file ()
23716 "Finish an iCalendar file by inserting the END statement."
23717 (princ "END:VCALENDAR\n"))
23719 (defun org-ical-ts-to-string (s keyword &optional inc)
23720 "Take a time string S and convert it to iCalendar format.
23721 KEYWORD is added in front, to make a complete line like DTSTART....
23722 When INC is non-nil, increase the hour by two (if time string contains
23723 a time), or the day by one (if it does not contain a time)."
23724 (let ((t1 (org-parse-time-string s 'nodefault))
23725 t2 fmt have-time time)
23726 (if (and (car t1) (nth 1 t1) (nth 2 t1))
23727 (setq t2 t1 have-time t)
23728 (setq t2 (org-parse-time-string s)))
23729 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
23730 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
23731 (when inc
23732 (if have-time
23733 (if org-agenda-default-appointment-duration
23734 (setq mi (+ org-agenda-default-appointment-duration mi))
23735 (setq h (+ 2 h)))
23736 (setq d (1+ d))))
23737 (setq time (encode-time s mi h d m y)))
23738 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
23739 (concat keyword (format-time-string fmt time))))
23741 ;;; XOXO export
23743 (defun org-export-as-xoxo-insert-into (buffer &rest output)
23744 (with-current-buffer buffer
23745 (apply 'insert output)))
23746 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
23748 (defun org-export-as-xoxo (&optional buffer)
23749 "Export the org buffer as XOXO.
23750 The XOXO buffer is named *xoxo-<source buffer name>*"
23751 (interactive (list (current-buffer)))
23752 ;; A quickie abstraction
23754 ;; Output everything as XOXO
23755 (with-current-buffer (get-buffer buffer)
23756 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
23757 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23758 (org-infile-export-plist)))
23759 (filename (concat (file-name-as-directory
23760 (org-export-directory :xoxo opt-plist))
23761 (file-name-sans-extension
23762 (file-name-nondirectory buffer-file-name))
23763 ".html"))
23764 (out (find-file-noselect filename))
23765 (last-level 1)
23766 (hanging-li nil))
23767 ;; Check the output buffer is empty.
23768 (with-current-buffer out (erase-buffer))
23769 ;; Kick off the output
23770 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
23771 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
23772 (let* ((hd (match-string-no-properties 1))
23773 (level (length hd))
23774 (text (concat
23775 (match-string-no-properties 2)
23776 (save-excursion
23777 (goto-char (match-end 0))
23778 (let ((str ""))
23779 (catch 'loop
23780 (while 't
23781 (forward-line)
23782 (if (looking-at "^[ \t]\\(.*\\)")
23783 (setq str (concat str (match-string-no-properties 1)))
23784 (throw 'loop str)))))))))
23786 ;; Handle level rendering
23787 (cond
23788 ((> level last-level)
23789 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
23791 ((< level last-level)
23792 (dotimes (- (- last-level level) 1)
23793 (if hanging-li
23794 (org-export-as-xoxo-insert-into out "</li>\n"))
23795 (org-export-as-xoxo-insert-into out "</ol>\n"))
23796 (when hanging-li
23797 (org-export-as-xoxo-insert-into out "</li>\n")
23798 (setq hanging-li nil)))
23800 ((equal level last-level)
23801 (if hanging-li
23802 (org-export-as-xoxo-insert-into out "</li>\n")))
23805 (setq last-level level)
23807 ;; And output the new li
23808 (setq hanging-li 't)
23809 (if (equal ?+ (elt text 0))
23810 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
23811 (org-export-as-xoxo-insert-into out "<li>" text))))
23813 ;; Finally finish off the ol
23814 (dotimes (- last-level 1)
23815 (if hanging-li
23816 (org-export-as-xoxo-insert-into out "</li>\n"))
23817 (org-export-as-xoxo-insert-into out "</ol>\n"))
23819 ;; Finish the buffer off and clean it up.
23820 (switch-to-buffer-other-window out)
23821 (indent-region (point-min) (point-max) nil)
23822 (save-buffer)
23823 (goto-char (point-min))
23827 ;;;; Key bindings
23829 ;; Make `C-c C-x' a prefix key
23830 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
23832 ;; TAB key with modifiers
23833 (org-defkey org-mode-map "\C-i" 'org-cycle)
23834 (org-defkey org-mode-map [(tab)] 'org-cycle)
23835 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
23836 (org-defkey org-mode-map [(meta tab)] 'org-complete)
23837 (org-defkey org-mode-map "\M-\t" 'org-complete)
23838 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
23839 ;; The following line is necessary under Suse GNU/Linux
23840 (unless (featurep 'xemacs)
23841 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
23842 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
23843 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
23845 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
23846 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
23847 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
23849 ;; Cursor keys with modifiers
23850 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
23851 (org-defkey org-mode-map [(meta right)] 'org-metaright)
23852 (org-defkey org-mode-map [(meta up)] 'org-metaup)
23853 (org-defkey org-mode-map [(meta down)] 'org-metadown)
23855 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
23856 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
23857 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
23858 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
23860 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
23861 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
23862 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
23863 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
23865 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
23866 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
23868 ;;; Extra keys for tty access.
23869 ;; We only set them when really needed because otherwise the
23870 ;; menus don't show the simple keys
23872 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
23873 (not window-system))
23874 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
23875 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
23876 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
23877 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
23878 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
23879 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
23880 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
23881 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
23882 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
23883 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
23884 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
23885 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
23886 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
23887 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
23888 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
23889 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
23890 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
23891 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
23892 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
23893 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
23894 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
23895 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
23897 ;; All the other keys
23899 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
23900 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
23901 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
23902 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
23903 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
23904 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
23905 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
23906 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
23907 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
23908 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
23909 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
23910 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
23911 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
23912 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
23913 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
23914 (org-defkey org-mode-map "\C-c\C-x/" 'org-occur-in-agenda-files)
23915 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
23916 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
23917 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
23918 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
23919 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
23920 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
23921 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
23922 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
23923 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
23924 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
23925 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
23926 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
23927 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
23928 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
23929 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
23930 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
23931 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
23932 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
23933 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
23934 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
23935 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
23936 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
23937 (org-defkey org-mode-map "\C-c^" 'org-sort)
23938 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
23939 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
23940 (org-defkey org-mode-map "\C-m" 'org-return)
23941 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
23942 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
23943 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
23944 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
23945 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
23946 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
23947 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
23948 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
23949 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
23950 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
23951 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
23952 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
23953 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
23954 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
23955 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
23956 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
23958 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
23959 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
23960 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
23961 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
23963 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
23964 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
23965 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
23966 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
23967 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
23968 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
23969 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
23970 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
23971 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
23972 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
23974 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
23976 (when (featurep 'xemacs)
23977 (org-defkey org-mode-map 'button3 'popup-mode-menu))
23979 (defsubst org-table-p () (org-at-table-p))
23981 (defun org-self-insert-command (N)
23982 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
23983 If the cursor is in a table looking at whitespace, the whitespace is
23984 overwritten, and the table is not marked as requiring realignment."
23985 (interactive "p")
23986 (if (and (org-table-p)
23987 (progn
23988 ;; check if we blank the field, and if that triggers align
23989 (and org-table-auto-blank-field
23990 (member last-command
23991 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
23992 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
23993 ;; got extra space, this field does not determine column width
23994 (let (org-table-may-need-update) (org-table-blank-field))
23995 ;; no extra space, this field may determine column width
23996 (org-table-blank-field)))
23998 (eq N 1)
23999 (looking-at "[^|\n]* |"))
24000 (let (org-table-may-need-update)
24001 (goto-char (1- (match-end 0)))
24002 (delete-backward-char 1)
24003 (goto-char (match-beginning 0))
24004 (self-insert-command N))
24005 (setq org-table-may-need-update t)
24006 (self-insert-command N)
24007 (org-fix-tags-on-the-fly)))
24009 (defun org-fix-tags-on-the-fly ()
24010 (when (and (equal (char-after (point-at-bol)) ?*)
24011 (org-on-heading-p))
24012 (org-align-tags-here org-tags-column)))
24014 (defun org-delete-backward-char (N)
24015 "Like `delete-backward-char', insert whitespace at field end in tables.
24016 When deleting backwards, in tables this function will insert whitespace in
24017 front of the next \"|\" separator, to keep the table aligned. The table will
24018 still be marked for re-alignment if the field did fill the entire column,
24019 because, in this case the deletion might narrow the column."
24020 (interactive "p")
24021 (if (and (org-table-p)
24022 (eq N 1)
24023 (string-match "|" (buffer-substring (point-at-bol) (point)))
24024 (looking-at ".*?|"))
24025 (let ((pos (point))
24026 (noalign (looking-at "[^|\n\r]* |"))
24027 (c org-table-may-need-update))
24028 (backward-delete-char N)
24029 (skip-chars-forward "^|")
24030 (insert " ")
24031 (goto-char (1- pos))
24032 ;; noalign: if there were two spaces at the end, this field
24033 ;; does not determine the width of the column.
24034 (if noalign (setq org-table-may-need-update c)))
24035 (backward-delete-char N)
24036 (org-fix-tags-on-the-fly)))
24038 (defun org-delete-char (N)
24039 "Like `delete-char', but insert whitespace at field end in tables.
24040 When deleting characters, in tables this function will insert whitespace in
24041 front of the next \"|\" separator, to keep the table aligned. The table will
24042 still be marked for re-alignment if the field did fill the entire column,
24043 because, in this case the deletion might narrow the column."
24044 (interactive "p")
24045 (if (and (org-table-p)
24046 (not (bolp))
24047 (not (= (char-after) ?|))
24048 (eq N 1))
24049 (if (looking-at ".*?|")
24050 (let ((pos (point))
24051 (noalign (looking-at "[^|\n\r]* |"))
24052 (c org-table-may-need-update))
24053 (replace-match (concat
24054 (substring (match-string 0) 1 -1)
24055 " |"))
24056 (goto-char pos)
24057 ;; noalign: if there were two spaces at the end, this field
24058 ;; does not determine the width of the column.
24059 (if noalign (setq org-table-may-need-update c)))
24060 (delete-char N))
24061 (delete-char N)
24062 (org-fix-tags-on-the-fly)))
24064 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
24065 (put 'org-self-insert-command 'delete-selection t)
24066 (put 'orgtbl-self-insert-command 'delete-selection t)
24067 (put 'org-delete-char 'delete-selection 'supersede)
24068 (put 'org-delete-backward-char 'delete-selection 'supersede)
24070 ;; Make `flyspell-mode' delay after some commands
24071 (put 'org-self-insert-command 'flyspell-delayed t)
24072 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
24073 (put 'org-delete-char 'flyspell-delayed t)
24074 (put 'org-delete-backward-char 'flyspell-delayed t)
24076 (eval-after-load "pabbrev"
24077 '(progn
24078 (add-to-list 'pabbrev-expand-after-command-list
24079 'orgtbl-self-insert-command t)
24080 (add-to-list 'pabbrev-expand-after-command-list
24081 'org-self-insert-command t)))
24083 ;; How to do this: Measure non-white length of current string
24084 ;; If equal to column width, we should realign.
24086 (defun org-remap (map &rest commands)
24087 "In MAP, remap the functions given in COMMANDS.
24088 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
24089 (let (new old)
24090 (while commands
24091 (setq old (pop commands) new (pop commands))
24092 (if (fboundp 'command-remapping)
24093 (org-defkey map (vector 'remap old) new)
24094 (substitute-key-definition old new map global-map)))))
24096 (when (eq org-enable-table-editor 'optimized)
24097 ;; If the user wants maximum table support, we need to hijack
24098 ;; some standard editing functions
24099 (org-remap org-mode-map
24100 'self-insert-command 'org-self-insert-command
24101 'delete-char 'org-delete-char
24102 'delete-backward-char 'org-delete-backward-char)
24103 (org-defkey org-mode-map "|" 'org-force-self-insert))
24105 (defun org-shiftcursor-error ()
24106 "Throw an error because Shift-Cursor command was applied in wrong context."
24107 (error "This command is active in special context like tables, headlines or timestamps"))
24109 (defun org-shifttab (&optional arg)
24110 "Global visibility cycling or move to previous table field.
24111 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
24112 on context.
24113 See the individual commands for more information."
24114 (interactive "P")
24115 (cond
24116 ((org-at-table-p) (call-interactively 'org-table-previous-field))
24117 (arg (message "Content view to level: ")
24118 (org-content (prefix-numeric-value arg))
24119 (setq org-cycle-global-status 'overview))
24120 (t (call-interactively 'org-global-cycle))))
24122 (defun org-shiftmetaleft ()
24123 "Promote subtree or delete table column.
24124 Calls `org-promote-subtree', `org-outdent-item',
24125 or `org-table-delete-column', depending on context.
24126 See the individual commands for more information."
24127 (interactive)
24128 (cond
24129 ((org-at-table-p) (call-interactively 'org-table-delete-column))
24130 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
24131 ((org-at-item-p) (call-interactively 'org-outdent-item))
24132 (t (org-shiftcursor-error))))
24134 (defun org-shiftmetaright ()
24135 "Demote subtree or insert table column.
24136 Calls `org-demote-subtree', `org-indent-item',
24137 or `org-table-insert-column', depending on context.
24138 See the individual commands for more information."
24139 (interactive)
24140 (cond
24141 ((org-at-table-p) (call-interactively 'org-table-insert-column))
24142 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
24143 ((org-at-item-p) (call-interactively 'org-indent-item))
24144 (t (org-shiftcursor-error))))
24146 (defun org-shiftmetaup (&optional arg)
24147 "Move subtree up or kill table row.
24148 Calls `org-move-subtree-up' or `org-table-kill-row' or
24149 `org-move-item-up' depending on context. See the individual commands
24150 for more information."
24151 (interactive "P")
24152 (cond
24153 ((org-at-table-p) (call-interactively 'org-table-kill-row))
24154 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24155 ((org-at-item-p) (call-interactively 'org-move-item-up))
24156 (t (org-shiftcursor-error))))
24157 (defun org-shiftmetadown (&optional arg)
24158 "Move subtree down or insert table row.
24159 Calls `org-move-subtree-down' or `org-table-insert-row' or
24160 `org-move-item-down', depending on context. See the individual
24161 commands for more information."
24162 (interactive "P")
24163 (cond
24164 ((org-at-table-p) (call-interactively 'org-table-insert-row))
24165 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24166 ((org-at-item-p) (call-interactively 'org-move-item-down))
24167 (t (org-shiftcursor-error))))
24169 (defun org-metaleft (&optional arg)
24170 "Promote heading or move table column to left.
24171 Calls `org-do-promote' or `org-table-move-column', depending on context.
24172 With no specific context, calls the Emacs default `backward-word'.
24173 See the individual commands for more information."
24174 (interactive "P")
24175 (cond
24176 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
24177 ((or (org-on-heading-p) (org-region-active-p))
24178 (call-interactively 'org-do-promote))
24179 ((org-at-item-p) (call-interactively 'org-outdent-item))
24180 (t (call-interactively 'backward-word))))
24182 (defun org-metaright (&optional arg)
24183 "Demote subtree or move table column to right.
24184 Calls `org-do-demote' or `org-table-move-column', depending on context.
24185 With no specific context, calls the Emacs default `forward-word'.
24186 See the individual commands for more information."
24187 (interactive "P")
24188 (cond
24189 ((org-at-table-p) (call-interactively 'org-table-move-column))
24190 ((or (org-on-heading-p) (org-region-active-p))
24191 (call-interactively 'org-do-demote))
24192 ((org-at-item-p) (call-interactively 'org-indent-item))
24193 (t (call-interactively 'forward-word))))
24195 (defun org-metaup (&optional arg)
24196 "Move subtree up or move table row up.
24197 Calls `org-move-subtree-up' or `org-table-move-row' or
24198 `org-move-item-up', depending on context. See the individual commands
24199 for more information."
24200 (interactive "P")
24201 (cond
24202 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
24203 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
24204 ((org-at-item-p) (call-interactively 'org-move-item-up))
24205 (t (org-shiftcursor-error))))
24207 (defun org-metadown (&optional arg)
24208 "Move subtree down or move table row down.
24209 Calls `org-move-subtree-down' or `org-table-move-row' or
24210 `org-move-item-down', depending on context. See the individual
24211 commands for more information."
24212 (interactive "P")
24213 (cond
24214 ((org-at-table-p) (call-interactively 'org-table-move-row))
24215 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
24216 ((org-at-item-p) (call-interactively 'org-move-item-down))
24217 (t (org-shiftcursor-error))))
24219 (defun org-shiftup (&optional arg)
24220 "Increase item in timestamp or increase priority of current headline.
24221 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
24222 depending on context. See the individual commands for more information."
24223 (interactive "P")
24224 (cond
24225 ((org-at-timestamp-p t)
24226 (call-interactively (if org-edit-timestamp-down-means-later
24227 'org-timestamp-down 'org-timestamp-up)))
24228 ((org-on-heading-p) (call-interactively 'org-priority-up))
24229 ((org-at-item-p) (call-interactively 'org-previous-item))
24230 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
24232 (defun org-shiftdown (&optional arg)
24233 "Decrease item in timestamp or decrease priority of current headline.
24234 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
24235 depending on context. See the individual commands for more information."
24236 (interactive "P")
24237 (cond
24238 ((org-at-timestamp-p t)
24239 (call-interactively (if org-edit-timestamp-down-means-later
24240 'org-timestamp-up 'org-timestamp-down)))
24241 ((org-on-heading-p) (call-interactively 'org-priority-down))
24242 (t (call-interactively 'org-next-item))))
24244 (defun org-shiftright ()
24245 "Next TODO keyword or timestamp one day later, depending on context."
24246 (interactive)
24247 (cond
24248 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
24249 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
24250 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
24251 (t (org-shiftcursor-error))))
24253 (defun org-shiftleft ()
24254 "Previous TODO keyword or timestamp one day earlier, depending on context."
24255 (interactive)
24256 (cond
24257 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
24258 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
24259 ((org-at-property-p)
24260 (call-interactively 'org-property-previous-allowed-value))
24261 (t (org-shiftcursor-error))))
24263 (defun org-shiftcontrolright ()
24264 "Switch to next TODO set."
24265 (interactive)
24266 (cond
24267 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
24268 (t (org-shiftcursor-error))))
24270 (defun org-shiftcontrolleft ()
24271 "Switch to previous TODO set."
24272 (interactive)
24273 (cond
24274 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
24275 (t (org-shiftcursor-error))))
24277 (defun org-ctrl-c-ret ()
24278 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
24279 (interactive)
24280 (cond
24281 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
24282 (t (call-interactively 'org-insert-heading))))
24284 (defun org-copy-special ()
24285 "Copy region in table or copy current subtree.
24286 Calls `org-table-copy' or `org-copy-subtree', depending on context.
24287 See the individual commands for more information."
24288 (interactive)
24289 (call-interactively
24290 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
24292 (defun org-cut-special ()
24293 "Cut region in table or cut current subtree.
24294 Calls `org-table-copy' or `org-cut-subtree', depending on context.
24295 See the individual commands for more information."
24296 (interactive)
24297 (call-interactively
24298 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
24300 (defun org-paste-special (arg)
24301 "Paste rectangular region into table, or past subtree relative to level.
24302 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
24303 See the individual commands for more information."
24304 (interactive "P")
24305 (if (org-at-table-p)
24306 (org-table-paste-rectangle)
24307 (org-paste-subtree arg)))
24309 (defun org-ctrl-c-ctrl-c (&optional arg)
24310 "Set tags in headline, or update according to changed information at point.
24312 This command does many different things, depending on context:
24314 - If the cursor is in a headline, prompt for tags and insert them
24315 into the current line, aligned to `org-tags-column'. When called
24316 with prefix arg, realign all tags in the current buffer.
24318 - If the cursor is in one of the special #+KEYWORD lines, this
24319 triggers scanning the buffer for these lines and updating the
24320 information.
24322 - If the cursor is inside a table, realign the table. This command
24323 works even if the automatic table editor has been turned off.
24325 - If the cursor is on a #+TBLFM line, re-apply the formulas to
24326 the entire table.
24328 - If the cursor is a the beginning of a dynamic block, update it.
24330 - If the cursor is inside a table created by the table.el package,
24331 activate that table.
24333 - If the current buffer is a remember buffer, close note and file it.
24334 with a prefix argument, file it without further interaction to the default
24335 location.
24337 - If the cursor is on a <<<target>>>, update radio targets and corresponding
24338 links in this buffer.
24340 - If the cursor is on a numbered item in a plain list, renumber the
24341 ordered list."
24342 (interactive "P")
24343 (let ((org-enable-table-editor t))
24344 (cond
24345 ((or org-clock-overlays
24346 org-occur-highlights
24347 org-latex-fragment-image-overlays)
24348 (org-remove-clock-overlays)
24349 (org-remove-occur-highlights)
24350 (org-remove-latex-fragment-image-overlays)
24351 (message "Temporary highlights/overlays removed from current buffer"))
24352 ((and (local-variable-p 'org-finish-function (current-buffer))
24353 (fboundp org-finish-function))
24354 (funcall org-finish-function))
24355 ((org-at-property-p)
24356 (call-interactively 'org-property-action))
24357 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
24358 ((org-on-heading-p) (call-interactively 'org-set-tags))
24359 ((org-at-table.el-p)
24360 (require 'table)
24361 (beginning-of-line 1)
24362 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
24363 (call-interactively 'table-recognize-table))
24364 ((org-at-table-p)
24365 (org-table-maybe-eval-formula)
24366 (if arg
24367 (call-interactively 'org-table-recalculate)
24368 (org-table-maybe-recalculate-line))
24369 (call-interactively 'org-table-align))
24370 ((org-at-item-checkbox-p)
24371 (call-interactively 'org-toggle-checkbox))
24372 ((org-at-item-p)
24373 (call-interactively 'org-maybe-renumber-ordered-list))
24374 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
24375 ;; Dynamic block
24376 (beginning-of-line 1)
24377 (org-update-dblock))
24378 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
24379 (cond
24380 ((equal (match-string 1) "TBLFM")
24381 ;; Recalculate the table before this line
24382 (save-excursion
24383 (beginning-of-line 1)
24384 (skip-chars-backward " \r\n\t")
24385 (if (org-at-table-p)
24386 (org-call-with-arg 'org-table-recalculate t))))
24388 (call-interactively 'org-mode-restart))))
24389 (t (error "C-c C-c can do nothing useful at this location.")))))
24391 (defun org-mode-restart ()
24392 "Restart Org-mode, to scan again for special lines.
24393 Also updates the keyword regular expressions."
24394 (interactive)
24395 (let ((org-inhibit-startup t)) (org-mode))
24396 (message "Org-mode restarted to refresh keyword and special line setup"))
24398 (defun org-return ()
24399 "Goto next table row or insert a newline.
24400 Calls `org-table-next-row' or `newline', depending on context.
24401 See the individual commands for more information."
24402 (interactive)
24403 (cond
24404 ((bobp) (newline))
24405 ((org-at-table-p)
24406 (org-table-justify-field-maybe)
24407 (call-interactively 'org-table-next-row))
24408 (t (newline))))
24410 (defun org-ctrl-c-minus ()
24411 "Insert separator line in table or modify bullet type in list.
24412 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
24413 depending on context."
24414 (interactive)
24415 (cond
24416 ((org-at-table-p)
24417 (call-interactively 'org-table-insert-hline))
24418 ((org-in-item-p)
24419 (call-interactively 'org-cycle-list-bullet))
24420 (t (error "`C-c -' does have no function here."))))
24422 (defun org-meta-return (&optional arg)
24423 "Insert a new heading or wrap a region in a table.
24424 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
24425 See the individual commands for more information."
24426 (interactive "P")
24427 (cond
24428 ((org-at-table-p)
24429 (call-interactively 'org-table-wrap-region))
24430 (t (call-interactively 'org-insert-heading))))
24432 ;;; Menu entries
24434 ;; Define the Org-mode menus
24435 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
24436 '("Tbl"
24437 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
24438 ["Next Field" org-cycle (org-at-table-p)]
24439 ["Previous Field" org-shifttab (org-at-table-p)]
24440 ["Next Row" org-return (org-at-table-p)]
24441 "--"
24442 ["Blank Field" org-table-blank-field (org-at-table-p)]
24443 ["Edit Field" org-table-edit-field (org-at-table-p)]
24444 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
24445 "--"
24446 ("Column"
24447 ["Move Column Left" org-metaleft (org-at-table-p)]
24448 ["Move Column Right" org-metaright (org-at-table-p)]
24449 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
24450 ["Insert Column" org-shiftmetaright (org-at-table-p)])
24451 ("Row"
24452 ["Move Row Up" org-metaup (org-at-table-p)]
24453 ["Move Row Down" org-metadown (org-at-table-p)]
24454 ["Delete Row" org-shiftmetaup (org-at-table-p)]
24455 ["Insert Row" org-shiftmetadown (org-at-table-p)]
24456 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
24457 "--"
24458 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
24459 ("Rectangle"
24460 ["Copy Rectangle" org-copy-special (org-at-table-p)]
24461 ["Cut Rectangle" org-cut-special (org-at-table-p)]
24462 ["Paste Rectangle" org-paste-special (org-at-table-p)]
24463 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
24464 "--"
24465 ("Calculate"
24466 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
24467 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
24468 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
24469 "--"
24470 ["Recalculate line" org-table-recalculate (org-at-table-p)]
24471 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
24472 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
24473 "--"
24474 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
24475 "--"
24476 ["Sum Column/Rectangle" org-table-sum
24477 (or (org-at-table-p) (org-region-active-p))]
24478 ["Which Column?" org-table-current-column (org-at-table-p)])
24479 ["Debug Formulas"
24480 org-table-toggle-formula-debugger
24481 :style toggle :selected org-table-formula-debug]
24482 ["Show Col/Row Numbers"
24483 org-table-toggle-coordinate-overlays
24484 :style toggle :selected org-table-overlay-coordinates]
24485 "--"
24486 ["Create" org-table-create (and (not (org-at-table-p))
24487 org-enable-table-editor)]
24488 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
24489 ["Import from File" org-table-import (not (org-at-table-p))]
24490 ["Export to File" org-table-export (org-at-table-p)]
24491 "--"
24492 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
24494 (easy-menu-define org-org-menu org-mode-map "Org menu"
24495 '("Org"
24496 ("Show/Hide"
24497 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
24498 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
24499 ["Sparse Tree" org-occur t]
24500 ["Reveal Context" org-reveal t]
24501 ["Show All" show-all t]
24502 "--"
24503 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
24504 "--"
24505 ["New Heading" org-insert-heading t]
24506 ("Navigate Headings"
24507 ["Up" outline-up-heading t]
24508 ["Next" outline-next-visible-heading t]
24509 ["Previous" outline-previous-visible-heading t]
24510 ["Next Same Level" outline-forward-same-level t]
24511 ["Previous Same Level" outline-backward-same-level t]
24512 "--"
24513 ["Jump" org-goto t])
24514 ("Edit Structure"
24515 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
24516 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
24517 "--"
24518 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
24519 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
24520 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
24521 "--"
24522 ["Promote Heading" org-metaleft (not (org-at-table-p))]
24523 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
24524 ["Demote Heading" org-metaright (not (org-at-table-p))]
24525 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
24526 "--"
24527 ["Sort Region/Children" org-sort (not (org-at-table-p))]
24528 "--"
24529 ["Convert to odd levels" org-convert-to-odd-levels t]
24530 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
24531 ("Editing"
24532 ["Emphasis..." org-emphasize t])
24533 ("Archive"
24534 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
24535 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
24536 ; :active t :keys "C-u C-c C-x C-a"]
24537 ["Sparse trees open ARCHIVE trees"
24538 (setq org-sparse-tree-open-archived-trees
24539 (not org-sparse-tree-open-archived-trees))
24540 :style toggle :selected org-sparse-tree-open-archived-trees]
24541 ["Cycling opens ARCHIVE trees"
24542 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
24543 :style toggle :selected org-cycle-open-archived-trees]
24544 ["Agenda includes ARCHIVE trees"
24545 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
24546 :style toggle :selected (not org-agenda-skip-archived-trees)]
24547 "--"
24548 ["Move Subtree to Archive" org-advertized-archive-subtree t]
24549 ; ["Check and Move Children" (org-archive-subtree '(4))
24550 ; :active t :keys "C-u C-c C-x C-s"]
24552 "--"
24553 ("TODO Lists"
24554 ["TODO/DONE/-" org-todo t]
24555 ("Select keyword"
24556 ["Next keyword" org-shiftright (org-on-heading-p)]
24557 ["Previous keyword" org-shiftleft (org-on-heading-p)]
24558 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
24559 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
24560 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
24561 ["Show TODO Tree" org-show-todo-tree t]
24562 ["Global TODO list" org-todo-list t]
24563 "--"
24564 ["Set Priority" org-priority t]
24565 ["Priority Up" org-shiftup t]
24566 ["Priority Down" org-shiftdown t])
24567 ("TAGS and Properties"
24568 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
24569 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
24570 ["Column view of properties" org-columns t])
24571 ("Dates and Scheduling"
24572 ["Timestamp" org-time-stamp t]
24573 ["Timestamp (inactive)" org-time-stamp-inactive t]
24574 ("Change Date"
24575 ["1 Day Later" org-shiftright t]
24576 ["1 Day Earlier" org-shiftleft t]
24577 ["1 ... Later" org-shiftup t]
24578 ["1 ... Earlier" org-shiftdown t])
24579 ["Compute Time Range" org-evaluate-time-range t]
24580 ["Schedule Item" org-schedule t]
24581 ["Deadline" org-deadline t]
24582 "--"
24583 ["Custom time format" org-toggle-time-stamp-overlays
24584 :style radio :selected org-display-custom-times]
24585 "--"
24586 ["Goto Calendar" org-goto-calendar t]
24587 ["Date from Calendar" org-date-from-calendar t])
24588 ("Logging work"
24589 ["Clock in" org-clock-in t]
24590 ["Clock out" org-clock-out t]
24591 ["Clock cancel" org-clock-cancel t]
24592 ["Goto running clock" org-clock-goto t]
24593 ["Display times" org-clock-display t]
24594 ["Create clock table" org-clock-report t]
24595 "--"
24596 ["Record DONE time"
24597 (progn (setq org-log-done (not org-log-done))
24598 (message "Switching to %s will %s record a timestamp"
24599 (car org-done-keywords)
24600 (if org-log-done "automatically" "not")))
24601 :style toggle :selected org-log-done])
24602 "--"
24603 ["Agenda Command..." org-agenda t]
24604 ("File List for Agenda")
24605 ("Special views current file"
24606 ["TODO Tree" org-show-todo-tree t]
24607 ["Check Deadlines" org-check-deadlines t]
24608 ["Timeline" org-timeline t]
24609 ["Tags Tree" org-tags-sparse-tree t])
24610 "--"
24611 ("Hyperlinks"
24612 ["Store Link (Global)" org-store-link t]
24613 ["Insert Link" org-insert-link t]
24614 ["Follow Link" org-open-at-point t]
24615 "--"
24616 ["Next link" org-next-link t]
24617 ["Previous link" org-previous-link t]
24618 "--"
24619 ["Descriptive Links"
24620 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
24621 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
24622 ["Literal Links"
24623 (progn
24624 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
24625 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
24626 "--"
24627 ["Export/Publish..." org-export t]
24628 ("LaTeX"
24629 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
24630 :selected org-cdlatex-mode]
24631 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
24632 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
24633 ["Modify math symbol" org-cdlatex-math-modify
24634 (org-inside-LaTeX-fragment-p)]
24635 ["Export LaTeX fragments as images"
24636 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
24637 :style toggle :selected org-export-with-LaTeX-fragments])
24638 "--"
24639 ("Documentation"
24640 ["Show Version" org-version t]
24641 ["Info Documentation" org-info t])
24642 ("Customize"
24643 ["Browse Org Group" org-customize t]
24644 "--"
24645 ["Expand This Menu" org-create-customize-menu
24646 (fboundp 'customize-menu-create)])
24647 "--"
24648 ["Refresh setup" org-mode-restart t]
24651 (defun org-info (&optional node)
24652 "Read documentation for Org-mode in the info system.
24653 With optional NODE, go directly to that node."
24654 (interactive)
24655 (require 'info)
24656 (Info-goto-node (format "(org)%s" (or node ""))))
24658 (defun org-install-agenda-files-menu ()
24659 (let ((bl (buffer-list)))
24660 (save-excursion
24661 (while bl
24662 (set-buffer (pop bl))
24663 (if (org-mode-p) (setq bl nil)))
24664 (when (org-mode-p)
24665 (easy-menu-change
24666 '("Org") "File List for Agenda"
24667 (append
24668 (list
24669 ["Edit File List" (org-edit-agenda-file-list) t]
24670 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
24671 ["Remove Current File from List" org-remove-file t]
24672 ["Cycle through agenda files" org-cycle-agenda-files t]
24673 ["Occur in all agenda files" org-occur-in-agenda-files t]
24674 "--")
24675 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
24677 ;;;; Documentation
24679 (defun org-customize ()
24680 "Call the customize function with org as argument."
24681 (interactive)
24682 (customize-browse 'org))
24684 (defun org-create-customize-menu ()
24685 "Create a full customization menu for Org-mode, insert it into the menu."
24686 (interactive)
24687 (if (fboundp 'customize-menu-create)
24688 (progn
24689 (easy-menu-change
24690 '("Org") "Customize"
24691 `(["Browse Org group" org-customize t]
24692 "--"
24693 ,(customize-menu-create 'org)
24694 ["Set" Custom-set t]
24695 ["Save" Custom-save t]
24696 ["Reset to Current" Custom-reset-current t]
24697 ["Reset to Saved" Custom-reset-saved t]
24698 ["Reset to Standard Settings" Custom-reset-standard t]))
24699 (message "\"Org\"-menu now contains full customization menu"))
24700 (error "Cannot expand menu (outdated version of cus-edit.el)")))
24702 ;;;; Miscellaneous stuff
24705 ;;; Generally useful functions
24707 (defun org-context ()
24708 "Return a list of contexts of the current cursor position.
24709 If several contexts apply, all are returned.
24710 Each context entry is a list with a symbol naming the context, and
24711 two positions indicating start and end of the context. Possible
24712 contexts are:
24714 :headline anywhere in a headline
24715 :headline-stars on the leading stars in a headline
24716 :todo-keyword on a TODO keyword (including DONE) in a headline
24717 :tags on the TAGS in a headline
24718 :priority on the priority cookie in a headline
24719 :item on the first line of a plain list item
24720 :item-bullet on the bullet/number of a plain list item
24721 :checkbox on the checkbox in a plain list item
24722 :table in an org-mode table
24723 :table-special on a special filed in a table
24724 :table-table in a table.el table
24725 :link on a hyperlink
24726 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
24727 :target on a <<target>>
24728 :radio-target on a <<<radio-target>>>
24729 :latex-fragment on a LaTeX fragment
24730 :latex-preview on a LaTeX fragment with overlayed preview image
24732 This function expects the position to be visible because it uses font-lock
24733 faces as a help to recognize the following contexts: :table-special, :link,
24734 and :keyword."
24735 (let* ((f (get-text-property (point) 'face))
24736 (faces (if (listp f) f (list f)))
24737 (p (point)) clist o)
24738 ;; First the large context
24739 (cond
24740 ((org-on-heading-p t)
24741 (push (list :headline (point-at-bol) (point-at-eol)) clist)
24742 (when (progn
24743 (beginning-of-line 1)
24744 (looking-at org-todo-line-tags-regexp))
24745 (push (org-point-in-group p 1 :headline-stars) clist)
24746 (push (org-point-in-group p 2 :todo-keyword) clist)
24747 (push (org-point-in-group p 4 :tags) clist))
24748 (goto-char p)
24749 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
24750 (if (looking-at "\\[#[A-Z0-9]\\]")
24751 (push (org-point-in-group p 0 :priority) clist)))
24753 ((org-at-item-p)
24754 (push (org-point-in-group p 2 :item-bullet) clist)
24755 (push (list :item (point-at-bol)
24756 (save-excursion (org-end-of-item) (point)))
24757 clist)
24758 (and (org-at-item-checkbox-p)
24759 (push (org-point-in-group p 0 :checkbox) clist)))
24761 ((org-at-table-p)
24762 (push (list :table (org-table-begin) (org-table-end)) clist)
24763 (if (memq 'org-formula faces)
24764 (push (list :table-special
24765 (previous-single-property-change p 'face)
24766 (next-single-property-change p 'face)) clist)))
24767 ((org-at-table-p 'any)
24768 (push (list :table-table) clist)))
24769 (goto-char p)
24771 ;; Now the small context
24772 (cond
24773 ((org-at-timestamp-p)
24774 (push (org-point-in-group p 0 :timestamp) clist))
24775 ((memq 'org-link faces)
24776 (push (list :link
24777 (previous-single-property-change p 'face)
24778 (next-single-property-change p 'face)) clist))
24779 ((memq 'org-special-keyword faces)
24780 (push (list :keyword
24781 (previous-single-property-change p 'face)
24782 (next-single-property-change p 'face)) clist))
24783 ((org-on-target-p)
24784 (push (org-point-in-group p 0 :target) clist)
24785 (goto-char (1- (match-beginning 0)))
24786 (if (looking-at org-radio-target-regexp)
24787 (push (org-point-in-group p 0 :radio-target) clist))
24788 (goto-char p))
24789 ((setq o (car (delq nil
24790 (mapcar
24791 (lambda (x)
24792 (if (memq x org-latex-fragment-image-overlays) x))
24793 (org-overlays-at (point))))))
24794 (push (list :latex-fragment
24795 (org-overlay-start o) (org-overlay-end o)) clist)
24796 (push (list :latex-preview
24797 (org-overlay-start o) (org-overlay-end o)) clist))
24798 ((org-inside-LaTeX-fragment-p)
24799 ;; FIXME: positions wrong.
24800 (push (list :latex-fragment (point) (point)) clist)))
24802 (setq clist (nreverse (delq nil clist)))
24803 clist))
24805 ;; FIXME: Compare with at-regexp-p Do we need both?
24806 (defun org-in-regexp (re &optional nlines visually)
24807 "Check if point is inside a match of regexp.
24808 Normally only the current line is checked, but you can include NLINES extra
24809 lines both before and after point into the search.
24810 If VISUALLY is set, require that the cursor is not after the match but
24811 really on, so that the block visually is on the match."
24812 (catch 'exit
24813 (let ((pos (point))
24814 (eol (point-at-eol (+ 1 (or nlines 0))))
24815 (inc (if visually 1 0)))
24816 (save-excursion
24817 (beginning-of-line (- 1 (or nlines 0)))
24818 (while (re-search-forward re eol t)
24819 (if (and (<= (match-beginning 0) pos)
24820 (>= (+ inc (match-end 0)) pos))
24821 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
24823 (defun org-at-regexp-p (regexp)
24824 "Is point inside a match of REGEXP in the current line?"
24825 (catch 'exit
24826 (save-excursion
24827 (let ((pos (point)) (end (point-at-eol)))
24828 (beginning-of-line 1)
24829 (while (re-search-forward regexp end t)
24830 (if (and (<= (match-beginning 0) pos)
24831 (>= (match-end 0) pos))
24832 (throw 'exit t)))
24833 nil))))
24835 (defun org-occur-in-agenda-files (regexp)
24836 "Call `multi-occur' with buffers for all agenda files."
24837 (interactive "sList all lines matching: ")
24838 (multi-occur
24839 (mapcar
24840 (lambda (x) (or (get-file-buffer x) (find-file-noselect x)))
24841 (org-agenda-files))
24842 regexp))
24844 (defun org-uniquify (list)
24845 "Remove duplicate elements from LIST."
24846 (let (res)
24847 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
24848 res))
24850 (defun org-delete-all (elts list)
24851 "Remove all elements in ELTS from LIST."
24852 (while elts
24853 (setq list (delete (pop elts) list)))
24854 list)
24856 (defun org-point-in-group (point group &optional context)
24857 "Check if POINT is in match-group GROUP.
24858 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
24859 match. If the match group does ot exist or point is not inside it,
24860 return nil."
24861 (and (match-beginning group)
24862 (>= point (match-beginning group))
24863 (<= point (match-end group))
24864 (if context
24865 (list context (match-beginning group) (match-end group))
24866 t)))
24868 (defun org-switch-to-buffer-other-window (&rest args)
24869 "Switch to buffer in a second window on the current frame.
24870 In particular, do not allow pop-up frames."
24871 (let (pop-up-frames special-display-buffer-names special-display-regexps
24872 special-display-function)
24873 (apply 'switch-to-buffer-other-window args)))
24875 (defun org-combine-plists (&rest plists)
24876 "Create a single property list from all plists in PLISTS.
24877 The process starts by copying the first list, and then setting properties
24878 from the other lists. Settings in the last list are the most significant
24879 ones and overrule settings in the other lists."
24880 (let ((rtn (copy-sequence (pop plists)))
24881 p v ls)
24882 (while plists
24883 (setq ls (pop plists))
24884 (while ls
24885 (setq p (pop ls) v (pop ls))
24886 (setq rtn (plist-put rtn p v))))
24887 rtn))
24889 (defun org-move-line-down (arg)
24890 "Move the current line down. With prefix argument, move it past ARG lines."
24891 (interactive "p")
24892 (let ((col (current-column))
24893 beg end pos)
24894 (beginning-of-line 1) (setq beg (point))
24895 (beginning-of-line 2) (setq end (point))
24896 (beginning-of-line (+ 1 arg))
24897 (setq pos (move-marker (make-marker) (point)))
24898 (insert (delete-and-extract-region beg end))
24899 (goto-char pos)
24900 (move-to-column col)))
24902 (defun org-move-line-up (arg)
24903 "Move the current line up. With prefix argument, move it past ARG lines."
24904 (interactive "p")
24905 (let ((col (current-column))
24906 beg end pos)
24907 (beginning-of-line 1) (setq beg (point))
24908 (beginning-of-line 2) (setq end (point))
24909 (beginning-of-line (- arg))
24910 (setq pos (move-marker (make-marker) (point)))
24911 (insert (delete-and-extract-region beg end))
24912 (goto-char pos)
24913 (move-to-column col)))
24915 (defun org-replace-escapes (string table)
24916 "Replace %-escapes in STRING with values in TABLE.
24917 TABLE is an association list with keys like \"%a\" and string values.
24918 The sequences in STRING may contain normal field width and padding information,
24919 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
24920 so values can contain further %-escapes if they are define later in TABLE."
24921 (let ((case-fold-search nil)
24922 e re rpl)
24923 (while (setq e (pop table))
24924 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
24925 (while (string-match re string)
24926 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
24927 (cdr e)))
24928 (setq string (replace-match rpl t t string))))
24929 string))
24932 (defun org-sublist (list start end)
24933 "Return a section of LIST, from START to END.
24934 Counting starts at 1."
24935 (let (rtn (c start))
24936 (setq list (nthcdr (1- start) list))
24937 (while (and list (<= c end))
24938 (push (pop list) rtn)
24939 (setq c (1+ c)))
24940 (nreverse rtn)))
24942 (defun org-find-base-buffer-visiting (file)
24943 "Like `find-buffer-visiting' but alway return the base buffer and
24944 not an indirect buffer"
24945 (let ((buf (find-buffer-visiting file)))
24946 (if buf
24947 (or (buffer-base-buffer buf) buf)
24948 nil)))
24950 (defun org-image-file-name-regexp ()
24951 "Return regexp matching the file names of images."
24952 (if (fboundp 'image-file-name-regexp)
24953 (image-file-name-regexp)
24954 (let ((image-file-name-extensions
24955 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
24956 "xbm" "xpm" "pbm" "pgm" "ppm")))
24957 (concat "\\."
24958 (regexp-opt (nconc (mapcar 'upcase
24959 image-file-name-extensions)
24960 image-file-name-extensions)
24962 "\\'"))))
24964 (defun org-file-image-p (file)
24965 "Return non-nil if FILE is an image."
24966 (save-match-data
24967 (string-match (org-image-file-name-regexp) file)))
24969 ;;; Paragraph filling stuff.
24970 ;; We want this to be just right, so use the full arsenal.
24972 (defun org-indent-line-function ()
24973 "Indent line like previous, but further if previous was headline or item."
24974 (interactive)
24975 (let* ((pos (point))
24976 (itemp (org-at-item-p))
24977 column bpos bcol tpos tcol bullet btype bullet-type)
24978 ;; Find the previous relevant line
24979 (beginning-of-line 1)
24980 (cond
24981 ((looking-at "#") (setq column 0))
24982 ((looking-at "\\*+ ") (setq column 0))
24984 (beginning-of-line 0)
24985 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
24986 (beginning-of-line 0))
24987 (cond
24988 ((looking-at "\\*+[ \t]+")
24989 (goto-char (match-end 0))
24990 (setq column (current-column)))
24991 ((org-in-item-p)
24992 (org-beginning-of-item)
24993 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24994 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
24995 (setq bpos (match-beginning 1) tpos (match-end 0)
24996 bcol (progn (goto-char bpos) (current-column))
24997 tcol (progn (goto-char tpos) (current-column))
24998 bullet (match-string 1)
24999 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
25000 (if (not itemp)
25001 (setq column tcol)
25002 (goto-char pos)
25003 (beginning-of-line 1)
25004 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25005 (setq bullet (match-string 1)
25006 btype (if (string-match "[0-9]" bullet) "n" bullet))
25007 (setq column (if (equal btype bullet-type) bcol tcol))))
25008 (t (setq column (org-get-indentation))))))
25009 (goto-char pos)
25010 (if (<= (current-column) (current-indentation))
25011 (indent-line-to column)
25012 (save-excursion (indent-line-to column)))
25013 (setq column (current-column))
25014 (beginning-of-line 1)
25015 (if (looking-at
25016 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
25017 (replace-match (concat "\\1" (format org-property-format
25018 (match-string 2) (match-string 3)))
25019 t nil))
25020 (move-to-column column)))
25022 (defun org-set-autofill-regexps ()
25023 (interactive)
25024 ;; In the paragraph separator we include headlines, because filling
25025 ;; text in a line directly attached to a headline would otherwise
25026 ;; fill the headline as well.
25027 (org-set-local 'comment-start-skip "^#+[ \t]*")
25028 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
25029 ;; The paragraph starter includes hand-formatted lists.
25030 (org-set-local 'paragraph-start
25031 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
25032 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
25033 ;; But only if the user has not turned off tables or fixed-width regions
25034 (org-set-local
25035 'auto-fill-inhibit-regexp
25036 (concat "\\*+ \\|#\\+"
25037 "\\|[ \t]*" org-keyword-time-regexp
25038 (if (or org-enable-table-editor org-enable-fixed-width-editor)
25039 (concat
25040 "\\|[ \t]*["
25041 (if org-enable-table-editor "|" "")
25042 (if org-enable-fixed-width-editor ":" "")
25043 "]"))))
25044 ;; We use our own fill-paragraph function, to make sure that tables
25045 ;; and fixed-width regions are not wrapped. That function will pass
25046 ;; through to `fill-paragraph' when appropriate.
25047 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
25048 ; Adaptive filling: To get full control, first make sure that
25049 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
25050 (org-set-local 'adaptive-fill-regexp "\000")
25051 (org-set-local 'adaptive-fill-function
25052 'org-adaptive-fill-function))
25054 (defun org-fill-paragraph (&optional justify)
25055 "Re-align a table, pass through to fill-paragraph if no table."
25056 (let ((table-p (org-at-table-p))
25057 (table.el-p (org-at-table.el-p)))
25058 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25059 (table.el-p t) ; skip table.el tables
25060 (table-p (org-table-align) t) ; align org-mode tables
25061 (t nil)))) ; call paragraph-fill
25063 ;; For reference, this is the default value of adaptive-fill-regexp
25064 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
25066 (defun org-adaptive-fill-function ()
25067 "Return a fill prefix for org-mode files.
25068 In particular, this makes sure hanging paragraphs for hand-formatted lists
25069 work correctly."
25070 (cond ((looking-at "#[ \t]+")
25071 (match-string 0))
25072 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
25073 (save-excursion
25074 (goto-char (match-end 0))
25075 (make-string (current-column) ?\ )))
25076 (t nil)))
25078 ;;;; Functions extending outline functionality
25080 (defun org-beginning-of-line (&optional arg)
25081 "Go to the beginning of the current line. If that is invisible, continue
25082 to a visible line beginning. This makes the function of C-a more intuitive.
25083 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25084 first attempt, and only move to after the tags when the cursor is already
25085 beyond the end of the headline."
25086 (interactive "P")
25087 (let ((pos (point)))
25088 (beginning-of-line 1)
25089 (if (bobp)
25091 (backward-char 1)
25092 (if (org-invisible-p)
25093 (while (and (not (bobp)) (org-invisible-p))
25094 (backward-char 1)
25095 (beginning-of-line 1))
25096 (forward-char 1)))
25097 (when org-special-ctrl-a/e
25098 (cond
25099 ((and (looking-at org-todo-line-regexp)
25100 (= (char-after (match-end 1)) ?\ ))
25101 (goto-char
25102 (if (eq org-special-ctrl-a/e t)
25103 (cond ((> pos (match-beginning 3)) (match-beginning 3))
25104 ((= pos (point)) (match-beginning 3))
25105 (t (point)))
25106 (cond ((> pos (point)) (point))
25107 ((not (eq last-command this-command)) (point))
25108 (t (match-beginning 3))))))
25109 ((org-at-item-p)
25110 (goto-char
25111 (if (eq org-special-ctrl-a/e t)
25112 (cond ((> pos (match-end 4)) (match-end 4))
25113 ((= pos (point)) (match-end 4))
25114 (t (point)))
25115 (cond ((> pos (point)) (point))
25116 ((not (eq last-command this-command)) (point))
25117 (t (match-end 4))))))))))
25119 (defun org-end-of-line (&optional arg)
25120 "Go to the end of the line.
25121 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
25122 first attempt, and only move to after the tags when the cursor is already
25123 beyond the end of the headline."
25124 (interactive "P")
25125 (if (or (not org-special-ctrl-a/e)
25126 (not (org-on-heading-p)))
25127 (end-of-line arg)
25128 (let ((pos (point)))
25129 (beginning-of-line 1)
25130 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
25131 (if (eq org-special-ctrl-a/e t)
25132 (if (or (< pos (match-beginning 1))
25133 (= pos (match-end 0)))
25134 (goto-char (match-beginning 1))
25135 (goto-char (match-end 0)))
25136 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
25137 (goto-char (match-end 0))
25138 (goto-char (match-beginning 1))))
25139 (end-of-line arg)))))
25141 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
25142 (define-key org-mode-map "\C-e" 'org-end-of-line)
25144 (defun org-invisible-p ()
25145 "Check if point is at a character currently not visible."
25146 ;; Early versions of noutline don't have `outline-invisible-p'.
25147 (if (fboundp 'outline-invisible-p)
25148 (outline-invisible-p)
25149 (get-char-property (point) 'invisible)))
25151 (defun org-invisible-p2 ()
25152 "Check if point is at a character currently not visible."
25153 (save-excursion
25154 (if (and (eolp) (not (bobp))) (backward-char 1))
25155 ;; Early versions of noutline don't have `outline-invisible-p'.
25156 (if (fboundp 'outline-invisible-p)
25157 (outline-invisible-p)
25158 (get-char-property (point) 'invisible))))
25160 (defalias 'org-back-to-heading 'outline-back-to-heading)
25161 (defalias 'org-on-heading-p 'outline-on-heading-p)
25162 (defalias 'org-at-heading-p 'outline-on-heading-p)
25163 (defun org-at-heading-or-item-p ()
25164 (or (org-on-heading-p) (org-at-item-p)))
25166 (defun org-on-target-p ()
25167 (or (org-in-regexp org-radio-target-regexp)
25168 (org-in-regexp org-target-regexp)))
25170 (defun org-up-heading-all (arg)
25171 "Move to the heading line of which the present line is a subheading.
25172 This function considers both visible and invisible heading lines.
25173 With argument, move up ARG levels."
25174 (if (fboundp 'outline-up-heading-all)
25175 (outline-up-heading-all arg) ; emacs 21 version of outline.el
25176 (outline-up-heading arg t))) ; emacs 22 version of outline.el
25178 (defun org-up-heading-safe ()
25179 "Move to the heading line of which the present line is a subheading.
25180 This version will not throw an error. It will return the level of the
25181 headline found, or nil if no higher level is found."
25182 (let ((pos (point)) start-level level
25183 (re (concat "^" outline-regexp)))
25184 (catch 'exit
25185 (outline-back-to-heading t)
25186 (setq start-level (funcall outline-level))
25187 (if (equal start-level 1) (throw 'exit nil))
25188 (while (re-search-backward re nil t)
25189 (setq level (funcall outline-level))
25190 (if (< level start-level) (throw 'exit level)))
25191 nil)))
25193 (defun org-goto-sibling (&optional previous)
25194 "Goto the next sibling, even if it is invisible.
25195 When PREVIOUS is set, go to the previous sibling instead. Returns t
25196 when a sibling was found. When none is found, return nil and don't
25197 move point."
25198 (let ((fun (if previous 're-search-backward 're-search-forward))
25199 (pos (point))
25200 (re (concat "^" outline-regexp))
25201 level l)
25202 (when (condition-case nil (org-back-to-heading t) (error nil))
25203 (setq level (funcall outline-level))
25204 (catch 'exit
25205 (or previous (forward-char 1))
25206 (while (funcall fun re nil t)
25207 (setq l (funcall outline-level))
25208 (when (< l level) (goto-char pos) (throw 'exit nil))
25209 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
25210 (goto-char pos)
25211 nil))))
25213 (defun org-show-siblings ()
25214 "Show all siblings of the current headline."
25215 (save-excursion
25216 (while (org-goto-sibling) (org-flag-heading nil)))
25217 (save-excursion
25218 (while (org-goto-sibling 'previous)
25219 (org-flag-heading nil))))
25221 (defun org-show-hidden-entry ()
25222 "Show an entry where even the heading is hidden."
25223 (save-excursion
25224 (org-show-entry)))
25226 (defun org-flag-heading (flag &optional entry)
25227 "Flag the current heading. FLAG non-nil means make invisible.
25228 When ENTRY is non-nil, show the entire entry."
25229 (save-excursion
25230 (org-back-to-heading t)
25231 ;; Check if we should show the entire entry
25232 (if entry
25233 (progn
25234 (org-show-entry)
25235 (save-excursion
25236 (and (outline-next-heading)
25237 (org-flag-heading nil))))
25238 (outline-flag-region (max (point-min) (1- (point)))
25239 (save-excursion (outline-end-of-heading) (point))
25240 flag))))
25242 (defun org-end-of-subtree (&optional invisible-OK to-heading)
25243 ;; This is an exact copy of the original function, but it uses
25244 ;; `org-back-to-heading', to make it work also in invisible
25245 ;; trees. And is uses an invisible-OK argument.
25246 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
25247 (org-back-to-heading invisible-OK)
25248 (let ((first t)
25249 (level (funcall outline-level)))
25250 (while (and (not (eobp))
25251 (or first (> (funcall outline-level) level)))
25252 (setq first nil)
25253 (outline-next-heading))
25254 (unless to-heading
25255 (if (memq (preceding-char) '(?\n ?\^M))
25256 (progn
25257 ;; Go to end of line before heading
25258 (forward-char -1)
25259 (if (memq (preceding-char) '(?\n ?\^M))
25260 ;; leave blank line before heading
25261 (forward-char -1))))))
25262 (point))
25264 (defun org-show-subtree ()
25265 "Show everything after this heading at deeper levels."
25266 (outline-flag-region
25267 (point)
25268 (save-excursion
25269 (outline-end-of-subtree) (outline-next-heading) (point))
25270 nil))
25272 (defun org-show-entry ()
25273 "Show the body directly following this heading.
25274 Show the heading too, if it is currently invisible."
25275 (interactive)
25276 (save-excursion
25277 (condition-case nil
25278 (progn
25279 (org-back-to-heading t)
25280 (outline-flag-region
25281 (max (point-min) (1- (point)))
25282 (save-excursion
25283 (re-search-forward
25284 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
25285 (or (match-beginning 1) (point-max)))
25286 nil))
25287 (error nil))))
25289 (defun org-make-options-regexp (kwds)
25290 "Make a regular expression for keyword lines."
25291 (concat
25293 "#?[ \t]*\\+\\("
25294 (mapconcat 'regexp-quote kwds "\\|")
25295 "\\):[ \t]*"
25296 "\\(.+\\)"))
25298 ;; Make isearch reveal the necessary context
25299 (defun org-isearch-end ()
25300 "Reveal context after isearch exits."
25301 (when isearch-success ; only if search was successful
25302 (if (featurep 'xemacs)
25303 ;; Under XEmacs, the hook is run in the correct place,
25304 ;; we directly show the context.
25305 (org-show-context 'isearch)
25306 ;; In Emacs the hook runs *before* restoring the overlays.
25307 ;; So we have to use a one-time post-command-hook to do this.
25308 ;; (Emacs 22 has a special variable, see function `org-mode')
25309 (unless (and (boundp 'isearch-mode-end-hook-quit)
25310 isearch-mode-end-hook-quit)
25311 ;; Only when the isearch was not quitted.
25312 (org-add-hook 'post-command-hook 'org-isearch-post-command
25313 'append 'local)))))
25315 (defun org-isearch-post-command ()
25316 "Remove self from hook, and show context."
25317 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
25318 (org-show-context 'isearch))
25321 ;;;; Address problems with some other packages
25323 ;; Make flyspell not check words in links, to not mess up our keymap
25324 (defun org-mode-flyspell-verify ()
25325 "Don't let flyspell put overlays at active buttons."
25326 (not (get-text-property (point) 'keymap)))
25328 ;; Make `bookmark-jump' show the jump location if it was hidden.
25329 (eval-after-load "bookmark"
25330 '(if (boundp 'bookmark-after-jump-hook)
25331 ;; We can use the hook
25332 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25333 ;; Hook not available, use advice
25334 (defadvice bookmark-jump (after org-make-visible activate)
25335 "Make the position visible."
25336 (org-bookmark-jump-unhide))))
25338 (defun org-bookmark-jump-unhide ()
25339 "Unhide the current position, to show the bookmark location."
25340 (and (org-mode-p)
25341 (or (org-invisible-p)
25342 (save-excursion (goto-char (max (point-min) (1- (point))))
25343 (org-invisible-p)))
25344 (org-show-context 'bookmark-jump)))
25346 ;; Make session.el ignore our circular variable
25347 (eval-after-load "session"
25348 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25350 ;;;; Experimental code
25353 (defun org-closed-in-range ()
25354 "Sparse tree of items closed in a certain time range.
25355 Still experimental, may disappear in the furture."
25356 (interactive)
25357 ;; Get the time interval from the user.
25358 (let* ((time1 (time-to-seconds
25359 (org-read-date nil 'to-time nil "Starting date: ")))
25360 (time2 (time-to-seconds
25361 (org-read-date nil 'to-time nil "End date:")))
25362 ;; callback function
25363 (callback (lambda ()
25364 (let ((time
25365 (time-to-seconds
25366 (apply 'encode-time
25367 (org-parse-time-string
25368 (match-string 1))))))
25369 ;; check if time in interval
25370 (and (>= time time1) (<= time time2))))))
25371 ;; make tree, check each match with the callback
25372 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
25374 (defun org-fill-paragraph-experimental (&optional justify)
25375 "Re-align a table, pass through to fill-paragraph if no table."
25376 (let ((table-p (org-at-table-p))
25377 (table.el-p (org-at-table.el-p)))
25378 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
25379 (table.el-p t) ; skip table.el tables
25380 (table-p (org-table-align) t) ; align org-mode tables
25381 ((save-excursion
25382 (let ((pos (1+ (point-at-eol))))
25383 (backward-paragraph 1)
25384 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
25385 (save-excursion
25386 (save-restriction
25387 (narrow-to-region (1+ (match-end 0)) (point-max))
25388 (fill-paragraph nil)
25389 t)))
25390 (t nil)))) ; call paragraph-fill
25392 ;; FIXME: this needs a much better algorithm
25393 (defun org-assign-fast-keys (alist)
25394 "Assign fast keys to a keyword-key alist.
25395 Respect keys that are already there."
25396 (let (new e k c c1 c2 (char ?a))
25397 (while (setq e (pop alist))
25398 (cond
25399 ((equal e '(:startgroup)) (push e new))
25400 ((equal e '(:endgroup)) (push e new))
25402 (setq k (car e) c2 nil)
25403 (if (cdr e)
25404 (setq c (cdr e))
25405 ;; automatically assign a character.
25406 (setq c1 (string-to-char
25407 (downcase (substring
25408 k (if (= (string-to-char k) ?@) 1 0)))))
25409 (if (or (rassoc c1 new) (rassoc c1 alist))
25410 (while (or (rassoc char new) (rassoc char alist))
25411 (setq char (1+ char)))
25412 (setq c2 c1))
25413 (setq c (or c2 char)))
25414 (push (cons k c) new))))
25415 (nreverse new)))
25417 (defun org-parse-local-options (string var)
25418 "Parse STRING for startup setting relevant for variable VAR."
25419 (let ((rtn (symbol-value var))
25420 e opts)
25421 (save-match-data
25422 (if (or (not string) (not (string-match "\\S-" string)))
25424 (setq opts (delq nil (mapcar (lambda (x)
25425 (setq e (assoc x org-startup-options))
25426 (if (eq (nth 1 e) var) e nil))
25427 (org-split-string string "[ \t]+"))))
25428 (if (not opts)
25430 (setq rtn nil)
25431 (while (setq e (pop opts))
25432 (if (not (nth 3 e))
25433 (setq rtn (nth 2 e))
25434 (if (not (listp rtn)) (setq rtn nil))
25435 (push (nth 2 e) rtn)))
25436 rtn)))))
25438 ;;;; Finish up
25440 (provide 'org)
25442 (run-hooks 'org-load-hook)
25444 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
25445 ;;; org.el ends here