Release 5.05
[org-mode.git] / org.el
blob629a847d8ebf69e17d04bf8412c73a46f0a2d8a8
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 <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 5.05
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 2, 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://staff.science.uva.nl/~dominik/Tools/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://www.astro.uva.nl/~dominik/Tools/org/Changes
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.05"
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 ss))
115 (defmacro org-preserve-lc (&rest body)
116 `(let ((_line (org-current-line))
117 (_col (current-column)))
118 (unwind-protect
119 (progn ,@body)
120 (goto-line _line)
121 (move-to-column _col))))
123 ;;; The custom variables
125 (defgroup org nil
126 "Outline-based notes management and organizer."
127 :tag "Org"
128 :group 'outlines
129 :group 'hypermedia
130 :group 'calendar)
132 (defgroup org-startup nil
133 "Options concerning startup of Org-mode."
134 :tag "Org Startup"
135 :group 'org)
137 (defcustom org-startup-folded t
138 "Non-nil means, entering Org-mode will switch to OVERVIEW.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
142 #+STARTUP: fold
143 #+STARTUP: nofold
144 #+STARTUP: content"
145 :group 'org-startup
146 :type '(choice
147 (const :tag "nofold: show all" nil)
148 (const :tag "fold: overview" t)
149 (const :tag "content: all headlines" content)))
151 (defcustom org-startup-truncated t
152 "Non-nil means, entering Org-mode will set `truncate-lines'.
153 This is useful since some lines containing links can be very long and
154 uninteresting. Also tables look terrible when wrapped."
155 :group 'org-startup
156 :type 'boolean)
158 (defcustom org-startup-align-all-tables nil
159 "Non-nil means, align all tables when visiting a file.
160 This is useful when the column width in tables is forced with <N> cookies
161 in table fields. Such tables will look correct only after the first re-align.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
164 #+STARTUP: align
165 #+STARTUP: noalign"
166 :group 'org-startup
167 :type 'boolean)
169 (defcustom org-insert-mode-line-in-empty-file nil
170 "Non-nil means insert the first line setting Org-mode in empty files.
171 When the function `org-mode' is called interactively in an empty file, this
172 normally means that the file name does not automatically trigger Org-mode.
173 To ensure that the file will always be in Org-mode in the future, a
174 line enforcing Org-mode will be inserted into the buffer, if this option
175 has been set."
176 :group 'org-startup
177 :type 'boolean)
179 (defcustom org-replace-disputed-keys nil
180 "Non-nil means use alternative key bindings for some keys.
181 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
182 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
183 If you want to use Org-mode together with one of these other modes,
184 or more generally if you would like to move some Org-mode commands to
185 other keys, set this variable and configure the keys with the variable
186 `org-disputed-keys'.
188 This option is only relevant at load-time of Org-mode, and must be set
189 *before* org.el is loaded. Changing it requires a restart of Emacs to
190 become effective."
191 :group 'org-startup
192 :type 'boolean)
194 (if (fboundp 'defvaralias)
195 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
197 (defcustom org-disputed-keys
198 '(([(shift up)] . [(meta p)])
199 ([(shift down)] . [(meta n)])
200 ([(shift left)] . [(meta -)])
201 ([(shift right)] . [(meta +)])
202 ([(control shift right)] . [(meta shift +)])
203 ([(control shift left)] . [(meta shift -)]))
204 "Keys for which Org-mode and other modes compete.
205 This is an alist, cars are the default keys, second element specifies
206 the alternative to use when `org-replace-disputed-keys' is t.
208 Keys can be specified in any syntax supported by `define-key'.
209 The value of this option takes effect only at Org-mode's startup,
210 therefore you'll have to restart Emacs to apply it after changing."
211 :group 'org-startup
212 :type 'alist)
214 (defun org-key (key)
215 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
216 Or return the original if not disputed."
217 (if org-replace-disputed-keys
218 (let* ((nkey (key-description key))
219 (x (org-find-if (lambda (x)
220 (equal (key-description (car x)) nkey))
221 org-disputed-keys)))
222 (if x (cdr x) key))
223 key))
225 (defun org-find-if (predicate seq)
226 (catch 'exit
227 (while seq
228 (if (funcall predicate (car seq))
229 (throw 'exit (car seq))
230 (pop seq)))))
232 (defun org-defkey (keymap key def)
233 "Define a key, possibly translated, as returned by `org-key'."
234 (define-key keymap (org-key key) def))
236 (defcustom org-ellipsis nil
237 "The ellipsis to use in the Org-mode outline.
238 When nil, just use the standard three dots. When a string, use that instead,
239 and just in Org-mode (which will then use its own display table).
240 Changing this requires executing `M-x org-mode' in a buffer to become
241 effective."
242 :group 'org-startup
243 :type '(choice (const :tag "Default" nil)
244 (string :tag "String" :value "...#")))
246 (defvar org-display-table nil
247 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
249 (defgroup org-keywords nil
250 "Keywords in Org-mode."
251 :tag "Org Keywords"
252 :group 'org)
254 (defcustom org-deadline-string "DEADLINE:"
255 "String to mark deadline entries.
256 A deadline is this string, followed by a time stamp. Should be a word,
257 terminated by a colon. You can insert a schedule keyword and
258 a timestamp with \\[org-deadline].
259 Changes become only effective after restarting Emacs."
260 :group 'org-keywords
261 :type 'string)
263 (defcustom org-scheduled-string "SCHEDULED:"
264 "String to mark scheduled TODO entries.
265 A schedule is this string, followed by a time stamp. Should be a word,
266 terminated by a colon. You can insert a schedule keyword and
267 a timestamp with \\[org-schedule].
268 Changes become only effective after restarting Emacs."
269 :group 'org-keywords
270 :type 'string)
272 (defcustom org-closed-string "CLOSED:"
273 "String used as the prefix for timestamps logging closing a TODO entry."
274 :group 'org-keywords
275 :type 'string)
277 (defcustom org-archived-string "ARCHIVED:"
278 "String used as the prefix for timestamps logging archiving a TODO entry."
279 :group 'org-keywords
280 :type 'string)
282 (defcustom org-clock-string "CLOCK:"
283 "String used as prefix for timestamps clocking work hours on an item."
284 :group 'org-keywords
285 :type 'string)
287 (defcustom org-comment-string "COMMENT"
288 "Entries starting with this keyword will never be exported.
289 An entry can be toggled between COMMENT and normal with
290 \\[org-toggle-comment].
291 Changes become only effective after restarting Emacs."
292 :group 'org-keywords
293 :type 'string)
295 (defcustom org-quote-string "QUOTE"
296 "Entries starting with this keyword will be exported in fixed-width font.
297 Quoting applies only to the text in the entry following the headline, and does
298 not extend beyond the next headline, even if that is lower level.
299 An entry can be toggled between QUOTE and normal with
300 \\[org-toggle-fixed-width-section]."
301 :group 'org-keywords
302 :type 'string)
304 (defconst org-repeat-re
305 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
306 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
307 "Regular expression for specifying repeated events.
308 After a match, group 1 contains the repeat expression.")
310 (defgroup org-structure nil
311 "Options concerning the general structure of Org-mode files."
312 :tag "Org Structure"
313 :group 'org)
315 (defgroup org-reveal-location nil
316 "Options about how to make context of a location visible."
317 :tag "Org Reveal Location"
318 :group 'org-structure)
320 (defcustom org-show-hierarchy-above '((default . t))
321 "Non-nil means, show full hierarchy when revealing a location.
322 Org-mode often shows locations in an org-mode file which might have
323 been invisible before. When this is set, the hierarchy of headings
324 above the exposed location is shown.
325 Turning this off for example for sparse trees makes them very compact.
326 Instead of t, this can also be an alist specifying this option for different
327 contexts. Valid contexts are
328 agenda when exposing an entry from the agenda
329 org-goto when using the command `org-goto' on key C-c C-j
330 occur-tree when using the command `org-occur' on key C-c /
331 tags-tree when constructing a sparse tree based on tags matches
332 link-search when exposing search matches associated with a link
333 mark-goto when exposing the jump goal of a mark
334 bookmark-jump when exposing a bookmark location
335 isearch when exiting from an incremental search
336 default default for all contexts not set explicitly"
337 :group 'org-reveal-location
338 :type '(choice
339 (const :tag "Always" t)
340 (const :tag "Never" nil)
341 (repeat :greedy t :tag "Individual contexts"
342 (cons
343 (choice :tag "Context"
344 (const agenda)
345 (const org-goto)
346 (const occur-tree)
347 (const tags-tree)
348 (const link-search)
349 (const mark-goto)
350 (const bookmark-jump)
351 (const isearch)
352 (const default))
353 (boolean)))))
355 (defcustom org-show-following-heading '((default . nil))
356 "Non-nil means, show following heading when revealing a location.
357 Org-mode often shows locations in an org-mode file which might have
358 been invisible before. When this is set, the heading following the
359 match is shown.
360 Turning this off for example for sparse trees makes them very compact,
361 but makes it harder to edit the location of the match. In such a case,
362 use the command \\[org-reveal] to show more context.
363 Instead of t, this can also be an alist specifying this option for different
364 contexts. See `org-show-hierarchy-above' for valid contexts."
365 :group 'org-reveal-location
366 :type '(choice
367 (const :tag "Always" t)
368 (const :tag "Never" nil)
369 (repeat :greedy t :tag "Individual contexts"
370 (cons
371 (choice :tag "Context"
372 (const agenda)
373 (const org-goto)
374 (const occur-tree)
375 (const tags-tree)
376 (const link-search)
377 (const mark-goto)
378 (const bookmark-jump)
379 (const isearch)
380 (const default))
381 (boolean)))))
383 (defcustom org-show-siblings '((default . nil) (isearch t))
384 "Non-nil means, show all sibling heading when revealing a location.
385 Org-mode often shows locations in an org-mode file which might have
386 been invisible before. When this is set, the sibling of the current entry
387 heading are all made visible. If `org-show-hierarchy-above' is t,
388 the same happens on each level of the hierarchy above the current entry.
390 By default this is on for the isearch context, off for all other contexts.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type '(choice
398 (const :tag "Always" t)
399 (const :tag "Never" nil)
400 (repeat :greedy t :tag "Individual contexts"
401 (cons
402 (choice :tag "Context"
403 (const agenda)
404 (const org-goto)
405 (const occur-tree)
406 (const tags-tree)
407 (const link-search)
408 (const mark-goto)
409 (const bookmark-jump)
410 (const isearch)
411 (const default))
412 (boolean)))))
414 (defgroup org-cycle nil
415 "Options concerning visibility cycling in Org-mode."
416 :tag "Org Cycle"
417 :group 'org-structure)
419 (defcustom org-drawers '("PROPERTIES")
420 "Names of drawers. Drawers are not opened by cycling on the headline above.
421 Drawers only open with a TAB on the drawer line itself. A drawer looks like
422 this:
423 :DRAWERNAME:
424 .....
425 :END:
426 The drawer \"PROPERTIES\" is special for capturing properties through
427 the property API."
428 :group 'org-structure
429 :type '(repeat (string :tag "Drawer Name")))
431 (defcustom org-cycle-global-at-bob t
432 "Cycle globally if cursor is at beginning of buffer and not at a headline.
433 This makes it possible to do global cycling without having to use S-TAB or
434 C-u TAB. For this special case to work, the first line of the buffer
435 must not be a headline - it may be empty ot some other text. When used in
436 this way, `org-cycle-hook' is disables temporarily, to make sure the
437 cursor stays at the beginning of the buffer.
438 When this option is nil, don't do anything special at the beginning
439 of the buffer."
440 :group 'org-cycle
441 :type 'boolean)
443 (defcustom org-cycle-emulate-tab t
444 "Where should `org-cycle' emulate TAB.
445 nil Never
446 white Only in completely white lines
447 whitestart Only at the beginning of lines, before the first non-white char.
448 t Everywhere except in headlines
449 exc-hl-bol Everywhere except at the start of a headline
450 If TAB is used in a place where it does not emulate TAB, the current subtree
451 visibility is cycled."
452 :group 'org-cycle
453 :type '(choice (const :tag "Never" nil)
454 (const :tag "Only in completely white lines" white)
455 (const :tag "Before first char in a line" whitestart)
456 (const :tag "Everywhere except in headlines" t)
457 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
460 (defcustom org-cycle-separator-lines 2
461 "Number of empty lines needed to keep an empty line between collapsed trees.
462 If you leave an empty line between the end of a subtree and the following
463 headline, this empty line is hidden when the subtree is folded.
464 Org-mode will leave (exactly) one empty line visible if the number of
465 empty lines is equal or larger to the number given in this variable.
466 So the default 2 means, at least 2 empty lines after the end of a subtree
467 are needed to produce free space between a collapsed subtree and the
468 following headline.
470 Special case: when 0, never leave empty lines in collapsed view."
471 :group 'org-cycle
472 :type 'integer)
474 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
475 org-cycle-hide-drawers
476 org-cycle-show-empty-lines
477 org-optimize-window-after-visibility-change)
478 "Hook that is run after `org-cycle' has changed the buffer visibility.
479 The function(s) in this hook must accept a single argument which indicates
480 the new state that was set by the most recent `org-cycle' command. The
481 argument is a symbol. After a global state change, it can have the values
482 `overview', `content', or `all'. After a local state change, it can have
483 the values `folded', `children', or `subtree'."
484 :group 'org-cycle
485 :type 'hook)
487 (defgroup org-edit-structure nil
488 "Options concerning structure editing in Org-mode."
489 :tag "Org Edit Structure"
490 :group 'org-structure)
493 (defcustom org-special-ctrl-a/e nil
494 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
495 When set, `C-a' will bring back the cursor to the beginning of the
496 headline text, i.e. after the stars and after a possible TODO keyword.
497 In an item, this will be the position after the bullet.
498 When the cursor is already at that position, another `C-a' will bring
499 it to the beginning of the line.
500 `C-e' will jump to the end of the headline, ignoring the presence of tags
501 in the headline. A second `C-e' will then jump to the true end of the
502 line, after any tags."
503 :group 'org-edit-structure
504 :type 'boolean)
506 (if (fboundp 'defvaralias)
507 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
509 (defcustom org-odd-levels-only nil
510 "Non-nil means, skip even levels and only use odd levels for the outline.
511 This has the effect that two stars are being added/taken away in
512 promotion/demotion commands. It also influences how levels are
513 handled by the exporters.
514 Changing it requires restart of `font-lock-mode' to become effective
515 for fontification also in regions already fontified.
516 You may also set this on a per-file basis by adding one of the following
517 lines to the buffer:
519 #+STARTUP: odd
520 #+STARTUP: oddeven"
521 :group 'org-edit-structure
522 :group 'org-font-lock
523 :type 'boolean)
525 (defcustom org-adapt-indentation t
526 "Non-nil means, adapt indentation when promoting and demoting.
527 When this is set and the *entire* text in an entry is indented, the
528 indentation is increased by one space in a demotion command, and
529 decreased by one in a promotion command. If any line in the entry
530 body starts at column 0, indentation is not changed at all."
531 :group 'org-edit-structure
532 :type 'boolean)
534 (defcustom org-blank-before-new-entry '((heading . nil)
535 (plain-list-item . nil))
536 "Should `org-insert-heading' leave a blank line before new heading/item?
537 The value is an alist, with `heading' and `plain-list-item' as car,
538 and a boolean flag as cdr."
539 :group 'org-edit-structure
540 :type '(list
541 (cons (const heading) (boolean))
542 (cons (const plain-list-item) (boolean))))
544 (defcustom org-insert-heading-hook nil
545 "Hook being run after inserting a new heading."
546 :group 'org-edit-structure
547 :type 'boolean)
549 (defcustom org-enable-fixed-width-editor t
550 "Non-nil means, lines starting with \":\" are treated as fixed-width.
551 This currently only means, they are never auto-wrapped.
552 When nil, such lines will be treated like ordinary lines.
553 See also the QUOTE keyword."
554 :group 'org-edit-structure
555 :type 'boolean)
557 (defgroup org-sparse-trees nil
558 "Options concerning sparse trees in Org-mode."
559 :tag "Org Sparse Trees"
560 :group 'org-structure)
562 (defcustom org-highlight-sparse-tree-matches t
563 "Non-nil means, highlight all matches that define a sparse tree.
564 The highlights will automatically disappear the next time the buffer is
565 changed by an edit command."
566 :group 'org-sparse-trees
567 :type 'boolean)
569 (defcustom org-remove-highlights-with-change t
570 "Non-nil means, any change to the buffer will remove temporary highlights.
571 Such highlights are created by `org-occur' and `org-clock-display'.
572 When nil, `C-c C-c needs to be used to get rid of the highlights.
573 The highlights created by `org-preview-latex-fragment' always need
574 `C-c C-c' to be removed."
575 :group 'org-sparse-trees
576 :group 'org-time
577 :type 'boolean)
580 (defcustom org-occur-hook '(org-first-headline-recenter)
581 "Hook that is run after `org-occur' has constructed a sparse tree.
582 This can be used to recenter the window to show as much of the structure
583 as possible."
584 :group 'org-sparse-trees
585 :type 'hook)
587 (defgroup org-plain-lists nil
588 "Options concerning plain lists in Org-mode."
589 :tag "Org Plain lists"
590 :group 'org-structure)
592 (defcustom org-cycle-include-plain-lists nil
593 "Non-nil means, include plain lists into visibility cycling.
594 This means that during cycling, plain list items will *temporarily* be
595 interpreted as outline headlines with a level given by 1000+i where i is the
596 indentation of the bullet. In all other operations, plain list items are
597 not seen as headlines. For example, you cannot assign a TODO keyword to
598 such an item."
599 :group 'org-plain-lists
600 :type 'boolean)
602 (defcustom org-plain-list-ordered-item-terminator t
603 "The character that makes a line with leading number an ordered list item.
604 Valid values are ?. and ?\). To get both terminators, use t. While
605 ?. may look nicer, it creates the danger that a line with leading
606 number may be incorrectly interpreted as an item. ?\) therefore is
607 the safe choice."
608 :group 'org-plain-lists
609 :type '(choice (const :tag "dot like in \"2.\"" ?.)
610 (const :tag "paren like in \"2)\"" ?\))
611 (const :tab "both" t)))
613 (defcustom org-auto-renumber-ordered-lists t
614 "Non-nil means, automatically renumber ordered plain lists.
615 Renumbering happens when the sequence have been changed with
616 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
617 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
618 :group 'org-plain-lists
619 :type 'boolean)
621 (defcustom org-provide-checkbox-statistics t
622 "Non-nil means, update checkbox statistics after insert and toggle.
623 When this is set, checkbox statistics is updated each time you either insert
624 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
625 with \\[org-ctrl-c-ctrl-c\\]."
626 :group 'org-plain-lists
627 :type 'boolean)
629 (defgroup org-archive nil
630 "Options concerning archiving in Org-mode."
631 :tag "Org Archive"
632 :group 'org-structure)
634 (defcustom org-archive-tag "ARCHIVE"
635 "The tag that marks a subtree as archived.
636 An archived subtree does not open during visibility cycling, and does
637 not contribute to the agenda listings."
638 :group 'org-archive
639 :group 'org-keywords
640 :type 'string)
642 (defcustom org-agenda-skip-archived-trees t
643 "Non-nil means, the agenda will skip any items located in archived trees.
644 An archived tree is a tree marked with the tag ARCHIVE."
645 :group 'org-archive
646 :group 'org-agenda-skip
647 :type 'boolean)
649 (defcustom org-cycle-open-archived-trees nil
650 "Non-nil means, `org-cycle' will open archived trees.
651 An archived tree is a tree marked with the tag ARCHIVE.
652 When nil, archived trees will stay folded. You can still open them with
653 normal outline commands like `show-all', but not with the cycling commands."
654 :group 'org-archive
655 :group 'org-cycle
656 :type 'boolean)
658 (defcustom org-sparse-tree-open-archived-trees nil
659 "Non-nil means sparse tree construction shows matches in archived trees.
660 When nil, matches in these trees are highlighted, but the trees are kept in
661 collapsed state."
662 :group 'org-archive
663 :group 'org-sparse-trees
664 :type 'boolean)
666 (defcustom org-archive-location "%s_archive::"
667 "The location where subtrees should be archived.
668 This string consists of two parts, separated by a double-colon.
670 The first part is a file name - when omitted, archiving happens in the same
671 file. %s will be replaced by the current file name (without directory part).
672 Archiving to a different file is useful to keep archived entries from
673 contributing to the Org-mode Agenda.
675 The part after the double colon is a headline. The archived entries will be
676 filed under that headline. When omitted, the subtrees are simply filed away
677 at the end of the file, as top-level entries.
679 Here are a few examples:
680 \"%s_archive::\"
681 If the current file is Projects.org, archive in file
682 Projects.org_archive, as top-level trees. This is the default.
684 \"::* Archived Tasks\"
685 Archive in the current file, under the top-level headline
686 \"* Archived Tasks\".
688 \"~/org/archive.org::\"
689 Archive in file ~/org/archive.org (absolute path), as top-level trees.
691 \"basement::** Finished Tasks\"
692 Archive in file ./basement (relative path), as level 3 trees
693 below the level 2 heading \"** Finished Tasks\".
695 You may set this option on a per-file basis by adding to the buffer a
696 line like
698 #+ARCHIVE: basement::** Finished Tasks"
699 :group 'org-archive
700 :type 'string)
702 (defcustom org-archive-mark-done t
703 "Non-nil means, mark entries as DONE when they are moved to the archive file.
704 This can be a string to set the keyword to use. When t, Org-mode will
705 use the first keyword in its list that means done."
706 :group 'org-archive
707 :type '(choice
708 (const :tag "No" nil)
709 (const :tag "Yes" t)
710 (string :tag "Use this keyword")))
712 (defcustom org-archive-stamp-time t
713 "Non-nil means, add a time stamp to entries moved to an archive file."
714 :group 'org-archive
715 :type 'boolean)
717 (defgroup org-table nil
718 "Options concerning tables in Org-mode."
719 :tag "Org Table"
720 :group 'org)
722 (defcustom org-enable-table-editor 'optimized
723 "Non-nil means, lines starting with \"|\" are handled by the table editor.
724 When nil, such lines will be treated like ordinary lines.
726 When equal to the symbol `optimized', the table editor will be optimized to
727 do the following:
728 - Automatic overwrite mode in front of whitespace in table fields.
729 This makes the structure of the table stay in tact as long as the edited
730 field does not exceed the column width.
731 - Minimize the number of realigns. Normally, the table is aligned each time
732 TAB or RET are pressed to move to another field. With optimization this
733 happens only if changes to a field might have changed the column width.
734 Optimization requires replacing the functions `self-insert-command',
735 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
736 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
737 very good at guessing when a re-align will be necessary, but you can always
738 force one with \\[org-ctrl-c-ctrl-c].
740 If you would like to use the optimized version in Org-mode, but the
741 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
743 This variable can be used to turn on and off the table editor during a session,
744 but in order to toggle optimization, a restart is required.
746 See also the variable `org-table-auto-blank-field'."
747 :group 'org-table
748 :type '(choice
749 (const :tag "off" nil)
750 (const :tag "on" t)
751 (const :tag "on, optimized" optimized)))
753 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
754 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
755 In the optimized version, the table editor takes over all simple keys that
756 normally just insert a character. In tables, the characters are inserted
757 in a way to minimize disturbing the table structure (i.e. in overwrite mode
758 for empty fields). Outside tables, the correct binding of the keys is
759 restored.
761 The default for this option is t if the optimized version is also used in
762 Org-mode. See the variable `org-enable-table-editor' for details. Changing
763 this variable requires a restart of Emacs to become effective."
764 :group 'org-table
765 :type 'boolean)
767 (defcustom orgtbl-radio-table-templates
768 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
769 % END RECEIVE ORGTBL %n
770 \\begin{comment}
771 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
772 | | |
773 \\end{comment}\n")
774 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
775 @c END RECEIVE ORGTBL %n
776 @ignore
777 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
778 | | |
779 @end ignore\n")
780 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
781 <!-- END RECEIVE ORGTBL %n -->
782 <!--
783 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
784 | | |
785 -->\n"))
786 "Templates for radio tables in different major modes.
787 All occurrences of %n in a template will be replaced with the name of the
788 table, obtained by prompting the user."
789 :group 'org-table
790 :type '(repeat
791 (list (symbol :tag "Major mode")
792 (string :tag "Format"))))
794 (defgroup org-table-settings nil
795 "Settings for tables in Org-mode."
796 :tag "Org Table Settings"
797 :group 'org-table)
799 (defcustom org-table-default-size "5x2"
800 "The default size for newly created tables, Columns x Rows."
801 :group 'org-table-settings
802 :type 'string)
804 (defcustom org-table-number-regexp
805 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
806 "Regular expression for recognizing numbers in table columns.
807 If a table column contains mostly numbers, it will be aligned to the
808 right. If not, it will be aligned to the left.
810 The default value of this option is a regular expression which allows
811 anything which looks remotely like a number as used in scientific
812 context. For example, all of the following will be considered a
813 number:
814 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
816 Other options offered by the customize interface are more restrictive."
817 :group 'org-table-settings
818 :type '(choice
819 (const :tag "Positive Integers"
820 "^[0-9]+$")
821 (const :tag "Integers"
822 "^[-+]?[0-9]+$")
823 (const :tag "Floating Point Numbers"
824 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
825 (const :tag "Floating Point Number or Integer"
826 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
827 (const :tag "Exponential, Floating point, Integer"
828 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
829 (const :tag "Very General Number-Like, including hex"
830 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
831 (string :tag "Regexp:")))
833 (defcustom org-table-number-fraction 0.5
834 "Fraction of numbers in a column required to make the column align right.
835 In a column all non-white fields are considered. If at least this
836 fraction of fields is matched by `org-table-number-fraction',
837 alignment to the right border applies."
838 :group 'org-table-settings
839 :type 'number)
841 (defgroup org-table-editing nil
842 "Bahavior of tables during editing in Org-mode."
843 :tag "Org Table Editing"
844 :group 'org-table)
846 (defcustom org-table-automatic-realign t
847 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
848 When nil, aligning is only done with \\[org-table-align], or after column
849 removal/insertion."
850 :group 'org-table-editing
851 :type 'boolean)
853 (defcustom org-table-auto-blank-field t
854 "Non-nil means, automatically blank table field when starting to type into it.
855 This only happens when typing immediately after a field motion
856 command (TAB, S-TAB or RET).
857 Only relevant when `org-enable-table-editor' is equal to `optimized'."
858 :group 'org-table-editing
859 :type 'boolean)
861 (defcustom org-table-tab-jumps-over-hlines t
862 "Non-nil means, tab in the last column of a table with jump over a hline.
863 If a horizontal separator line is following the current line,
864 `org-table-next-field' can either create a new row before that line, or jump
865 over the line. When this option is nil, a new line will be created before
866 this line."
867 :group 'org-table-editing
868 :type 'boolean)
870 (defcustom org-table-tab-recognizes-table.el t
871 "Non-nil means, TAB will automatically notice a table.el table.
872 When it sees such a table, it moves point into it and - if necessary -
873 calls `table-recognize-table'."
874 :group 'org-table-editing
875 :type 'boolean)
877 (defgroup org-table-calculation nil
878 "Options concerning tables in Org-mode."
879 :tag "Org Table Calculation"
880 :group 'org-table)
882 (defcustom org-table-use-standard-references t
883 "Should org-mode work with table refrences like B3 instead of @3$2?
884 Possible values are:
885 nil never use them
886 from accept as input, do not present for editing
887 t: accept as input and present for editing"
888 :group 'org-table-calculation
889 :type '(choice
890 (const :tag "Never, don't even check unser input for them" nil)
891 (const :tag "Always, both as user input, and when editing" t)
892 (const :tag "Convert user input, don't offer during editing" 'from)))
894 (defcustom org-table-copy-increment t
895 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
896 :group 'org-table-calculation
897 :type 'boolean)
899 (defcustom org-calc-default-modes
900 '(calc-internal-prec 12
901 calc-float-format (float 5)
902 calc-angle-mode deg
903 calc-prefer-frac nil
904 calc-symbolic-mode nil
905 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
906 calc-display-working-message t
908 "List with Calc mode settings for use in calc-eval for table formulas.
909 The list must contain alternating symbols (Calc modes variables and values).
910 Don't remove any of the default settings, just change the values. Org-mode
911 relies on the variables to be present in the list."
912 :group 'org-table-calculation
913 :type 'plist)
915 (defcustom org-table-formula-evaluate-inline t
916 "Non-nil means, TAB and RET evaluate a formula in current table field.
917 If the current field starts with an equal sign, it is assumed to be a formula
918 which should be evaluated as described in the manual and in the documentation
919 string of the command `org-table-eval-formula'. This feature requires the
920 Emacs calc package.
921 When this variable is nil, formula calculation is only available through
922 the command \\[org-table-eval-formula]."
923 :group 'org-table-calculation
924 :type 'boolean)
926 (defcustom org-table-formula-use-constants t
927 "Non-nil means, interpret constants in formulas in tables.
928 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
929 by the value given in `org-table-formula-constants', or by a value obtained
930 from the `constants.el' package."
931 :group 'org-table-calculation
932 :type 'boolean)
934 (defcustom org-table-formula-constants nil
935 "Alist with constant names and values, for use in table formulas.
936 The car of each element is a name of a constant, without the `$' before it.
937 The cdr is the value as a string. For example, if you'd like to use the
938 speed of light in a formula, you would configure
940 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
942 and then use it in an equation like `$1*$c'.
944 Constants can also be defined on a per-file basis using a line like
946 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
947 :group 'org-table-calculation
948 :type '(repeat
949 (cons (string :tag "name")
950 (string :tag "value"))))
952 (defvar org-table-formula-constants-local nil
953 "Local version of `org-table-formula-constants'.")
954 (make-variable-buffer-local 'org-table-formula-constants-local)
956 (defcustom org-table-allow-automatic-line-recalculation t
957 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
958 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
959 :group 'org-table-calculation
960 :type 'boolean)
962 (defgroup org-link nil
963 "Options concerning links in Org-mode."
964 :tag "Org Link"
965 :group 'org)
967 (defvar org-link-abbrev-alist-local nil
968 "Buffer-local version of `org-link-abbrev-alist', which see.
969 The value of this is taken from the #+LINK lines.")
970 (make-variable-buffer-local 'org-link-abbrev-alist-local)
972 (defcustom org-link-abbrev-alist nil
973 "Alist of link abbreviations.
974 The car of each element is a string, to be replaced at the start of a link.
975 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
976 links in Org-mode buffers can have an optional tag after a double colon, e.g.
978 [[linkkey:tag][description]]
980 If REPLACE is a string, the tag will simply be appended to create the link.
981 If the string contains \"%s\", the tag will be inserted there. REPLACE may
982 also be a function that will be called with the tag as the only argument to
983 create the link. See the manual for examples."
984 :group 'org-link
985 :type 'alist)
987 (defcustom org-descriptive-links t
988 "Non-nil means, hide link part and only show description of bracket links.
989 Bracket links are like [[link][descritpion]]. This variable sets the initial
990 state in new org-mode buffers. The setting can then be toggled on a
991 per-buffer basis from the Org->Hyperlinks menu."
992 :group 'org-link
993 :type 'boolean)
995 (defcustom org-link-file-path-type 'adaptive
996 "How the path name in file links should be stored.
997 Valid values are:
999 relative relative to the current directory, i.e. the directory of the file
1000 into which the link is being inserted.
1001 absolute absolute path, if possible with ~ for home directory.
1002 noabbrev absolute path, no abbreviation of home directory.
1003 adaptive Use relative path for files in the current directory and sub-
1004 directories of it. For other files, use an absolute path."
1005 :group 'org-link
1006 :type '(choice
1007 (const relative)
1008 (const absolute)
1009 (const noabbrev)
1010 (const adaptive)))
1012 (defcustom org-activate-links '(bracket angle plain radio tag date)
1013 "Types of links that should be activated in Org-mode files.
1014 This is a list of symbols, each leading to the activation of a certain link
1015 type. In principle, it does not hurt to turn on most link types - there may
1016 be a small gain when turning off unused link types. The types are:
1018 bracket The recommended [[link][description]] or [[link]] links with hiding.
1019 angular Links in angular brackes that may contain whitespace like
1020 <bbdb:Carsten Dominik>.
1021 plain Plain links in normal text, no whitespace, like http://google.com.
1022 radio Text that is matched by a radio target, see manual for details.
1023 tag Tag settings in a headline (link to tag search).
1024 date Time stamps (link to calendar).
1026 Changing this variable requires a restart of Emacs to become effective."
1027 :group 'org-link
1028 :type '(set (const :tag "Double bracket links (new style)" bracket)
1029 (const :tag "Angular bracket links (old style)" angular)
1030 (const :tag "plain text links" plain)
1031 (const :tag "Radio target matches" radio)
1032 (const :tag "Tags" tag)
1033 (const :tag "Tags" target)
1034 (const :tag "Timestamps" date)))
1036 (defgroup org-link-store nil
1037 "Options concerning storing links in Org-mode"
1038 :tag "Org Store Link"
1039 :group 'org-link)
1041 (defcustom org-email-link-description-format "Email %c: %.30s"
1042 "Format of the description part of a link to an email or usenet message.
1043 The following %-excapes will be replaced by corresponding information:
1045 %F full \"From\" field
1046 %f name, taken from \"From\" field, address if no name
1047 %T full \"To\" field
1048 %t first name in \"To\" field, address if no name
1049 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1050 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1051 %s subject
1052 %m message-id.
1054 You may use normal field width specification between the % and the letter.
1055 This is for example useful to limit the length of the subject.
1057 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1058 :group 'org-link-store
1059 :type 'string)
1061 (defcustom org-from-is-user-regexp
1062 (let (r1 r2)
1063 (when (and user-mail-address (not (string= user-mail-address "")))
1064 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1065 (when (and user-full-name (not (string= user-full-name "")))
1066 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1067 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1068 "Regexp mached against the \"From:\" header of an email or usenet message.
1069 It should match if the message is from the user him/herself."
1070 :group 'org-link-store
1071 :type 'regexp)
1073 (defcustom org-context-in-file-links t
1074 "Non-nil means, file links from `org-store-link' contain context.
1075 A search string will be added to the file name with :: as separator and
1076 used to find the context when the link is activated by the command
1077 `org-open-at-point'.
1078 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1079 negates this setting for the duration of the command."
1080 :group 'org-link-store
1081 :type 'boolean)
1083 (defcustom org-keep-stored-link-after-insertion nil
1084 "Non-nil means, keep link in list for entire session.
1086 The command `org-store-link' adds a link pointing to the current
1087 location to an internal list. These links accumulate during a session.
1088 The command `org-insert-link' can be used to insert links into any
1089 Org-mode file (offering completion for all stored links). When this
1090 option is nil, every link which has been inserted once using \\[org-insert-link]
1091 will be removed from the list, to make completing the unused links
1092 more efficient."
1093 :group 'org-link-store
1094 :type 'boolean)
1096 (defcustom org-usenet-links-prefer-google nil
1097 "Non-nil means, `org-store-link' will create web links to Google groups.
1098 When nil, Gnus will be used for such links.
1099 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1100 negates this setting for the duration of the command."
1101 :group 'org-link-store
1102 :type 'boolean)
1104 (defgroup org-link-follow nil
1105 "Options concerning following links in Org-mode"
1106 :tag "Org Follow Link"
1107 :group 'org-link)
1109 (defcustom org-tab-follows-link nil
1110 "Non-nil means, on links TAB will follow the link.
1111 Needs to be set before org.el is loaded."
1112 :group 'org-link-follow
1113 :type 'boolean)
1115 (defcustom org-return-follows-link nil
1116 "Non-nil means, on links RET will follow the link.
1117 Needs to be set before org.el is loaded."
1118 :group 'org-link-follow
1119 :type 'boolean)
1121 (defcustom org-mouse-1-follows-link t
1122 "Non-nil means, mouse-1 on a link will follow the link.
1123 A longer mouse click will still set point. Does not wortk on XEmacs.
1124 Needs to be set before org.el is loaded."
1125 :group 'org-link-follow
1126 :type 'boolean)
1128 (defcustom org-mark-ring-length 4
1129 "Number of different positions to be recorded in the ring
1130 Changing this requires a restart of Emacs to work correctly."
1131 :group 'org-link-follow
1132 :type 'interger)
1134 (defcustom org-link-frame-setup
1135 '((vm . vm-visit-folder-other-frame)
1136 (gnus . gnus-other-frame)
1137 (file . find-file-other-window))
1138 "Setup the frame configuration for following links.
1139 When following a link with Emacs, it may often be useful to display
1140 this link in another window or frame. This variable can be used to
1141 set this up for the different types of links.
1142 For VM, use any of
1143 `vm-visit-folder'
1144 `vm-visit-folder-other-frame'
1145 For Gnus, use any of
1146 `gnus'
1147 `gnus-other-frame'
1148 For FILE, use any of
1149 `find-file'
1150 `find-file-other-window'
1151 `find-file-other-frame'
1152 For the calendar, use the variable `calendar-setup'.
1153 For BBDB, it is currently only possible to display the matches in
1154 another window."
1155 :group 'org-link-follow
1156 :type '(list
1157 (cons (const vm)
1158 (choice
1159 (const vm-visit-folder)
1160 (const vm-visit-folder-other-window)
1161 (const vm-visit-folder-other-frame)))
1162 (cons (const gnus)
1163 (choice
1164 (const gnus)
1165 (const gnus-other-frame)))
1166 (cons (const file)
1167 (choice
1168 (const find-file)
1169 (const find-file-other-window)
1170 (const find-file-other-frame)))))
1172 (defcustom org-display-internal-link-with-indirect-buffer nil
1173 "Non-nil means, use indirect buffer to display infile links.
1174 Activating internal links (from one location in a file to another location
1175 in the same file) normally just jumps to the location. When the link is
1176 activated with a C-u prefix (or with mouse-3), the link is displayed in
1177 another window. When this option is set, the other window actually displays
1178 an indirect buffer clone of the current buffer, to avoid any visibility
1179 changes to the current buffer."
1180 :group 'org-link-follow
1181 :type 'boolean)
1183 (defcustom org-open-non-existing-files nil
1184 "Non-nil means, `org-open-file' will open non-existing files.
1185 When nil, an error will be generated."
1186 :group 'org-link-follow
1187 :type 'boolean)
1189 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1190 "Function and arguments to call for following mailto links.
1191 This is a list with the first element being a lisp function, and the
1192 remaining elements being arguments to the function. In string arguments,
1193 %a will be replaced by the address, and %s will be replaced by the subject
1194 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1195 :group 'org-link-follow
1196 :type '(choice
1197 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1198 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1199 (const :tag "message-mail" (message-mail "%a" "%s"))
1200 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1202 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1203 "Non-nil means, ask for confirmation before executing shell links.
1204 Shell links can be dangerous, just thing about a link
1206 [[shell:rm -rf ~/*][Google Search]]
1208 This link would show up in your Org-mode document as \"Google Search\"
1209 but really it would remove your entire home directory.
1210 Therefore I *definitely* advise against setting this variable to nil.
1211 Just change it to `y-or-n-p' of you want to confirm with a single key press
1212 rather than having to type \"yes\"."
1213 :group 'org-link-follow
1214 :type '(choice
1215 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1216 (const :tag "with y-or-n (faster)" y-or-n-p)
1217 (const :tag "no confirmation (dangerous)" nil)))
1219 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1220 "Non-nil means, ask for confirmation before executing elisp links.
1221 Elisp links can be dangerous, just think about a link
1223 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1225 This link would show up in your Org-mode document as \"Google Search\"
1226 but really it would remove your entire home directory.
1227 Therefore I *definitely* advise against setting this variable to nil.
1228 Just change it to `y-or-n-p' of you want to confirm with a single key press
1229 rather than having to type \"yes\"."
1230 :group 'org-link-follow
1231 :type '(choice
1232 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1233 (const :tag "with y-or-n (faster)" y-or-n-p)
1234 (const :tag "no confirmation (dangerous)" nil)))
1236 (defconst org-file-apps-defaults-gnu
1237 '((remote . emacs)
1238 (t . mailcap))
1239 "Default file applications on a UNIX or GNU/Linux system.
1240 See `org-file-apps'.")
1242 (defconst org-file-apps-defaults-macosx
1243 '((remote . emacs)
1244 (t . "open %s")
1245 ("ps" . "gv %s")
1246 ("ps.gz" . "gv %s")
1247 ("eps" . "gv %s")
1248 ("eps.gz" . "gv %s")
1249 ("dvi" . "xdvi %s")
1250 ("fig" . "xfig %s"))
1251 "Default file applications on a MacOS X system.
1252 The system \"open\" is known as a default, but we use X11 applications
1253 for some files for which the OS does not have a good default.
1254 See `org-file-apps'.")
1256 (defconst org-file-apps-defaults-windowsnt
1257 (list
1258 '(remote . emacs)
1259 (cons t
1260 (list (if (featurep 'xemacs)
1261 'mswindows-shell-execute
1262 'w32-shell-execute)
1263 "open" 'file)))
1264 "Default file applications on a Windows NT system.
1265 The system \"open\" is used for most files.
1266 See `org-file-apps'.")
1268 (defcustom org-file-apps
1270 ("txt" . emacs)
1271 ("tex" . emacs)
1272 ("ltx" . emacs)
1273 ("org" . emacs)
1274 ("el" . emacs)
1275 ("bib" . emacs)
1277 "External applications for opening `file:path' items in a document.
1278 Org-mode uses system defaults for different file types, but
1279 you can use this variable to set the application for a given file
1280 extension. The entries in this list are cons cells where the car identifies
1281 files and the cdr the corresponding command. Possible values for the
1282 file identifier are
1283 \"ext\" A string identifying an extension
1284 `directory' Matches a directory
1285 `remote' Matches a remote file, accessible through tramp or efs.
1286 Remote files most likely should be visited through Emacs
1287 because external applications cannot handle such paths.
1288 t Default for all remaining files
1290 Possible values for the command are:
1291 `emacs' The file will be visited by the current Emacs process.
1292 `default' Use the default application for this file type.
1293 string A command to be executed by a shell; %s will be replaced
1294 by the path to the file.
1295 sexp A Lisp form which will be evaluated. The file path will
1296 be available in the Lisp variable `file'.
1297 For more examples, see the system specific constants
1298 `org-file-apps-defaults-macosx'
1299 `org-file-apps-defaults-windowsnt'
1300 `org-file-apps-defaults-gnu'."
1301 :group 'org-link-follow
1302 :type '(repeat
1303 (cons (choice :value ""
1304 (string :tag "Extension")
1305 (const :tag "Default for unrecognized files" t)
1306 (const :tag "Remote file" remote)
1307 (const :tag "Links to a directory" directory))
1308 (choice :value ""
1309 (const :tag "Visit with Emacs" emacs)
1310 (const :tag "Use system default" default)
1311 (string :tag "Command")
1312 (sexp :tag "Lisp form")))))
1314 (defcustom org-mhe-search-all-folders nil
1315 "Non-nil means, that the search for the mh-message will be extended to
1316 all folders if the message cannot be found in the folder given in the link.
1317 Searching all folders is very efficient with one of the search engines
1318 supported by MH-E, but will be slow with pick."
1319 :group 'org-link-follow
1320 :type 'boolean)
1322 (defgroup org-remember nil
1323 "Options concerning interaction with remember.el."
1324 :tag "Org Remember"
1325 :group 'org)
1327 (defcustom org-directory "~/org"
1328 "Directory with org files.
1329 This directory will be used as default to prompt for org files.
1330 Used by the hooks for remember.el."
1331 :group 'org-remember
1332 :type 'directory)
1334 (defcustom org-default-notes-file "~/.notes"
1335 "Default target for storing notes.
1336 Used by the hooks for remember.el. This can be a string, or nil to mean
1337 the value of `remember-data-file'.
1338 You can set this on a per-template basis with the variable
1339 `org-remember-templates'."
1340 :group 'org-remember
1341 :type '(choice
1342 (const :tag "Default from remember-data-file" nil)
1343 file))
1345 (defcustom org-remember-store-without-prompt nil
1346 "Non-nil means, `C-c C-c' stores remember note without further promts.
1347 In this case, you need `C-u C-c C-c' to get the prompts for
1348 note file and headline.
1349 When this variable is nil, `C-c C-c' give you the prompts, and
1350 `C-u C-c C-c' trigger the fasttrack."
1351 :group 'org-remember
1352 :type 'boolean)
1354 (defcustom org-remember-default-headline ""
1355 "The headline that should be the default location in the notes file.
1356 When filing remember notes, the cursor will start at that position.
1357 You can set this on a per-template basis with the variable
1358 `org-remember-templates'."
1359 :group 'org-remember
1360 :type 'string)
1362 (defcustom org-remember-templates nil
1363 "Templates for the creation of remember buffers.
1364 When nil, just let remember make the buffer.
1365 When not nil, this is a list of 4-element lists. In each entry, the first
1366 element is a character, a unique key to select this template.
1367 The second element is the template. The third element is optional and can
1368 specify a destination file for remember items created with this template.
1369 The default file is given by `org-default-notes-file'. An optional forth
1370 element can specify the headline in that file that should be offered
1371 first when the user is asked to file the entry. The default headline is
1372 given in the variable `org-remember-default-headline'.
1374 The template specifies the structure of the remember buffer. It should have
1375 a first line starting with a star, to act as the org-mode headline.
1376 Furthermore, the following %-escapes will be replaced with content:
1378 %^{prompt} prompt the user for a string and replace this sequence with it.
1379 %t time stamp, date only
1380 %T time stamp with date and time
1381 %u, %U like the above, but inactive time stamps
1382 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1383 You may define a prompt like %^{Please specify birthday}t
1384 %n user name (taken from `user-full-name')
1385 %a annotation, normally the link created with org-store-link
1386 %i initial content, the region when remember is called with C-u.
1387 If %i is indented, the entire inserted text will be indented
1388 as well.
1390 %? After completing the template, position cursor here.
1392 Apart from these general escapes, you can access information specific to the
1393 link type that is created. For example, calling `remember' in emails or gnus
1394 will record the author and the subject of the message, which you can access
1395 with %:author and %:subject, respectively. Here is a complete list of what
1396 is recorded for each link type.
1398 Link type | Available information
1399 -------------------+------------------------------------------------------
1400 bbdb | %:type %:name %:company
1401 vm, wl, mh, rmail | %:type %:subject %:message-id
1402 | %:from %:fromname %:fromaddress
1403 | %:to %:toname %:toaddress
1404 | %:fromto (either \"to NAME\" or \"from NAME\")
1405 gnus | %:group, for messages also all email fields
1406 w3, w3m | %:type %:url
1407 info | %:type %:file %:node
1408 calendar | %:type %:date"
1409 :group 'org-remember
1410 :get (lambda (var) ; Make sure all entries have 4 elements
1411 (mapcar (lambda (x)
1412 (cond ((= (length x) 3) (append x '("")))
1413 ((= (length x) 2) (append x '("" "")))
1414 (t x)))
1415 (default-value var)))
1416 :type '(repeat
1417 :tag "enabled"
1418 (list :value (?a "\n" nil nil)
1419 (character :tag "Selection Key")
1420 (string :tag "Template")
1421 (file :tag "Destination file (optional)")
1422 (string :tag "Destination headline (optional)"))))
1424 (defcustom org-reverse-note-order nil
1425 "Non-nil means, store new notes at the beginning of a file or entry.
1426 When nil, new notes will be filed to the end of a file or entry."
1427 :group 'org-remember
1428 :type '(choice
1429 (const :tag "Reverse always" t)
1430 (const :tag "Reverse never" nil)
1431 (repeat :tag "By file name regexp"
1432 (cons regexp boolean))))
1434 (defgroup org-todo nil
1435 "Options concerning TODO items in Org-mode."
1436 :tag "Org TODO"
1437 :group 'org)
1439 (defgroup org-progress nil
1440 "Options concerning Progress logging in Org-mode."
1441 :tag "Org Progress"
1442 :group 'org-time)
1444 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1445 "List of TODO entry keyword sequences and their interpretation.
1446 \\<org-mode-map>This is a list of sequences.
1448 Each sequence starts with a symbol, either `sequence' or `type',
1449 indicating if the keywords should be interpreted as a sequence of
1450 action steps, or as different types of TODO items. The first
1451 keywords are states requiring action - these states will select a headline
1452 for inclusion into the global TODO list Org-mode produces. If one of
1453 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1454 signify that no further action is necessary. If \"|\" is not found,
1455 the last keyword is treated as the only DONE state of the sequence.
1457 The command \\[org-todo] cycles an entry through these states, and one
1458 additional state where no keyword is present. For details about this
1459 cycling, see the manual.
1461 TODO keywords and interpretation can also be set on a per-file basis with
1462 the special #+SEQ_TODO and #+TYP_TODO lines.
1464 For backward compatibility, this variable may also be just a list
1465 of keywords - in this case the interptetation (sequence or type) will be
1466 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1467 :group 'org-todo
1468 :group 'org-keywords
1469 :type '(choice
1470 (repeat :tag "Old syntax, just keywords"
1471 (string :tag "Keyword"))
1472 (repeat :tag "New syntax"
1473 (cons
1474 (choice
1475 :tag "Interpretation"
1476 (const :tag "Sequence (cycling hits every state)" sequence)
1477 (const :tag "Type (cycling directly to DONE)" type))
1478 (repeat
1479 (string :tag "Keyword"))))))
1481 (defvar org-todo-keywords-1 nil)
1482 (make-variable-buffer-local 'org-todo-keywords-1)
1483 (defvar org-todo-keywords-for-agenda nil)
1484 (defvar org-done-keywords-for-agenda nil)
1485 (defvar org-not-done-keywords nil)
1486 (make-variable-buffer-local 'org-not-done-keywords)
1487 (defvar org-done-keywords nil)
1488 (make-variable-buffer-local 'org-done-keywords)
1489 (defvar org-todo-heads nil)
1490 (make-variable-buffer-local 'org-todo-heads)
1491 (defvar org-todo-sets nil)
1492 (make-variable-buffer-local 'org-todo-sets)
1493 (defvar org-todo-kwd-alist nil)
1494 (make-variable-buffer-local 'org-todo-kwd-alist)
1496 (defcustom org-todo-interpretation 'sequence
1497 "Controls how TODO keywords are interpreted.
1498 This variable is in principle obsolete and is only used for
1499 backward compatibility, if the interpretation of todo keywords is
1500 not given already in `org-todo-keywords'. See that variable for
1501 more information."
1502 :group 'org-todo
1503 :group 'org-keywords
1504 :type '(choice (const sequence)
1505 (const type)))
1507 (defcustom org-after-todo-state-change-hook nil
1508 "Hook which is run after the state of a TODO item was changed.
1509 The new state (a string with a TODO keyword, or nil) is available in the
1510 Lisp variable `state'."
1511 :group 'org-todo
1512 :type 'hook)
1514 (defcustom org-log-done nil
1515 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1516 When the state of an entry is changed from nothing to TODO, remove a previous
1517 closing date.
1519 This can also be a list of symbols indicating under which conditions
1520 the time stamp recording the action should be annotated with a short note.
1521 Valid members of this list are
1523 done Offer to record a note when marking entries done
1524 state Offer to record a note whenever changing the TODO state
1525 of an item. This is only relevant if TODO keywords are
1526 interpreted as sequence, see variable `org-todo-interpretation'.
1527 When `state' is set, this includes tracking `done'.
1528 clock-out Offer to record a note when clocking out of an item.
1530 A separate window will then pop up and allow you to type a note.
1531 After finishing with C-c C-c, the note will be added directly after the
1532 timestamp, as a plain list item. See also the variable
1533 `org-log-note-headings'.
1535 Logging can also be configured on a per-file basis by adding one of
1536 the following lines anywhere in the buffer:
1538 #+STARTUP: logdone
1539 #+STARTUP: nologging
1540 #+STARTUP: lognotedone
1541 #+STARTUP: lognotestate
1542 #+STARTUP: lognoteclock-out"
1543 :group 'org-todo
1544 :group 'org-progress
1545 :type '(choice
1546 (const :tag "off" nil)
1547 (const :tag "on" t)
1548 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1549 (const :tag "when item is marked DONE" done)
1550 (const :tag "when TODO state changes" state)
1551 (const :tag "when clocking out" clock-out))))
1553 (defcustom org-log-done-with-time t
1554 "Non-nil means, the CLOSED time stamp will contain date and time.
1555 When nil, only the date will be recorded."
1556 :group 'org-progress
1557 :type 'boolean)
1559 (defcustom org-log-note-headings
1560 '((done . "CLOSING NOTE %t")
1561 (state . "State %-12s %t")
1562 (clock-out . ""))
1563 "Headings for notes added when clocking out or closing TODO items.
1564 The value is an alist, with the car being a symbol indicating the note
1565 context, and the cdr is the heading to be used. The heading may also be the
1566 empty string.
1567 %t in the heading will be replaced by a time stamp.
1568 %s will be replaced by the new TODO state, in double quotes.
1569 %u will be replaced by the user name.
1570 %U will be replaced by the full user name."
1571 :group 'org-todo
1572 :group 'org-progress
1573 :type '(list :greedy t
1574 (cons (const :tag "Heading when closing an item" done) string)
1575 (cons (const :tag
1576 "Heading when changing todo state (todo sequence only)"
1577 state) string)
1578 (cons (const :tag "Heading when clocking out" clock-out) string)))
1580 (defcustom org-log-states-order-reversed t
1581 "Non-nil means, the latest state change note will be directly after heading.
1582 When nil, the notes will be orderer according to time."
1583 :group 'org-todo
1584 :group 'org-progress
1585 :type 'boolean)
1587 (defcustom org-log-repeat t
1588 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1589 When nil, no note will be taken."
1590 :group 'org-todo
1591 :group 'org-progress
1592 :type 'boolean)
1594 (defcustom org-clock-out-when-done t
1595 "When t, the clock will be stopped when the relevant entry is marked DONE.
1596 Nil means, clock will keep running until stopped explicitly with
1597 `C-c C-x C-o', or until the clock is started in a different item."
1598 :group 'org-progress
1599 :type 'boolean)
1601 (defgroup org-priorities nil
1602 "Priorities in Org-mode."
1603 :tag "Org Priorities"
1604 :group 'org-todo)
1606 (defcustom org-highest-priority ?A
1607 "The highest priority of TODO items. A character like ?A, ?B etc.
1608 Must have a smaller ASCII number than `org-lowest-priority'."
1609 :group 'org-priorities
1610 :type 'character)
1612 (defcustom org-lowest-priority ?C
1613 "The lowest priority of TODO items. A character like ?A, ?B etc.
1614 Must have a larger ASCII number than `org-highest-priority'."
1615 :group 'org-priorities
1616 :type 'character)
1618 (defcustom org-default-priority ?B
1619 "The default priority of TODO items.
1620 This is the priority an item get if no explicit priority is given."
1621 :group 'org-priorities
1622 :type 'character)
1624 (defgroup org-time nil
1625 "Options concerning time stamps and deadlines in Org-mode."
1626 :tag "Org Time"
1627 :group 'org)
1629 (defcustom org-insert-labeled-timestamps-at-point nil
1630 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1631 When nil, these labeled time stamps are forces into the second line of an
1632 entry, just after the headline. When scheduling from the global TODO list,
1633 the time stamp will always be forced into the second line."
1634 :group 'org-time
1635 :type 'boolean)
1637 (defcustom org-insert-labeled-timestamps-before-properties-drawer t
1638 "Non-nil means, always insert planning info before property drawer.
1639 When this is nil and there is a property drawer *directly* after
1640 the headline, move the planning info into the drawer. If the property
1641 drawer separated from the headline by at least one line, this variable
1642 has no effect."
1643 :group 'org-time
1644 :type 'boolean)
1646 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1647 "Formats for `format-time-string' which are used for time stamps.
1648 It is not recommended to change this constant.")
1650 (defcustom org-time-stamp-rounding-minutes 0
1651 "Number of minutes to round time stamps to upon insertion.
1652 When zero, insert the time unmodified. Useful rounding numbers
1653 should be factors of 60, so for example 5, 10, 15.
1654 When this is not zero, you can still force an exact time-stamp by using
1655 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1656 :group 'org-time
1657 :type 'integer)
1659 (defcustom org-display-custom-times nil
1660 "Non-nil means, overlay custom formats over all time stamps.
1661 The formats are defined through the variable `org-time-stamp-custom-formats'.
1662 To turn this on on a per-file basis, insert anywhere in the file:
1663 #+STARTUP: customtime"
1664 :group 'org-time
1665 :set 'set-default
1666 :type 'sexp)
1667 (make-variable-buffer-local 'org-display-custom-times)
1669 (defcustom org-time-stamp-custom-formats
1670 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1671 "Custom formats for time stamps. See `format-time-string' for the syntax.
1672 These are overlayed over the default ISO format if the variable
1673 `org-display-custom-times' is set. Time like %H:%M should be at the
1674 end of the second format."
1675 :group 'org-time
1676 :type 'sexp)
1678 (defun org-time-stamp-format (&optional long inactive)
1679 "Get the right format for a time string."
1680 (let ((f (if long (cdr org-time-stamp-formats)
1681 (car org-time-stamp-formats))))
1682 (if inactive
1683 (concat "[" (substring f 1 -1) "]")
1684 f)))
1686 (defcustom org-deadline-warning-days 30
1687 "No. of days before expiration during which a deadline becomes active.
1688 This variable governs the display in sparse trees and in the agenda."
1689 :group 'org-time
1690 :type 'number)
1692 (defcustom org-popup-calendar-for-date-prompt t
1693 "Non-nil means, pop up a calendar when prompting for a date.
1694 In the calendar, the date can be selected with mouse-1. However, the
1695 minibuffer will also be active, and you can simply enter the date as well.
1696 When nil, only the minibuffer will be available."
1697 :group 'org-time
1698 :type 'boolean)
1700 (defcustom org-calendar-follow-timestamp-change t
1701 "Non-nil means, make the calendar window follow timestamp changes.
1702 When a timestamp is modified and the calendar window is visible, it will be
1703 moved to the new date."
1704 :group 'org-time
1705 :type 'boolean)
1707 (defgroup org-tags nil
1708 "Options concerning tags in Org-mode."
1709 :tag "Org Tags"
1710 :group 'org)
1712 (defcustom org-tag-alist nil
1713 "List of tags allowed in Org-mode files.
1714 When this list is nil, Org-mode will base TAG input on what is already in the
1715 buffer.
1716 The value of this variable is an alist, the car may be (and should) be a
1717 character that is used to select that tag through the fast-tag-selection
1718 interface. See the manual for details."
1719 :group 'org-tags
1720 :type '(repeat
1721 (choice
1722 (cons (string :tag "Tag name")
1723 (character :tag "Access char"))
1724 (const :tag "Start radio group" (:startgroup))
1725 (const :tag "End radio group" (:endgroup)))))
1727 (defcustom org-use-fast-tag-selection 'auto
1728 "Non-nil means, use fast tag selection scheme.
1729 This is a special interface to select and deselect tags with single keys.
1730 When nil, fast selection is never used.
1731 When the symbol `auto', fast selection is used if and only if selection
1732 characters for tags have been configured, either through the variable
1733 `org-tag-alist' or through a #+TAGS line in the buffer.
1734 When t, fast selection is always used and selection keys are assigned
1735 automatically if necessary."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Always" t)
1739 (const :tag "Never" nil)
1740 (const :tag "When selection characters are configured" 'auto)))
1742 (defcustom org-fast-tag-selection-single-key nil
1743 "Non-nil means, fast tag selection exits after first change.
1744 When nil, you have to press RET to exit it.
1745 During fast tag selection, you can toggle this flag with `C-c'.
1746 This variable can also have the value `expert'. In this case, the window
1747 displaying the tags menu is not even shown, until you press C-c again."
1748 :group 'org-tags
1749 :type '(choice
1750 (const :tag "No" nil)
1751 (const :tag "Yes" t)
1752 (const :tag "Expert" expert)))
1754 (defcustom org-tags-column 48
1755 "The column to which tags should be indented in a headline.
1756 If this number is positive, it specifies the column. If it is negative,
1757 it means that the tags should be flushright to that column. For example,
1758 -79 works well for a normal 80 character screen."
1759 :group 'org-tags
1760 :type 'integer)
1762 (defcustom org-auto-align-tags t
1763 "Non-nil means, realign tags after pro/demotion of TODO state change.
1764 These operations change the length of a headline and therefore shift
1765 the tags around. With this options turned on, after each such operation
1766 the tags are again aligned to `org-tags-column'."
1767 :group 'org-tags
1768 :type 'boolean)
1770 (defcustom org-use-tag-inheritance t
1771 "Non-nil means, tags in levels apply also for sublevels.
1772 When nil, only the tags directly given in a specific line apply there.
1773 If you turn off this option, you very likely want to turn on the
1774 companion option `org-tags-match-list-sublevels'."
1775 :group 'org-tags
1776 :type 'boolean)
1778 (defcustom org-tags-match-list-sublevels nil
1779 "Non-nil means list also sublevels of headlines matching tag search.
1780 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1781 the sublevels of a headline matching a tag search often also match
1782 the same search. Listing all of them can create very long lists.
1783 Setting this variable to nil causes subtrees of a match to be skipped.
1784 This option is off by default, because inheritance in on. If you turn
1785 inheritance off, you very likely want to turn this option on.
1787 As a special case, if the tag search is restricted to TODO items, the
1788 value of this variable is ignored and sublevels are always checked, to
1789 make sure all corresponding TODO items find their way into the list."
1790 :group 'org-tags
1791 :type 'boolean)
1793 (defvar org-tags-history nil
1794 "History of minibuffer reads for tags.")
1795 (defvar org-last-tags-completion-table nil
1796 "The last used completion table for tags.")
1798 (defgroup org-properties nil
1799 "Options concerning properties in Org-mode."
1800 :tag "Org Properties"
1801 :group 'org)
1803 (defcustom org-property-format "%-10s %s"
1804 "How property key/value pairs should be formatted by `indent-line'.
1805 When `indent-line' hits a property definition, it will format the line
1806 according to this format, mainly to make sure that the values are
1807 lined-up with respect to each other."
1808 :group 'org-properties
1809 :type 'string)
1811 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1812 "The default column format, if no other format has been defined.
1813 This variable can be set on the per-file basis by inserting a line
1815 #+COLUMNS: %25ITEM ....."
1816 :group 'org-properties
1817 :type 'string)
1819 (defcustom org-global-properties nil
1820 "List of property/value pairs that can be inherited by any entry.
1821 You can set buffer-local values for this by adding lines like
1823 #+PROPERTY: NAME VALUE"
1824 :group 'org-properties
1825 :type '(repeat
1826 (cons (string :tag "Property")
1827 (string :tag "Value"))))
1829 (defvar org-local-properties nil
1830 "List of property/value pairs that can be inherited by any entry.
1831 Valid for the current buffer.
1832 This variable is populated from #+PROPERTY lines.")
1834 (defgroup org-agenda nil
1835 "Options concerning agenda views in Org-mode."
1836 :tag "Org Agenda"
1837 :group 'org)
1839 (defvar org-category nil
1840 "Variable used by org files to set a category for agenda display.
1841 Such files should use a file variable to set it, for example
1843 # -*- mode: org; org-category: \"ELisp\"
1845 or contain a special line
1847 #+CATEGORY: ELisp
1849 If the file does not specify a category, then file's base name
1850 is used instead.")
1851 (make-variable-buffer-local 'org-category)
1853 (defcustom org-agenda-files nil
1854 "The files to be used for agenda display.
1855 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1856 \\[org-remove-file]. You can also use customize to edit the list.
1858 If the value of the variable is not a list but a single file name, then
1859 the list of agenda files is actually stored and maintained in that file, one
1860 agenda file per line."
1861 :group 'org-agenda
1862 :type '(choice
1863 (repeat :tag "List of files" file)
1864 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1867 (defcustom org-agenda-confirm-kill 1
1868 "When set, remote killing from the agenda buffer needs confirmation.
1869 When t, a confirmation is always needed. When a number N, confirmation is
1870 only needed when the text to be killed contains more than N non-white lines."
1871 :group 'org-agenda
1872 :type '(choice
1873 (const :tag "Never" nil)
1874 (const :tag "Always" t)
1875 (number :tag "When more than N lines")))
1877 (defcustom org-calendar-to-agenda-key [?c]
1878 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1879 The command `org-calendar-goto-agenda' will be bound to this key. The
1880 default is the character `c' because then `c' can be used to switch back and
1881 forth between agenda and calendar."
1882 :group 'org-agenda
1883 :type 'sexp)
1885 (defgroup org-agenda-export nil
1886 "Options concerning exporting agenda views in Org-mode."
1887 :tag "Org Agenda Export"
1888 :group 'org-agenda)
1890 (defcustom org-agenda-with-colors t
1891 "Non-nil means, use colors in agenda views."
1892 :group 'org-agenda-export
1893 :type 'boolean)
1895 (defcustom org-agenda-exporter-settings nil
1896 "Alist of variable/value pairs that should be active during agenda export.
1897 This is a good place to set uptions for ps-print and for htmlize."
1898 :group 'org-agenda-export
1899 :type '(repeat
1900 (list
1901 (variable)
1902 (sexp :tag "Value"))))
1904 (defcustom org-agenda-export-html-style ""
1905 "The style specification for exported HTML Agenda files.
1906 If this variable contains a string, it will replace the default <style>
1907 section as produced by `htmlize'.
1908 Since there are different ways of setting style information, this variable
1909 needs to contain the full HTML structure to provide a style, including the
1910 surrounding HTML tags. The style specifications should include definitions
1911 the fonts used by the agenda, here is an example:
1913 <style type=\"text/css\">
1914 p { font-weight: normal; color: gray; }
1915 .org-agenda-structure {
1916 font-size: 110%;
1917 color: #003399;
1918 font-weight: 600;
1920 .org-todo {
1921 color: #cc6666;Week-agenda:
1922 font-weight: bold;
1924 .org-done {
1925 color: #339933;
1927 .title { text-align: center; }
1928 .todo, .deadline { color: red; }
1929 .done { color: green; }
1930 </style>
1932 or, if you want to keep the style in a file,
1934 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1936 As the value of this option simply gets inserted into the HTML <head> header,
1937 you can \"misuse\" it to also add other text to the header. However,
1938 <style>...</style> is required, if not present the variable will be ignored."
1939 :group 'org-agenda-export
1940 :group 'org-export-html
1941 :type 'string)
1943 (defgroup org-agenda-custom-commands nil
1944 "Options concerning agenda views in Org-mode."
1945 :tag "Org Agenda Custom Commands"
1946 :group 'org-agenda)
1948 (defcustom org-agenda-custom-commands nil
1949 "Custom commands for the agenda.
1950 These commands will be offered on the splash screen displayed by the
1951 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1953 (key type match options files)
1955 key The key (a single char as a string) to be associated with the command.
1956 type The command type, any of the following symbols:
1957 todo Entries with a specific TODO keyword, in all agenda files.
1958 tags Tags match in all agenda files.
1959 tags-todo Tags match in all agenda files, TODO entries only.
1960 todo-tree Sparse tree of specific TODO keyword in *current* file.
1961 tags-tree Sparse tree with all tags matches in *current* file.
1962 occur-tree Occur sparse tree for *current* file.
1963 match What to search for:
1964 - a single keyword for TODO keyword searches
1965 - a tags match expression for tags searches
1966 - a regular expression for occur searches
1967 options A list of option settings, similar to that in a let form, so like
1968 this: ((opt1 val1) (opt2 val2) ...)
1969 files A list of files file to write the produced agenda buffer to
1970 with the command `org-store-agenda-views'.
1971 If a file name ends in \".html\", an HTML version of the buffer
1972 is written out. If it ends in \".ps\", a postscript version is
1973 produced. Otherwide, only the plain text is written to the file.
1975 You can also define a set of commands, to create a composite agenda buffer.
1976 In this case, an entry looks like this:
1978 (key desc (cmd1 cmd2 ...) general-options file)
1980 where
1982 desc A description string to be displayed in the dispatcher menu.
1983 cmd An agenda command, similar to the above. However, tree commands
1984 are no allowed, but instead you can get agenda and global todo list.
1985 So valid commands for a set are:
1986 (agenda)
1987 (alltodo)
1988 (stuck)
1989 (todo \"match\" options files)
1990 (tags \"match\" options files)
1991 (tags-todo \"match\" options files)
1993 Each command can carry a list of options, and another set of options can be
1994 given for the whole set of commands. Individual command options take
1995 precedence over the general options."
1996 :group 'org-agenda-custom-commands
1997 :type '(repeat
1998 (choice :value ("a" tags "" nil)
1999 (list :tag "Single command"
2000 (string :tag "Key")
2001 (choice
2002 (const :tag "Agenda" agenda)
2003 (const :tag "TODO list" alltodo)
2004 (const :tag "Stuck projects" stuck)
2005 (const :tag "Tags search (all agenda files)" tags)
2006 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2007 (const :tag "TODO keyword search (all agenda files)" todo)
2008 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2009 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2010 (const :tag "Occur tree (current buffer)" occur-tree)
2011 (symbol :tag "Other, user-defined function"))
2012 (string :tag "Match")
2013 (repeat :tag "Local options"
2014 (list (variable :tag "Option") (sexp :tag "Value")))
2015 (option (repeat :tag "Export" (file :tag "Export to"))))
2016 (list :tag "Command series, all agenda files"
2017 (string :tag "Key")
2018 (string :tag "Description")
2019 (repeat
2020 (choice
2021 (const :tag "Agenda" (agenda))
2022 (const :tag "TODO list" (alltodo))
2023 (const :tag "Stuck projects" (stuck))
2024 (list :tag "Tags search"
2025 (const :format "" tags)
2026 (string :tag "Match")
2027 (repeat :tag "Local options"
2028 (list (variable :tag "Option")
2029 (sexp :tag "Value"))))
2031 (list :tag "Tags search, TODO entries only"
2032 (const :format "" tags-todo)
2033 (string :tag "Match")
2034 (repeat :tag "Local options"
2035 (list (variable :tag "Option")
2036 (sexp :tag "Value"))))
2038 (list :tag "TODO keyword search"
2039 (const :format "" todo)
2040 (string :tag "Match")
2041 (repeat :tag "Local options"
2042 (list (variable :tag "Option")
2043 (sexp :tag "Value"))))
2045 (list :tag "Other, user-defined function"
2046 (symbol :tag "function")
2047 (string :tag "Match")
2048 (repeat :tag "Local options"
2049 (list (variable :tag "Option")
2050 (sexp :tag "Value"))))))
2052 (repeat :tag "General options"
2053 (list (variable :tag "Option")
2054 (sexp :tag "Value")))
2055 (option (repeat :tag "Export" (file :tag "Export to")))))))
2057 (defcustom org-stuck-projects
2058 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2059 "How to identify stuck projects.
2060 This is a list of four items:
2061 1. A tags/todo matcher string that is used to identify a project.
2062 The entire tree below a headline matched by this is considered one project.
2063 2. A list of TODO keywords identifying non-stuck projects.
2064 If the project subtree contains any headline with one of these todo
2065 keywords, the project is considered to be not stuck. If you specify
2066 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2067 3. A list of tags identifying non-stuck projects.
2068 If the project subtree contains any headline with one of these tags,
2069 the project is considered to be not stuck. If you specify \"*\" as
2070 a tag, any tag will mark the project unstuck.
2071 4. An arbitrary regular expression matching non-stuck projects.
2073 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2074 or `C-c a #' to produce the list."
2075 :group 'org-agenda-custom-commands
2076 :type '(list
2077 (string :tag "Tags/TODO match to identify a project")
2078 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2079 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2080 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2083 (defgroup org-agenda-skip nil
2084 "Options concerning skipping parts of agenda files."
2085 :tag "Org Agenda Skip"
2086 :group 'org-agenda)
2088 (defcustom org-agenda-todo-list-sublevels t
2089 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2090 When nil, the sublevels of a TODO entry are not checked, resulting in
2091 potentially much shorter TODO lists."
2092 :group 'org-agenda-skip
2093 :group 'org-todo
2094 :type 'boolean)
2096 (defcustom org-agenda-todo-ignore-scheduled nil
2097 "Non-nil means, don't show scheduled entries in the global todo list.
2098 The idea behind this is that by scheduling it, you have already taken care
2099 of this item."
2100 :group 'org-agenda-skip
2101 :group 'org-todo
2102 :type 'boolean)
2104 (defcustom org-agenda-todo-ignore-deadlines nil
2105 "Non-nil means, don't show near deadline entries in the global todo list.
2106 Near means closer than `org-deadline-warning-days' days.
2107 The idea behind this is that such items will appear in the agenda anyway."
2108 :group 'org-agenda-skip
2109 :group 'org-todo
2110 :type 'boolean)
2112 (defcustom org-agenda-skip-scheduled-if-done nil
2113 "Non-nil means don't show scheduled items in agenda when they are done.
2114 This is relevant for the daily/weekly agenda, not for the TODO list."
2115 :group 'org-agenda-skip
2116 :type 'boolean)
2118 (defcustom org-agenda-skip-deadline-if-done nil
2119 "Non-nil means don't show deadines when the corresponding item is done.
2120 When nil, the deadline is still shown and should give you a happy feeling.
2122 This is relevant for the daily/weekly agenda."
2123 :group 'org-agenda-skip
2124 :type 'boolean)
2126 (defcustom org-timeline-show-empty-dates 3
2127 "Non-nil means, `org-timeline' also shows dates without an entry.
2128 When nil, only the days which actually have entries are shown.
2129 When t, all days between the first and the last date are shown.
2130 When an integer, show also empty dates, but if there is a gap of more than
2131 N days, just insert a special line indicating the size of the gap."
2132 :group 'org-agenda-skip
2133 :type '(choice
2134 (const :tag "None" nil)
2135 (const :tag "All" t)
2136 (number :tag "at most")))
2139 (defgroup org-agenda-startup nil
2140 "Options concerning initial settings in the Agenda in Org Mode."
2141 :tag "Org Agenda Startup"
2142 :group 'org-agenda)
2144 (defcustom org-finalize-agenda-hook nil
2145 "Hook run just before displaying an agenda buffer."
2146 :group 'org-agenda-startup
2147 :type 'hook)
2149 (defcustom org-agenda-mouse-1-follows-link nil
2150 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2151 A longer mouse click will still set point. Does not wortk on XEmacs.
2152 Needs to be set before org.el is loaded."
2153 :group 'org-agenda-startup
2154 :type 'boolean)
2156 (defcustom org-agenda-start-with-follow-mode nil
2157 "The initial value of follow-mode in a newly created agenda window."
2158 :group 'org-agenda-startup
2159 :type 'boolean)
2161 (defgroup org-agenda-windows nil
2162 "Options concerning the windows used by the Agenda in Org Mode."
2163 :tag "Org Agenda Windows"
2164 :group 'org-agenda)
2166 (defcustom org-agenda-window-setup 'reorganize-frame
2167 "How the agenda buffer should be displayed.
2168 Possible values for this option are:
2170 current-window Show agenda in the current window, keeping all other windows.
2171 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2172 other-window Use `switch-to-buffer-other-window' to display agenda.
2173 reorganize-frame Show only two windows on the current frame, the current
2174 window and the agenda.
2175 See also the variable `org-agenda-restore-windows-after-quit'."
2176 :group 'org-agenda-windows
2177 :type '(choice
2178 (const current-window)
2179 (const other-frame)
2180 (const other-window)
2181 (const reorganize-frame)))
2183 (defcustom org-agenda-restore-windows-after-quit nil
2184 "Non-nil means, restore window configuration open exiting agenda.
2185 Before the window configuration is changed for displaying the agenda,
2186 the current status is recorded. When the agenda is exited with
2187 `q' or `x' and this option is set, the old state is restored. If
2188 `org-agenda-window-setup' is `other-frame', the value of this
2189 option will be ignored.."
2190 :group 'org-agenda-windows
2191 :type 'boolean)
2193 (defcustom org-indirect-buffer-display 'other-window
2194 "How should indirect tree buffers be displayed?
2195 This applies to indirect buffers created with the commands
2196 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2197 Valid values are:
2198 current-window Display in the current window
2199 other-window Just display in another window.
2200 dedicated-frame Create one new frame, and re-use it each time.
2201 new-frame Make a new frame each time."
2202 :group 'org-structure
2203 :group 'org-agenda-windows
2204 :type '(choice
2205 (const :tag "In current window" current-window)
2206 (const :tag "In current frame, other window" other-window)
2207 (const :tag "Each time a new frame" new-frame)
2208 (const :tag "One dedicated frame" dedicated-frame)))
2210 (defgroup org-agenda-daily/weekly nil
2211 "Options concerning the daily/weekly agenda."
2212 :tag "Org Agenda Daily/Weekly"
2213 :group 'org-agenda)
2215 (defcustom org-agenda-ndays 7
2216 "Number of days to include in overview display.
2217 Should be 1 or 7."
2218 :group 'org-agenda-daily/weekly
2219 :type 'number)
2221 (defcustom org-agenda-start-on-weekday 1
2222 "Non-nil means, start the overview always on the specified weekday.
2223 0 denotes Sunday, 1 denotes Monday etc.
2224 When nil, always start on the current day."
2225 :group 'org-agenda-daily/weekly
2226 :type '(choice (const :tag "Today" nil)
2227 (number :tag "Weekday No.")))
2229 (defcustom org-agenda-show-all-dates t
2230 "Non-nil means, `org-agenda' shows every day in the selected range.
2231 When nil, only the days which actually have entries are shown."
2232 :group 'org-agenda-daily/weekly
2233 :type 'boolean)
2235 (defcustom org-agenda-date-format "%A %d %B %Y"
2236 "Format string for displaying dates in the agenda.
2237 Used by the daily/weekly agenda and by the timeline. This should be
2238 a format string understood by `format-time-string'.
2239 FIXME: Not used currently, because of timezone problem."
2240 :group 'org-agenda-daily/weekly
2241 :type 'string)
2243 (defcustom org-agenda-include-diary nil
2244 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2245 :group 'org-agenda-daily/weekly
2246 :type 'boolean)
2248 (defcustom org-agenda-include-all-todo nil
2249 "Set means weekly/daily agenda will always contain all TODO entries.
2250 The TODO entries will be listed at the top of the agenda, before
2251 the entries for specific days."
2252 :group 'org-agenda-daily/weekly
2253 :type 'boolean)
2255 (defcustom org-agenda-repeating-timestamp-show-all t
2256 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2257 When nil, only one occurence is shown, either today or the
2258 nearest into the future."
2259 :group 'org-agenda-daily/weekly
2260 :type 'boolean)
2262 (defgroup org-agenda-time-grid nil
2263 "Options concerning the time grid in the Org-mode Agenda."
2264 :tag "Org Agenda Time Grid"
2265 :group 'org-agenda)
2267 (defcustom org-agenda-use-time-grid t
2268 "Non-nil means, show a time grid in the agenda schedule.
2269 A time grid is a set of lines for specific times (like every two hours between
2270 8:00 and 20:00). The items scheduled for a day at specific times are
2271 sorted in between these lines.
2272 For details about when the grid will be shown, and what it will look like, see
2273 the variable `org-agenda-time-grid'."
2274 :group 'org-agenda-time-grid
2275 :type 'boolean)
2277 (defcustom org-agenda-time-grid
2278 '((daily today require-timed)
2279 "----------------"
2280 (800 1000 1200 1400 1600 1800 2000))
2282 "The settings for time grid for agenda display.
2283 This is a list of three items. The first item is again a list. It contains
2284 symbols specifying conditions when the grid should be displayed:
2286 daily if the agenda shows a single day
2287 weekly if the agenda shows an entire week
2288 today show grid on current date, independent of daily/weekly display
2289 require-timed show grid only if at least one item has a time specification
2291 The second item is a string which will be places behing the grid time.
2293 The third item is a list of integers, indicating the times that should have
2294 a grid line."
2295 :group 'org-agenda-time-grid
2296 :type
2297 '(list
2298 (set :greedy t :tag "Grid Display Options"
2299 (const :tag "Show grid in single day agenda display" daily)
2300 (const :tag "Show grid in weekly agenda display" weekly)
2301 (const :tag "Always show grid for today" today)
2302 (const :tag "Show grid only if any timed entries are present"
2303 require-timed)
2304 (const :tag "Skip grid times already present in an entry"
2305 remove-match))
2306 (string :tag "Grid String")
2307 (repeat :tag "Grid Times" (integer :tag "Time"))))
2309 (defgroup org-agenda-sorting nil
2310 "Options concerning sorting in the Org-mode Agenda."
2311 :tag "Org Agenda Sorting"
2312 :group 'org-agenda)
2314 (let ((sorting-choice
2315 '(choice
2316 (const time-up) (const time-down)
2317 (const category-keep) (const category-up) (const category-down)
2318 (const tag-down) (const tag-up)
2319 (const priority-up) (const priority-down))))
2321 (defcustom org-agenda-sorting-strategy
2322 '((agenda time-up category-keep priority-down)
2323 (todo category-keep priority-down)
2324 (tags category-keep priority-down))
2325 "Sorting structure for the agenda items of a single day.
2326 This is a list of symbols which will be used in sequence to determine
2327 if an entry should be listed before another entry. The following
2328 symbols are recognized:
2330 time-up Put entries with time-of-day indications first, early first
2331 time-down Put entries with time-of-day indications first, late first
2332 category-keep Keep the default order of categories, corresponding to the
2333 sequence in `org-agenda-files'.
2334 category-up Sort alphabetically by category, A-Z.
2335 category-down Sort alphabetically by category, Z-A.
2336 tag-up Sort alphabetically by last tag, A-Z.
2337 tag-down Sort alphabetically by last tag, Z-A.
2338 priority-up Sort numerically by priority, high priority last.
2339 priority-down Sort numerically by priority, high priority first.
2341 The different possibilities will be tried in sequence, and testing stops
2342 if one comparison returns a \"not-equal\". For example, the default
2343 '(time-up category-keep priority-down)
2344 means: Pull out all entries having a specified time of day and sort them,
2345 in order to make a time schedule for the current day the first thing in the
2346 agenda listing for the day. Of the entries without a time indication, keep
2347 the grouped in categories, don't sort the categories, but keep them in
2348 the sequence given in `org-agenda-files'. Within each category sort by
2349 priority.
2351 Leaving out `category-keep' would mean that items will be sorted across
2352 categories by priority."
2353 :group 'org-agenda-sorting
2354 :type `(choice
2355 (repeat :tag "General" ,sorting-choice)
2356 (list :tag "Individually"
2357 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2358 (repeat ,sorting-choice))
2359 (cons (const :tag "Strategy for TODO lists" todo)
2360 (repeat ,sorting-choice))
2361 (cons (const :tag "Strategy for Tags matches" tags)
2362 (repeat ,sorting-choice))))))
2364 (defcustom org-sort-agenda-notime-is-late t
2365 "Non-nil means, items without time are considered late.
2366 This is only relevant for sorting. When t, items which have no explicit
2367 time like 15:30 will be considered as 99:01, i.e. later than any items which
2368 do have a time. When nil, the default time is before 0:00. You can use this
2369 option to decide if the schedule for today should come before or after timeless
2370 agenda entries."
2371 :group 'org-agenda-sorting
2372 :type 'boolean)
2374 (defgroup org-agenda-prefix nil
2375 "Options concerning the entry prefix in the Org-mode agenda display."
2376 :tag "Org Agenda Prefix"
2377 :group 'org-agenda)
2379 (defcustom org-agenda-prefix-format
2380 '((agenda . " %-12:c%?-12t% s")
2381 (timeline . " % s")
2382 (todo . " %-12:c")
2383 (tags . " %-12:c"))
2384 "Format specifications for the prefix of items in the agenda views.
2385 An alist with four entries, for the different agenda types. The keys to the
2386 sublists are `agenda', `timeline', `todo', and `tags'. The values
2387 are format strings.
2388 This format works similar to a printf format, with the following meaning:
2390 %c the category of the item, \"Diary\" for entries from the diary, or
2391 as given by the CATEGORY keyword or derived from the file name.
2392 %T the *last* tag of the item. Last because inherited tags come
2393 first in the list.
2394 %t the time-of-day specification if one applies to the entry, in the
2395 format HH:MM
2396 %s Scheduling/Deadline information, a short string
2398 All specifiers work basically like the standard `%s' of printf, but may
2399 contain two additional characters: A question mark just after the `%' and
2400 a whitespace/punctuation character just before the final letter.
2402 If the first character after `%' is a question mark, the entire field
2403 will only be included if the corresponding value applies to the
2404 current entry. This is useful for fields which should have fixed
2405 width when present, but zero width when absent. For example,
2406 \"%?-12t\" will result in a 12 character time field if a time of the
2407 day is specified, but will completely disappear in entries which do
2408 not contain a time.
2410 If there is punctuation or whitespace character just before the final
2411 format letter, this character will be appended to the field value if
2412 the value is not empty. For example, the format \"%-12:c\" leads to
2413 \"Diary: \" if the category is \"Diary\". If the category were be
2414 empty, no additional colon would be interted.
2416 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2417 - Indent the line with two space characters
2418 - Give the category in a 12 chars wide field, padded with whitespace on
2419 the right (because of `-'). Append a colon if there is a category
2420 (because of `:').
2421 - If there is a time-of-day, put it into a 12 chars wide field. If no
2422 time, don't put in an empty field, just skip it (because of '?').
2423 - Finally, put the scheduling information and append a whitespace.
2425 As another example, if you don't want the time-of-day of entries in
2426 the prefix, you could use:
2428 (setq org-agenda-prefix-format \" %-11:c% s\")
2430 See also the variables `org-agenda-remove-times-when-in-prefix' and
2431 `org-agenda-remove-tags'."
2432 :type '(choice
2433 (string :tag "General format")
2434 (list :greedy t :tag "View dependent"
2435 (cons (const agenda) (string :tag "Format"))
2436 (cons (const timeline) (string :tag "Format"))
2437 (cons (const todo) (string :tag "Format"))
2438 (cons (const tags) (string :tag "Format"))))
2439 :group 'org-agenda-prefix)
2441 (defvar org-prefix-format-compiled nil
2442 "The compiled version of the most recently used prefix format.
2443 See the variable `org-agenda-prefix-format'.")
2445 (defcustom org-agenda-remove-times-when-in-prefix t
2446 "Non-nil means, remove duplicate time specifications in agenda items.
2447 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2448 time-of-day specification in a headline or diary entry is extracted and
2449 placed into the prefix. If this option is non-nil, the original specification
2450 \(a timestamp or -range, or just a plain time(range) specification like
2451 11:30-4pm) will be removed for agenda display. This makes the agenda less
2452 cluttered.
2453 The option can be t or nil. It may also be the symbol `beg', indicating
2454 that the time should only be removed what it is located at the beginning of
2455 the headline/diary entry."
2456 :group 'org-agenda-prefix
2457 :type '(choice
2458 (const :tag "Always" t)
2459 (const :tag "Never" nil)
2460 (const :tag "When at beginning of entry" beg)))
2463 (defcustom org-agenda-default-appointment-duration nil
2464 "Default duration for appointments that only have a starting time.
2465 When nil, no duration is specified in such cases.
2466 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2467 :group 'org-agenda-prefix
2468 :type '(choice
2469 (integer :tag "Minutes")
2470 (const :tag "No default duration")))
2473 (defcustom org-agenda-remove-tags nil
2474 "Non-nil means, remove the tags from the headline copy in the agenda.
2475 When this is the symbol `prefix', only remove tags when
2476 `org-agenda-prefix-format' contains a `%T' specifier."
2477 :group 'org-agenda-prefix
2478 :type '(choice
2479 (const :tag "Always" t)
2480 (const :tag "Never" nil)
2481 (const :tag "When prefix format contains %T" prefix)))
2483 (if (fboundp 'defvaralias)
2484 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2485 'org-agenda-remove-tags))
2487 (defcustom org-agenda-align-tags-to-column 65
2488 "Shift tags in agenda items to this column."
2489 :group 'org-agenda-prefix
2490 :type 'integer)
2492 (defgroup org-latex nil
2493 "Options for embedding LaTeX code into Org-mode"
2494 :tag "Org LaTeX"
2495 :group 'org)
2497 (defcustom org-format-latex-options
2498 '(:foreground default :background default :scale 1.0
2499 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2500 :matchers ("begin" "$" "$$" "\\(" "\\["))
2501 "Options for creating images from LaTeX fragments.
2502 This is a property list with the following properties:
2503 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2504 `default' means use the forground of the default face.
2505 :background the background color, or \"Transparent\".
2506 `default' means use the background of the default face.
2507 :scale a scaling factor for the size of the images
2508 :html-foreground, :html-background, :html-scale
2509 The same numbers for HTML export.
2510 :matchers a list indicating which matchers should be used to
2511 find LaTeX fragments. Valid members of this list are:
2512 \"begin\" find environments
2513 \"$\" find math expressions surrounded by $...$
2514 \"$$\" find math expressions surrounded by $$....$$
2515 \"\\(\" find math expressions surrounded by \\(...\\)
2516 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2517 :group 'org-export-latex
2518 :type 'plist)
2520 (defcustom org-format-latex-header "\\documentclass{article}
2521 \\usepackage{fullpage} % do not remove
2522 \\usepackage{amssymb}
2523 \\usepackage[usenames]{color}
2524 \\usepackage{amsmath}
2525 \\usepackage{latexsym}
2526 \\usepackage[mathscr]{eucal}
2527 \\pagestyle{empty} % do not remove"
2528 "The document header used for processing LaTeX fragments."
2529 :group 'org-export-latex
2530 :type 'string)
2532 (defgroup org-export nil
2533 "Options for exporting org-listings."
2534 :tag "Org Export"
2535 :group 'org)
2537 (defgroup org-export-general nil
2538 "General options for exporting Org-mode files."
2539 :tag "Org Export General"
2540 :group 'org-export)
2542 (defcustom org-export-publishing-directory "."
2543 "Path to the location where exported files should be located.
2544 This path may be relative to the directory where the Org-mode file lives.
2545 The default is to put them into the same directory as the Org-mode file.
2546 The variable may also be an alist with export types `:html', `:ascii',
2547 `:ical', or `:xoxo' and the corresponding directories. If a directory path
2548 is relative, it is interpreted relative to the directory where the exported
2549 Org-mode files lives."
2550 :group 'org-export-general
2551 :type '(choice
2552 (directory)
2553 (repeat
2554 (cons
2555 (choice :tag "Type"
2556 (const :html) (const :ascii) (const :ical) (const :xoxo))
2557 (directory)))))
2559 (defcustom org-export-language-setup
2560 '(("en" "Author" "Date" "Table of Contents")
2561 ("cs" "Autor" "Datum" "Obsah")
2562 ("da" "Ophavsmand" "Dato" "Indhold")
2563 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2564 ("es" "Autor" "Fecha" "\xccndice")
2565 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2566 ("it" "Autore" "Data" "Indice")
2567 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2568 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2569 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2570 "Terms used in export text, translated to different languages.
2571 Use the variable `org-export-default-language' to set the language,
2572 or use the +OPTION lines for a per-file setting."
2573 :group 'org-export-general
2574 :type '(repeat
2575 (list
2576 (string :tag "HTML language tag")
2577 (string :tag "Author")
2578 (string :tag "Date")
2579 (string :tag "Table of Contents"))))
2581 (defcustom org-export-default-language "en"
2582 "The default language of HTML export, as a string.
2583 This should have an association in `org-export-language-setup'."
2584 :group 'org-export-general
2585 :type 'string)
2587 (defcustom org-export-skip-text-before-1st-heading t
2588 "Non-nil means, skip all text before the first headline when exporting.
2589 When nil, that text is exported as well."
2590 :group 'org-export-general
2591 :type 'boolean)
2593 (defcustom org-export-headline-levels 3
2594 "The last level which is still exported as a headline.
2595 Inferior levels will produce itemize lists when exported.
2596 Note that a numeric prefix argument to an exporter function overrides
2597 this setting.
2599 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2600 :group 'org-export-general
2601 :type 'number)
2603 (defcustom org-export-with-section-numbers t
2604 "Non-nil means, add section numbers to headlines when exporting.
2606 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2607 :group 'org-export-general
2608 :type 'boolean)
2610 (defcustom org-export-with-toc t
2611 "Non-nil means, create a table of contents in exported files.
2612 The TOC contains headlines with levels up to`org-export-headline-levels'.
2613 When an integer, include levels up to N in the toc, this may then be
2614 different from `org-export-headline-levels', but it will not be allowed
2615 to be larger than the number of headline levels.
2616 When nil, no table of contents is made.
2618 Headlines which contain any TODO items will be marked with \"(*)\" in
2619 ASCII export, and with red color in HTML output, if the option
2620 `org-export-mark-todo-in-toc' is set.
2622 In HTML output, the TOC will be clickable.
2624 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2625 or \"toc:3\"."
2626 :group 'org-export-general
2627 :type '(choice
2628 (const :tag "No Table of Contents" nil)
2629 (const :tag "Full Table of Contents" t)
2630 (integer :tag "TOC to level")))
2632 (defcustom org-export-mark-todo-in-toc nil
2633 "Non-nil means, mark TOC lines that contain any open TODO items."
2634 :group 'org-export-general
2635 :type 'boolean)
2637 (defcustom org-export-preserve-breaks nil
2638 "Non-nil means, preserve all line breaks when exporting.
2639 Normally, in HTML output paragraphs will be reformatted. In ASCII
2640 export, line breaks will always be preserved, regardless of this variable.
2642 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2643 :group 'org-export-general
2644 :type 'boolean)
2646 (defcustom org-export-with-archived-trees 'headline
2647 "Whether subtrees with the ARCHIVE tag should be exported.
2648 This can have three different values
2649 nil Do not export, pretend this tree is not present
2650 t Do export the entire tree
2651 headline Only export the headline, but skip the tree below it."
2652 :group 'org-export-general
2653 :group 'org-archive
2654 :type '(choice
2655 (const :tag "not at all" nil)
2656 (const :tag "headline only" 'headline)
2657 (const :tag "entirely" t)))
2659 (defcustom org-export-author-info t
2660 "Non-nil means, insert author name and email into the exported file.
2662 This option can also be set with the +OPTIONS line,
2663 e.g. \"author-info:nil\"."
2664 :group 'org-export-general
2665 :type 'boolean)
2667 (defcustom org-export-time-stamp-file t
2668 "Non-nil means, insert a time stamp into the exported file.
2669 The time stamp shows when the file was created.
2671 This option can also be set with the +OPTIONS line,
2672 e.g. \"timestamp:nil\"."
2673 :group 'org-export-general
2674 :type 'boolean)
2676 (defcustom org-export-with-timestamps t
2677 "If nil, do not export time stamps and associated keywords."
2678 :group 'org-export-general
2679 :type 'boolean)
2681 (defcustom org-export-remove-timestamps-from-toc t
2682 "If nil, remove timestamps from the table of contents entries."
2683 :group 'org-export-general
2684 :type 'boolean)
2686 (defcustom org-export-with-tags 'not-in-toc
2687 "If nil, do not export tags, just remove them from headlines.
2688 If this is the symbol `not-in-toc', tags will be removed from table of
2689 contents entries, but still be shown in the headlines of the document."
2690 :group 'org-export-general
2691 :type '(choice
2692 (const :tag "Off" nil)
2693 (const :tag "Not in TOC" not-in-toc)
2694 (const :tag "On" t)))
2696 (defcustom org-export-with-property-drawer nil
2697 "Non-nil means, export property drawers.
2698 When nil, these drawers are removed before export.
2700 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2701 :group 'org-export-general
2702 :type 'boolean)
2704 (defgroup org-export-translation nil
2705 "Options for translating special ascii sequences for the export backends."
2706 :tag "Org Export Translation"
2707 :group 'org-export)
2709 (defcustom org-export-with-emphasize t
2710 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2711 If the export target supports emphasizing text, the word will be
2712 typeset in bold, italic, or underlined, respectively. Works only for
2713 single words, but you can say: I *really* *mean* *this*.
2714 Not all export backends support this.
2716 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2717 :group 'org-export-translation
2718 :type 'boolean)
2720 (defcustom org-export-with-footnotes t
2721 "If nil, export [1] as a footnote marker.
2722 Lines starting with [1] will be formatted as footnotes.
2724 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2725 :group 'org-export-translation
2726 :type 'boolean)
2728 (defcustom org-export-with-sub-superscripts t
2729 "Non-nil means, interpret \"_\" and \"^\" for export.
2730 When this option is turned on, you can use TeX-like syntax for sub- and
2731 superscripts. Several characters after \"_\" or \"^\" will be
2732 considered as a single item - so grouping with {} is normally not
2733 needed. For example, the following things will be parsed as single
2734 sub- or superscripts.
2736 10^24 or 10^tau several digits will be considered 1 item.
2737 10^-12 or 10^-tau a leading sign with digits or a word
2738 x^2-y^3 will be read as x^2 - y^3, because items are
2739 terminated by almost any nonword/nondigit char.
2740 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2742 Still, ambiguity is possible - so when in doubt use {} to enclose the
2743 sub/superscript. If you set this variable to the symbol `{}',
2744 the braces are *required* in order to trigger interpretations as
2745 sub/superscript. This can be helpful in documents that need \"_\"
2746 frequently in plain text.
2748 Not all export backends support this, but HTML does.
2750 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2751 :group 'org-export-translation
2752 :type '(choice
2753 (const :tag "Always interpret" t)
2754 (const :tag "Only with braces" {})
2755 (const :tag "Never interpret" nil)))
2757 (defcustom org-export-with-TeX-macros t
2758 "Non-nil means, interpret simple TeX-like macros when exporting.
2759 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2760 No only real TeX macros will work here, but the standard HTML entities
2761 for math can be used as macro names as well. For a list of supported
2762 names in HTML export, see the constant `org-html-entities'.
2763 Not all export backends support this.
2765 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2766 :group 'org-export-translation
2767 :group 'org-export-latex
2768 :type 'boolean)
2770 (defcustom org-export-with-LaTeX-fragments nil
2771 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2772 When set, the exporter will find LaTeX environments if the \\begin line is
2773 the first non-white thing on a line. It will also find the math delimiters
2774 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2775 display math.
2777 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2778 :group 'org-export-translation
2779 :group 'org-export-latex
2780 :type 'boolean)
2782 (defcustom org-export-with-fixed-width t
2783 "Non-nil means, lines starting with \":\" will be in fixed width font.
2784 This can be used to have pre-formatted text, fragments of code etc. For
2785 example:
2786 : ;; Some Lisp examples
2787 : (while (defc cnt)
2788 : (ding))
2789 will be looking just like this in also HTML. See also the QUOTE keyword.
2790 Not all export backends support this.
2792 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2793 :group 'org-export-translation
2794 :type 'boolean)
2796 (defcustom org-match-sexp-depth 3
2797 "Number of stacked braces for sub/superscript matching.
2798 This has to be set before loading org.el to be effective."
2799 :group 'org-export-translation
2800 :type 'integer)
2802 (defgroup org-export-tables nil
2803 "Options for exporting tables in Org-mode."
2804 :tag "Org Export Tables"
2805 :group 'org-export)
2807 (defcustom org-export-with-tables t
2808 "If non-nil, lines starting with \"|\" define a table.
2809 For example:
2811 | Name | Address | Birthday |
2812 |-------------+----------+-----------|
2813 | Arthur Dent | England | 29.2.2100 |
2815 Not all export backends support this.
2817 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2818 :group 'org-export-tables
2819 :type 'boolean)
2821 (defcustom org-export-highlight-first-table-line t
2822 "Non-nil means, highlight the first table line.
2823 In HTML export, this means use <th> instead of <td>.
2824 In tables created with table.el, this applies to the first table line.
2825 In Org-mode tables, all lines before the first horizontal separator
2826 line will be formatted with <th> tags."
2827 :group 'org-export-tables
2828 :type 'boolean)
2830 (defcustom org-export-table-remove-special-lines t
2831 "Remove special lines and marking characters in calculating tables.
2832 This removes the special marking character column from tables that are set
2833 up for spreadsheet calculations. It also removes the entire lines
2834 marked with `!', `_', or `^'. The lines with `$' are kept, because
2835 the values of constants may be useful to have."
2836 :group 'org-export-tables
2837 :type 'boolean)
2839 (defcustom org-export-prefer-native-exporter-for-tables nil
2840 "Non-nil means, always export tables created with table.el natively.
2841 Natively means, use the HTML code generator in table.el.
2842 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2843 the table does not use row- or column-spanning). This has the
2844 advantage, that the automatic HTML conversions for math symbols and
2845 sub/superscripts can be applied. Org-mode's HTML generator is also
2846 much faster."
2847 :group 'org-export-tables
2848 :type 'boolean)
2850 (defgroup org-export-ascii nil
2851 "Options specific for ASCII export of Org-mode files."
2852 :tag "Org Export ASCII"
2853 :group 'org-export)
2855 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2856 "Characters for underlining headings in ASCII export.
2857 In the given sequence, these characters will be used for level 1, 2, ..."
2858 :group 'org-export-ascii
2859 :type '(repeat character))
2861 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2862 "Bullet characters for headlines converted to lists in ASCII export.
2863 The first character is is used for the first lest level generated in this
2864 way, and so on. If there are more levels than characters given here,
2865 the list will be repeated.
2866 Note that plain lists will keep the same bullets as the have in the
2867 Org-mode file."
2868 :group 'org-export-ascii
2869 :type '(repeat character))
2871 (defgroup org-export-xml nil
2872 "Options specific for XML export of Org-mode files."
2873 :tag "Org Export XML"
2874 :group 'org-export)
2876 (defgroup org-export-html nil
2877 "Options specific for HTML export of Org-mode files."
2878 :tag "Org Export HTML"
2879 :group 'org-export)
2881 (defcustom org-export-html-coding-system nil
2883 :group 'org-export-html
2884 :type 'coding-system)
2886 (defcustom org-export-html-style
2887 "<style type=\"text/css\">
2888 html {
2889 font-family: Times, serif;
2890 font-size: 12pt;
2892 .title { text-align: center; }
2893 .todo { color: red; }
2894 .done { color: green; }
2895 .timestamp { color: grey }
2896 .timestamp-kwd { color: CadetBlue }
2897 .tag { background-color:lightblue; font-weight:normal }
2898 .target { background-color: lavender; }
2899 pre {
2900 border: 1pt solid #AEBDCC;
2901 background-color: #F3F5F7;
2902 padding: 5pt;
2903 font-family: courier, monospace;
2905 table { border-collapse: collapse; }
2906 td, th {
2907 vertical-align: top;
2908 <!--border: 1pt solid #ADB9CC;-->
2910 </style>"
2911 "The default style specification for exported HTML files.
2912 Since there are different ways of setting style information, this variable
2913 needs to contain the full HTML structure to provide a style, including the
2914 surrounding HTML tags. The style specifications should include definitions
2915 for new classes todo, done, title, and deadline. For example, legal values
2916 would be:
2918 <style type=\"text/css\">
2919 p { font-weight: normal; color: gray; }
2920 h1 { color: black; }
2921 .title { text-align: center; }
2922 .todo, .deadline { color: red; }
2923 .done { color: green; }
2924 </style>
2926 or, if you want to keep the style in a file,
2928 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2930 As the value of this option simply gets inserted into the HTML <head> header,
2931 you can \"misuse\" it to add arbitrary text to the header."
2932 :group 'org-export-html
2933 :type 'string)
2936 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2937 "Format for typesetting the document title in HTML export."
2938 :group 'org-export-html
2939 :type 'string)
2941 (defcustom org-export-html-toplevel-hlevel 2
2942 "The <H> level for level 1 headings in HTML export."
2943 :group 'org-export-html
2944 :type 'string)
2946 (defcustom org-export-html-link-org-files-as-html t
2947 "Non-nil means, make file links to `file.org' point to `file.html'.
2948 When org-mode is exporting an org-mode file to HTML, links to
2949 non-html files are directly put into a href tag in HTML.
2950 However, links to other Org-mode files (recognized by the
2951 extension `.org.) should become links to the corresponding html
2952 file, assuming that the linked org-mode file will also be
2953 converted to HTML.
2954 When nil, the links still point to the plain `.org' file."
2955 :group 'org-export-html
2956 :type 'boolean)
2958 (defcustom org-export-html-inline-images 'maybe
2959 "Non-nil means, inline images into exported HTML pages.
2960 This is done using an <img> tag. When nil, an anchor with href is used to
2961 link to the image. If this option is `maybe', then images in links with
2962 an empty description will be inlined, while images with a description will
2963 be linked only."
2964 :group 'org-export-html
2965 :type '(choice (const :tag "Never" nil)
2966 (const :tag "Always" t)
2967 (const :tag "When there is no description" maybe)))
2969 ;; FIXME: rename
2970 (defcustom org-export-html-expand t
2971 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2972 When nil, these tags will be exported as plain text and therefore
2973 not be interpreted by a browser.
2975 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2976 :group 'org-export-html
2977 :type 'boolean)
2979 (defcustom org-export-html-table-tag
2980 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2981 "The HTML tag that is used to start a table.
2982 This must be a <table> tag, but you may change the options like
2983 borders and spacing."
2984 :group 'org-export-html
2985 :type 'string)
2987 (defcustom org-export-table-header-tags '("<th>" . "</th>")
2988 "The opening tag for table header fields.
2989 This is customizable so that alignment options can be specified."
2990 :group 'org-export-tables
2991 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2993 (defcustom org-export-table-data-tags '("<td>" . "</td>")
2994 "The opening tag for table data fields.
2995 This is customizable so that alignment options can be specified."
2996 :group 'org-export-tables
2997 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2999 (defcustom org-export-html-with-timestamp nil
3000 "If non-nil, write `org-export-html-html-helper-timestamp'
3001 into the exported HTML text. Otherwise, the buffer will just be saved
3002 to a file."
3003 :group 'org-export-html
3004 :type 'boolean)
3006 (defcustom org-export-html-html-helper-timestamp
3007 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3008 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3009 :group 'org-export-html
3010 :type 'string)
3012 (defgroup org-export-icalendar nil
3013 "Options specific for iCalendar export of Org-mode files."
3014 :tag "Org Export iCalendar"
3015 :group 'org-export)
3017 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3018 "The file name for the iCalendar file covering all agenda files.
3019 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3020 The file name should be absolute."
3021 :group 'org-export-icalendar
3022 :type 'file)
3024 (defcustom org-icalendar-include-todo nil
3025 "Non-nil means, export to iCalendar files should also cover TODO items."
3026 :group 'org-export-icalendar
3027 :type '(choice
3028 (const :tag "None" nil)
3029 (const :tag "Unfinished" t)
3030 (const :tag "All" all)))
3032 (defcustom org-icalendar-include-sexps t
3033 "Non-nil means, export to iCalendar files should also cover sexp entries.
3034 These are entries like in the diary, but directly in an Org-mode file."
3035 :group 'org-export-icalendar
3036 :type 'boolean)
3038 (defcustom org-icalendar-combined-name "OrgMode"
3039 "Calendar name for the combined iCalendar representing all agenda files."
3040 :group 'org-export-icalendar
3041 :type 'string)
3043 (defgroup org-font-lock nil
3044 "Font-lock settings for highlighting in Org-mode."
3045 :tag "Org Font Lock"
3046 :group 'org)
3048 (defcustom org-level-color-stars-only nil
3049 "Non-nil means fontify only the stars in each headline.
3050 When nil, the entire headline is fontified.
3051 Changing it requires restart of `font-lock-mode' to become effective
3052 also in regions already fontified."
3053 :group 'org-font-lock
3054 :type 'boolean)
3056 (defcustom org-hide-leading-stars nil
3057 "Non-nil means, hide the first N-1 stars in a headline.
3058 This works by using the face `org-hide' for these stars. This
3059 face is white for a light background, and black for a dark
3060 background. You may have to customize the face `org-hide' to
3061 make this work.
3062 Changing it requires restart of `font-lock-mode' to become effective
3063 also in regions already fontified.
3064 You may also set this on a per-file basis by adding one of the following
3065 lines to the buffer:
3067 #+STARTUP: hidestars
3068 #+STARTUP: showstars"
3069 :group 'org-font-lock
3070 :type 'boolean)
3072 (defcustom org-fontify-done-headline nil
3073 "Non-nil means, change the face of a headline if it is marked DONE.
3074 Normally, only the TODO/DONE keyword indicates the state of a headline.
3075 When this is non-nil, the headline after the keyword is set to the
3076 `org-headline-done' as an additional indication."
3077 :group 'org-font-lock
3078 :type 'boolean)
3080 (defcustom org-fontify-emphasized-text t
3081 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3082 Changing this variable requires a restart of Emacs to take effect."
3083 :group 'org-font-lock
3084 :type 'boolean)
3086 (defvar org-emph-re nil
3087 "Regular expression for matching emphasis.")
3088 (defvar org-emphasis-regexp-components) ; defined just below
3089 (defvar org-emphasis-alist) ; defined just below
3090 (defun org-set-emph-re (var val)
3091 "Set variable and compute the emphasis regular expression."
3092 (set var val)
3093 (when (and (boundp 'org-emphasis-alist)
3094 (boundp 'org-emphasis-regexp-components)
3095 org-emphasis-alist org-emphasis-regexp-components)
3096 (let* ((e org-emphasis-regexp-components)
3097 (pre (car e))
3098 (post (nth 1 e))
3099 (border (nth 2 e))
3100 (body (nth 3 e))
3101 (nl (nth 4 e))
3102 (stacked (nth 5 e))
3103 (body1 (concat body "*?"))
3104 (markers (mapconcat 'car org-emphasis-alist "")))
3105 ;; make sure special characters appear at the right position in the class
3106 (if (string-match "\\^" markers)
3107 (setq markers (concat (replace-match "" t t markers) "^")))
3108 (if (string-match "-" markers)
3109 (setq markers (concat (replace-match "" t t markers) "-")))
3110 (if (> nl 0)
3111 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3112 (int-to-string nl) "\\}")))
3113 ;; Make the regexp
3114 (setq org-emph-re
3115 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3116 "\\("
3117 "\\([" markers "]\\)"
3118 "\\("
3119 "[^" border (if (and nil stacked) markers) "]"
3120 body1
3121 "[^" border (if (and nil stacked) markers) "]"
3122 "\\)"
3123 "\\3\\)"
3124 "\\([" post (if stacked markers) "]\\|$\\)")))))
3126 (defcustom org-emphasis-regexp-components
3127 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3128 "Components used to build the reqular expression for emphasis.
3129 This is a list with 6 entries. Terminology: In an emphasis string
3130 like \" *strong word* \", we call the initial space PREMATCH, the final
3131 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3132 and \"trong wor\" is the body. The different components in this variable
3133 specify what is allowed/forbidden in each part:
3135 pre Chars allowed as prematch. Beginning of line will be allowed too.
3136 post Chars allowed as postmatch. End of line will be allowed too.
3137 border The chars *forbidden* as border characters.
3138 body-regexp A regexp like \".\" to match a body character. Don't use
3139 non-shy groups here, and don't allow newline here.
3140 newline The maximum number of newlines allowed in an emphasis exp.
3141 stacked Non-nil means, allow stacked styles. This works only in HTML
3142 export. When this is set, all marker characters (as given in
3143 `org-emphasis-alist') will be allowed as pre/post, aiding
3144 inside-out matching.
3145 Use customize to modify this, or restart Emacs after changing it."
3146 :group 'org-font-lock
3147 :set 'org-set-emph-re
3148 :type '(list
3149 (sexp :tag "Allowed chars in pre ")
3150 (sexp :tag "Allowed chars in post ")
3151 (sexp :tag "Forbidden chars in border ")
3152 (sexp :tag "Regexp for body ")
3153 (integer :tag "number of newlines allowed")
3154 (boolean :tag "Stacking allowed ")))
3156 (defcustom org-emphasis-alist
3157 '(("*" bold "<b>" "</b>")
3158 ("/" italic "<i>" "</i>")
3159 ("_" underline "<u>" "</u>")
3160 ("=" shadow "<code>" "</code>")
3161 ("+" (:strike-through t) "<del>" "</del>")
3163 "Special syntax for emphasized text.
3164 Text starting and ending with a special character will be emphasized, for
3165 example *bold*, _underlined_ and /italic/. This variable sets the marker
3166 characters, the face to be used by font-lock for highlighting in Org-mode
3167 Emacs buffers, and the HTML tags to be used for this.
3168 Use customize to modify this, or restart Emacs after changing it."
3169 :group 'org-font-lock
3170 :set 'org-set-emph-re
3171 :type '(repeat
3172 (list
3173 (string :tag "Marker character")
3174 (choice
3175 (face :tag "Font-lock-face")
3176 (plist :tag "Face property list"))
3177 (string :tag "HTML start tag")
3178 (string :tag "HTML end tag"))))
3180 ;;; The faces
3182 (defgroup org-faces nil
3183 "Faces in Org-mode."
3184 :tag "Org Faces"
3185 :group 'org-font-lock)
3187 ;; FIXME: convert that into a macro? Not critical, because this
3188 ;; is only executed a few times at load time.
3189 (defun org-compatible-face (specs)
3190 "Make a compatible face specification.
3191 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3192 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3193 to the top of the list. The `min-colors' attribute will be removed from
3194 any other entries, and any resulting duplicates will be removed entirely."
3195 (if (or (featurep 'xemacs) (< emacs-major-version 22))
3196 (let (r e a)
3197 (while (setq e (pop specs))
3198 (cond
3199 ((memq (car e) '(t default)) (push e r))
3200 ((setq a (member '(min-colors 8) (car e)))
3201 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3202 (cdr e)))))
3203 ((setq a (assq 'min-colors (car e)))
3204 (setq e (cons (delq a (car e)) (cdr e)))
3205 (or (assoc (car e) r) (push e r)))
3206 (t (or (assoc (car e) r) (push e r)))))
3207 (nreverse r))
3208 specs))
3210 (defface org-hide
3211 '((((background light)) (:foreground "white"))
3212 (((background dark)) (:foreground "black")))
3213 "Face used to hide leading stars in headlines.
3214 The forground color of this face should be equal to the background
3215 color of the frame."
3216 :group 'org-faces)
3218 (defface org-level-1 ;; font-lock-function-name-face
3219 (org-compatible-face
3220 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3221 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3222 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3223 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3224 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3225 (t (:bold t))))
3226 "Face used for level 1 headlines."
3227 :group 'org-faces)
3229 (defface org-level-2 ;; font-lock-variable-name-face
3230 (org-compatible-face
3231 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3232 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3233 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3234 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3235 (t (:bold t))))
3236 "Face used for level 2 headlines."
3237 :group 'org-faces)
3239 (defface org-level-3 ;; font-lock-keyword-face
3240 (org-compatible-face
3241 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3242 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3243 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3244 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3245 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3246 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3247 (t (:bold t))))
3248 "Face used for level 3 headlines."
3249 :group 'org-faces)
3251 (defface org-level-4 ;; font-lock-comment-face
3252 (org-compatible-face
3253 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3254 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3255 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3256 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3257 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3258 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3259 (t (:bold t))))
3260 "Face used for level 4 headlines."
3261 :group 'org-faces)
3263 (defface org-level-5 ;; font-lock-type-face
3264 (org-compatible-face
3265 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3266 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3267 (((class color) (min-colors 8)) (:foreground "green"))))
3268 "Face used for level 5 headlines."
3269 :group 'org-faces)
3271 (defface org-level-6 ;; font-lock-constant-face
3272 (org-compatible-face
3273 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3274 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3275 (((class color) (min-colors 8)) (:foreground "magenta"))))
3276 "Face used for level 6 headlines."
3277 :group 'org-faces)
3279 (defface org-level-7 ;; font-lock-builtin-face
3280 (org-compatible-face
3281 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3282 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3283 (((class color) (min-colors 8)) (:foreground "blue"))))
3284 "Face used for level 7 headlines."
3285 :group 'org-faces)
3287 (defface org-level-8 ;; font-lock-string-face
3288 (org-compatible-face
3289 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3290 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3291 (((class color) (min-colors 8)) (:foreground "green"))))
3292 "Face used for level 8 headlines."
3293 :group 'org-faces)
3295 (defface org-special-keyword ;; font-lock-string-face
3296 (org-compatible-face
3297 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3298 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3299 (t (:italic t))))
3300 "Face used for special keywords."
3301 :group 'org-faces)
3303 (defface org-drawer ;; font-lock-function-name-face
3304 (org-compatible-face
3305 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3306 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3307 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3308 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3309 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3310 (t (:bold t))))
3311 "Face used for drawers."
3312 :group 'org-faces)
3314 (defface org-property-value nil
3315 "Face used for the value of a property."
3316 :group 'org-faces)
3318 (defface org-column
3319 (org-compatible-face
3320 '((((class color) (min-colors 16) (background light))
3321 (:background "grey90"))
3322 (((class color) (min-colors 16) (background dark))
3323 (:background "grey30"))
3324 (((class color) (min-colors 8))
3325 (:background "cyan" :foreground "black"))
3326 (t (:inverse-video t))))
3327 "Face for column display of entry properties."
3328 :group 'org-faces)
3330 (when (fboundp 'set-face-attribute)
3331 ;; Make sure that a fixed-width face is used when we have a column table.
3332 (set-face-attribute 'org-column nil
3333 :height (face-attribute 'default :height)
3334 :family (face-attribute 'default :family)))
3336 (defface org-warning ;; font-lock-warning-face
3337 (org-compatible-face
3338 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3339 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3340 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3341 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3342 (t (:bold t))))
3343 "Face for deadlines and TODO keywords."
3344 :group 'org-faces)
3346 (defface org-archived ; similar to shadow
3347 (org-compatible-face
3348 '((((class color grayscale) (min-colors 88) (background light))
3349 (:foreground "grey50"))
3350 (((class color grayscale) (min-colors 88) (background dark))
3351 (:foreground "grey70"))
3352 (((class color) (min-colors 8) (background light))
3353 (:foreground "green"))
3354 (((class color) (min-colors 8) (background dark))
3355 (:foreground "yellow"))))
3356 "Face for headline with the ARCHIVE tag."
3357 :group 'org-faces)
3359 (defface org-link
3360 '((((class color) (background light)) (:foreground "Purple" :underline t))
3361 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3362 (t (:underline t)))
3363 "Face for links."
3364 :group 'org-faces)
3366 (defface org-target
3367 '((((class color) (background light)) (:underline t))
3368 (((class color) (background dark)) (:underline t))
3369 (t (:underline t)))
3370 "Face for links."
3371 :group 'org-faces)
3373 (defface org-date
3374 '((((class color) (background light)) (:foreground "Purple" :underline t))
3375 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3376 (t (:underline t)))
3377 "Face for links."
3378 :group 'org-faces)
3380 (defface org-sexp-date
3381 '((((class color) (background light)) (:foreground "Purple"))
3382 (((class color) (background dark)) (:foreground "Cyan"))
3383 (t (:underline t)))
3384 "Face for links."
3385 :group 'org-faces)
3387 (defface org-tag
3388 '((t (:bold t)))
3389 "Face for tags."
3390 :group 'org-faces)
3392 (defface org-todo ;; font-lock-warning-face
3393 (org-compatible-face
3394 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3395 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3396 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3397 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3398 (t (:inverse-video t :bold t))))
3399 "Face for TODO keywords."
3400 :group 'org-faces)
3402 (defface org-done ;; font-lock-type-face
3403 (org-compatible-face
3404 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3405 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3406 (((class color) (min-colors 8)) (:foreground "green"))
3407 (t (:bold t))))
3408 "Face used for todo keywords that indicate DONE items."
3409 :group 'org-faces)
3411 (defface org-headline-done ;; font-lock-string-face
3412 (org-compatible-face
3413 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3414 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3415 (((class color) (min-colors 8) (background light)) (:bold nil))))
3416 "Face used to indicate that a headline is DONE.
3417 This face is only used if `org-fontify-done-headline' is set. If applies
3418 to the part of the headline after the DONE keyword."
3419 :group 'org-faces)
3421 (defface org-table ;; font-lock-function-name-face
3422 (org-compatible-face
3423 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3424 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3425 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3426 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3427 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3428 (((class color) (min-colors 8) (background dark)))))
3429 "Face used for tables."
3430 :group 'org-faces)
3432 (defface org-formula
3433 (org-compatible-face
3434 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3435 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3436 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3437 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3438 (t (:bold t :italic t))))
3439 "Face for formulas."
3440 :group 'org-faces)
3442 (defface org-agenda-structure ;; font-lock-function-name-face
3443 (org-compatible-face
3444 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3445 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3446 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3447 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3448 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3449 (t (:bold t))))
3450 "Face used in agenda for captions and dates."
3451 :group 'org-faces)
3453 (defface org-scheduled-today
3454 (org-compatible-face
3455 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3456 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3457 (((class color) (min-colors 8)) (:foreground "green"))
3458 (t (:bold t :italic t))))
3459 "Face for items scheduled for a certain day."
3460 :group 'org-faces)
3462 (defface org-scheduled-previously
3463 (org-compatible-face
3464 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3465 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3466 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3467 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3468 (t (:bold t))))
3469 "Face for items scheduled previously, and not yet done."
3470 :group 'org-faces)
3472 (defface org-upcoming-deadline
3473 (org-compatible-face
3474 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3475 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3476 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3477 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3478 (t (:bold t))))
3479 "Face for items scheduled previously, and not yet done."
3480 :group 'org-faces)
3482 (defcustom org-agenda-deadline-faces
3483 '((1.0 . org-warning)
3484 (0.5 . org-upcoming-deadline)
3485 (0.0 . default))
3486 "Faces for showing deadlines in the agenda.
3487 This is a list of cons cells. The cdr of each cess is a face to be used,
3488 and it can also just be a like like '(:foreground \"yellow\").
3489 Each car is a fraction of the head-warning time that must have passed for
3490 this the face in the cdr to be used for display. The numbers must be
3491 given in descending order. The head-warning time is normally taken
3492 from `org-deadline-warning-days', but can also be specified in the deadline
3493 timestamp itself, like this:
3495 DEADLINE: <2007-08-13 Mon -8d>
3497 You may use d for days, w for weeks, m for months and y for years. Months
3498 and years will only be treated in an approximate fashion (30.4 days for a
3499 month and 365.24 days for a year)."
3500 :group 'org-faces
3501 :group 'org-agenda-daily/weekly
3502 :type '(repeat
3503 (cons
3504 (number :tag "Fraction of head-warning time passed")
3505 (sexp :tag "Face"))))
3507 (defface org-time-grid ;; font-lock-variable-name-face
3508 (org-compatible-face
3509 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3510 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3511 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3512 "Face used for time grids."
3513 :group 'org-faces)
3515 (defconst org-level-faces
3516 '(org-level-1 org-level-2 org-level-3 org-level-4
3517 org-level-5 org-level-6 org-level-7 org-level-8
3520 (defcustom org-n-level-faces (length org-level-faces)
3521 "The number different faces to be used for headlines.
3522 Org-mode defines 8 different headline faces, so this can be at most 8.
3523 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3524 :type 'number
3525 :group 'org-faces)
3527 ;;; Variables for pre-computed regular expressions, all buffer local
3529 (defvar org-drawer-regexp nil
3530 "Matches first line of a hidden block.")
3531 (make-variable-buffer-local 'org-drawer-regexp)
3532 (defvar org-todo-regexp nil
3533 "Matches any of the TODO state keywords.")
3534 (make-variable-buffer-local 'org-todo-regexp)
3535 (defvar org-not-done-regexp nil
3536 "Matches any of the TODO state keywords except the last one.")
3537 (make-variable-buffer-local 'org-not-done-regexp)
3538 (defvar org-todo-line-regexp nil
3539 "Matches a headline and puts TODO state into group 2 if present.")
3540 (make-variable-buffer-local 'org-todo-line-regexp)
3541 (defvar org-todo-line-tags-regexp nil
3542 "Matches a headline and puts TODO state into group 2 if present.
3543 Also put tags into group 4 if tags are present.")
3544 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3545 (defvar org-nl-done-regexp nil
3546 "Matches newline followed by a headline with the DONE keyword.")
3547 (make-variable-buffer-local 'org-nl-done-regexp)
3548 (defvar org-looking-at-done-regexp nil
3549 "Matches the DONE keyword a point.")
3550 (make-variable-buffer-local 'org-looking-at-done-regexp)
3551 (defvar org-ds-keyword-length 12
3552 "Maximum length of the Deadline and SCHEDULED keywords.")
3553 (make-variable-buffer-local 'org-ds-keyword-length)
3554 (defvar org-deadline-regexp nil
3555 "Matches the DEADLINE keyword.")
3556 (make-variable-buffer-local 'org-deadline-regexp)
3557 (defvar org-deadline-time-regexp nil
3558 "Matches the DEADLINE keyword together with a time stamp.")
3559 (make-variable-buffer-local 'org-deadline-time-regexp)
3560 (defvar org-deadline-line-regexp nil
3561 "Matches the DEADLINE keyword and the rest of the line.")
3562 (make-variable-buffer-local 'org-deadline-line-regexp)
3563 (defvar org-scheduled-regexp nil
3564 "Matches the SCHEDULED keyword.")
3565 (make-variable-buffer-local 'org-scheduled-regexp)
3566 (defvar org-scheduled-time-regexp nil
3567 "Matches the SCHEDULED keyword together with a time stamp.")
3568 (make-variable-buffer-local 'org-scheduled-time-regexp)
3569 (defvar org-closed-time-regexp nil
3570 "Matches the CLOSED keyword together with a time stamp.")
3571 (make-variable-buffer-local 'org-closed-time-regexp)
3573 (defvar org-keyword-time-regexp nil
3574 "Matches any of the 4 keywords, together with the time stamp.")
3575 (make-variable-buffer-local 'org-keyword-time-regexp)
3576 (defvar org-keyword-time-not-clock-regexp nil
3577 "Matches any of the 3 keywords, together with the time stamp.")
3578 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3579 (defvar org-maybe-keyword-time-regexp nil
3580 "Matches a timestamp, possibly preceeded by a keyword.")
3581 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3582 (defvar org-planning-or-clock-line-re nil
3583 "Matches a line with planning or clock info.")
3584 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3586 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3587 rear-nonsticky t mouse-map t fontified t)
3588 "Properties to remove when a string without properties is wanted.")
3590 (defsubst org-match-string-no-properties (num &optional string)
3591 (if (featurep 'xemacs)
3592 (let ((s (match-string num string)))
3593 (remove-text-properties 0 (length s) org-rm-props s)
3595 (match-string-no-properties num string)))
3597 (defsubst org-no-properties (s)
3598 (if (fboundp 'set-text-properties)
3599 (set-text-properties 0 (length s) nil s)
3600 (remove-text-properties 0 (length s) org-rm-props s))
3603 (defsubst org-get-alist-option (option key)
3604 (cond ((eq key t) t)
3605 ((eq option t) t)
3606 ((assoc key option) (cdr (assoc key option)))
3607 (t (cdr (assq 'default option)))))
3609 (defsubst org-inhibit-invisibility ()
3610 "Modified `buffer-invisibility-spec' for Emacs 21.
3611 Some ops with invisible text do not work correctly on Emacs 21. For these
3612 we turn off invisibility temporarily. Use this in a `let' form."
3613 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3615 (defsubst org-set-local (var value)
3616 "Make VAR local in current buffer and set it to VALUE."
3617 (set (make-variable-buffer-local var) value))
3619 (defsubst org-mode-p ()
3620 "Check if the current buffer is in Org-mode."
3621 (eq major-mode 'org-mode))
3623 (defsubst org-last (list)
3624 "Return the last element of LIST."
3625 (car (last list)))
3627 (defun org-let (list &rest body)
3628 (eval (cons 'let (cons list body))))
3629 (put 'org-let 'lisp-indent-function 1)
3631 (defun org-let2 (list1 list2 &rest body)
3632 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3633 (put 'org-let2 'lisp-indent-function 2)
3634 (defconst org-startup-options
3635 '(("fold" org-startup-folded t)
3636 ("overview" org-startup-folded t)
3637 ("nofold" org-startup-folded nil)
3638 ("showall" org-startup-folded nil)
3639 ("content" org-startup-folded content)
3640 ("hidestars" org-hide-leading-stars t)
3641 ("showstars" org-hide-leading-stars nil)
3642 ("odd" org-odd-levels-only t)
3643 ("oddeven" org-odd-levels-only nil)
3644 ("align" org-startup-align-all-tables t)
3645 ("noalign" org-startup-align-all-tables nil)
3646 ("customtime" org-display-custom-times t)
3647 ("logging" org-log-done t)
3648 ("logdone" org-log-done t)
3649 ("nologging" org-log-done nil)
3650 ("lognotedone" org-log-done done push)
3651 ("lognotestate" org-log-done state push)
3652 ("lognoteclock-out" org-log-done clock-out push)
3653 ("logrepeat" org-log-repeat t)
3654 ("nologrepeat" org-log-repeat nil)
3655 ("constcgs" constants-unit-system cgs)
3656 ("constSI" constants-unit-system SI))
3657 "Variable associated with STARTUP options for org-mode.
3658 Each element is a list of three items: The startup options as written
3659 in the #+STARTUP line, the corresponding variable, and the value to
3660 set this variable to if the option is found. An optional forth element PUSH
3661 means to push this value onto the list in the variable.")
3663 (defun org-set-regexps-and-options ()
3664 "Precompute regular expressions for current buffer."
3665 (when (org-mode-p)
3666 (org-set-local 'org-todo-kwd-alist nil)
3667 (org-set-local 'org-todo-keywords-1 nil)
3668 (org-set-local 'org-done-keywords nil)
3669 (org-set-local 'org-todo-heads nil)
3670 (org-set-local 'org-todo-sets nil)
3671 (let ((re (org-make-options-regexp
3672 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "COLUMNS"
3673 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3674 "CONSTANTS" "PROPERTY")))
3675 (splitre "[ \t]+")
3676 kwds key value cat arch tags const links hw dws tail sep kws1 prio
3677 props)
3678 (save-excursion
3679 (save-restriction
3680 (widen)
3681 (goto-char (point-min))
3682 (while (re-search-forward re nil t)
3683 (setq key (match-string 1) value (org-match-string-no-properties 2))
3684 (cond
3685 ((equal key "CATEGORY")
3686 (if (string-match "[ \t]+$" value)
3687 (setq value (replace-match "" t t value)))
3688 (setq cat (intern value)))
3689 ((equal key "SEQ_TODO")
3690 (push (cons 'sequence (org-split-string value splitre)) kwds))
3691 ((equal key "TYP_TODO")
3692 (push (cons 'type (org-split-string value splitre)) kwds))
3693 ((equal key "TAGS")
3694 (setq tags (append tags (org-split-string value splitre))))
3695 ((equal key "COLUMNS")
3696 (org-set-local 'org-columns-default-format value))
3697 ((equal key "LINK")
3698 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3699 (push (cons (match-string 1 value)
3700 (org-trim (match-string 2 value)))
3701 links)))
3702 ((equal key "PRIORITIES")
3703 (setq prio (org-split-string value " +")))
3704 ((equal key "PROPERTY")
3705 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3706 (push (cons (match-string 1 value) (match-string 2 value))
3707 props)))
3708 ((equal key "CONSTANTS")
3709 (setq const (append const (org-split-string value splitre))))
3710 ((equal key "STARTUP")
3711 (let ((opts (org-split-string value splitre))
3712 l var val)
3713 (while (setq l (pop opts))
3714 (when (setq l (assoc l org-startup-options))
3715 (setq var (nth 1 l) val (nth 2 l))
3716 (if (not (nth 3 l))
3717 (set (make-local-variable var) val)
3718 (if (not (listp (symbol-value var)))
3719 (set (make-local-variable var) nil))
3720 (set (make-local-variable var) (symbol-value var))
3721 (add-to-list var val))))))
3722 ((equal key "ARCHIVE")
3723 (string-match " *$" value)
3724 (setq arch (replace-match "" t t value))
3725 (remove-text-properties 0 (length arch)
3726 '(face t fontified t) arch)))
3728 (and cat (org-set-local 'org-category cat))
3729 (when prio
3730 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3731 (setq prio (mapcar 'string-to-char prio))
3732 (org-set-local 'org-highest-priority (nth 0 prio))
3733 (org-set-local 'org-lowest-priority (nth 1 prio))
3734 (org-set-local 'org-default-priority (nth 2 prio)))
3735 (and props (org-set-local 'org-local-properties (nreverse props)))
3736 (and arch (org-set-local 'org-archive-location arch))
3737 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3738 ;; Process the TODO keywords
3739 (unless kwds
3740 ;; Use the global values as if they had been given locally.
3741 (setq kwds (default-value 'org-todo-keywords))
3742 (if (stringp (car kwds))
3743 (setq kwds (list (cons org-todo-interpretation
3744 (default-value 'org-todo-keywords)))))
3745 (setq kwds (reverse kwds)))
3746 (setq kwds (nreverse kwds))
3747 (let (inter kws)
3748 (while (setq kws (pop kwds))
3749 (setq inter (pop kws) sep (member "|" kws)
3750 kws1 (delete "|" (copy-sequence kws))
3751 hw (car kws1)
3752 dws (if sep (cdr sep) (last kws1))
3753 tail (list inter hw (car dws) (org-last dws)))
3754 (add-to-list 'org-todo-heads hw 'append)
3755 (push kws1 org-todo-sets)
3756 (setq org-done-keywords (append org-done-keywords dws nil))
3757 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3758 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3759 (setq org-todo-sets (nreverse org-todo-sets)
3760 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3761 ;; Process the constants
3762 (when const
3763 (let (e cst)
3764 (while (setq e (pop const))
3765 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3766 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3767 (setq org-table-formula-constants-local cst)))
3769 ;; Process the tags.
3770 (when tags
3771 (let (e tgs)
3772 (while (setq e (pop tags))
3773 (cond
3774 ((equal e "{") (push '(:startgroup) tgs))
3775 ((equal e "}") (push '(:endgroup) tgs))
3776 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3777 (push (cons (match-string 1 e)
3778 (string-to-char (match-string 2 e)))
3779 tgs))
3780 (t (push (list e) tgs))))
3781 (org-set-local 'org-tag-alist nil)
3782 (while (setq e (pop tgs))
3783 (or (and (stringp (car e))
3784 (assoc (car e) org-tag-alist))
3785 (push e org-tag-alist))))))
3787 ;; Compute the regular expressions and other local variables
3788 (if (not org-done-keywords)
3789 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3790 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3791 (length org-scheduled-string)))
3792 org-drawer-regexp
3793 (concat "^[ \t]*:\\("
3794 (mapconcat 'regexp-quote org-drawers "\\|")
3795 "\\):[ \t]*$")
3796 org-not-done-keywords
3797 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3798 org-todo-regexp
3799 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3800 "\\|") "\\)\\>")
3801 org-not-done-regexp
3802 (concat "\\<\\("
3803 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3804 "\\)\\>")
3805 org-todo-line-regexp
3806 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3807 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3808 "\\)\\>\\)?[ \t]*\\(.*\\)")
3809 org-nl-done-regexp
3810 (concat "\n\\*+[ \t]+"
3811 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3812 "\\)" "\\>")
3813 org-todo-line-tags-regexp
3814 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3815 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3816 (org-re
3817 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3818 org-looking-at-done-regexp
3819 (concat "^" "\\(?:"
3820 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3821 "\\>")
3822 org-deadline-regexp (concat "\\<" org-deadline-string)
3823 org-deadline-time-regexp
3824 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3825 org-deadline-line-regexp
3826 (concat "\\<\\(" org-deadline-string "\\).*")
3827 org-scheduled-regexp
3828 (concat "\\<" org-scheduled-string)
3829 org-scheduled-time-regexp
3830 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3831 org-closed-time-regexp
3832 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3833 org-keyword-time-regexp
3834 (concat "\\<\\(" org-scheduled-string
3835 "\\|" org-deadline-string
3836 "\\|" org-closed-string
3837 "\\|" org-archived-string
3838 "\\|" org-clock-string "\\)"
3839 " *[[<]\\([^]>]+\\)[]>]")
3840 org-keyword-time-not-clock-regexp
3841 (concat "\\<\\(" org-scheduled-string
3842 "\\|" org-deadline-string
3843 "\\|" org-closed-string
3844 "\\|" org-archived-string
3845 "\\)"
3846 " *[[<]\\([^]>]+\\)[]>]")
3847 org-maybe-keyword-time-regexp
3848 (concat "\\(\\<\\(" org-scheduled-string
3849 "\\|" org-deadline-string
3850 "\\|" org-closed-string
3851 "\\|" org-archived-string
3852 "\\|" org-clock-string "\\)\\)?"
3853 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3854 org-planning-or-clock-line-re
3855 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3856 "\\|" org-deadline-string
3857 "\\|" org-closed-string "\\|" org-clock-string
3858 "\\|" org-archived-string "\\)\\>\\)")
3861 (org-set-font-lock-defaults)))
3864 ;;; Some variables ujsed in various places
3866 (defvar org-window-configuration nil
3867 "Used in various places to store a window configuration.")
3868 (defvar org-finish-function nil
3869 "Function to be called when `C-c C-c' is used.
3870 This is for getting out of special buffers like remember.")
3872 ;;; Foreign variables, to inform the compiler
3874 ;; XEmacs only
3875 (defvar outline-mode-menu-heading)
3876 (defvar outline-mode-menu-show)
3877 (defvar outline-mode-menu-hide)
3878 (defvar zmacs-regions) ; XEmacs regions
3879 ;; Emacs only
3880 (defvar mark-active)
3882 ;; Packages that org-mode interacts with
3883 (defvar calc-embedded-close-formula)
3884 (defvar calc-embedded-open-formula)
3885 (defvar font-lock-unfontify-region-function)
3886 (defvar org-goto-start-pos)
3887 (defvar vm-message-pointer)
3888 (defvar vm-folder-directory)
3889 (defvar wl-summary-buffer-elmo-folder)
3890 (defvar wl-summary-buffer-folder-name)
3891 (defvar gnus-other-frame-object)
3892 (defvar gnus-group-name)
3893 (defvar gnus-article-current)
3894 (defvar w3m-current-url)
3895 (defvar w3m-current-title)
3896 (defvar mh-progs)
3897 (defvar mh-current-folder)
3898 (defvar mh-show-folder-buffer)
3899 (defvar mh-index-folder)
3900 (defvar mh-searcher)
3901 (defvar calendar-mode-map)
3902 (defvar Info-current-file)
3903 (defvar Info-current-node)
3904 (defvar texmathp-why)
3905 (defvar remember-save-after-remembering)
3906 (defvar remember-data-file)
3907 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3908 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3909 (defvar org-latex-regexps)
3910 (defvar constants-unit-system)
3912 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3914 ;; FIXME: Occasionally check by commenting these, to make sure
3915 ;; no other functions uses these, forgetting to let-bind them.
3916 (defvar entry)
3917 (defvar state)
3918 (defvar last-state)
3919 (defvar date)
3920 (defvar description)
3923 ;; Defined somewhere in this file, but used before definition.
3924 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3925 (defvar org-agenda-undo-list)
3926 (defvar org-agenda-pending-undo-list)
3927 (defvar org-agenda-overriding-header)
3928 (defvar orgtbl-mode)
3929 (defvar org-html-entities)
3930 (defvar org-struct-menu)
3931 (defvar org-org-menu)
3932 (defvar org-tbl-menu)
3933 (defvar org-agenda-keymap)
3934 (defvar org-category-table)
3936 ;;;; Emacs/XEmacs compatibility
3938 ;; Overlay compatibility functions
3939 (defun org-make-overlay (beg end &optional buffer)
3940 (if (featurep 'xemacs)
3941 (make-extent beg end buffer)
3942 (make-overlay beg end buffer)))
3943 (defun org-delete-overlay (ovl)
3944 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3945 (defun org-detach-overlay (ovl)
3946 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3947 (defun org-move-overlay (ovl beg end &optional buffer)
3948 (if (featurep 'xemacs)
3949 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3950 (move-overlay ovl beg end buffer)))
3951 (defun org-overlay-put (ovl prop value)
3952 (if (featurep 'xemacs)
3953 (set-extent-property ovl prop value)
3954 (overlay-put ovl prop value)))
3955 (defun org-overlay-display (ovl text &optional face evap)
3956 "Make overlay OVL display TEXT with face FACE."
3957 (if (featurep 'xemacs)
3958 (let ((gl (make-glyph text)))
3959 (and face (set-glyph-face gl face))
3960 (set-extent-property ovl 'invisible t)
3961 (set-extent-property ovl 'end-glyph gl))
3962 (overlay-put ovl 'display text)
3963 (if face (overlay-put ovl 'face face))
3964 (if evap (overlay-put ovl 'evaporate t))))
3965 (defun org-overlay-before-string (ovl text &optional face evap)
3966 "Make overlay OVL display TEXT with face FACE."
3967 (if (featurep 'xemacs)
3968 (let ((gl (make-glyph text)))
3969 (and face (set-glyph-face gl face))
3970 (set-extent-property ovl 'begin-glyph gl))
3971 (if face (org-add-props text nil 'face face))
3972 (overlay-put ovl 'before-string text)
3973 (if evap (overlay-put ovl 'evaporate t))))
3974 (defun org-overlay-get (ovl prop)
3975 (if (featurep 'xemacs)
3976 (extent-property ovl prop)
3977 (overlay-get ovl prop)))
3978 (defun org-overlays-at (pos)
3979 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3980 ;; FIXME: this is currently not used
3981 (defun org-overlays-in (&optional start end)
3982 (if (featurep 'xemacs)
3983 (extent-list nil start end)
3984 (overlays-in start end)))
3985 (defun org-overlay-start (o)
3986 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3987 (defun org-overlay-end (o)
3988 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3989 ;; FIXME: this is currently not used
3990 (defun org-find-overlays (prop &optional pos delete)
3991 "Find all overlays specifying PROP at POS or point.
3992 If DELETE is non-nil, delete all those overlays."
3993 (let ((overlays (org-overlays-at (or pos (point))))
3994 ov found)
3995 (while (setq ov (pop overlays))
3996 (if (org-overlay-get ov prop)
3997 (if delete (org-delete-overlay ov) (push ov found))))
3998 found))
4000 ;; Region compatibility
4002 (defun org-add-hook (hook function &optional append local)
4003 "Add-hook, compatible with both Emacsen."
4004 (if (and local (featurep 'xemacs))
4005 (add-local-hook hook function append)
4006 (add-hook hook function append local)))
4008 (defvar org-ignore-region nil
4009 "To temporarily disable the active region.")
4011 (defun org-region-active-p ()
4012 "Is `transient-mark-mode' on and the region active?
4013 Works on both Emacs and XEmacs."
4014 (if org-ignore-region
4016 (if (featurep 'xemacs)
4017 (and zmacs-regions (region-active-p))
4018 (and transient-mark-mode mark-active))))
4020 ;; Invisibility compatibility
4022 (defun org-add-to-invisibility-spec (arg)
4023 "Add elements to `buffer-invisibility-spec'.
4024 See documentation for `buffer-invisibility-spec' for the kind of elements
4025 that can be added."
4026 (cond
4027 ((fboundp 'add-to-invisibility-spec)
4028 (add-to-invisibility-spec arg))
4029 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4030 (setq buffer-invisibility-spec (list arg)))
4032 (setq buffer-invisibility-spec
4033 (cons arg buffer-invisibility-spec)))))
4035 (defun org-remove-from-invisibility-spec (arg)
4036 "Remove elements from `buffer-invisibility-spec'."
4037 (if (fboundp 'remove-from-invisibility-spec)
4038 (remove-from-invisibility-spec arg)
4039 (if (consp buffer-invisibility-spec)
4040 (setq buffer-invisibility-spec
4041 (delete arg buffer-invisibility-spec)))))
4043 ;; FIXME: this is currently not used
4044 (defun org-in-invisibility-spec-p (arg)
4045 "Is ARG a member of `buffer-invisibility-spec'?"
4046 (if (consp buffer-invisibility-spec)
4047 (member arg buffer-invisibility-spec)
4048 nil))
4050 ;;;; Define the Org-mode
4052 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4053 (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."))
4056 ;; We use a before-change function to check if a table might need
4057 ;; an update.
4058 (defvar org-table-may-need-update t
4059 "Indicates that a table might need an update.
4060 This variable is set by `org-before-change-function'.
4061 `org-table-align' sets it back to nil.")
4062 (defvar org-mode-map)
4063 (defvar org-mode-hook nil)
4064 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4065 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4066 (defvar org-table-buffer-is-an nil)
4069 ;;;###autoload
4070 (define-derived-mode org-mode outline-mode "Org"
4071 "Outline-based notes management and organizer, alias
4072 \"Carsten's outline-mode for keeping track of everything.\"
4074 Org-mode develops organizational tasks around a NOTES file which
4075 contains information about projects as plain text. Org-mode is
4076 implemented on top of outline-mode, which is ideal to keep the content
4077 of large files well structured. It supports ToDo items, deadlines and
4078 time stamps, which magically appear in the diary listing of the Emacs
4079 calendar. Tables are easily created with a built-in table editor.
4080 Plain text URL-like links connect to websites, emails (VM), Usenet
4081 messages (Gnus), BBDB entries, and any files related to the project.
4082 For printing and sharing of notes, an Org-mode file (or a part of it)
4083 can be exported as a structured ASCII or HTML file.
4085 The following commands are available:
4087 \\{org-mode-map}"
4089 ;; Get rid of Outline menus, they are not needed
4090 ;; Need to do this here because define-derived-mode sets up
4091 ;; the keymap so late. Still, it is a waste to call this each time
4092 ;; we switch another buffer into org-mode.
4093 (if (featurep 'xemacs)
4094 (when (boundp 'outline-mode-menu-heading)
4095 ;; Assume this is Greg's port, it used easymenu
4096 (easy-menu-remove outline-mode-menu-heading)
4097 (easy-menu-remove outline-mode-menu-show)
4098 (easy-menu-remove outline-mode-menu-hide))
4099 (define-key org-mode-map [menu-bar headings] 'undefined)
4100 (define-key org-mode-map [menu-bar hide] 'undefined)
4101 (define-key org-mode-map [menu-bar show] 'undefined))
4103 (easy-menu-add org-org-menu)
4104 (easy-menu-add org-tbl-menu)
4105 (org-install-agenda-files-menu)
4106 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4107 (org-add-to-invisibility-spec '(org-cwidth))
4108 (when (featurep 'xemacs)
4109 (org-set-local 'line-move-ignore-invisible t))
4110 (org-set-local 'outline-regexp "\\*+ ")
4111 (setq outline-level 'org-outline-level)
4112 (when (and org-ellipsis (stringp org-ellipsis)
4113 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
4114 (unless org-display-table
4115 (setq org-display-table (make-display-table)))
4116 (set-display-table-slot org-display-table
4117 4 (string-to-vector org-ellipsis))
4118 (setq buffer-display-table org-display-table))
4119 (org-set-regexps-and-options)
4120 ;; Calc embedded
4121 (org-set-local 'calc-embedded-open-mode "# ")
4122 (modify-syntax-entry ?# "<")
4123 (modify-syntax-entry ?@ "w")
4124 (if org-startup-truncated (setq truncate-lines t))
4125 (org-set-local 'font-lock-unfontify-region-function
4126 'org-unfontify-region)
4127 ;; Activate before-change-function
4128 (org-set-local 'org-table-may-need-update t)
4129 (org-add-hook 'before-change-functions 'org-before-change-function nil
4130 'local)
4131 ;; Check for running clock before killing a buffer
4132 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4133 ;; Paragraphs and auto-filling
4134 (org-set-autofill-regexps)
4135 (setq indent-line-function 'org-indent-line-function)
4136 (org-update-radio-target-regexp)
4138 ;; Comment characters
4139 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4140 (org-set-local 'comment-padding " ")
4142 ;; Make isearch reveal context
4143 (if (or (featurep 'xemacs)
4144 (not (boundp 'outline-isearch-open-invisible-function)))
4145 ;; Emacs 21 and XEmacs make use of the hook
4146 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4147 ;; Emacs 22 deals with this through a special variable
4148 (org-set-local 'outline-isearch-open-invisible-function
4149 (lambda (&rest ignore) (org-show-context 'isearch))))
4151 ;; If empty file that did not turn on org-mode automatically, make it to.
4152 (if (and org-insert-mode-line-in-empty-file
4153 (interactive-p)
4154 (= (point-min) (point-max)))
4155 (insert "# -*- mode: org -*-\n\n"))
4157 (unless org-inhibit-startup
4158 (when org-startup-align-all-tables
4159 (let ((bmp (buffer-modified-p)))
4160 (org-table-map-tables 'org-table-align)
4161 (set-buffer-modified-p bmp)))
4162 (cond
4163 ((eq org-startup-folded t)
4164 (org-cycle '(4)))
4165 ((eq org-startup-folded 'content)
4166 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4167 (org-cycle '(4)) (org-cycle '(4)))))))
4169 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4171 (defsubst org-call-with-arg (command arg)
4172 "Call COMMAND interactively, but pretend prefix are was ARG."
4173 (let ((current-prefix-arg arg)) (call-interactively command)))
4175 (defsubst org-current-line (&optional pos)
4176 (save-excursion
4177 (and pos (goto-char pos))
4178 ;; works also in narrowed buffer, because we start at 1, not point-min
4179 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4181 (defun org-current-time ()
4182 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4183 (if (> org-time-stamp-rounding-minutes 0)
4184 (let ((r org-time-stamp-rounding-minutes)
4185 (time (decode-time)))
4186 (apply 'encode-time
4187 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4188 (nthcdr 2 time))))
4189 (current-time)))
4191 (defun org-add-props (string plist &rest props)
4192 "Add text properties to entire string, from beginning to end.
4193 PLIST may be a list of properties, PROPS are individual properties and values
4194 that will be added to PLIST. Returns the string that was modified."
4195 (add-text-properties
4196 0 (length string) (if props (append plist props) plist) string)
4197 string)
4198 (put 'org-add-props 'lisp-indent-function 2)
4201 ;;;; Font-Lock stuff, including the activators
4203 (defvar org-mouse-map (make-sparse-keymap))
4204 (org-defkey org-mouse-map
4205 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4206 (org-defkey org-mouse-map
4207 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4208 (when org-mouse-1-follows-link
4209 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4210 (when org-tab-follows-link
4211 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4212 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4213 (when org-return-follows-link
4214 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4215 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4217 (require 'font-lock)
4219 (defconst org-non-link-chars "]\t\n\r<>")
4220 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4221 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4222 (defvar org-link-re-with-space nil
4223 "Matches a link with spaces, optional angular brackets around it.")
4224 (defvar org-link-re-with-space2 nil
4225 "Matches a link with spaces, optional angular brackets around it.")
4226 (defvar org-angle-link-re nil
4227 "Matches link with angular brackets, spaces are allowed.")
4228 (defvar org-plain-link-re nil
4229 "Matches plain link, without spaces.")
4230 (defvar org-bracket-link-regexp nil
4231 "Matches a link in double brackets.")
4232 (defvar org-bracket-link-analytic-regexp nil
4233 "Regular expression used to analyze links.
4234 Here is what the match groups contain after a match:
4235 1: http:
4236 2: http
4237 3: path
4238 4: [desc]
4239 5: desc")
4240 (defvar org-any-link-re nil
4241 "Regular expression matching any link.")
4243 (defun org-make-link-regexps ()
4244 "Update the link regular expressions.
4245 This should be called after the variable `org-link-types' has changed."
4246 (setq org-link-re-with-space
4247 (concat
4248 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4249 "\\([^" org-non-link-chars " ]"
4250 "[^" org-non-link-chars "]*"
4251 "[^" org-non-link-chars " ]\\)>?")
4252 org-link-re-with-space2
4253 (concat
4254 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4255 "\\([^" org-non-link-chars " ]"
4256 "[^]\t\n\r]*"
4257 "[^" org-non-link-chars " ]\\)>?")
4258 org-angle-link-re
4259 (concat
4260 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4261 "\\([^" org-non-link-chars " ]"
4262 "[^" org-non-link-chars "]*"
4263 "\\)>")
4264 org-plain-link-re
4265 (concat
4266 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4267 "\\([^]\t\n\r<>,;() ]+\\)")
4268 org-bracket-link-regexp
4269 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4270 org-bracket-link-analytic-regexp
4271 (concat
4272 "\\[\\["
4273 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4274 "\\([^]]+\\)"
4275 "\\]"
4276 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4277 "\\]")
4278 org-any-link-re
4279 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4280 org-angle-link-re "\\)\\|\\("
4281 org-plain-link-re "\\)")))
4283 (org-make-link-regexps)
4285 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4286 "Regular expression for fast time stamp matching.")
4287 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4288 "Regular expression for fast time stamp matching.")
4289 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4290 "Regular expression matching time strings for analysis.
4291 This one does not require the space after the date.")
4292 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4293 "Regular expression matching time strings for analysis.")
4294 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4295 "Regular expression matching time stamps, with groups.")
4296 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4297 "Regular expression matching time stamps (also [..]), with groups.")
4298 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4299 "Regular expression matching a time stamp range.")
4300 (defconst org-tr-regexp-both
4301 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4302 "Regular expression matching a time stamp range.")
4303 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4304 org-ts-regexp "\\)?")
4305 "Regular expression matching a time stamp or time stamp range.")
4306 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4307 org-ts-regexp-both "\\)?")
4308 "Regular expression matching a time stamp or time stamp range.
4309 The time stamps may be either active or inactive.")
4311 (defvar org-emph-face nil)
4313 (defun org-do-emphasis-faces (limit)
4314 "Run through the buffer and add overlays to links."
4315 (let (rtn)
4316 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4317 (if (not (= (char-after (match-beginning 3))
4318 (char-after (match-beginning 4))))
4319 (progn
4320 (setq rtn t)
4321 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4322 'face
4323 (nth 1 (assoc (match-string 3)
4324 org-emphasis-alist)))
4325 (add-text-properties (match-beginning 2) (match-end 2)
4326 '(font-lock-multiline t))
4327 (backward-char 1))))
4328 rtn))
4330 (defun org-emphasize (&optional char)
4331 "Insert or change an emphasis, i.e. a font like bold or italic.
4332 If there is an active region, change that region to a new emphasis.
4333 If there is no region, just insert the marker characters and position
4334 the cursor between them.
4335 CHAR should be either the marker character, or the first character of the
4336 HTML tag associated with that emphasis. If CHAR is a space, the means
4337 to remove the emphasis of the selected region.
4338 If char is not given (for example in an interactive call) it
4339 will be prompted for."
4340 (interactive)
4341 (let ((eal org-emphasis-alist) e det
4342 (erc org-emphasis-regexp-components)
4343 (prompt "")
4344 (string "") beg end move tag c s)
4345 (if (org-region-active-p)
4346 (setq beg (region-beginning) end (region-end)
4347 string (buffer-substring beg end))
4348 (setq move t))
4350 (while (setq e (pop eal))
4351 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4352 c (aref tag 0))
4353 (push (cons c (string-to-char (car e))) det)
4354 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4355 (substring tag 1)))))
4356 (unless char
4357 (message "%s" (concat "Emphasis marker or tag:" prompt))
4358 (setq char (read-char-exclusive)))
4359 (setq char (or (cdr (assoc char det)) char))
4360 (if (equal char ?\ )
4361 (setq s "" move nil)
4362 (unless (assoc (char-to-string char) org-emphasis-alist)
4363 (error "No such emphasis marker: \"%c\"" char))
4364 (setq s (char-to-string char)))
4365 (while (and (> (length string) 1)
4366 (equal (substring string 0 1) (substring string -1))
4367 (assoc (substring string 0 1) org-emphasis-alist))
4368 (setq string (substring string 1 -1)))
4369 (setq string (concat s string s))
4370 (if beg (delete-region beg end))
4371 (unless (or (bolp)
4372 (string-match (concat "[" (nth 0 erc) "\n]")
4373 (char-to-string (char-before (point)))))
4374 (insert " "))
4375 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4376 (char-to-string (char-after (point))))
4377 (insert " ") (backward-char 1))
4378 (insert string)
4379 (and move (backward-char 1))))
4381 (defun org-activate-plain-links (limit)
4382 "Run through the buffer and add overlays to links."
4383 (catch 'exit
4384 (let (f)
4385 (while (re-search-forward org-plain-link-re limit t)
4386 (setq f (get-text-property (match-beginning 0) 'face))
4387 (if (or (eq f 'org-tag)
4388 (and (listp f) (memq 'org-tag f)))
4390 (add-text-properties (match-beginning 0) (match-end 0)
4391 (list 'mouse-face 'highlight
4392 'rear-nonsticky t
4393 'keymap org-mouse-map
4395 (throw 'exit t))))))
4397 (defun org-activate-angle-links (limit)
4398 "Run through the buffer and add overlays to links."
4399 (if (re-search-forward org-angle-link-re limit t)
4400 (progn
4401 (add-text-properties (match-beginning 0) (match-end 0)
4402 (list 'mouse-face 'highlight
4403 'rear-nonsticky t
4404 'keymap org-mouse-map
4406 t)))
4408 (defmacro org-maybe-intangible (props)
4409 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4410 In emacs 21, invisible text is not avoided by the command loop, so the
4411 intangible property is needed to make sure point skips this text.
4412 In Emacs 22, this is not necessary. The intangible text property has
4413 led to problems with flyspell. These problems are fixed in flyspell.el,
4414 but we still avoid setting the property in Emacs 22 and later.
4415 We use a macro so that the test can happen at compilation time."
4416 (if (< emacs-major-version 22)
4417 `(append '(intangible t) ,props)
4418 props))
4420 (defun org-activate-bracket-links (limit)
4421 "Run through the buffer and add overlays to bracketed links."
4422 (if (re-search-forward org-bracket-link-regexp limit t)
4423 (let* ((help (concat "LINK: "
4424 (org-match-string-no-properties 1)))
4425 ;; FIXME: above we should remove the escapes.
4426 ;; but that requires another match, protecting match data,
4427 ;; a lot of overhead for font-lock.
4428 (ip (org-maybe-intangible
4429 (list 'invisible 'org-link 'rear-nonsticky t
4430 'keymap org-mouse-map 'mouse-face 'highlight
4431 'help-echo help)))
4432 (vp (list 'rear-nonsticky t
4433 'keymap org-mouse-map 'mouse-face 'highlight
4434 'help-echo help)))
4435 ;; We need to remove the invisible property here. Table narrowing
4436 ;; may have made some of this invisible.
4437 (remove-text-properties (match-beginning 0) (match-end 0)
4438 '(invisible nil))
4439 (if (match-end 3)
4440 (progn
4441 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4442 (add-text-properties (match-beginning 3) (match-end 3) vp)
4443 (add-text-properties (match-end 3) (match-end 0) ip))
4444 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4445 (add-text-properties (match-beginning 1) (match-end 1) vp)
4446 (add-text-properties (match-end 1) (match-end 0) ip))
4447 t)))
4449 (defun org-activate-dates (limit)
4450 "Run through the buffer and add overlays to dates."
4451 (if (re-search-forward org-tsr-regexp-both limit t)
4452 (progn
4453 (add-text-properties (match-beginning 0) (match-end 0)
4454 (list 'mouse-face 'highlight
4455 'rear-nonsticky t
4456 'keymap org-mouse-map))
4457 (when org-display-custom-times
4458 (if (match-end 3)
4459 (org-display-custom-time (match-beginning 3) (match-end 3)))
4460 (org-display-custom-time (match-beginning 1) (match-end 1)))
4461 t)))
4463 (defvar org-target-link-regexp nil
4464 "Regular expression matching radio targets in plain text.")
4465 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4466 "Regular expression matching a link target.")
4467 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4468 "Regular expression matching a radio target.")
4469 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4470 "Regular expression matching any target.")
4472 (defun org-activate-target-links (limit)
4473 "Run through the buffer and add overlays to target matches."
4474 (when org-target-link-regexp
4475 (let ((case-fold-search t))
4476 (if (re-search-forward org-target-link-regexp limit t)
4477 (progn
4478 (add-text-properties (match-beginning 0) (match-end 0)
4479 (list 'mouse-face 'highlight
4480 'rear-nonsticky t
4481 'keymap org-mouse-map
4482 'help-echo "Radio target link"
4483 'org-linked-text t))
4484 t)))))
4486 (defun org-update-radio-target-regexp ()
4487 "Find all radio targets in this file and update the regular expression."
4488 (interactive)
4489 (when (memq 'radio org-activate-links)
4490 (setq org-target-link-regexp
4491 (org-make-target-link-regexp (org-all-targets 'radio)))
4492 (org-restart-font-lock)))
4494 (defun org-hide-wide-columns (limit)
4495 (let (s e)
4496 (setq s (text-property-any (point) (or limit (point-max))
4497 'org-cwidth t))
4498 (when s
4499 (setq e (next-single-property-change s 'org-cwidth))
4500 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4501 (goto-char e)
4502 t)))
4504 (defun org-restart-font-lock ()
4505 "Restart font-lock-mode, to force refontification."
4506 (when (and (boundp 'font-lock-mode) font-lock-mode)
4507 ;; FIXME: Could font-lock-fontify-buffer be enough???
4508 (font-lock-mode -1)
4509 (font-lock-mode 1)))
4511 (defun org-all-targets (&optional radio)
4512 "Return a list of all targets in this file.
4513 With optional argument RADIO, only find radio targets."
4514 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4515 rtn)
4516 (save-excursion
4517 (goto-char (point-min))
4518 (while (re-search-forward re nil t)
4519 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4520 rtn)))
4522 (defun org-make-target-link-regexp (targets)
4523 "Make regular expression matching all strings in TARGETS.
4524 The regular expression finds the targets also if there is a line break
4525 between words."
4526 (and targets
4527 (concat
4528 "\\<\\("
4529 (mapconcat
4530 (lambda (x)
4531 (while (string-match " +" x)
4532 (setq x (replace-match "\\s-+" t t x)))
4534 targets
4535 "\\|")
4536 "\\)\\>")))
4538 (defun org-activate-tags (limit)
4539 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4540 (progn
4541 (add-text-properties (match-beginning 1) (match-end 1)
4542 (list 'mouse-face 'highlight
4543 'rear-nonsticky t
4544 'keymap org-mouse-map))
4545 t)))
4547 (defun org-outline-level ()
4548 (save-excursion
4549 (looking-at outline-regexp)
4550 (if (match-beginning 1)
4551 (+ (org-get-string-indentation (match-string 1)) 1000)
4552 (1- (- (match-end 0) (match-beginning 0))))))
4554 (defvar org-font-lock-keywords nil)
4556 (defconst org-property-re "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(\\S-.*\\)"
4557 "Regular expression matching a property line.")
4559 (defun org-set-font-lock-defaults ()
4560 (let* ((em org-fontify-emphasized-text)
4561 (lk org-activate-links)
4562 (org-font-lock-extra-keywords
4563 ;; Headlines
4564 (list
4565 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4566 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4567 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4568 (1 'org-table))
4569 ;; Links
4570 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4571 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4572 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4573 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4574 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4575 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4576 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4577 '(org-hide-wide-columns (0 nil append))
4578 ;; TODO lines
4579 (list (concat "^\\*+[ \t]+" org-not-done-regexp)
4580 '(1 'org-todo t))
4581 ;; Priorities
4582 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4583 ;; Special keywords
4584 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4585 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4586 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4587 (list (concat "\\<" org-archived-string) '(0 'org-special-keyword t))
4588 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4589 ;; Emphasis
4590 (if em
4591 (if (featurep 'xemacs)
4592 '(org-do-emphasis-faces (0 nil append))
4593 '(org-do-emphasis-faces)))
4594 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4595 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4596 2 'bold prepend)
4597 (if org-provide-checkbox-statistics
4598 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4599 (0 (org-get-checkbox-statistics-face) t)))
4600 ;; COMMENT
4601 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4602 "\\|" org-quote-string "\\)\\>")
4603 '(1 'org-special-keyword t))
4604 '("^#.*" (0 'font-lock-comment-face t))
4605 ;; DONE
4606 (if org-fontify-done-headline
4607 (list (concat "^[*]+ +\\<\\("
4608 (mapconcat 'regexp-quote org-done-keywords "\\|")
4609 "\\)\\(.*\\)")
4610 '(1 'org-done t) '(2 'org-headline-done t))
4611 (list (concat "^[*]+ +\\<\\("
4612 (mapconcat 'regexp-quote org-done-keywords "\\|")
4613 "\\)\\>")
4614 '(1 'org-done t)))
4615 ;; Table stuff
4616 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4617 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4618 ; '("^[ \t]*| *\\([#!$*_^/]\\) *|" (1 'org-formula t))
4619 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4620 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4621 ;; Drawers
4622 ; (list org-drawer-regexp '(0 'org-drawer t))
4623 ; (list "^[ \t]*:END:" '(0 'org-drawer t))
4624 (list org-drawer-regexp '(0 'org-special-keyword t))
4625 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4626 ;; Properties
4627 (list org-property-re
4628 '(1 'org-special-keyword t)
4629 '(3 'org-property-value t))
4630 (if org-format-transports-properties-p
4631 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4632 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4634 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4635 ;; Now set the full font-lock-keywords
4636 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4637 (org-set-local 'font-lock-defaults
4638 '(org-font-lock-keywords t nil nil backward-paragraph))
4639 (kill-local-variable 'font-lock-keywords) nil))
4641 (defvar org-m nil)
4642 (defvar org-l nil)
4643 (defvar org-f nil)
4644 (defun org-get-level-face (n)
4645 "Get the right face for match N in font-lock matching of healdines."
4646 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4647 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4648 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4649 (cond
4650 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4651 ((eq n 2) org-f)
4652 (t (if org-level-color-stars-only nil org-f))))
4654 (defun org-unfontify-region (beg end &optional maybe_loudly)
4655 "Remove fontification and activation overlays from links."
4656 (font-lock-default-unfontify-region beg end)
4657 (let* ((buffer-undo-list t)
4658 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4659 (inhibit-modification-hooks t)
4660 deactivate-mark buffer-file-name buffer-file-truename)
4661 (remove-text-properties beg end
4662 '(mouse-face t keymap t org-linked-text t
4663 rear-nonsticky t
4664 invisible t intangible t))))
4666 ;;;; Visibility cycling, including org-goto and indirect buffer
4668 ;;; Cycling
4670 (defvar org-cycle-global-status nil)
4671 (make-variable-buffer-local 'org-cycle-global-status)
4672 (defvar org-cycle-subtree-status nil)
4673 (make-variable-buffer-local 'org-cycle-subtree-status)
4675 ;;;###autoload
4676 (defun org-cycle (&optional arg)
4677 "Visibility cycling for Org-mode.
4679 - When this function is called with a prefix argument, rotate the entire
4680 buffer through 3 states (global cycling)
4681 1. OVERVIEW: Show only top-level headlines.
4682 2. CONTENTS: Show all headlines of all levels, but no body text.
4683 3. SHOW ALL: Show everything.
4685 - When point is at the beginning of a headline, rotate the subtree started
4686 by this line through 3 different states (local cycling)
4687 1. FOLDED: Only the main headline is shown.
4688 2. CHILDREN: The main headline and the direct children are shown.
4689 From this state, you can move to one of the children
4690 and zoom in further.
4691 3. SUBTREE: Show the entire subtree, including body text.
4693 - When there is a numeric prefix, go up to a heading with level ARG, do
4694 a `show-subtree' and return to the previous cursor position. If ARG
4695 is negative, go up that many levels.
4697 - When point is not at the beginning of a headline, execute
4698 `indent-relative', like TAB normally does. See the option
4699 `org-cycle-emulate-tab' for details.
4701 - Special case: if point is at the beginning of the buffer and there is
4702 no headline in line 1, this function will act as if called with prefix arg."
4703 (interactive "P")
4704 (let* ((outline-regexp
4705 (if (and (org-mode-p) org-cycle-include-plain-lists)
4706 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4707 outline-regexp))
4708 (bob-special (and org-cycle-global-at-bob (bobp)
4709 (not (looking-at outline-regexp))))
4710 (org-cycle-hook
4711 (if bob-special
4712 (delq 'org-optimize-window-after-visibility-change
4713 (copy-sequence org-cycle-hook))
4714 org-cycle-hook))
4715 (pos (point)))
4717 (if (or bob-special (equal arg '(4)))
4718 ;; special case: use global cycling
4719 (setq arg t))
4721 (cond
4723 ((org-at-table-p 'any)
4724 ;; Enter the table or move to the next field in the table
4725 (or (org-table-recognize-table.el)
4726 (progn
4727 (if arg (org-table-edit-field t)
4728 (org-table-justify-field-maybe)
4729 (call-interactively 'org-table-next-field)))))
4731 ((eq arg t) ;; Global cycling
4733 (cond
4734 ((and (eq last-command this-command)
4735 (eq org-cycle-global-status 'overview))
4736 ;; We just created the overview - now do table of contents
4737 ;; This can be slow in very large buffers, so indicate action
4738 (message "CONTENTS...")
4739 (org-content)
4740 (message "CONTENTS...done")
4741 (setq org-cycle-global-status 'contents)
4742 (run-hook-with-args 'org-cycle-hook 'contents))
4744 ((and (eq last-command this-command)
4745 (eq org-cycle-global-status 'contents))
4746 ;; We just showed the table of contents - now show everything
4747 (show-all)
4748 (message "SHOW ALL")
4749 (setq org-cycle-global-status 'all)
4750 (run-hook-with-args 'org-cycle-hook 'all))
4753 ;; Default action: go to overview
4754 (org-overview)
4755 (message "OVERVIEW")
4756 (setq org-cycle-global-status 'overview)
4757 (run-hook-with-args 'org-cycle-hook 'overview))))
4759 ((and org-drawers
4760 (save-excursion
4761 (beginning-of-line 1)
4762 (looking-at org-drawer-regexp)))
4763 ;; Toggle block visibility
4764 (org-flag-drawer
4765 (not (get-char-property (match-end 0) 'invisible))))
4767 ((integerp arg)
4768 ;; Show-subtree, ARG levels up from here.
4769 (save-excursion
4770 (org-back-to-heading)
4771 (outline-up-heading (if (< arg 0) (- arg)
4772 (- (funcall outline-level) arg)))
4773 (org-show-subtree)))
4775 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4776 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4777 ;; At a heading: rotate between three different views
4778 (org-back-to-heading)
4779 (let ((goal-column 0) eoh eol eos)
4780 ;; First, some boundaries
4781 (save-excursion
4782 (org-back-to-heading)
4783 (save-excursion
4784 (beginning-of-line 2)
4785 (while (and (not (eobp)) ;; this is like `next-line'
4786 (get-char-property (1- (point)) 'invisible))
4787 (beginning-of-line 2)) (setq eol (point)))
4788 (outline-end-of-heading) (setq eoh (point))
4789 (org-end-of-subtree t)
4790 (unless (eobp)
4791 (skip-chars-forward " \t\n")
4792 (beginning-of-line 1) ; in case this is an item
4794 (setq eos (1- (point))))
4795 ;; Find out what to do next and set `this-command'
4796 (cond
4797 ((= eos eoh)
4798 ;; Nothing is hidden behind this heading
4799 (message "EMPTY ENTRY")
4800 (setq org-cycle-subtree-status nil)
4801 (save-excursion
4802 (goto-char eos)
4803 (outline-next-heading)
4804 (if (org-invisible-p) (org-flag-heading nil))))
4805 ((or (>= eol eos)
4806 (not (string-match "\\S-" (buffer-substring eol eos))))
4807 ;; Entire subtree is hidden in one line: open it
4808 (org-show-entry)
4809 (show-children)
4810 (message "CHILDREN")
4811 (save-excursion
4812 (goto-char eos)
4813 (outline-next-heading)
4814 (if (org-invisible-p) (org-flag-heading nil)))
4815 (setq org-cycle-subtree-status 'children)
4816 (run-hook-with-args 'org-cycle-hook 'children))
4817 ((and (eq last-command this-command)
4818 (eq org-cycle-subtree-status 'children))
4819 ;; We just showed the children, now show everything.
4820 (org-show-subtree)
4821 (message "SUBTREE")
4822 (setq org-cycle-subtree-status 'subtree)
4823 (run-hook-with-args 'org-cycle-hook 'subtree))
4825 ;; Default action: hide the subtree.
4826 (hide-subtree)
4827 (message "FOLDED")
4828 (setq org-cycle-subtree-status 'folded)
4829 (run-hook-with-args 'org-cycle-hook 'folded)))))
4831 ;; TAB emulation
4832 (buffer-read-only (org-back-to-heading))
4834 ((org-try-cdlatex-tab))
4836 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4837 (or (not (bolp))
4838 (not (looking-at outline-regexp))))
4839 (call-interactively (global-key-binding "\t")))
4841 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4842 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4843 (or (and (eq org-cycle-emulate-tab 'white)
4844 (= (match-end 0) (point-at-eol)))
4845 (and (eq org-cycle-emulate-tab 'whitestart)
4846 (>= (match-end 0) pos))))
4848 (eq org-cycle-emulate-tab t))
4849 (if (and (looking-at "[ \n\r\t]")
4850 (string-match "^[ \t]*$" (buffer-substring
4851 (point-at-bol) (point))))
4852 (progn
4853 (beginning-of-line 1)
4854 (and (looking-at "[ \t]+") (replace-match ""))))
4855 (call-interactively (global-key-binding "\t")))
4857 (t (save-excursion
4858 (org-back-to-heading)
4859 (org-cycle))))))
4861 ;;;###autoload
4862 (defun org-global-cycle (&optional arg)
4863 "Cycle the global visibility. For details see `org-cycle'."
4864 (interactive "P")
4865 (let ((org-cycle-include-plain-lists
4866 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4867 (if (integerp arg)
4868 (progn
4869 (show-all)
4870 (hide-sublevels arg)
4871 (setq org-cycle-global-status 'contents))
4872 (org-cycle '(4)))))
4874 (defun org-overview ()
4875 "Switch to overview mode, shoing only top-level headlines.
4876 Really, this shows all headlines with level equal or greater than the level
4877 of the first headline in the buffer. This is important, because if the
4878 first headline is not level one, then (hide-sublevels 1) gives confusing
4879 results."
4880 (interactive)
4881 (let ((level (save-excursion
4882 (goto-char (point-min))
4883 (if (re-search-forward (concat "^" outline-regexp) nil t)
4884 (progn
4885 (goto-char (match-beginning 0))
4886 (funcall outline-level))))))
4887 (and level (hide-sublevels level))))
4889 (defun org-content (&optional arg)
4890 "Show all headlines in the buffer, like a table of contents.
4891 With numerical argument N, show content up to level N."
4892 (interactive "P")
4893 (save-excursion
4894 ;; Visit all headings and show their offspring
4895 (and (integerp arg) (org-overview))
4896 (goto-char (point-max))
4897 (catch 'exit
4898 (while (and (progn (condition-case nil
4899 (outline-previous-visible-heading 1)
4900 (error (goto-char (point-min))))
4902 (looking-at outline-regexp))
4903 (if (integerp arg)
4904 (show-children (1- arg))
4905 (show-branches))
4906 (if (bobp) (throw 'exit nil))))))
4909 (defun org-optimize-window-after-visibility-change (state)
4910 "Adjust the window after a change in outline visibility.
4911 This function is the default value of the hook `org-cycle-hook'."
4912 (when (get-buffer-window (current-buffer))
4913 (cond
4914 ; ((eq state 'overview) (org-first-headline-recenter 1))
4915 ; ((eq state 'overview) (org-beginning-of-line))
4916 ((eq state 'content) nil)
4917 ((eq state 'all) nil)
4918 ((eq state 'folded) nil)
4919 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4920 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4923 (defun org-cycle-show-empty-lines (state)
4924 "Show empty lines above all visible headlines.
4925 The region to be covered depends on STATE when called through
4926 `org-cycle-hook'. Lisp program can use t for STATE to get the
4927 entire buffer covered. Note that an empty line is only shown if there
4928 are at least `org-cycle-separator-lines' empty lines before the headeline."
4929 (when (> org-cycle-separator-lines 0)
4930 (save-excursion
4931 (let* ((n org-cycle-separator-lines)
4932 (re (cond
4933 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4934 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4935 (t (let ((ns (number-to-string (- n 2))))
4936 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4937 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4938 beg end)
4939 (cond
4940 ((memq state '(overview contents t))
4941 (setq beg (point-min) end (point-max)))
4942 ((memq state '(children folded))
4943 (setq beg (point) end (progn (org-end-of-subtree t t)
4944 (beginning-of-line 2)
4945 (point)))))
4946 (when beg
4947 (goto-char beg)
4948 (while (re-search-forward re end t)
4949 (if (not (get-char-property (match-end 1) 'invisible))
4950 (outline-flag-region
4951 (match-beginning 1) (match-end 1) nil)))))))
4952 ;; Never hide empty lines at the end of the file.
4953 (save-excursion
4954 (goto-char (point-max))
4955 (outline-previous-heading)
4956 (outline-end-of-heading)
4957 (if (and (looking-at "[ \t\n]+")
4958 (= (match-end 0) (point-max)))
4959 (outline-flag-region (point) (match-end 0) nil))))
4961 (defun org-subtree-end-visible-p ()
4962 "Is the end of the current subtree visible?"
4963 (pos-visible-in-window-p
4964 (save-excursion (org-end-of-subtree t) (point))))
4966 (defun org-first-headline-recenter (&optional N)
4967 "Move cursor to the first headline and recenter the headline.
4968 Optional argument N means, put the headline into the Nth line of the window."
4969 (goto-char (point-min))
4970 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4971 (beginning-of-line)
4972 (recenter (prefix-numeric-value N))))
4974 ;;; Org-goto
4976 (defvar org-goto-window-configuration nil)
4977 (defvar org-goto-marker nil)
4978 (defvar org-goto-map
4979 (let ((map (make-sparse-keymap)))
4980 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4981 (while (setq cmd (pop cmds))
4982 (substitute-key-definition cmd cmd map global-map)))
4983 (org-defkey map "\C-m" 'org-goto-ret)
4984 (org-defkey map [(left)] 'org-goto-left)
4985 (org-defkey map [(right)] 'org-goto-right)
4986 (org-defkey map [(?q)] 'org-goto-quit)
4987 (org-defkey map [(control ?g)] 'org-goto-quit)
4988 (org-defkey map "\C-i" 'org-cycle)
4989 (org-defkey map [(tab)] 'org-cycle)
4990 (org-defkey map [(down)] 'outline-next-visible-heading)
4991 (org-defkey map [(up)] 'outline-previous-visible-heading)
4992 (org-defkey map "n" 'outline-next-visible-heading)
4993 (org-defkey map "p" 'outline-previous-visible-heading)
4994 (org-defkey map "f" 'outline-forward-same-level)
4995 (org-defkey map "b" 'outline-backward-same-level)
4996 (org-defkey map "u" 'outline-up-heading)
4997 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4998 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4999 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5000 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5001 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5002 ;; FIXME: Could we use suppress-keymap?
5003 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5004 (while l (org-defkey map (int-to-string (pop l)) 'digit-argument)))
5005 map))
5007 (defconst org-goto-help
5008 "Select a location to jump to, press RET
5009 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
5011 (defun org-goto ()
5012 "Go to a different location of the document, keeping current visibility.
5014 When you want to go to a different location in a document, the fastest way
5015 is often to fold the entire buffer and then dive into the tree. This
5016 method has the disadvantage, that the previous location will be folded,
5017 which may not be what you want.
5019 This command works around this by showing a copy of the current buffer in
5020 overview mode. You can dive into the tree in that copy, to find the
5021 location you want to reach. When pressing RET, the command returns to the
5022 original buffer in which the visibility is still unchanged. It then jumps
5023 to the new location, making it and the headline hierarchy above it visible."
5024 (interactive)
5025 (let* ((org-goto-start-pos (point))
5026 (selected-point
5027 (org-get-location (current-buffer) org-goto-help)))
5028 (if selected-point
5029 (progn
5030 (org-mark-ring-push org-goto-start-pos)
5031 (goto-char selected-point)
5032 (if (or (org-invisible-p) (org-invisible-p2))
5033 (org-show-context 'org-goto)))
5034 (error "Quit"))))
5036 (defvar org-selected-point nil) ; dynamically scoped parameter
5038 (defun org-get-location (buf help)
5039 "Let the user select a location in the Org-mode buffer BUF.
5040 This function uses a recursive edit. It returns the selected position
5041 or nil."
5042 (let (org-selected-point)
5043 (save-excursion
5044 (save-window-excursion
5045 (delete-other-windows)
5046 (switch-to-buffer (get-buffer-create "*org-goto*"))
5047 (with-output-to-temp-buffer "*Help*"
5048 (princ help))
5049 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5050 (setq buffer-read-only nil)
5051 (erase-buffer)
5052 (insert-buffer-substring buf)
5053 (let ((org-startup-truncated t)
5054 (org-startup-folded t)
5055 (org-startup-align-all-tables nil))
5056 (org-mode))
5057 (setq buffer-read-only t)
5058 (if (and (boundp 'org-goto-start-pos)
5059 (integer-or-marker-p org-goto-start-pos))
5060 (let ((org-show-hierarchy-above t)
5061 (org-show-siblings t)
5062 (org-show-following-heading t))
5063 (goto-char org-goto-start-pos)
5064 (and (org-invisible-p) (org-show-context)))
5065 (goto-char (point-min)))
5066 (org-beginning-of-line)
5067 (message "Select location and press RET")
5068 ;; now we make sure that during selection, ony very few keys work
5069 ;; and that it is impossible to switch to another window.
5070 (let ((gm (current-global-map))
5071 (overriding-local-map org-goto-map))
5072 (unwind-protect
5073 (progn
5074 (use-global-map org-goto-map)
5075 (recursive-edit))
5076 (use-global-map gm)))))
5077 (kill-buffer "*org-goto*")
5078 org-selected-point))
5080 (defun org-goto-ret (&optional arg)
5081 "Finish `org-goto' by going to the new location."
5082 (interactive "P")
5083 (setq org-selected-point (point)
5084 current-prefix-arg arg)
5085 (throw 'exit nil))
5087 (defun org-goto-left ()
5088 "Finish `org-goto' by going to the new location."
5089 (interactive)
5090 (if (org-on-heading-p)
5091 (progn
5092 (beginning-of-line 1)
5093 (setq org-selected-point (point)
5094 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5095 (throw 'exit nil))
5096 (error "Not on a heading")))
5098 (defun org-goto-right ()
5099 "Finish `org-goto' by going to the new location."
5100 (interactive)
5101 (if (org-on-heading-p)
5102 (progn
5103 (outline-end-of-subtree)
5104 (or (eobp) (forward-char 1))
5105 (setq org-selected-point (point)
5106 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5107 (throw 'exit nil))
5108 (error "Not on a heading")))
5110 (defun org-goto-quit ()
5111 "Finish `org-goto' without cursor motion."
5112 (interactive)
5113 (setq org-selected-point nil)
5114 (throw 'exit nil))
5116 ;;; Indirect buffer display of subtrees
5118 (defvar org-indirect-dedicated-frame nil
5119 "This is the frame being used for indirect tree display.")
5120 (defvar org-last-indirect-buffer nil)
5122 (defun org-tree-to-indirect-buffer (&optional arg)
5123 "Create indirect buffer and narrow it to current subtree.
5124 With numerical prefix ARG, go up to this level and then take that tree.
5125 If ARG is negative, go up that many levels.
5126 Normally this command removes the indirect buffer previously made
5127 with this command. However, when called with a C-u prefix, the last buffer
5128 is kept so that you can work with several indirect buffers at the same time.
5129 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5130 requests that a new frame be made for the new buffer, so that the dedicated
5131 frame is not changed."
5132 (interactive "P")
5133 (let ((cbuf (current-buffer))
5134 (cwin (selected-window))
5135 (pos (point))
5136 beg end level heading ibuf)
5137 (save-excursion
5138 (org-back-to-heading t)
5139 (when (numberp arg)
5140 (setq level (org-outline-level))
5141 (if (< arg 0) (setq arg (+ level arg)))
5142 (while (> (setq level (org-outline-level)) arg)
5143 (outline-up-heading 1 t)))
5144 (setq beg (point)
5145 heading (org-get-heading))
5146 (org-end-of-subtree t) (setq end (point)))
5147 (if (and (not arg)
5148 (buffer-live-p org-last-indirect-buffer))
5149 (kill-buffer org-last-indirect-buffer))
5150 (setq ibuf (org-get-indirect-buffer cbuf)
5151 org-last-indirect-buffer ibuf)
5152 (cond
5153 ((or (eq org-indirect-buffer-display 'new-frame)
5154 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5155 (select-frame (make-frame))
5156 (delete-other-windows)
5157 (switch-to-buffer ibuf)
5158 (org-set-frame-title heading))
5159 ((eq org-indirect-buffer-display 'dedicated-frame)
5160 (raise-frame
5161 (select-frame (or (and org-indirect-dedicated-frame
5162 (frame-live-p org-indirect-dedicated-frame)
5163 org-indirect-dedicated-frame)
5164 (setq org-indirect-dedicated-frame (make-frame)))))
5165 (delete-other-windows)
5166 (switch-to-buffer ibuf)
5167 (org-set-frame-title (concat "Indirect: " heading)))
5168 ((eq org-indirect-buffer-display 'current-window)
5169 (switch-to-buffer ibuf))
5170 ((eq org-indirect-buffer-display 'other-window)
5171 (pop-to-buffer ibuf))
5172 (t (error "Invalid value.")))
5173 (if (featurep 'xemacs)
5174 (save-excursion (org-mode) (turn-on-font-lock)))
5175 (narrow-to-region beg end)
5176 (show-all)
5177 (goto-char pos)
5178 (and (window-live-p cwin) (select-window cwin))))
5180 (defun org-get-indirect-buffer (&optional buffer)
5181 (setq buffer (or buffer (current-buffer)))
5182 (let ((n 1) (base (buffer-name buffer)) bname)
5183 (while (buffer-live-p
5184 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5185 (setq n (1+ n)))
5186 (condition-case nil
5187 (make-indirect-buffer buffer bname 'clone)
5188 (error (make-indirect-buffer buffer bname)))))
5190 (defun org-set-frame-title (title)
5191 "Set the title of the current frame to the string TITLE."
5192 ;; FIXME: how to name a single frame in XEmacs???
5193 (unless (featurep 'xemacs)
5194 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5196 ;;;; Structure editing
5198 ;;; Inserting headlines
5200 (defun org-insert-heading (&optional force-heading)
5201 "Insert a new heading or item with same depth at point.
5202 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5203 If point is at the beginning of a headline, insert a sibling before the
5204 current headline. If point is in the middle of a headline, split the headline
5205 at that position and make the rest of the headline part of the sibling below
5206 the current headline."
5207 (interactive "P")
5208 (if (= (buffer-size) 0)
5209 (insert "\n* ")
5210 (when (or force-heading (not (org-insert-item)))
5211 (let* ((head (save-excursion
5212 (condition-case nil
5213 (progn
5214 (org-back-to-heading)
5215 (match-string 0))
5216 (error "*"))))
5217 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5218 pos)
5219 (cond
5220 ((and (org-on-heading-p) (bolp)
5221 (or (bobp)
5222 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5223 (open-line (if blank 2 1)))
5224 ((and (bolp)
5225 (or (bobp)
5226 (save-excursion
5227 (backward-char 1) (not (org-invisible-p)))))
5228 nil)
5229 (t (newline (if blank 2 1))))
5230 (insert head) (just-one-space)
5231 (setq pos (point))
5232 (end-of-line 1)
5233 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5234 (run-hooks 'org-insert-heading-hook)))))
5236 (defun org-insert-todo-heading (arg)
5237 "Insert a new heading with the same level and TODO state as current heading.
5238 If the heading has no TODO state, or if the state is DONE, use the first
5239 state (TODO by default). Also with prefix arg, force first state."
5240 (interactive "P")
5241 (when (not (org-insert-item 'checkbox))
5242 (org-insert-heading)
5243 (save-excursion
5244 (org-back-to-heading)
5245 (outline-previous-heading)
5246 (looking-at org-todo-line-regexp))
5247 (if (or arg
5248 (not (match-beginning 2))
5249 (member (match-string 2) org-done-keywords))
5250 (insert (car org-todo-keywords-1) " ")
5251 (insert (match-string 2) " "))))
5253 (defun org-insert-subheading (arg)
5254 "Insert a new subheading and demote it.
5255 Works for outline headings and for plain lists alike."
5256 (interactive "P")
5257 (org-insert-heading arg)
5258 (cond
5259 ((org-on-heading-p) (org-do-demote))
5260 ((org-at-item-p) (org-indent-item 1))))
5262 (defun org-insert-todo-subheading (arg)
5263 "Insert a new subheading with TODO keyword or checkbox and demote it.
5264 Works for outline headings and for plain lists alike."
5265 (interactive "P")
5266 (org-insert-todo-heading arg)
5267 (cond
5268 ((org-on-heading-p) (org-do-demote))
5269 ((org-at-item-p) (org-indent-item 1))))
5271 ;;; Promotion and Demotion
5273 (defun org-promote-subtree ()
5274 "Promote the entire subtree.
5275 See also `org-promote'."
5276 (interactive)
5277 (save-excursion
5278 (org-map-tree 'org-promote))
5279 (org-fix-position-after-promote))
5281 (defun org-demote-subtree ()
5282 "Demote the entire subtree. See `org-demote'.
5283 See also `org-promote'."
5284 (interactive)
5285 (save-excursion
5286 (org-map-tree 'org-demote))
5287 (org-fix-position-after-promote))
5290 (defun org-do-promote ()
5291 "Promote the current heading higher up the tree.
5292 If the region is active in `transient-mark-mode', promote all headings
5293 in the region."
5294 (interactive)
5295 (save-excursion
5296 (if (org-region-active-p)
5297 (org-map-region 'org-promote (region-beginning) (region-end))
5298 (org-promote)))
5299 (org-fix-position-after-promote))
5301 (defun org-do-demote ()
5302 "Demote the current heading lower down the tree.
5303 If the region is active in `transient-mark-mode', demote all headings
5304 in the region."
5305 (interactive)
5306 (save-excursion
5307 (if (org-region-active-p)
5308 (org-map-region 'org-demote (region-beginning) (region-end))
5309 (org-demote)))
5310 (org-fix-position-after-promote))
5312 (defun org-fix-position-after-promote ()
5313 "Make sure that after pro/demotion cursor position is right."
5314 (let ((pos (point)))
5315 (when (save-excursion
5316 (beginning-of-line 1)
5317 (looking-at org-todo-line-regexp)
5318 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5319 (cond ((eobp) (insert " "))
5320 ((eolp) (insert " "))
5321 ((equal (char-after) ?\ ) (forward-char 1))))))
5323 (defun org-reduced-level (l)
5324 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5326 (defun org-get-legal-level (level &optional change)
5327 "Rectify a level change under the influence of `org-odd-levels-only'
5328 LEVEL is a current level, CHANGE is by how much the level should be
5329 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5330 even level numbers will become the next higher odd number."
5331 (if org-odd-levels-only
5332 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5333 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5334 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5335 (max 1 (+ level change))))
5337 (defun org-promote ()
5338 "Promote the current heading higher up the tree.
5339 If the region is active in `transient-mark-mode', promote all headings
5340 in the region."
5341 (org-back-to-heading t)
5342 (let* ((level (save-match-data (funcall outline-level)))
5343 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5344 (diff (abs (- level (length up-head) -1))))
5345 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5346 (replace-match up-head nil t)
5347 ;; Fixup tag positioning
5348 (and org-auto-align-tags (org-set-tags nil t))
5349 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5351 (defun org-demote ()
5352 "Demote the current heading lower down the tree.
5353 If the region is active in `transient-mark-mode', demote all headings
5354 in the region."
5355 (org-back-to-heading t)
5356 (let* ((level (save-match-data (funcall outline-level)))
5357 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5358 (diff (abs (- level (length down-head) -1))))
5359 (replace-match down-head nil t)
5360 ;; Fixup tag positioning
5361 (and org-auto-align-tags (org-set-tags nil t))
5362 (if org-adapt-indentation (org-fixup-indentation diff))))
5364 (defun org-map-tree (fun)
5365 "Call FUN for every heading underneath the current one."
5366 (org-back-to-heading)
5367 (let ((level (funcall outline-level)))
5368 (save-excursion
5369 (funcall fun)
5370 (while (and (progn
5371 (outline-next-heading)
5372 (> (funcall outline-level) level))
5373 (not (eobp)))
5374 (funcall fun)))))
5376 (defun org-map-region (fun beg end)
5377 "Call FUN for every heading between BEG and END."
5378 (let ((org-ignore-region t))
5379 (save-excursion
5380 (setq end (copy-marker end))
5381 (goto-char beg)
5382 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5383 (< (point) end))
5384 (funcall fun))
5385 (while (and (progn
5386 (outline-next-heading)
5387 (< (point) end))
5388 (not (eobp)))
5389 (funcall fun)))))
5391 (defun org-fixup-indentation (diff)
5392 "Change the indentation in the current entry by DIFF
5393 However, if any line in the current entry has no indentation, or if it
5394 would end up with no indentation after the change, nothing at all is done."
5395 (save-excursion
5396 (let ((end (save-excursion (outline-next-heading)
5397 (point-marker)))
5398 (prohibit (if (> diff 0)
5399 "^\\S-"
5400 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5401 col)
5402 (unless (save-excursion (end-of-line 1)
5403 (re-search-forward prohibit end t))
5404 (while (re-search-forward "^[ \t]+" end t)
5405 (goto-char (match-end 0))
5406 (setq col (current-column))
5407 (if (< diff 0) (replace-match ""))
5408 (indent-to (+ diff col))))
5409 (move-marker end nil))))
5411 (defun org-convert-to-odd-levels ()
5412 "Convert an org-mode file with all levels allowed to one with odd levels.
5413 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5414 level 5 etc."
5415 (interactive)
5416 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5417 (let ((org-odd-levels-only nil) n)
5418 (save-excursion
5419 (goto-char (point-min))
5420 (while (re-search-forward "^\\*\\*+ " nil t)
5421 (setq n (- (length (match-string 0)) 2))
5422 (while (>= (setq n (1- n)) 0)
5423 (org-demote))
5424 (end-of-line 1))))))
5427 (defun org-convert-to-oddeven-levels ()
5428 "Convert an org-mode file with only odd levels to one with odd and even levels.
5429 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5430 section with an even level, conversion would destroy the structure of the file. An error
5431 is signaled in this case."
5432 (interactive)
5433 (goto-char (point-min))
5434 ;; First check if there are no even levels
5435 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5436 (org-show-context t)
5437 (error "Not all levels are odd in this file. Conversion not possible."))
5438 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5439 (let ((org-odd-levels-only nil) n)
5440 (save-excursion
5441 (goto-char (point-min))
5442 (while (re-search-forward "^\\*\\*+ " nil t)
5443 (setq n (/ (length (1- (match-string 0))) 2))
5444 (while (>= (setq n (1- n)) 0)
5445 (org-promote))
5446 (end-of-line 1))))))
5448 (defun org-tr-level (n)
5449 "Make N odd if required."
5450 (if org-odd-levels-only (1+ (/ n 2)) n))
5452 ;;; Vertical tree motion, cutting and pasting of subtrees
5454 (defun org-move-subtree-up (&optional arg)
5455 "Move the current subtree up past ARG headlines of the same level."
5456 (interactive "p")
5457 (org-move-subtree-down (- (prefix-numeric-value arg))))
5459 (defun org-move-subtree-down (&optional arg)
5460 "Move the current subtree down past ARG headlines of the same level."
5461 (interactive "p")
5462 (setq arg (prefix-numeric-value arg))
5463 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5464 'outline-get-last-sibling))
5465 (ins-point (make-marker))
5466 (cnt (abs arg))
5467 beg end txt folded)
5468 ;; Select the tree
5469 (org-back-to-heading)
5470 (setq beg (point))
5471 (save-match-data
5472 (save-excursion (outline-end-of-heading)
5473 (setq folded (org-invisible-p)))
5474 (outline-end-of-subtree))
5475 (outline-next-heading)
5476 (setq end (point))
5477 ;; Find insertion point, with error handling
5478 (goto-char beg)
5479 (while (> cnt 0)
5480 (or (and (funcall movfunc) (looking-at outline-regexp))
5481 (progn (goto-char beg)
5482 (error "Cannot move past superior level or buffer limit")))
5483 (setq cnt (1- cnt)))
5484 (if (> arg 0)
5485 ;; Moving forward - still need to move over subtree
5486 (progn (outline-end-of-subtree)
5487 (outline-next-heading)
5488 (if (not (or (looking-at (concat "^" outline-regexp))
5489 (bolp)))
5490 (newline))))
5491 (move-marker ins-point (point))
5492 (setq txt (buffer-substring beg end))
5493 (delete-region beg end)
5494 (insert txt)
5495 (or (bolp) (insert "\n"))
5496 (goto-char ins-point)
5497 (if folded (hide-subtree))
5498 (move-marker ins-point nil)))
5500 (defvar org-subtree-clip ""
5501 "Clipboard for cut and paste of subtrees.
5502 This is actually only a copy of the kill, because we use the normal kill
5503 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5505 (defvar org-subtree-clip-folded nil
5506 "Was the last copied subtree folded?
5507 This is used to fold the tree back after pasting.")
5509 (defun org-cut-subtree ()
5510 "Cut the current subtree into the clipboard.
5511 This is a short-hand for marking the subtree and then cutting it."
5512 (interactive)
5513 (org-copy-subtree 'cut))
5515 (defun org-copy-subtree (&optional cut)
5516 "Cut the current subtree into the clipboard.
5517 This is a short-hand for marking the subtree and then copying it.
5518 If CUT is non-nil, actually cut the subtree."
5519 (interactive)
5520 (let (beg end folded)
5521 (if (interactive-p)
5522 (org-back-to-heading nil) ; take what looks like a subtree
5523 (org-back-to-heading t)) ; take what is really there
5524 (setq beg (point))
5525 (save-match-data
5526 (save-excursion (outline-end-of-heading)
5527 (setq folded (org-invisible-p)))
5528 (outline-end-of-subtree))
5529 (if (equal (char-after) ?\n) (forward-char 1))
5530 (setq end (point))
5531 (goto-char beg)
5532 (when (> end beg)
5533 (setq org-subtree-clip-folded folded)
5534 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5535 (setq org-subtree-clip (current-kill 0))
5536 (message "%s: Subtree with %d characters"
5537 (if cut "Cut" "Copied")
5538 (length org-subtree-clip)))))
5540 (defun org-paste-subtree (&optional level tree)
5541 "Paste the clipboard as a subtree, with modification of headline level.
5542 The entire subtree is promoted or demoted in order to match a new headline
5543 level. By default, the new level is derived from the visible headings
5544 before and after the insertion point, and taken to be the inferior headline
5545 level of the two. So if the previous visible heading is level 3 and the
5546 next is level 4 (or vice versa), level 4 will be used for insertion.
5547 This makes sure that the subtree remains an independent subtree and does
5548 not swallow low level entries.
5550 You can also force a different level, either by using a numeric prefix
5551 argument, or by inserting the heading marker by hand. For example, if the
5552 cursor is after \"*****\", then the tree will be shifted to level 5.
5554 If you want to insert the tree as is, just use \\[yank].
5556 If optional TREE is given, use this text instead of the kill ring."
5557 (interactive "P")
5558 (unless (org-kill-is-subtree-p tree)
5559 (error
5560 (substitute-command-keys
5561 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5562 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5563 (^re (concat "^\\(" outline-regexp "\\)"))
5564 (re (concat "\\(" outline-regexp "\\)"))
5565 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5567 (old-level (if (string-match ^re txt)
5568 (- (match-end 0) (match-beginning 0) 1)
5569 -1))
5570 (force-level (cond (level (prefix-numeric-value level))
5571 ((string-match
5572 ^re_ (buffer-substring (point-at-bol) (point)))
5573 (- (match-end 0) (match-beginning 0)))
5574 (t nil)))
5575 (previous-level (save-excursion
5576 (condition-case nil
5577 (progn
5578 (outline-previous-visible-heading 1)
5579 (if (looking-at re)
5580 (- (match-end 0) (match-beginning 0))
5582 (error 1))))
5583 (next-level (save-excursion
5584 (condition-case nil
5585 (progn
5586 (outline-next-visible-heading 1)
5587 (if (looking-at re)
5588 (- (match-end 0) (match-beginning 0))
5590 (error 1))))
5591 (new-level (or force-level (max previous-level next-level)))
5592 (shift (if (or (= old-level -1)
5593 (= new-level -1)
5594 (= old-level new-level))
5596 (- new-level old-level)))
5597 (shift1 shift)
5598 (delta (if (> shift 0) -1 1))
5599 (func (if (> shift 0) 'org-demote 'org-promote))
5600 (org-odd-levels-only nil)
5601 beg end)
5602 ;; Remove the forces level indicator
5603 (if force-level
5604 (delete-region (point-at-bol) (point)))
5605 ;; Make sure we start at the beginning of an empty line
5606 (if (not (bolp)) (insert "\n"))
5607 (if (not (looking-at "[ \t]*$"))
5608 (progn (insert "\n") (backward-char 1)))
5609 ;; Paste
5610 (setq beg (point))
5611 (if (string-match "[ \t\r\n]+\\'" txt)
5612 (setq txt (replace-match "\n" t t txt)))
5613 (insert txt)
5614 (setq end (point))
5615 (if (looking-at "[ \t\r\n]+")
5616 (replace-match "\n"))
5617 (goto-char beg)
5618 ;; Shift if necessary
5619 (if (= shift 0)
5620 (message "Pasted at level %d, without shift" new-level)
5621 (save-restriction
5622 (narrow-to-region beg end)
5623 (while (not (= shift 0))
5624 (org-map-region func (point-min) (point-max))
5625 (setq shift (+ delta shift)))
5626 (goto-char (point-min))
5627 (message "Pasted at level %d, with shift by %d levels"
5628 new-level shift1)))
5629 (if (and kill-ring
5630 (eq org-subtree-clip (current-kill 0))
5631 org-subtree-clip-folded)
5632 ;; The tree was folded before it was killed/copied
5633 (hide-subtree))))
5635 (defun org-kill-is-subtree-p (&optional txt)
5636 "Check if the current kill is an outline subtree, or a set of trees.
5637 Returns nil if kill does not start with a headline, or if the first
5638 headline level is not the largest headline level in the tree.
5639 So this will actually accept several entries of equal levels as well,
5640 which is OK for `org-paste-subtree'.
5641 If optional TXT is given, check this string instead of the current kill."
5642 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5643 (start-level (and kill
5644 (string-match (concat "\\`" outline-regexp) kill)
5645 (- (match-end 0) (match-beginning 0))))
5646 (re (concat "^" outline-regexp))
5647 (start 1))
5648 (if (not start-level)
5649 nil ;; does not even start with a heading
5650 (catch 'exit
5651 (while (setq start (string-match re kill (1+ start)))
5652 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5653 (throw 'exit nil)))
5654 t))))
5656 (defun org-narrow-to-subtree ()
5657 "Narrow buffer to the current subtree."
5658 (interactive)
5659 (save-excursion
5660 (narrow-to-region
5661 (progn (org-back-to-heading) (point))
5662 (progn (org-end-of-subtree t t) (point)))))
5665 ;;; Outline Sorting
5667 (defun org-sort (with-case)
5668 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5669 (interactive "P")
5670 (if (org-at-table-p)
5671 (org-call-with-arg 'org-table-sort-lines with-case)
5672 (org-call-with-arg 'org-sort-entries with-case)))
5674 (defun org-sort-entries (&optional with-case sorting-type)
5675 "Sort entries on a certain level of an outline tree.
5676 If there is an active region, the entries in the region are sorted.
5677 Else, if the cursor is before the first entry, sort the top-level items.
5678 Else, the children of the entry at point are sorted.
5680 Sorting can be alphabetically, numerically, and by date/time as given by
5681 the first time stamp in the entry. The command prompts for the sorting
5682 type unless it has been given to the function through the SORTING-TYPE
5683 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5685 Comparing entries ignores case by default. However, with an optional argument
5686 WITH-CASE, the sorting considers case as well. With two prefix arguments
5687 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5688 (interactive "P")
5689 (let ((unique (equal with-case '(16)))
5690 start beg end entries stars re re2 p nentries (nremoved 0)
5691 last txt what)
5692 ;; Find beginning and end of region to sort
5693 (cond
5694 ((org-region-active-p)
5695 ;; we will sort the region
5696 (setq end (region-end)
5697 what "region")
5698 (goto-char (region-beginning))
5699 (if (not (org-on-heading-p)) (outline-next-heading))
5700 (setq start (point)))
5701 ((or (org-on-heading-p)
5702 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5703 ;; we will sort the children of the current headline
5704 (org-back-to-heading)
5705 (setq start (point) end (org-end-of-subtree) what "children")
5706 (goto-char start)
5707 (show-subtree)
5708 (outline-next-heading))
5710 ;; we will sort the top-level entries in this file
5711 (goto-char (point-min))
5712 (or (org-on-heading-p) (outline-next-heading))
5713 (setq start (point) end (point-max) what "top-level")
5714 (goto-char start)
5715 (show-all)))
5716 (setq beg (point))
5717 (if (>= (point) end) (error "Nothing to sort"))
5718 (looking-at "\\(\\*+\\)")
5719 (setq stars (match-string 1)
5720 re (concat "^" (regexp-quote stars) " +")
5721 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5722 txt (buffer-substring beg end))
5723 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5724 (if (and (not (equal stars "*")) (string-match re2 txt))
5725 (error "Region to sort contains a level above the first entry"))
5726 ;; Make a list that can be sorted.
5727 ;; The car is the string for comparison, the cdr is the subtree
5728 (message "Sorting entries...")
5729 (setq entries
5730 (mapcar
5731 (lambda (x)
5732 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5733 (cons (match-string 0 x) x))
5734 (org-split-string txt re)))
5736 ;; Sort the list
5737 (save-excursion
5738 (goto-char start)
5739 (setq entries (org-do-sort entries what with-case sorting-type)))
5741 ;; Delete the old stuff
5742 (goto-char beg)
5743 (kill-region beg end)
5744 (setq nentries (length entries))
5745 ;; Insert the sorted entries, and remove duplicates if this is required
5746 (while (setq p (pop entries))
5747 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5748 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5749 (insert stars " " (cdr p))))
5750 (goto-char start)
5751 (message "Sorting entries...done (%d entries%s)"
5752 nentries
5753 (if unique (format ", %d duplicates removed" nremoved) ""))))
5755 (defun org-do-sort (table what &optional with-case sorting-type)
5756 "Sort TABLE of WHAT according to SORTING-TYPE.
5757 The user will be prompted for the SORTING-TYPE if the call to this
5758 function does not specify it. WHAT is only for the prompt, to indicate
5759 what is being sorted. The sorting key will be extracted from
5760 the car of the elements of the table.
5761 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5762 (unless sorting-type
5763 (message
5764 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5765 what)
5766 (setq sorting-type (read-char-exclusive)))
5767 (let ((dcst (downcase sorting-type))
5768 extractfun comparefun)
5769 ;; Define the appropriate functions
5770 (cond
5771 ((= dcst ?n)
5772 (setq extractfun 'string-to-number
5773 comparefun (if (= dcst sorting-type) '< '>)))
5774 ((= dcst ?a)
5775 (setq extractfun (if with-case 'identity 'downcase)
5776 comparefun (if (= dcst sorting-type)
5777 'string<
5778 (lambda (a b) (and (not (string< a b))
5779 (not (string= a b)))))))
5780 ((= dcst ?t)
5781 (setq extractfun
5782 (lambda (x)
5783 (if (string-match org-ts-regexp x)
5784 (time-to-seconds
5785 (org-time-string-to-time (match-string 0 x)))
5787 comparefun (if (= dcst sorting-type) '< '>)))
5788 (t (error "Invalid sorting type `%c'" sorting-type)))
5790 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5791 table)
5792 (lambda (a b) (funcall comparefun (car a) (car b))))))
5794 ;;;; Plain list items, including checkboxes
5796 ;;; Plain list items
5798 (defun org-at-item-p ()
5799 "Is point in a line starting a hand-formatted item?"
5800 (let ((llt org-plain-list-ordered-item-terminator))
5801 (save-excursion
5802 (goto-char (point-at-bol))
5803 (looking-at
5804 (cond
5805 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5806 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5807 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5808 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5810 (defun org-in-item-p ()
5811 "It the cursor inside a plain list item.
5812 Does not have to be the first line."
5813 (save-excursion
5814 (condition-case nil
5815 (progn
5816 (org-beginning-of-item)
5817 (org-at-item-p)
5819 (error nil))))
5821 (defun org-insert-item (&optional checkbox)
5822 "Insert a new item at the current level.
5823 Return t when things worked, nil when we are not in an item."
5824 (when (save-excursion
5825 (condition-case nil
5826 (progn
5827 (org-beginning-of-item)
5828 (org-at-item-p)
5829 (if (org-invisible-p) (error "Invisible item"))
5831 (error nil)))
5832 (let* ((bul (match-string 0))
5833 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5834 (match-end 0)))
5835 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5836 pos)
5837 (cond
5838 ((and (org-at-item-p) (<= (point) eow))
5839 ;; before the bullet
5840 (beginning-of-line 1)
5841 (open-line (if blank 2 1)))
5842 ((<= (point) eow)
5843 (beginning-of-line 1))
5844 (t (newline (if blank 2 1))))
5845 (insert bul (if checkbox "[ ]" ""))
5846 (just-one-space)
5847 (setq pos (point))
5848 (end-of-line 1)
5849 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5850 (org-maybe-renumber-ordered-list)
5851 (and checkbox (org-update-checkbox-count-maybe))
5854 ;;; Checkboxes
5856 (defun org-at-item-checkbox-p ()
5857 "Is point at a line starting a plain-list item with a checklet?"
5858 (and (org-at-item-p)
5859 (save-excursion
5860 (goto-char (match-end 0))
5861 (skip-chars-forward " \t")
5862 (looking-at "\\[[- X]\\]"))))
5864 (defun org-toggle-checkbox (&optional arg)
5865 "Toggle the checkbox in the current line."
5866 (interactive "P")
5867 (catch 'exit
5868 (let (beg end status (firstnew 'unknown))
5869 (cond
5870 ((org-region-active-p)
5871 (setq beg (region-beginning) end (region-end)))
5872 ((org-on-heading-p)
5873 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5874 ((org-at-item-checkbox-p)
5875 (save-excursion
5876 (replace-match
5877 (cond (arg "[-]")
5878 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5879 (t "[ ]"))
5880 t t))
5881 (throw 'exit t))
5882 (t (error "Not at a checkbox or heading, and no active region")))
5883 (save-excursion
5884 (goto-char beg)
5885 (while (< (point) end)
5886 (when (org-at-item-checkbox-p)
5887 (setq status (equal (match-string 0) "[X]"))
5888 (when (eq firstnew 'unknown)
5889 (setq firstnew (not status)))
5890 (replace-match
5891 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5892 (beginning-of-line 2)))))
5893 (org-update-checkbox-count-maybe))
5895 (defun org-update-checkbox-count-maybe ()
5896 "Update checkbox statistics unless turned off by user."
5897 (when org-provide-checkbox-statistics
5898 (org-update-checkbox-count)))
5900 (defun org-update-checkbox-count (&optional all)
5901 "Update the checkbox statistics in the current section.
5902 This will find all statistic cookies like [57%] and [6/12] and update them
5903 with the current numbers. With optional prefix argument ALL, do this for
5904 the whole buffer."
5905 (interactive "P")
5906 (save-excursion
5907 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5908 (beg (condition-case nil
5909 (progn (outline-back-to-heading) (point))
5910 (error (point-min))))
5911 (end (move-marker (make-marker)
5912 (progn (outline-next-heading) (point))))
5913 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5914 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5915 b1 e1 f1 c-on c-off lim (cstat 0))
5916 (when all
5917 (goto-char (point-min))
5918 (outline-next-heading)
5919 (setq beg (point) end (point-max)))
5920 (goto-char beg)
5921 (while (re-search-forward re end t)
5922 (setq cstat (1+ cstat)
5923 b1 (match-beginning 0)
5924 e1 (match-end 0)
5925 f1 (match-beginning 1)
5926 lim (cond
5927 ((org-on-heading-p) (outline-next-heading) (point))
5928 ((org-at-item-p) (org-end-of-item) (point))
5929 (t nil))
5930 c-on 0 c-off 0)
5931 (goto-char e1)
5932 (when lim
5933 (while (re-search-forward re-box lim t)
5934 (if (member (match-string 2) '("[ ]" "[-]"))
5935 (setq c-off (1+ c-off))
5936 (setq c-on (1+ c-on))))
5937 ; (delete-region b1 e1)
5938 (goto-char b1)
5939 (insert (if f1
5940 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5941 (format "[%d/%d]" c-on (+ c-on c-off))))
5942 (and (looking-at "\\[.*?\\]")
5943 (replace-match ""))))
5944 (when (interactive-p)
5945 (message "Checkbox satistics updated %s (%d places)"
5946 (if all "in entire file" "in current outline entry") cstat)))))
5948 (defun org-get-checkbox-statistics-face ()
5949 "Select the face for checkbox statistics.
5950 The face will be `org-done' when all relevant boxes are checked. Otherwise
5951 it will be `org-todo'."
5952 (if (match-end 1)
5953 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5954 (if (and (> (match-end 2) (match-beginning 2))
5955 (equal (match-string 2) (match-string 3)))
5956 'org-done
5957 'org-todo)))
5959 (defun org-get-indentation (&optional line)
5960 "Get the indentation of the current line, interpreting tabs.
5961 When LINE is given, assume it represents a line and compute its indentation."
5962 (if line
5963 (if (string-match "^ *" (org-remove-tabs line))
5964 (match-end 0))
5965 (save-excursion
5966 (beginning-of-line 1)
5967 (skip-chars-forward " \t")
5968 (current-column))))
5970 (defun org-remove-tabs (s &optional width)
5971 "Replace tabulators in S with spaces.
5972 Assumes that s is a single line, starting in column 0."
5973 (setq width (or width tab-width))
5974 (while (string-match "\t" s)
5975 (setq s (replace-match
5976 (make-string
5977 (- (* width (/ (+ (match-beginning 0) width) width))
5978 (match-beginning 0)) ?\ )
5979 t t s)))
5982 (defun org-fix-indentation (line ind)
5983 "Fix indentation in LINE.
5984 IND is a cons cell with target and minimum indentation.
5985 If the current indenation in LINE is smaller than the minimum,
5986 leave it alone. If it is larger than ind, set it to the target."
5987 (let* ((l (org-remove-tabs line))
5988 (i (org-get-indentation l))
5989 (i1 (car ind)) (i2 (cdr ind)))
5990 (if (>= i i2) (setq l (substring line i2)))
5991 (if (> i1 0)
5992 (concat (make-string i1 ?\ ) l)
5993 l)))
5995 (defcustom org-empty-line-terminates-plain-lists nil
5996 "Non-nil means, an empty line ends all plain list levels.
5997 When nil, empty lines are part of the preceeding item."
5998 :group 'org-plain-lists
5999 :type 'boolean)
6001 (defun org-beginning-of-item ()
6002 "Go to the beginning of the current hand-formatted item.
6003 If the cursor is not in an item, throw an error."
6004 (interactive)
6005 (let ((pos (point))
6006 (limit (save-excursion
6007 (condition-case nil
6008 (progn
6009 (org-back-to-heading)
6010 (beginning-of-line 2) (point))
6011 (error (point-min)))))
6012 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6013 ind ind1)
6014 (if (org-at-item-p)
6015 (beginning-of-line 1)
6016 (beginning-of-line 1)
6017 (skip-chars-forward " \t")
6018 (setq ind (current-column))
6019 (if (catch 'exit
6020 (while t
6021 (beginning-of-line 0)
6022 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6024 (if (looking-at "[ \t]*$")
6025 (setq ind1 ind-empty)
6026 (skip-chars-forward " \t")
6027 (setq ind1 (current-column)))
6028 (if (< ind1 ind)
6029 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6031 (goto-char pos)
6032 (error "Not in an item")))))
6034 (defun org-end-of-item ()
6035 "Go to the end of the current hand-formatted item.
6036 If the cursor is not in an item, throw an error."
6037 (interactive)
6038 (let* ((pos (point))
6039 ind1
6040 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6041 (limit (save-excursion (outline-next-heading) (point)))
6042 (ind (save-excursion
6043 (org-beginning-of-item)
6044 (skip-chars-forward " \t")
6045 (current-column)))
6046 (end (catch 'exit
6047 (while t
6048 (beginning-of-line 2)
6049 (if (eobp) (throw 'exit (point)))
6050 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6051 (if (looking-at "[ \t]*$")
6052 (setq ind1 ind-empty)
6053 (skip-chars-forward " \t")
6054 (setq ind1 (current-column)))
6055 (if (<= ind1 ind)
6056 (throw 'exit (point-at-bol)))))))
6057 (if end
6058 (goto-char end)
6059 (goto-char pos)
6060 (error "Not in an item"))))
6062 (defun org-next-item ()
6063 "Move to the beginning of the next item in the current plain list.
6064 Error if not at a plain list, or if this is the last item in the list."
6065 (interactive)
6066 (let (ind ind1 (pos (point)))
6067 (org-beginning-of-item)
6068 (setq ind (org-get-indentation))
6069 (org-end-of-item)
6070 (setq ind1 (org-get-indentation))
6071 (unless (and (org-at-item-p) (= ind ind1))
6072 (goto-char pos)
6073 (error "On last item"))))
6075 (defun org-previous-item ()
6076 "Move to the beginning of the previous item in the current plain list.
6077 Error if not at a plain list, or if this is the first item in the list."
6078 (interactive)
6079 (let (beg ind ind1 (pos (point)))
6080 (org-beginning-of-item)
6081 (setq beg (point))
6082 (setq ind (org-get-indentation))
6083 (goto-char beg)
6084 (catch 'exit
6085 (while t
6086 (beginning-of-line 0)
6087 (if (looking-at "[ \t]*$")
6089 (if (<= (setq ind1 (org-get-indentation)) ind)
6090 (throw 'exit t)))))
6091 (condition-case nil
6092 (if (or (not (org-at-item-p))
6093 (< ind1 (1- ind)))
6094 (error "")
6095 (org-beginning-of-item))
6096 (error (goto-char pos)
6097 (error "On first item")))))
6099 (defun org-move-item-down ()
6100 "Move the plain list item at point down, i.e. swap with following item.
6101 Subitems (items with larger indentation) are considered part of the item,
6102 so this really moves item trees."
6103 (interactive)
6104 (let (beg end ind ind1 (pos (point)) txt)
6105 (org-beginning-of-item)
6106 (setq beg (point))
6107 (setq ind (org-get-indentation))
6108 (org-end-of-item)
6109 (setq end (point))
6110 (setq ind1 (org-get-indentation))
6111 (if (and (org-at-item-p) (= ind ind1))
6112 (progn
6113 (org-end-of-item)
6114 (setq txt (buffer-substring beg end))
6115 (save-excursion
6116 (delete-region beg end))
6117 (setq pos (point))
6118 (insert txt)
6119 (goto-char pos)
6120 (org-maybe-renumber-ordered-list))
6121 (goto-char pos)
6122 (error "Cannot move this item further down"))))
6124 (defun org-move-item-up (arg)
6125 "Move the plain list item at point up, i.e. swap with previous item.
6126 Subitems (items with larger indentation) are considered part of the item,
6127 so this really moves item trees."
6128 (interactive "p")
6129 (let (beg end ind ind1 (pos (point)) txt)
6130 (org-beginning-of-item)
6131 (setq beg (point))
6132 (setq ind (org-get-indentation))
6133 (org-end-of-item)
6134 (setq end (point))
6135 (goto-char beg)
6136 (catch 'exit
6137 (while t
6138 (beginning-of-line 0)
6139 (if (looking-at "[ \t]*$")
6140 (if org-empty-line-terminates-plain-lists
6141 (progn
6142 (goto-char pos)
6143 (error "Cannot move this item further up"))
6144 nil)
6145 (if (<= (setq ind1 (org-get-indentation)) ind)
6146 (throw 'exit t)))))
6147 (condition-case nil
6148 (org-beginning-of-item)
6149 (error (goto-char beg)
6150 (error "Cannot move this item further up")))
6151 (setq ind1 (org-get-indentation))
6152 (if (and (org-at-item-p) (= ind ind1))
6153 (progn
6154 (setq txt (buffer-substring beg end))
6155 (save-excursion
6156 (delete-region beg end))
6157 (setq pos (point))
6158 (insert txt)
6159 (goto-char pos)
6160 (org-maybe-renumber-ordered-list))
6161 (goto-char pos)
6162 (error "Cannot move this item further up"))))
6164 (defun org-maybe-renumber-ordered-list ()
6165 "Renumber the ordered list at point if setup allows it.
6166 This tests the user option `org-auto-renumber-ordered-lists' before
6167 doing the renumbering."
6168 (interactive)
6169 (when (and org-auto-renumber-ordered-lists
6170 (org-at-item-p))
6171 (if (match-beginning 3)
6172 (org-renumber-ordered-list 1)
6173 (org-fix-bullet-type 1))))
6175 (defun org-maybe-renumber-ordered-list-safe ()
6176 (condition-case nil
6177 (save-excursion
6178 (org-maybe-renumber-ordered-list))
6179 (error nil)))
6181 (defun org-cycle-list-bullet (&optional which)
6182 "Cycle through the different itemize/enumerate bullets.
6183 This cycle the entire list level through the sequence:
6185 `-' -> `+' -> `*' -> `1.' -> `1)'
6187 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6188 0 meand `-', 1 means `+' etc."
6189 (interactive "P")
6190 (org-preserve-lc
6191 (org-beginning-of-item-list)
6192 (org-at-item-p)
6193 (beginning-of-line 1)
6194 (let ((current (match-string 0)) new)
6195 (setq new (cond
6196 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6197 ((string-match "-" current) "+")
6198 ((string-match "\\+" current)
6199 (if (looking-at "\\S-") "1." "*"))
6200 ((string-match "\\*" current) "1.")
6201 ((string-match "\\." current) "1)")
6202 ((string-match ")" current) "-")
6203 (t (error "This should not happen"))))
6204 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6205 (org-fix-bullet-type 1)
6206 (org-maybe-renumber-ordered-list))))
6208 (defun org-get-string-indentation (s)
6209 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6210 (let ((n -1) (i 0) (w tab-width) c)
6211 (catch 'exit
6212 (while (< (setq n (1+ n)) (length s))
6213 (setq c (aref s n))
6214 (cond ((= c ?\ ) (setq i (1+ i)))
6215 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6216 (t (throw 'exit t)))))
6219 (defun org-renumber-ordered-list (arg)
6220 "Renumber an ordered plain list.
6221 Cursor needs to be in the first line of an item, the line that starts
6222 with something like \"1.\" or \"2)\"."
6223 (interactive "p")
6224 (unless (and (org-at-item-p)
6225 (match-beginning 3))
6226 (error "This is not an ordered list"))
6227 (let ((line (org-current-line))
6228 (col (current-column))
6229 (ind (org-get-string-indentation
6230 (buffer-substring (point-at-bol) (match-beginning 3))))
6231 ;; (term (substring (match-string 3) -1))
6232 ind1 (n (1- arg))
6233 fmt)
6234 ;; find where this list begins
6235 (org-beginning-of-item-list)
6236 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6237 (setq fmt (concat "%d" (match-string 1)))
6238 (beginning-of-line 0)
6239 ;; walk forward and replace these numbers
6240 (catch 'exit
6241 (while t
6242 (catch 'next
6243 (beginning-of-line 2)
6244 (if (eobp) (throw 'exit nil))
6245 (if (looking-at "[ \t]*$") (throw 'next nil))
6246 (skip-chars-forward " \t") (setq ind1 (current-column))
6247 (if (> ind1 ind) (throw 'next t))
6248 (if (< ind1 ind) (throw 'exit t))
6249 (if (not (org-at-item-p)) (throw 'exit nil))
6250 (delete-region (match-beginning 2) (match-end 2))
6251 (goto-char (match-beginning 2))
6252 (insert (format fmt (setq n (1+ n)))))))
6253 (goto-line line)
6254 (move-to-column col)))
6256 (defun org-fix-bullet-type (arg)
6257 "Make sure all items in this list have the same bullet."
6258 (interactive "p")
6259 (unless (org-at-item-p) (error "This is not a list"))
6260 (let ((line (org-current-line))
6261 (col (current-column))
6262 (ind (current-indentation))
6263 ind1 bullet)
6264 ;; find where this list begins
6265 (org-beginning-of-item-list)
6266 (beginning-of-line 1)
6267 ;; find out what the bullet type is
6268 (looking-at "[ \t]*\\(\\S-+\\)")
6269 (setq bullet (match-string 1))
6270 ;; walk forward and replace these numbers
6271 (beginning-of-line 0)
6272 (catch 'exit
6273 (while t
6274 (catch 'next
6275 (beginning-of-line 2)
6276 (if (eobp) (throw 'exit nil))
6277 (if (looking-at "[ \t]*$") (throw 'next nil))
6278 (skip-chars-forward " \t") (setq ind1 (current-column))
6279 (if (> ind1 ind) (throw 'next t))
6280 (if (< ind1 ind) (throw 'exit t))
6281 (if (not (org-at-item-p)) (throw 'exit nil))
6282 (skip-chars-forward " \t")
6283 (looking-at "\\S-+")
6284 (replace-match bullet))))
6285 (goto-line line)
6286 (move-to-column col)
6287 (if (string-match "[0-9]" bullet)
6288 (org-renumber-ordered-list 1))))
6290 (defun org-beginning-of-item-list ()
6291 "Go to the beginning of the current item list.
6292 I.e. to the first item in this list."
6293 (interactive)
6294 (org-beginning-of-item)
6295 (let ((pos (point-at-bol))
6296 (ind (org-get-indentation))
6297 ind1)
6298 ;; find where this list begins
6299 (catch 'exit
6300 (while t
6301 (catch 'next
6302 (beginning-of-line 0)
6303 (if (looking-at "[ \t]*$")
6304 (throw (if (bobp) 'exit 'next) t))
6305 (skip-chars-forward " \t") (setq ind1 (current-column))
6306 (if (or (< ind1 ind)
6307 (and (= ind1 ind)
6308 (not (org-at-item-p)))
6309 (bobp))
6310 (throw 'exit t)
6311 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6312 (goto-char pos)))
6314 (defvar org-last-indent-begin-marker (make-marker))
6315 (defvar org-last-indent-end-marker (make-marker))
6317 (defun org-outdent-item (arg)
6318 "Outdent a local list item."
6319 (interactive "p")
6320 (org-indent-item (- arg)))
6322 (defun org-indent-item (arg)
6323 "Indent a local list item."
6324 (interactive "p")
6325 (unless (org-at-item-p)
6326 (error "Not on an item"))
6327 (save-excursion
6328 (let (beg end ind ind1 tmp delta ind-down ind-up)
6329 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6330 (setq beg org-last-indent-begin-marker
6331 end org-last-indent-end-marker)
6332 (org-beginning-of-item)
6333 (setq beg (move-marker org-last-indent-begin-marker (point)))
6334 (org-end-of-item)
6335 (setq end (move-marker org-last-indent-end-marker (point))))
6336 (goto-char beg)
6337 (setq tmp (org-item-indent-positions)
6338 ind (car tmp)
6339 ind-down (nth 2 tmp)
6340 ind-up (nth 1 tmp)
6341 delta (if (> arg 0)
6342 (if ind-down (- ind-down ind) 2)
6343 (if ind-up (- ind-up ind) -2)))
6344 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6345 (while (< (point) end)
6346 (beginning-of-line 1)
6347 (skip-chars-forward " \t") (setq ind1 (current-column))
6348 (delete-region (point-at-bol) (point))
6349 (or (eolp) (indent-to-column (+ ind1 delta)))
6350 (beginning-of-line 2))))
6351 (org-maybe-renumber-ordered-list-safe)
6352 (save-excursion
6353 (beginning-of-line 0)
6354 (condition-case nil (org-beginning-of-item) (error nil))
6355 (org-maybe-renumber-ordered-list-safe)))
6358 (defun org-item-indent-positions ()
6359 "Assumes cursor in item line. FIXME"
6360 (let* ((bolpos (point-at-bol))
6361 (ind (org-get-indentation))
6362 ind-down ind-up pos)
6363 (save-excursion
6364 (org-beginning-of-item-list)
6365 (skip-chars-backward "\n\r \t")
6366 (when (org-in-item-p)
6367 (org-beginning-of-item)
6368 (setq ind-up (org-get-indentation))))
6369 (setq pos (point))
6370 (save-excursion
6371 (cond
6372 ((and (condition-case nil (progn (org-previous-item) t)
6373 (error nil))
6374 (or (forward-char 1) t)
6375 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6376 (setq ind-down (org-get-indentation)))
6377 ((and (goto-char pos)
6378 (org-at-item-p))
6379 (goto-char (match-end 0))
6380 (skip-chars-forward " \t")
6381 (setq ind-down (current-column)))))
6382 (list ind ind-up ind-down)))
6384 ;;; The orgstruct minor mode
6386 ;; Define a minor mode which can be used in other modes in order to
6387 ;; integrate the org-mode structure editing commands.
6389 ;; This is really a hack, because the org-mode structure commands use
6390 ;; keys which normally belong to the major mode. Here is how it
6391 ;; works: The minor mode defines all the keys necessary to operate the
6392 ;; structure commands, but wraps the commands into a function which
6393 ;; tests if the cursor is currently at a headline or a plain list
6394 ;; item. If that is the case, the structure command is used,
6395 ;; temporarily setting many Org-mode variables like regular
6396 ;; expressions for filling etc. However, when any of those keys is
6397 ;; used at a different location, function uses `key-binding' to look
6398 ;; up if the key has an associated command in another currently active
6399 ;; keymap (minor modes, major mode, global), and executes that
6400 ;; command. There might be problems if any of the keys is otherwise
6401 ;; used as a prefix key.
6403 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6404 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6405 ;; addresses this by checking explicitly for both bindings.
6407 (defvar orgstruct-mode-map (make-sparse-keymap)
6408 "Keymap for the minor `orgstruct-mode'.")
6410 ;;;###autoload
6411 (define-minor-mode orgstruct-mode
6412 "Toggle the minor more `orgstruct-mode'.
6413 This mode is for using Org-mode structure commands in other modes.
6414 The following key behave as if Org-mode was active, if the cursor
6415 is on a headline, or on a plain list item (both in the definition
6416 of Org-mode).
6418 M-up Move entry/item up
6419 M-down Move entry/item down
6420 M-left Promote
6421 M-right Demote
6422 M-S-up Move entry/item up
6423 M-S-down Move entry/item down
6424 M-S-left Promote subtree
6425 M-S-right Demote subtree
6426 M-q Fill paragraph and items like in Org-mode
6427 C-c ^ Sort entries
6428 C-c - Cycle list bullet
6429 TAB Cycle item visibility
6430 M-RET Insert new heading/item
6431 S-M-RET Insert new TODO heading / Chekbox item
6432 C-c C-c Set tags / toggle checkbox"
6433 nil " OrgStruct" nil
6434 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6436 ;;;###autoload
6437 (defun turn-on-orgstruct ()
6438 "Unconditionally turn on `orgstruct-mode'."
6439 (orgstruct-mode 1))
6441 (defun orgstruct-error ()
6442 "Error when there is no default binding for a structure key."
6443 (interactive)
6444 (error "This key is has no function outside structure elements"))
6446 (defvar org-local-vars nil
6447 "List of local variables, for use by `orgstruct-mode'")
6449 (defun orgstruct-setup ()
6450 "Setup orgstruct keymaps."
6451 (let ((nfunc 0)
6452 (bindings
6453 (list
6454 '([(meta up)] org-metaup)
6455 '([(meta down)] org-metadown)
6456 '([(meta left)] org-metaleft)
6457 '([(meta right)] org-metaright)
6458 '([(meta shift up)] org-shiftmetaup)
6459 '([(meta shift down)] org-shiftmetadown)
6460 '([(meta shift left)] org-shiftmetaleft)
6461 '([(meta shift right)] org-shiftmetaright)
6462 '([(shift up)] org-shiftup)
6463 '([(shift down)] org-shiftdown)
6464 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6465 '("\M-q" fill-paragraph)
6466 '("\C-c^" org-sort)
6467 '("\C-c-" org-cycle-list-bullet)))
6468 elt key fun cmd)
6469 (while (setq elt (pop bindings))
6470 (setq nfunc (1+ nfunc))
6471 (setq key (org-key (car elt))
6472 fun (nth 1 elt)
6473 cmd (orgstruct-make-binding fun nfunc key))
6474 (org-defkey orgstruct-mode-map key cmd))
6476 ;; Special treatment needed for TAB and RET
6477 (org-defkey orgstruct-mode-map [(tab)]
6478 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6479 (org-defkey orgstruct-mode-map "\C-i"
6480 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6482 (org-defkey orgstruct-mode-map "\M-\C-m"
6483 (orgstruct-make-binding 'org-insert-heading 105
6484 "\M-\C-m" [(meta return)]))
6485 (org-defkey orgstruct-mode-map [(meta return)]
6486 (orgstruct-make-binding 'org-insert-heading 106
6487 [(meta return)] "\M-\C-m"))
6489 (org-defkey orgstruct-mode-map [(shift meta return)]
6490 (orgstruct-make-binding 'org-insert-todo-heading 107
6491 [(meta return)] "\M-\C-m"))
6493 (unless org-local-vars
6494 (setq org-local-vars (org-get-local-variables)))
6498 (defun orgstruct-make-binding (fun n &rest keys)
6499 "Create a function for binding in the structure minor mode.
6500 FUN is the command to call inside a table. N is used to create a unique
6501 command name. KEYS are keys that should be checked in for a command
6502 to execute outside of tables."
6503 (eval
6504 (list 'defun
6505 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6506 '(arg)
6507 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6508 "Outside of structure, run the binding of `"
6509 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6510 "'.")
6511 '(interactive "p")
6512 (list 'if
6513 '(org-context-p 'headline 'item)
6514 (list 'org-run-like-in-org-mode (list 'quote fun))
6515 (list 'let '(orgstruct-mode)
6516 (list 'call-interactively
6517 (append '(or)
6518 (mapcar (lambda (k)
6519 (list 'key-binding k))
6520 keys)
6521 '('orgstruct-error))))))))
6523 (defun org-context-p (&rest contexts)
6524 "FIXME:"
6525 (let ((pos (point)))
6526 (goto-char (point-at-bol))
6527 (prog1 (or (and (memq 'table contexts)
6528 (looking-at "[ \t]*|"))
6529 (and (memq 'headline contexts)
6530 (looking-at "\\*+"))
6531 (and (memq 'item contexts)
6532 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6533 (goto-char pos))))
6535 (defun org-get-local-variables ()
6536 "Return a list of all local variables in an org-mode buffer."
6537 (let (varlist)
6538 (with-current-buffer (get-buffer-create "*Org tmp*")
6539 (erase-buffer)
6540 (org-mode)
6541 (setq varlist (buffer-local-variables)))
6542 (kill-buffer "*Org tmp*")
6543 (delq nil
6544 (mapcar
6545 (lambda (x)
6546 (setq x
6547 (if (symbolp x)
6548 (list x)
6549 (list (car x) (list 'quote (cdr x)))))
6550 (if (string-match
6551 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6552 (symbol-name (car x)))
6553 x nil))
6554 varlist))))
6556 ;;;###autoload
6557 (defun org-run-like-in-org-mode (cmd)
6558 (unless org-local-vars
6559 (setq org-local-vars (org-get-local-variables)))
6560 (eval (list 'let org-local-vars
6561 (list 'call-interactively (list 'quote cmd)))))
6563 ;;;; Archiving
6565 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6567 (defun org-archive-subtree (&optional find-done)
6568 "Move the current subtree to the archive.
6569 The archive can be a certain top-level heading in the current file, or in
6570 a different file. The tree will be moved to that location, the subtree
6571 heading be marked DONE, and the current time will be added.
6573 When called with prefix argument FIND-DONE, find whole trees without any
6574 open TODO items and archive them (after getting confirmation from the user).
6575 If the cursor is not at a headline when this comand is called, try all level
6576 1 trees. If the cursor is on a headline, only try the direct children of
6577 this heading."
6578 (interactive "P")
6579 (if find-done
6580 (org-archive-all-done)
6581 ;; Save all relevant TODO keyword-relatex variables
6583 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6584 (tr-org-todo-keywords-1 org-todo-keywords-1)
6585 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6586 (tr-org-done-keywords org-done-keywords)
6587 (tr-org-todo-regexp org-todo-regexp)
6588 (tr-org-todo-line-regexp org-todo-line-regexp)
6589 (tr-org-odd-levels-only org-odd-levels-only)
6590 (this-buffer (current-buffer))
6591 (org-archive-location org-archive-location)
6592 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6593 file heading buffer level newfile-p)
6595 ;; Try to find a local archive location
6596 (save-excursion
6597 (save-restriction
6598 (widen)
6599 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6600 (setq org-archive-location (match-string 1)))))
6602 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6603 (progn
6604 (setq file (format (match-string 1 org-archive-location)
6605 (file-name-nondirectory buffer-file-name))
6606 heading (match-string 2 org-archive-location)))
6607 (error "Invalid `org-archive-location'"))
6608 (if (> (length file) 0)
6609 (setq newfile-p (not (file-exists-p file))
6610 buffer (find-file-noselect file))
6611 (setq buffer (current-buffer)))
6612 (unless buffer
6613 (error "Cannot access file \"%s\"" file))
6614 (if (and (> (length heading) 0)
6615 (string-match "^\\*+" heading))
6616 (setq level (match-end 0))
6617 (setq heading nil level 0))
6618 (save-excursion
6619 ;; We first only copy, in case something goes wrong
6620 ;; we need to protect this-command, to avoid kill-region sets it,
6621 ;; which would lead to duplication of subtrees
6622 (let (this-command) (org-copy-subtree))
6623 (set-buffer buffer)
6624 ;; Enforce org-mode for the archive buffer
6625 (if (not (org-mode-p))
6626 ;; Force the mode for future visits.
6627 (let ((org-insert-mode-line-in-empty-file t)
6628 (org-inhibit-startup t))
6629 (call-interactively 'org-mode)))
6630 (when newfile-p
6631 (goto-char (point-max))
6632 (insert (format "\nArchived entries from file %s\n\n"
6633 (buffer-file-name this-buffer))))
6634 ;; Force the TODO keywords of the original buffer
6635 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6636 (org-todo-keywords-1 tr-org-todo-keywords-1)
6637 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6638 (org-done-keywords tr-org-done-keywords)
6639 (org-todo-regexp tr-org-todo-regexp)
6640 (org-todo-line-regexp tr-org-todo-line-regexp)
6641 (org-odd-levels-only
6642 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6643 org-odd-levels-only
6644 tr-org-odd-levels-only)))
6645 (goto-char (point-min))
6646 (if heading
6647 (progn
6648 (if (re-search-forward
6649 (concat "^" (regexp-quote heading)
6650 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6651 nil t)
6652 (goto-char (match-end 0))
6653 ;; Heading not found, just insert it at the end
6654 (goto-char (point-max))
6655 (or (bolp) (insert "\n"))
6656 (insert "\n" heading "\n")
6657 (end-of-line 0))
6658 ;; Make the subtree visible
6659 (show-subtree)
6660 (org-end-of-subtree t)
6661 (skip-chars-backward " \t\r\n")
6662 (and (looking-at "[ \t\r\n]*")
6663 (replace-match "\n\n")))
6664 ;; No specific heading, just go to end of file.
6665 (goto-char (point-max)) (insert "\n"))
6666 ;; Paste
6667 (org-paste-subtree (org-get-legal-level level 1))
6669 ;; Mark the entry as done
6670 (when (and org-archive-mark-done
6671 (looking-at org-todo-line-regexp)
6672 (or (not (match-end 2))
6673 (not (member (match-string 2) org-done-keywords))))
6674 (let (org-log-done)
6675 (org-todo
6676 (car (or (member org-archive-mark-done org-done-keywords)
6677 org-done-keywords)))))
6679 ;; Move cursor to right after the TODO keyword
6680 (when org-archive-stamp-time
6681 (org-add-planning-info 'archived (org-current-time)))
6682 ;; Save the buffer, if it is not the same buffer.
6683 (if (not (eq this-buffer buffer)) (save-buffer))))
6684 ;; Here we are back in the original buffer. Everything seems to have
6685 ;; worked. So now cut the tree and finish up.
6686 (let (this-command) (org-cut-subtree))
6687 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6688 (message "Subtree archived %s"
6689 (if (eq this-buffer buffer)
6690 (concat "under heading: " heading)
6691 (concat "in file: " (abbreviate-file-name file)))))))
6693 (defun org-archive-all-done (&optional tag)
6694 "Archive sublevels of the current tree without open TODO items.
6695 If the cursor is not on a headline, try all level 1 trees. If
6696 it is on a headline, try all direct children.
6697 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6698 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6699 (rea (concat ".*:" org-archive-tag ":"))
6700 (begm (make-marker))
6701 (endm (make-marker))
6702 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6703 "Move subtree to archive (no open TODO items)? "))
6704 beg end (cntarch 0))
6705 (if (org-on-heading-p)
6706 (progn
6707 (setq re1 (concat "^" (regexp-quote
6708 (make-string
6709 (1+ (- (match-end 0) (match-beginning 0)))
6710 ?*))
6711 " "))
6712 (move-marker begm (point))
6713 (move-marker endm (org-end-of-subtree t)))
6714 (setq re1 "^* ")
6715 (move-marker begm (point-min))
6716 (move-marker endm (point-max)))
6717 (save-excursion
6718 (goto-char begm)
6719 (while (re-search-forward re1 endm t)
6720 (setq beg (match-beginning 0)
6721 end (save-excursion (org-end-of-subtree t) (point)))
6722 (goto-char beg)
6723 (if (re-search-forward re end t)
6724 (goto-char end)
6725 (goto-char beg)
6726 (if (and (or (not tag) (not (looking-at rea)))
6727 (y-or-n-p question))
6728 (progn
6729 (if tag
6730 (org-toggle-tag org-archive-tag 'on)
6731 (org-archive-subtree))
6732 (setq cntarch (1+ cntarch)))
6733 (goto-char end)))))
6734 (message "%d trees archived" cntarch)))
6736 (defun org-cycle-hide-drawers (state)
6737 "Re-hide all drawers after a visibility state change."
6738 (when (not (memq state '(overview folded)))
6739 (save-excursion
6740 (let* ((globalp (memq state '(contents all)))
6741 (beg (if globalp (point-min) (point)))
6742 (end (if globalp (point-max) (org-end-of-subtree t))))
6743 (goto-char beg)
6744 (while (re-search-forward org-drawer-regexp end t)
6745 (org-flag-drawer t))))))
6747 (defun org-flag-drawer (flag)
6748 (save-excursion
6749 (beginning-of-line 1)
6750 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6751 (let ((b (match-end 0)))
6752 (if (re-search-forward
6753 "^[ \t]*:END:"
6754 (save-excursion (outline-next-heading) (point)) t)
6755 (outline-flag-region b (point-at-eol) flag)
6756 (error ":END: line missing"))))))
6758 (defun org-cycle-hide-archived-subtrees (state)
6759 "Re-hide all archived subtrees after a visibility state change."
6760 (when (and (not org-cycle-open-archived-trees)
6761 (not (memq state '(overview folded))))
6762 (save-excursion
6763 (let* ((globalp (memq state '(contents all)))
6764 (beg (if globalp (point-min) (point)))
6765 (end (if globalp (point-max) (org-end-of-subtree t))))
6766 (org-hide-archived-subtrees beg end)
6767 (goto-char beg)
6768 (if (looking-at (concat ".*:" org-archive-tag ":"))
6769 (message (substitute-command-keys
6770 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6772 (defun org-force-cycle-archived ()
6773 "Cycle subtree even if it is archived."
6774 (interactive)
6775 (setq this-command 'org-cycle)
6776 (let ((org-cycle-open-archived-trees t))
6777 (call-interactively 'org-cycle)))
6779 (defun org-hide-archived-subtrees (beg end)
6780 "Re-hide all archived subtrees after a visibility state change."
6781 (save-excursion
6782 (let* ((re (concat ":" org-archive-tag ":")))
6783 (goto-char beg)
6784 (while (re-search-forward re end t)
6785 (and (org-on-heading-p) (hide-subtree))
6786 (org-end-of-subtree t)))))
6788 (defun org-toggle-tag (tag &optional onoff)
6789 "Toggle the tag TAG for the current line.
6790 If ONOFF is `on' or `off', don't toggle but set to this state."
6791 (unless (org-on-heading-p t) (error "Not on headling"))
6792 (let (res current)
6793 (save-excursion
6794 (beginning-of-line)
6795 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6796 (point-at-eol) t)
6797 (progn
6798 (setq current (match-string 1))
6799 (replace-match ""))
6800 (setq current ""))
6801 (setq current (nreverse (org-split-string current ":")))
6802 (cond
6803 ((eq onoff 'on)
6804 (setq res t)
6805 (or (member tag current) (push tag current)))
6806 ((eq onoff 'off)
6807 (or (not (member tag current)) (setq current (delete tag current))))
6808 (t (if (member tag current)
6809 (setq current (delete tag current))
6810 (setq res t)
6811 (push tag current))))
6812 (end-of-line 1)
6813 (when current
6814 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6815 (org-set-tags nil t))
6816 res))
6818 (defun org-toggle-archive-tag (&optional arg)
6819 "Toggle the archive tag for the current headline.
6820 With prefix ARG, check all children of current headline and offer tagging
6821 the children that do not contain any open TODO items."
6822 (interactive "P")
6823 (if arg
6824 (org-archive-all-done 'tag)
6825 (let (set)
6826 (save-excursion
6827 (org-back-to-heading t)
6828 (setq set (org-toggle-tag org-archive-tag))
6829 (when set (hide-subtree)))
6830 (and set (beginning-of-line 1))
6831 (message "Subtree %s" (if set "archived" "unarchived")))))
6834 ;;;; Tables
6836 ;;; The table editor
6838 ;; Watch out: Here we are talking about two different kind of tables.
6839 ;; Most of the code is for the tables created with the Org-mode table editor.
6840 ;; Sometimes, we talk about tables created and edited with the table.el
6841 ;; Emacs package. We call the former org-type tables, and the latter
6842 ;; table.el-type tables.
6844 (defun org-before-change-function (beg end)
6845 "Every change indicates that a table might need an update."
6846 (setq org-table-may-need-update t))
6848 (defconst org-table-line-regexp "^[ \t]*|"
6849 "Detects an org-type table line.")
6850 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6851 "Detects an org-type table line.")
6852 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6853 "Detects a table line marked for automatic recalculation.")
6854 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6855 "Detects a table line marked for automatic recalculation.")
6856 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6857 "Detects a table line marked for automatic recalculation.")
6858 (defconst org-table-hline-regexp "^[ \t]*|-"
6859 "Detects an org-type table hline.")
6860 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6861 "Detects a table-type table hline.")
6862 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6863 "Detects an org-type or table-type table.")
6864 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6865 "Searching from within a table (any type) this finds the first line
6866 outside the table.")
6867 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6868 "Searching from within a table (any type) this finds the first line
6869 outside the table.")
6871 (defvar org-table-last-highlighted-reference nil)
6872 (defvar org-table-formula-history nil)
6874 (defvar org-table-column-names nil
6875 "Alist with column names, derived from the `!' line.")
6876 (defvar org-table-column-name-regexp nil
6877 "Regular expression matching the current column names.")
6878 (defvar org-table-local-parameters nil
6879 "Alist with parameter names, derived from the `$' line.")
6880 (defvar org-table-named-field-locations nil
6881 "Alist with locations of named fields.")
6883 (defvar org-table-current-line-types nil
6884 "Table row types, non-nil only for the duration of a comand.")
6885 (defvar org-table-current-begin-line nil
6886 "Table begin line, non-nil only for the duration of a comand.")
6887 (defvar org-table-current-begin-pos nil
6888 "Table begin position, non-nil only for the duration of a comand.")
6889 (defvar org-table-dlines nil
6890 "Vector of data line line numbers in the current table.")
6891 (defvar org-table-hlines nil
6892 "Vector of hline line numbers in the current table.")
6894 (defconst org-table-range-regexp
6895 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
6896 ;; 1 2 3 4 5
6897 "Regular expression for matching ranges in formulas.")
6899 (defconst org-table-range-regexp2
6900 (concat
6901 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
6902 "\\.\\."
6903 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6904 "Match a range for reference display.")
6906 (defconst org-table-translate-regexp
6907 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6908 "Match a reference that needs translation, for reference display.")
6910 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6912 (defun org-table-create-with-table.el ()
6913 "Use the table.el package to insert a new table.
6914 If there is already a table at point, convert between Org-mode tables
6915 and table.el tables."
6916 (interactive)
6917 (require 'table)
6918 (cond
6919 ((org-at-table.el-p)
6920 (if (y-or-n-p "Convert table to Org-mode table? ")
6921 (org-table-convert)))
6922 ((org-at-table-p)
6923 (if (y-or-n-p "Convert table to table.el table? ")
6924 (org-table-convert)))
6925 (t (call-interactively 'table-insert))))
6927 (defun org-table-create-or-convert-from-region (arg)
6928 "Convert region to table, or create an empty table.
6929 If there is an active region, convert it to a table, using the function
6930 `org-table-convert-region'.
6931 If there is no such region, create an empty table with `org-table-create'."
6932 (interactive "P")
6933 (if (org-region-active-p)
6934 (org-table-convert-region (region-beginning) (region-end) arg)
6935 (org-table-create arg)))
6937 (defun org-table-create (&optional size)
6938 "Query for a size and insert a table skeleton.
6939 SIZE is a string Columns x Rows like for example \"3x2\"."
6940 (interactive "P")
6941 (unless size
6942 (setq size (read-string
6943 (concat "Table size Columns x Rows [e.g. "
6944 org-table-default-size "]: ")
6945 "" nil org-table-default-size)))
6947 (let* ((pos (point))
6948 (indent (make-string (current-column) ?\ ))
6949 (split (org-split-string size " *x *"))
6950 (rows (string-to-number (nth 1 split)))
6951 (columns (string-to-number (car split)))
6952 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6953 "\n")))
6954 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6955 (point-at-bol) (point)))
6956 (beginning-of-line 1)
6957 (newline))
6958 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6959 (dotimes (i rows) (insert line))
6960 (goto-char pos)
6961 (if (> rows 1)
6962 ;; Insert a hline after the first row.
6963 (progn
6964 (end-of-line 1)
6965 (insert "\n|-")
6966 (goto-char pos)))
6967 (org-table-align)))
6969 (defun org-table-convert-region (beg0 end0 &optional nspace)
6970 "Convert region to a table.
6971 The region goes from BEG0 to END0, but these borders will be moved
6972 slightly, to make sure a beginning of line in the first line is included.
6973 When NSPACE is non-nil, it indicates the minimum number of spaces that
6974 separate columns. By default, the function first checks if every line
6975 contains at lease one TAB. If yes, it assumes that the material is TAB
6976 separated. If not, it assumes a single space as separator."
6977 (interactive "rP")
6978 (let* ((beg (min beg0 end0))
6979 (end (max beg0 end0))
6980 (tabsep t)
6982 (goto-char beg)
6983 (beginning-of-line 1)
6984 (setq beg (move-marker (make-marker) (point)))
6985 (goto-char end)
6986 (if (bolp) (backward-char 1) (end-of-line 1))
6987 (setq end (move-marker (make-marker) (point)))
6988 ;; Lets see if this is tab-separated material. If every nonempty line
6989 ;; contains a tab, we will assume that it is tab-separated material
6990 (if nspace
6991 (setq tabsep nil)
6992 (goto-char beg)
6993 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6994 (if nspace (setq tabsep nil))
6995 (if tabsep
6996 (setq re "^\\|\t")
6997 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6998 (max 1 (prefix-numeric-value nspace)))))
6999 (goto-char beg)
7000 (while (re-search-forward re end t)
7001 (replace-match "| " t t))
7002 (goto-char beg)
7003 (insert " ")
7004 (org-table-align)))
7006 (defun org-table-import (file arg)
7007 "Import FILE as a table.
7008 The file is assumed to be tab-separated. Such files can be produced by most
7009 spreadsheet and database applications. If no tabs (at least one per line)
7010 are found, lines will be split on whitespace into fields."
7011 (interactive "f\nP")
7012 (or (bolp) (newline))
7013 (let ((beg (point))
7014 (pm (point-max)))
7015 (insert-file-contents file)
7016 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7018 (defun org-table-export ()
7019 "Export table as a tab-separated file.
7020 Such a file can be imported into a spreadsheet program like Excel."
7021 (interactive)
7022 (let* ((beg (org-table-begin))
7023 (end (org-table-end))
7024 (table (buffer-substring beg end))
7025 (file (read-file-name "Export table to: "))
7026 buf)
7027 (unless (or (not (file-exists-p file))
7028 (y-or-n-p (format "Overwrite file %s? " file)))
7029 (error "Abort"))
7030 (with-current-buffer (find-file-noselect file)
7031 (setq buf (current-buffer))
7032 (erase-buffer)
7033 (fundamental-mode)
7034 (insert table)
7035 (goto-char (point-min))
7036 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7037 (replace-match "" t t)
7038 (end-of-line 1))
7039 (goto-char (point-min))
7040 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7041 (replace-match "" t t)
7042 (goto-char (min (1+ (point)) (point-max))))
7043 (goto-char (point-min))
7044 (while (re-search-forward "^-[-+]*$" nil t)
7045 (replace-match "")
7046 (if (looking-at "\n")
7047 (delete-char 1)))
7048 (goto-char (point-min))
7049 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7050 (replace-match "\t" t t))
7051 (save-buffer))
7052 (kill-buffer buf)))
7054 (defvar org-table-aligned-begin-marker (make-marker)
7055 "Marker at the beginning of the table last aligned.
7056 Used to check if cursor still is in that table, to minimize realignment.")
7057 (defvar org-table-aligned-end-marker (make-marker)
7058 "Marker at the end of the table last aligned.
7059 Used to check if cursor still is in that table, to minimize realignment.")
7060 (defvar org-table-last-alignment nil
7061 "List of flags for flushright alignment, from the last re-alignment.
7062 This is being used to correctly align a single field after TAB or RET.")
7063 (defvar org-table-last-column-widths nil
7064 "List of max width of fields in each column.
7065 This is being used to correctly align a single field after TAB or RET.")
7066 (defvar org-table-overlay-coordinates nil
7067 "Overlay coordinates after each align of a table.")
7068 (make-variable-buffer-local 'org-table-overlay-coordinates)
7070 (defvar org-last-recalc-line nil)
7071 (defconst org-narrow-column-arrow "=>"
7072 "Used as display property in narrowed table columns.")
7074 (defun org-table-align ()
7075 "Align the table at point by aligning all vertical bars."
7076 (interactive)
7077 (let* (
7078 ;; Limits of table
7079 (beg (org-table-begin))
7080 (end (org-table-end))
7081 ;; Current cursor position
7082 (linepos (org-current-line))
7083 (colpos (org-table-current-column))
7084 (winstart (window-start))
7085 (winstartline (org-current-line (min winstart (1- (point-max)))))
7086 lines (new "") lengths l typenums ty fields maxfields i
7087 column
7088 (indent "") cnt frac
7089 rfmt hfmt
7090 (spaces '(1 . 1))
7091 (sp1 (car spaces))
7092 (sp2 (cdr spaces))
7093 (rfmt1 (concat
7094 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7095 (hfmt1 (concat
7096 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7097 emptystrings links dates narrow fmax f1 len c e)
7098 (untabify beg end)
7099 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7100 ;; Check if we have links or dates
7101 (goto-char beg)
7102 (setq links (re-search-forward org-bracket-link-regexp end t))
7103 (goto-char beg)
7104 (setq dates (and org-display-custom-times
7105 (re-search-forward org-ts-regexp-both end t)))
7106 ;; Make sure the link properties are right
7107 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7108 ;; Make sure the date properties are right
7109 (when dates (goto-char beg) (while (org-activate-dates end)))
7111 ;; Check if we are narrowing any columns
7112 (goto-char beg)
7113 (setq narrow (and org-format-transports-properties-p
7114 (re-search-forward "<[0-9]+>" end t)))
7115 ;; Get the rows
7116 (setq lines (org-split-string
7117 (buffer-substring beg end) "\n"))
7118 ;; Store the indentation of the first line
7119 (if (string-match "^ *" (car lines))
7120 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7121 ;; Mark the hlines by setting the corresponding element to nil
7122 ;; At the same time, we remove trailing space.
7123 (setq lines (mapcar (lambda (l)
7124 (if (string-match "^ *|-" l)
7126 (if (string-match "[ \t]+$" l)
7127 (substring l 0 (match-beginning 0))
7128 l)))
7129 lines))
7130 ;; Get the data fields by splitting the lines.
7131 (setq fields (mapcar
7132 (lambda (l)
7133 (org-split-string l " *| *"))
7134 (delq nil (copy-sequence lines))))
7135 ;; How many fields in the longest line?
7136 (condition-case nil
7137 (setq maxfields (apply 'max (mapcar 'length fields)))
7138 (error
7139 (kill-region beg end)
7140 (org-table-create org-table-default-size)
7141 (error "Empty table - created default table")))
7142 ;; A list of empty strings to fill any short rows on output
7143 (setq emptystrings (make-list maxfields ""))
7144 ;; Check for special formatting.
7145 (setq i -1)
7146 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7147 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7148 ;; Check if there is an explicit width specified
7149 (when narrow
7150 (setq c column fmax nil)
7151 (while c
7152 (setq e (pop c))
7153 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7154 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7155 ;; Find fields that are wider than fmax, and shorten them
7156 (when fmax
7157 (loop for xx in column do
7158 (when (and (stringp xx)
7159 (> (org-string-width xx) fmax))
7160 (org-add-props xx nil
7161 'help-echo
7162 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7163 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7164 (unless (> f1 1)
7165 (error "Cannot narrow field starting with wide link \"%s\""
7166 (match-string 0 xx)))
7167 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7168 (add-text-properties (- f1 2) f1
7169 (list 'display org-narrow-column-arrow)
7170 xx)))))
7171 ;; Get the maximum width for each column
7172 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7173 ;; Get the fraction of numbers, to decide about alignment of the column
7174 (setq cnt 0 frac 0.0)
7175 (loop for x in column do
7176 (if (equal x "")
7178 (setq frac ( / (+ (* frac cnt)
7179 (if (string-match org-table-number-regexp x) 1 0))
7180 (setq cnt (1+ cnt))))))
7181 (push (>= frac org-table-number-fraction) typenums))
7182 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7184 ;; Store the alignment of this table, for later editing of single fields
7185 (setq org-table-last-alignment typenums
7186 org-table-last-column-widths lengths)
7188 ;; With invisible characters, `format' does not get the field width right
7189 ;; So we need to make these fields wide by hand.
7190 (when links
7191 (loop for i from 0 upto (1- maxfields) do
7192 (setq len (nth i lengths))
7193 (loop for j from 0 upto (1- (length fields)) do
7194 (setq c (nthcdr i (car (nthcdr j fields))))
7195 (if (and (stringp (car c))
7196 (string-match org-bracket-link-regexp (car c))
7197 (< (org-string-width (car c)) len))
7198 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7200 ;; Compute the formats needed for output of the table
7201 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7202 (while (setq l (pop lengths))
7203 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7204 (setq rfmt (concat rfmt (format rfmt1 ty l))
7205 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7206 (setq rfmt (concat rfmt "\n")
7207 hfmt (concat (substring hfmt 0 -1) "|\n"))
7209 (setq new (mapconcat
7210 (lambda (l)
7211 (if l (apply 'format rfmt
7212 (append (pop fields) emptystrings))
7213 hfmt))
7214 lines ""))
7215 ;; Replace the old one
7216 (delete-region beg end)
7217 (move-marker end nil)
7218 (move-marker org-table-aligned-begin-marker (point))
7219 (insert new)
7220 (move-marker org-table-aligned-end-marker (point))
7221 (when (and orgtbl-mode (not (org-mode-p)))
7222 (goto-char org-table-aligned-begin-marker)
7223 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7224 ;; Try to move to the old location
7225 (goto-line winstartline)
7226 (setq winstart (point-at-bol))
7227 (goto-line linepos)
7228 (set-window-start (selected-window) winstart 'noforce)
7229 (org-table-goto-column colpos)
7230 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7231 (setq org-table-may-need-update nil)
7234 (defun org-string-width (s)
7235 "Compute width of string, ignoring invisible characters.
7236 This ignores character with invisibility property `org-link', and also
7237 characters with property `org-cwidth', because these will become invisible
7238 upon the next fontification round."
7239 (let (b l)
7240 (when (or (eq t buffer-invisibility-spec)
7241 (assq 'org-link buffer-invisibility-spec))
7242 (while (setq b (text-property-any 0 (length s)
7243 'invisible 'org-link s))
7244 (setq s (concat (substring s 0 b)
7245 (substring s (or (next-single-property-change
7246 b 'invisible s) (length s)))))))
7247 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7248 (setq s (concat (substring s 0 b)
7249 (substring s (or (next-single-property-change
7250 b 'org-cwidth s) (length s))))))
7251 (setq l (string-width s) b -1)
7252 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7253 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7256 (defun org-table-begin (&optional table-type)
7257 "Find the beginning of the table and return its position.
7258 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7259 (save-excursion
7260 (if (not (re-search-backward
7261 (if table-type org-table-any-border-regexp
7262 org-table-border-regexp)
7263 nil t))
7264 (progn (goto-char (point-min)) (point))
7265 (goto-char (match-beginning 0))
7266 (beginning-of-line 2)
7267 (point))))
7269 (defun org-table-end (&optional table-type)
7270 "Find the end of the table and return its position.
7271 With argument TABLE-TYPE, go to the end of a table.el-type table."
7272 (save-excursion
7273 (if (not (re-search-forward
7274 (if table-type org-table-any-border-regexp
7275 org-table-border-regexp)
7276 nil t))
7277 (goto-char (point-max))
7278 (goto-char (match-beginning 0)))
7279 (point-marker)))
7281 (defun org-table-justify-field-maybe (&optional new)
7282 "Justify the current field, text to left, number to right.
7283 Optional argument NEW may specify text to replace the current field content."
7284 (cond
7285 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7286 ((org-at-table-hline-p))
7287 ((and (not new)
7288 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7289 (current-buffer)))
7290 (< (point) org-table-aligned-begin-marker)
7291 (>= (point) org-table-aligned-end-marker)))
7292 ;; This is not the same table, force a full re-align
7293 (setq org-table-may-need-update t))
7294 (t ;; realign the current field, based on previous full realign
7295 (let* ((pos (point)) s
7296 (col (org-table-current-column))
7297 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7298 l f n o e)
7299 (when (> col 0)
7300 (skip-chars-backward "^|\n")
7301 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7302 (progn
7303 (setq s (match-string 1)
7304 o (match-string 0)
7305 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7306 e (not (= (match-beginning 2) (match-end 2))))
7307 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7308 l (if e "|" (setq org-table-may-need-update t) ""))
7309 n (format f s))
7310 (if new
7311 (if (<= (length new) l) ;; FIXME: length -> str-width?
7312 (setq n (format f new))
7313 (setq n (concat new "|") org-table-may-need-update t)))
7314 (or (equal n o)
7315 (let (org-table-may-need-update)
7316 (replace-match n t t))))
7317 (setq org-table-may-need-update t))
7318 (goto-char pos))))))
7320 (defun org-table-next-field ()
7321 "Go to the next field in the current table, creating new lines as needed.
7322 Before doing so, re-align the table if necessary."
7323 (interactive)
7324 (org-table-maybe-eval-formula)
7325 (org-table-maybe-recalculate-line)
7326 (if (and org-table-automatic-realign
7327 org-table-may-need-update)
7328 (org-table-align))
7329 (let ((end (org-table-end)))
7330 (if (org-at-table-hline-p)
7331 (end-of-line 1))
7332 (condition-case nil
7333 (progn
7334 (re-search-forward "|" end)
7335 (if (looking-at "[ \t]*$")
7336 (re-search-forward "|" end))
7337 (if (and (looking-at "-")
7338 org-table-tab-jumps-over-hlines
7339 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7340 (goto-char (match-beginning 1)))
7341 (if (looking-at "-")
7342 (progn
7343 (beginning-of-line 0)
7344 (org-table-insert-row 'below))
7345 (if (looking-at " ") (forward-char 1))))
7346 (error
7347 (org-table-insert-row 'below)))))
7349 (defun org-table-previous-field ()
7350 "Go to the previous field in the table.
7351 Before doing so, re-align the table if necessary."
7352 (interactive)
7353 (org-table-justify-field-maybe)
7354 (org-table-maybe-recalculate-line)
7355 (if (and org-table-automatic-realign
7356 org-table-may-need-update)
7357 (org-table-align))
7358 (if (org-at-table-hline-p)
7359 (end-of-line 1))
7360 (re-search-backward "|" (org-table-begin))
7361 (re-search-backward "|" (org-table-begin))
7362 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7363 (re-search-backward "|" (org-table-begin)))
7364 (if (looking-at "| ?")
7365 (goto-char (match-end 0))))
7367 (defun org-table-next-row ()
7368 "Go to the next row (same column) in the current table.
7369 Before doing so, re-align the table if necessary."
7370 (interactive)
7371 (org-table-maybe-eval-formula)
7372 (org-table-maybe-recalculate-line)
7373 (if (or (looking-at "[ \t]*$")
7374 (save-excursion (skip-chars-backward " \t") (bolp)))
7375 (newline)
7376 (if (and org-table-automatic-realign
7377 org-table-may-need-update)
7378 (org-table-align))
7379 (let ((col (org-table-current-column)))
7380 (beginning-of-line 2)
7381 (if (or (not (org-at-table-p))
7382 (org-at-table-hline-p))
7383 (progn
7384 (beginning-of-line 0)
7385 (org-table-insert-row 'below)))
7386 (org-table-goto-column col)
7387 (skip-chars-backward "^|\n\r")
7388 (if (looking-at " ") (forward-char 1)))))
7390 (defun org-table-copy-down (n)
7391 "Copy a field down in the current column.
7392 If the field at the cursor is empty, copy into it the content of the nearest
7393 non-empty field above. With argument N, use the Nth non-empty field.
7394 If the current field is not empty, it is copied down to the next row, and
7395 the cursor is moved with it. Therefore, repeating this command causes the
7396 column to be filled row-by-row.
7397 If the variable `org-table-copy-increment' is non-nil and the field is an
7398 integer or a timestamp, it will be incremented while copying. In the case of
7399 a timestamp, if the cursor is on the year, change the year. If it is on the
7400 month or the day, change that. Point will stay on the current date field
7401 in order to easily repeat the interval."
7402 (interactive "p")
7403 (let* ((colpos (org-table-current-column))
7404 (col (current-column))
7405 (field (org-table-get-field))
7406 (non-empty (string-match "[^ \t]" field))
7407 (beg (org-table-begin))
7408 txt)
7409 (org-table-check-inside-data-field)
7410 (if non-empty
7411 (progn
7412 (setq txt (org-trim field))
7413 (org-table-next-row)
7414 (org-table-blank-field))
7415 (save-excursion
7416 (setq txt
7417 (catch 'exit
7418 (while (progn (beginning-of-line 1)
7419 (re-search-backward org-table-dataline-regexp
7420 beg t))
7421 (org-table-goto-column colpos t)
7422 (if (and (looking-at
7423 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7424 (= (setq n (1- n)) 0))
7425 (throw 'exit (match-string 1))))))))
7426 (if txt
7427 (progn
7428 (if (and org-table-copy-increment
7429 (string-match "^[0-9]+$" txt))
7430 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7431 (insert txt)
7432 (move-to-column col)
7433 (if (and org-table-copy-increment (org-at-timestamp-p t))
7434 (org-timestamp-up 1)
7435 (org-table-maybe-recalculate-line))
7436 (org-table-align)
7437 (move-to-column col))
7438 (error "No non-empty field found"))))
7440 (defun org-table-check-inside-data-field ()
7441 "Is point inside a table data field?
7442 I.e. not on a hline or before the first or after the last column?
7443 This actually throws an error, so it aborts the current command."
7444 (if (or (not (org-at-table-p))
7445 (= (org-table-current-column) 0)
7446 (org-at-table-hline-p)
7447 (looking-at "[ \t]*$"))
7448 (error "Not in table data field")))
7450 (defvar org-table-clip nil
7451 "Clipboard for table regions.")
7453 (defun org-table-blank-field ()
7454 "Blank the current table field or active region."
7455 (interactive)
7456 (org-table-check-inside-data-field)
7457 (if (and (interactive-p) (org-region-active-p))
7458 (let (org-table-clip)
7459 (org-table-cut-region (region-beginning) (region-end)))
7460 (skip-chars-backward "^|")
7461 (backward-char 1)
7462 (if (looking-at "|[^|\n]+")
7463 (let* ((pos (match-beginning 0))
7464 (match (match-string 0))
7465 (len (org-string-width match)))
7466 (replace-match (concat "|" (make-string (1- len) ?\ )))
7467 (goto-char (+ 2 pos))
7468 (substring match 1)))))
7470 (defun org-table-get-field (&optional n replace)
7471 "Return the value of the field in column N of current row.
7472 N defaults to current field.
7473 If REPLACE is a string, replace field with this value. The return value
7474 is always the old value."
7475 (and n (org-table-goto-column n))
7476 (skip-chars-backward "^|\n")
7477 (backward-char 1)
7478 (if (looking-at "|[^|\r\n]*")
7479 (let* ((pos (match-beginning 0))
7480 (val (buffer-substring (1+ pos) (match-end 0))))
7481 (if replace
7482 (replace-match (concat "|" replace) t t))
7483 (goto-char (min (point-at-eol) (+ 2 pos)))
7484 val)
7485 (forward-char 1) ""))
7487 (defun org-table-field-info (arg)
7488 "Show info about the current field, and highlight any reference at point."
7489 (interactive "P")
7490 (org-table-get-specials)
7491 (save-excursion
7492 (let* ((pos (point))
7493 (col (org-table-current-column))
7494 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7495 (name (car (rassoc (list (org-current-line) col)
7496 org-table-named-field-locations)))
7497 (eql (org-table-get-stored-formulas))
7498 (dline (org-table-current-dline))
7499 (ref (format "@%d$%d" dline col))
7500 (ref1 (org-table-convert-refs-to-an ref))
7501 (fequation (or (assoc name eql) (assoc ref eql)))
7502 (cequation (assoc (int-to-string col) eql))
7503 (eqn (or fequation cequation)))
7504 (goto-char pos)
7505 (condition-case nil
7506 (org-table-show-reference 'local)
7507 (error nil))
7508 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7509 dline col
7510 (if cname (concat " or $" cname) "")
7511 dline col ref1
7512 (if name (concat " or $" name) "")
7513 ;; FIXME: formula info not correct if special table line
7514 (if eqn
7515 (concat ", formula: "
7516 (org-table-formula-to-user
7517 (concat
7518 (if (string-match "^[$@]"(car eqn)) "" "$")
7519 (car eqn) "=" (cdr eqn))))
7520 "")))))
7522 (defun org-table-current-column ()
7523 "Find out which column we are in.
7524 When called interactively, column is also displayed in echo area."
7525 (interactive)
7526 (if (interactive-p) (org-table-check-inside-data-field))
7527 (save-excursion
7528 (let ((cnt 0) (pos (point)))
7529 (beginning-of-line 1)
7530 (while (search-forward "|" pos t)
7531 (setq cnt (1+ cnt)))
7532 (if (interactive-p) (message "This is table column %d" cnt))
7533 cnt)))
7535 (defun org-table-current-dline ()
7536 "Find out what table data line we are in.
7537 Only datalins count for this."
7538 (interactive)
7539 (if (interactive-p) (org-table-check-inside-data-field))
7540 (save-excursion
7541 (let ((cnt 0) (pos (point)))
7542 (goto-char (org-table-begin))
7543 (while (<= (point) pos)
7544 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7545 (beginning-of-line 2))
7546 (if (interactive-p) (message "This is table line %d" cnt))
7547 cnt)))
7549 (defun org-table-goto-column (n &optional on-delim force)
7550 "Move the cursor to the Nth column in the current table line.
7551 With optional argument ON-DELIM, stop with point before the left delimiter
7552 of the field.
7553 If there are less than N fields, just go to after the last delimiter.
7554 However, when FORCE is non-nil, create new columns if necessary."
7555 (interactive "p")
7556 (let ((pos (point-at-eol)))
7557 (beginning-of-line 1)
7558 (when (> n 0)
7559 (while (and (> (setq n (1- n)) -1)
7560 (or (search-forward "|" pos t)
7561 (and force
7562 (progn (end-of-line 1)
7563 (skip-chars-backward "^|")
7564 (insert " | "))))))
7565 ; (backward-char 2) t)))))
7566 (when (and force (not (looking-at ".*|")))
7567 (save-excursion (end-of-line 1) (insert " | ")))
7568 (if on-delim
7569 (backward-char 1)
7570 (if (looking-at " ") (forward-char 1))))))
7572 (defun org-at-table-p (&optional table-type)
7573 "Return t if the cursor is inside an org-type table.
7574 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7575 (if org-enable-table-editor
7576 (save-excursion
7577 (beginning-of-line 1)
7578 (looking-at (if table-type org-table-any-line-regexp
7579 org-table-line-regexp)))
7580 nil))
7582 (defun org-at-table.el-p ()
7583 "Return t if and only if we are at a table.el table."
7584 (and (org-at-table-p 'any)
7585 (save-excursion
7586 (goto-char (org-table-begin 'any))
7587 (looking-at org-table1-hline-regexp))))
7589 (defun org-table-recognize-table.el ()
7590 "If there is a table.el table nearby, recognize it and move into it."
7591 (if org-table-tab-recognizes-table.el
7592 (if (org-at-table.el-p)
7593 (progn
7594 (beginning-of-line 1)
7595 (if (looking-at org-table-dataline-regexp)
7597 (if (looking-at org-table1-hline-regexp)
7598 (progn
7599 (beginning-of-line 2)
7600 (if (looking-at org-table-any-border-regexp)
7601 (beginning-of-line -1)))))
7602 (if (re-search-forward "|" (org-table-end t) t)
7603 (progn
7604 (require 'table)
7605 (if (table--at-cell-p (point))
7607 (message "recognizing table.el table...")
7608 (table-recognize-table)
7609 (message "recognizing table.el table...done")))
7610 (error "This should not happen..."))
7612 nil)
7613 nil))
7615 (defun org-at-table-hline-p ()
7616 "Return t if the cursor is inside a hline in a table."
7617 (if org-enable-table-editor
7618 (save-excursion
7619 (beginning-of-line 1)
7620 (looking-at org-table-hline-regexp))
7621 nil))
7623 (defun org-table-insert-column ()
7624 "Insert a new column into the table."
7625 (interactive)
7626 (if (not (org-at-table-p))
7627 (error "Not at a table"))
7628 (org-table-find-dataline)
7629 (let* ((col (max 1 (org-table-current-column)))
7630 (beg (org-table-begin))
7631 (end (org-table-end))
7632 ;; Current cursor position
7633 (linepos (org-current-line))
7634 (colpos col))
7635 (goto-char beg)
7636 (while (< (point) end)
7637 (if (org-at-table-hline-p)
7639 (org-table-goto-column col t)
7640 (insert "| "))
7641 (beginning-of-line 2))
7642 (move-marker end nil)
7643 (goto-line linepos)
7644 (org-table-goto-column colpos)
7645 (org-table-align)
7646 (org-table-fix-formulas "$" nil (1- col) 1)))
7648 (defun org-table-find-dataline ()
7649 "Find a dataline in the current table, which is needed for column commands."
7650 (if (and (org-at-table-p)
7651 (not (org-at-table-hline-p)))
7653 (let ((col (current-column))
7654 (end (org-table-end)))
7655 (move-to-column col)
7656 (while (and (< (point) end)
7657 (or (not (= (current-column) col))
7658 (org-at-table-hline-p)))
7659 (beginning-of-line 2)
7660 (move-to-column col))
7661 (if (and (org-at-table-p)
7662 (not (org-at-table-hline-p)))
7664 (error
7665 "Please position cursor in a data line for column operations")))))
7667 (defun org-table-delete-column ()
7668 "Delete a column from the table."
7669 (interactive)
7670 (if (not (org-at-table-p))
7671 (error "Not at a table"))
7672 (org-table-find-dataline)
7673 (org-table-check-inside-data-field)
7674 (let* ((col (org-table-current-column))
7675 (beg (org-table-begin))
7676 (end (org-table-end))
7677 ;; Current cursor position
7678 (linepos (org-current-line))
7679 (colpos col))
7680 (goto-char beg)
7681 (while (< (point) end)
7682 (if (org-at-table-hline-p)
7684 (org-table-goto-column col t)
7685 (and (looking-at "|[^|\n]+|")
7686 (replace-match "|")))
7687 (beginning-of-line 2))
7688 (move-marker end nil)
7689 (goto-line linepos)
7690 (org-table-goto-column colpos)
7691 (org-table-align)
7692 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7693 col -1 col)))
7695 (defun org-table-move-column-right ()
7696 "Move column to the right."
7697 (interactive)
7698 (org-table-move-column nil))
7699 (defun org-table-move-column-left ()
7700 "Move column to the left."
7701 (interactive)
7702 (org-table-move-column 'left))
7704 (defun org-table-move-column (&optional left)
7705 "Move the current column to the right. With arg LEFT, move to the left."
7706 (interactive "P")
7707 (if (not (org-at-table-p))
7708 (error "Not at a table"))
7709 (org-table-find-dataline)
7710 (org-table-check-inside-data-field)
7711 (let* ((col (org-table-current-column))
7712 (col1 (if left (1- col) col))
7713 (beg (org-table-begin))
7714 (end (org-table-end))
7715 ;; Current cursor position
7716 (linepos (org-current-line))
7717 (colpos (if left (1- col) (1+ col))))
7718 (if (and left (= col 1))
7719 (error "Cannot move column further left"))
7720 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7721 (error "Cannot move column further right"))
7722 (goto-char beg)
7723 (while (< (point) end)
7724 (if (org-at-table-hline-p)
7726 (org-table-goto-column col1 t)
7727 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7728 (replace-match "|\\2|\\1|")))
7729 (beginning-of-line 2))
7730 (move-marker end nil)
7731 (goto-line linepos)
7732 (org-table-goto-column colpos)
7733 (org-table-align)
7734 (org-table-fix-formulas
7735 "$" (list (cons (number-to-string col) (number-to-string colpos))
7736 (cons (number-to-string colpos) (number-to-string col))))))
7738 (defun org-table-move-row-down ()
7739 "Move table row down."
7740 (interactive)
7741 (org-table-move-row nil))
7742 (defun org-table-move-row-up ()
7743 "Move table row up."
7744 (interactive)
7745 (org-table-move-row 'up))
7747 (defun org-table-move-row (&optional up)
7748 "Move the current table line down. With arg UP, move it up."
7749 (interactive "P")
7750 (let* ((col (current-column))
7751 (pos (point))
7752 (hline1p (save-excursion (beginning-of-line 1)
7753 (looking-at org-table-hline-regexp)))
7754 (dline1 (org-table-current-dline))
7755 (dline2 (+ dline1 (if up -1 1)))
7756 (tonew (if up 0 2))
7757 txt hline2p)
7758 (beginning-of-line tonew)
7759 (unless (org-at-table-p)
7760 (goto-char pos)
7761 (error "Cannot move row further"))
7762 (setq hline2p (looking-at org-table-hline-regexp))
7763 (goto-char pos)
7764 (beginning-of-line 1)
7765 (setq pos (point))
7766 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7767 (delete-region (point) (1+ (point-at-eol)))
7768 (beginning-of-line tonew)
7769 (insert txt)
7770 (beginning-of-line 0)
7771 (move-to-column col)
7772 (unless (or hline1p hline2p)
7773 (org-table-fix-formulas
7774 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7775 (cons (number-to-string dline2) (number-to-string dline1)))))))
7777 (defun org-table-insert-row (&optional arg)
7778 "Insert a new row above the current line into the table.
7779 With prefix ARG, insert below the current line."
7780 (interactive "P")
7781 (if (not (org-at-table-p))
7782 (error "Not at a table"))
7783 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7784 (new (org-table-clean-line line)))
7785 ;; Fix the first field if necessary
7786 (if (string-match "^[ \t]*| *[#$] *|" line)
7787 (setq new (replace-match (match-string 0 line) t t new)))
7788 (beginning-of-line (if arg 2 1))
7789 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7790 (beginning-of-line 0)
7791 (re-search-forward "| ?" (point-at-eol) t)
7792 (and (or org-table-may-need-update org-table-overlay-coordinates)
7793 (org-table-align))
7794 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7796 (defun org-table-insert-hline (&optional above)
7797 "Insert a horizontal-line below the current line into the table.
7798 With prefix ABOVE, insert above the current line."
7799 (interactive "P")
7800 (if (not (org-at-table-p))
7801 (error "Not at a table"))
7802 (let ((line (org-table-clean-line
7803 (buffer-substring (point-at-bol) (point-at-eol))))
7804 (col (current-column)))
7805 (while (string-match "|\\( +\\)|" line)
7806 (setq line (replace-match
7807 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7808 ?-) "|") t t line)))
7809 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7810 (beginning-of-line (if above 1 2))
7811 (insert line "\n")
7812 (beginning-of-line (if above 1 -1))
7813 (move-to-column col)
7814 (and org-table-overlay-coordinates (org-table-align))))
7816 (defun org-table-hline-and-move (&optional same-column)
7817 "Insert a hline and move to the row below that line."
7818 (interactive "P")
7819 (let ((col (org-table-current-column)))
7820 (org-table-maybe-eval-formula)
7821 (org-table-maybe-recalculate-line)
7822 (org-table-insert-hline)
7823 (end-of-line 2)
7824 (if (looking-at "\n[ \t]*|-")
7825 (progn (insert "\n|") (org-table-align))
7826 (org-table-next-field))
7827 (if same-column (org-table-goto-column col))))
7829 (defun org-table-clean-line (s)
7830 "Convert a table line S into a string with only \"|\" and space.
7831 In particular, this does handle wide and invisible characters."
7832 (if (string-match "^[ \t]*|-" s)
7833 ;; It's a hline, just map the characters
7834 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7835 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7836 (setq s (replace-match
7837 (concat "|" (make-string (org-string-width (match-string 1 s))
7838 ?\ ) "|")
7839 t t s)))
7842 (defun org-table-kill-row ()
7843 "Delete the current row or horizontal line from the table."
7844 (interactive)
7845 (if (not (org-at-table-p))
7846 (error "Not at a table"))
7847 (let ((col (current-column))
7848 (dline (org-table-current-dline)))
7849 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7850 (if (not (org-at-table-p)) (beginning-of-line 0))
7851 (move-to-column col)
7852 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7853 dline -1 dline)))
7856 (defun org-table-sort-lines (with-case &optional sorting-type)
7857 "Sort table lines according to the column at point.
7859 The position of point indicates the column to be used for
7860 sorting, and the range of lines is the range between the nearest
7861 horizontal separator lines, or the entire table of no such lines
7862 exist. If point is before the first column, you will be prompted
7863 for the sorting column. If there is an active region, the mark
7864 specifies the first line and the sorting column, while point
7865 should be in the last line to be included into the sorting.
7867 The command then prompts for the sorting type which can be
7868 alphabetically, numerically, or by time (as given in a time stamp
7869 in the field). Sorting in reverse order is also possible.
7871 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7873 If SORTING-TYPE is specified when this function is called from a Lisp
7874 program, no prompting will take place. SORTING-TYPE must be a character,
7875 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
7876 should be done in reverse order."
7877 (interactive "P")
7878 (let* ((thisline (org-current-line))
7879 (thiscol (org-table-current-column))
7880 beg end bcol ecol tend tbeg column lns pos)
7881 (when (equal thiscol 0)
7882 (if (interactive-p)
7883 (setq thiscol
7884 (string-to-number
7885 (read-string "Use column N for sorting: ")))
7886 (setq thiscol 1))
7887 (org-table-goto-column thiscol))
7888 (org-table-check-inside-data-field)
7889 (if (org-region-active-p)
7890 (progn
7891 (setq beg (region-beginning) end (region-end))
7892 (goto-char beg)
7893 (setq column (org-table-current-column)
7894 beg (point-at-bol))
7895 (goto-char end)
7896 (setq end (point-at-bol 2)))
7897 (setq column (org-table-current-column)
7898 pos (point)
7899 tbeg (org-table-begin)
7900 tend (org-table-end))
7901 (if (re-search-backward org-table-hline-regexp tbeg t)
7902 (setq beg (point-at-bol 2))
7903 (goto-char tbeg)
7904 (setq beg (point-at-bol 1)))
7905 (goto-char pos)
7906 (if (re-search-forward org-table-hline-regexp tend t)
7907 (setq end (point-at-bol 1))
7908 (goto-char tend)
7909 (setq end (point-at-bol))))
7910 (setq beg (move-marker (make-marker) beg)
7911 end (move-marker (make-marker) end))
7912 (untabify beg end)
7913 (goto-char beg)
7914 (org-table-goto-column column)
7915 (skip-chars-backward "^|")
7916 (setq bcol (current-column))
7917 (org-table-goto-column (1+ column))
7918 (skip-chars-backward "^|")
7919 (setq ecol (1- (current-column)))
7920 (org-table-goto-column column)
7921 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7922 (org-split-string (buffer-substring beg end) "\n")))
7923 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7924 (delete-region beg end)
7925 (move-marker beg nil)
7926 (move-marker end nil)
7927 (insert (mapconcat 'cdr lns "\n") "\n")
7928 (goto-line thisline)
7929 (org-table-goto-column thiscol)
7930 (message "%d lines sorted, based on column %d" (length lns) column)))
7932 (defun org-table-cut-region (beg end)
7933 "Copy region in table to the clipboard and blank all relevant fields."
7934 (interactive "r")
7935 (org-table-copy-region beg end 'cut))
7937 (defun org-table-copy-region (beg end &optional cut)
7938 "Copy rectangular region in table to clipboard.
7939 A special clipboard is used which can only be accessed
7940 with `org-table-paste-rectangle'."
7941 (interactive "rP")
7942 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7943 region cols
7944 (rpl (if cut " " nil)))
7945 (goto-char beg)
7946 (org-table-check-inside-data-field)
7947 (setq l01 (org-current-line)
7948 c01 (org-table-current-column))
7949 (goto-char end)
7950 (org-table-check-inside-data-field)
7951 (setq l02 (org-current-line)
7952 c02 (org-table-current-column))
7953 (setq l1 (min l01 l02) l2 (max l01 l02)
7954 c1 (min c01 c02) c2 (max c01 c02))
7955 (catch 'exit
7956 (while t
7957 (catch 'nextline
7958 (if (> l1 l2) (throw 'exit t))
7959 (goto-line l1)
7960 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7961 (setq cols nil ic1 c1 ic2 c2)
7962 (while (< ic1 (1+ ic2))
7963 (push (org-table-get-field ic1 rpl) cols)
7964 (setq ic1 (1+ ic1)))
7965 (push (nreverse cols) region)
7966 (setq l1 (1+ l1)))))
7967 (setq org-table-clip (nreverse region))
7968 (if cut (org-table-align))
7969 org-table-clip))
7971 (defun org-table-paste-rectangle ()
7972 "Paste a rectangular region into a table.
7973 The upper right corner ends up in the current field. All involved fields
7974 will be overwritten. If the rectangle does not fit into the present table,
7975 the table is enlarged as needed. The process ignores horizontal separator
7976 lines."
7977 (interactive)
7978 (unless (and org-table-clip (listp org-table-clip))
7979 (error "First cut/copy a region to paste!"))
7980 (org-table-check-inside-data-field)
7981 (let* ((clip org-table-clip)
7982 (line (org-current-line))
7983 (col (org-table-current-column))
7984 (org-enable-table-editor t)
7985 (org-table-automatic-realign nil)
7986 c cols field)
7987 (while (setq cols (pop clip))
7988 (while (org-at-table-hline-p) (beginning-of-line 2))
7989 (if (not (org-at-table-p))
7990 (progn (end-of-line 0) (org-table-next-field)))
7991 (setq c col)
7992 (while (setq field (pop cols))
7993 (org-table-goto-column c nil 'force)
7994 (org-table-get-field nil field)
7995 (setq c (1+ c)))
7996 (beginning-of-line 2))
7997 (goto-line line)
7998 (org-table-goto-column col)
7999 (org-table-align)))
8001 (defun org-table-convert ()
8002 "Convert from `org-mode' table to table.el and back.
8003 Obviously, this only works within limits. When an Org-mode table is
8004 converted to table.el, all horizontal separator lines get lost, because
8005 table.el uses these as cell boundaries and has no notion of horizontal lines.
8006 A table.el table can be converted to an Org-mode table only if it does not
8007 do row or column spanning. Multiline cells will become multiple cells.
8008 Beware, Org-mode does not test if the table can be successfully converted - it
8009 blindly applies a recipe that works for simple tables."
8010 (interactive)
8011 (require 'table)
8012 (if (org-at-table.el-p)
8013 ;; convert to Org-mode table
8014 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8015 (end (move-marker (make-marker) (org-table-end t))))
8016 (table-unrecognize-region beg end)
8017 (goto-char beg)
8018 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8019 (replace-match ""))
8020 (goto-char beg))
8021 (if (org-at-table-p)
8022 ;; convert to table.el table
8023 (let ((beg (move-marker (make-marker) (org-table-begin)))
8024 (end (move-marker (make-marker) (org-table-end))))
8025 ;; first, get rid of all horizontal lines
8026 (goto-char beg)
8027 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8028 (replace-match ""))
8029 ;; insert a hline before first
8030 (goto-char beg)
8031 (org-table-insert-hline 'above)
8032 (beginning-of-line -1)
8033 ;; insert a hline after each line
8034 (while (progn (beginning-of-line 3) (< (point) end))
8035 (org-table-insert-hline))
8036 (goto-char beg)
8037 (setq end (move-marker end (org-table-end)))
8038 ;; replace "+" at beginning and ending of hlines
8039 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8040 (replace-match "\\1+-"))
8041 (goto-char beg)
8042 (while (re-search-forward "-|[ \t]*$" end t)
8043 (replace-match "-+"))
8044 (goto-char beg)))))
8046 (defun org-table-wrap-region (arg)
8047 "Wrap several fields in a column like a paragraph.
8048 This is useful if you'd like to spread the contents of a field over several
8049 lines, in order to keep the table compact.
8051 If there is an active region, and both point and mark are in the same column,
8052 the text in the column is wrapped to minimum width for the given number of
8053 lines. Generally, this makes the table more compact. A prefix ARG may be
8054 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8055 formats the selected text to two lines. If the region was longer than two
8056 lines, the remaining lines remain empty. A negative prefix argument reduces
8057 the current number of lines by that amount. The wrapped text is pasted back
8058 into the table. If you formatted it to more lines than it was before, fields
8059 further down in the table get overwritten - so you might need to make space in
8060 the table first.
8062 If there is no region, the current field is split at the cursor position and
8063 the text fragment to the right of the cursor is prepended to the field one
8064 line down.
8066 If there is no region, but you specify a prefix ARG, the current field gets
8067 blank, and the content is appended to the field above."
8068 (interactive "P")
8069 (org-table-check-inside-data-field)
8070 (if (org-region-active-p)
8071 ;; There is a region: fill as a paragraph
8072 (let* ((beg (region-beginning))
8073 (cline (save-excursion (goto-char beg) (org-current-line)))
8074 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8075 nlines)
8076 (org-table-cut-region (region-beginning) (region-end))
8077 (if (> (length (car org-table-clip)) 1)
8078 (error "Region must be limited to single column"))
8079 (setq nlines (if arg
8080 (if (< arg 1)
8081 (+ (length org-table-clip) arg)
8082 arg)
8083 (length org-table-clip)))
8084 (setq org-table-clip
8085 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8086 nil nlines)))
8087 (goto-line cline)
8088 (org-table-goto-column ccol)
8089 (org-table-paste-rectangle))
8090 ;; No region, split the current field at point
8091 (if arg
8092 ;; combine with field above
8093 (let ((s (org-table-blank-field))
8094 (col (org-table-current-column)))
8095 (beginning-of-line 0)
8096 (while (org-at-table-hline-p) (beginning-of-line 0))
8097 (org-table-goto-column col)
8098 (skip-chars-forward "^|")
8099 (skip-chars-backward " ")
8100 (insert " " (org-trim s))
8101 (org-table-align))
8102 ;; split field
8103 (when (looking-at "\\([^|]+\\)+|")
8104 (let ((s (match-string 1)))
8105 (replace-match " |")
8106 (goto-char (match-beginning 0))
8107 (org-table-next-row)
8108 (insert (org-trim s) " ")
8109 (org-table-align))))))
8111 (defvar org-field-marker nil)
8113 (defun org-table-edit-field (arg)
8114 "Edit table field in a different window.
8115 This is mainly useful for fields that contain hidden parts.
8116 When called with a \\[universal-argument] prefix, just make the full field visible so that
8117 it can be edited in place."
8118 (interactive "P")
8119 (if arg
8120 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8121 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8122 (remove-text-properties b e '(org-cwidth t invisible t
8123 display t intangible t))
8124 (if (and (boundp 'font-lock-mode) font-lock-mode)
8125 (font-lock-fontify-block)))
8126 (let ((pos (move-marker (make-marker) (point)))
8127 (field (org-table-get-field))
8128 (cw (current-window-configuration))
8130 (switch-to-buffer-other-window "*Org tmp*")
8131 (erase-buffer)
8132 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8133 (let ((org-inhibit-startup t)) (org-mode))
8134 (goto-char (setq p (point-max)))
8135 (insert (org-trim field))
8136 (remove-text-properties p (point-max)
8137 '(invisible t org-cwidth t display t
8138 intangible t))
8139 (goto-char p)
8140 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8141 (org-set-local 'org-window-configuration cw)
8142 (org-set-local 'org-field-marker pos)
8143 (message "Edit and finish with C-c C-c"))))
8145 (defun org-table-finish-edit-field ()
8146 "Finish editing a table data field.
8147 Remove all newline characters, insert the result into the table, realign
8148 the table and kill the editing buffer."
8149 (let ((pos org-field-marker)
8150 (cw org-window-configuration)
8151 (cb (current-buffer))
8152 text)
8153 (goto-char (point-min))
8154 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8155 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8156 (replace-match " "))
8157 (setq text (org-trim (buffer-string)))
8158 (set-window-configuration cw)
8159 (kill-buffer cb)
8160 (select-window (get-buffer-window (marker-buffer pos)))
8161 (goto-char pos)
8162 (move-marker pos nil)
8163 (org-table-check-inside-data-field)
8164 (org-table-get-field nil text)
8165 (org-table-align)
8166 (message "New field value inserted")))
8168 (defun org-trim (s)
8169 "Remove whitespace at beginning and end of string."
8170 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8171 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
8174 (defun org-wrap (string &optional width lines)
8175 "Wrap string to either a number of lines, or a width in characters.
8176 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8177 that costs. If there is a word longer than WIDTH, the text is actually
8178 wrapped to the length of that word.
8179 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8180 many lines, whatever width that takes.
8181 The return value is a list of lines, without newlines at the end."
8182 (let* ((words (org-split-string string "[ \t\n]+"))
8183 (maxword (apply 'max (mapcar 'org-string-width words)))
8184 w ll)
8185 (cond (width
8186 (org-do-wrap words (max maxword width)))
8187 (lines
8188 (setq w maxword)
8189 (setq ll (org-do-wrap words maxword))
8190 (if (<= (length ll) lines)
8192 (setq ll words)
8193 (while (> (length ll) lines)
8194 (setq w (1+ w))
8195 (setq ll (org-do-wrap words w)))
8196 ll))
8197 (t (error "Cannot wrap this")))))
8200 (defun org-do-wrap (words width)
8201 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8202 (let (lines line)
8203 (while words
8204 (setq line (pop words))
8205 (while (and words (< (+ (length line) (length (car words))) width))
8206 (setq line (concat line " " (pop words))))
8207 (setq lines (push line lines)))
8208 (nreverse lines)))
8210 (defun org-split-string (string &optional separators)
8211 "Splits STRING into substrings at SEPARATORS.
8212 No empty strings are returned if there are matches at the beginning
8213 and end of string."
8214 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8215 (start 0)
8216 notfirst
8217 (list nil))
8218 (while (and (string-match rexp string
8219 (if (and notfirst
8220 (= start (match-beginning 0))
8221 (< start (length string)))
8222 (1+ start) start))
8223 (< (match-beginning 0) (length string)))
8224 (setq notfirst t)
8225 (or (eq (match-beginning 0) 0)
8226 (and (eq (match-beginning 0) (match-end 0))
8227 (eq (match-beginning 0) start))
8228 (setq list
8229 (cons (substring string start (match-beginning 0))
8230 list)))
8231 (setq start (match-end 0)))
8232 (or (eq start (length string))
8233 (setq list
8234 (cons (substring string start)
8235 list)))
8236 (nreverse list)))
8238 (defun org-table-map-tables (function)
8239 "Apply FUNCTION to the start of all tables in the buffer."
8240 (save-excursion
8241 (save-restriction
8242 (widen)
8243 (goto-char (point-min))
8244 (while (re-search-forward org-table-any-line-regexp nil t)
8245 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8246 (beginning-of-line 1)
8247 (if (looking-at org-table-line-regexp)
8248 (save-excursion (funcall function)))
8249 (re-search-forward org-table-any-border-regexp nil 1))))
8250 (message "Mapping tables: done"))
8252 (defvar org-timecnt) ; dynamically scoped parameter
8254 (defun org-table-sum (&optional beg end nlast)
8255 "Sum numbers in region of current table column.
8256 The result will be displayed in the echo area, and will be available
8257 as kill to be inserted with \\[yank].
8259 If there is an active region, it is interpreted as a rectangle and all
8260 numbers in that rectangle will be summed. If there is no active
8261 region and point is located in a table column, sum all numbers in that
8262 column.
8264 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8265 numbers are assumed to be times as well (in decimal hours) and the
8266 numbers are added as such.
8268 If NLAST is a number, only the NLAST fields will actually be summed."
8269 (interactive)
8270 (save-excursion
8271 (let (col (org-timecnt 0) diff h m s org-table-clip)
8272 (cond
8273 ((and beg end)) ; beg and end given explicitly
8274 ((org-region-active-p)
8275 (setq beg (region-beginning) end (region-end)))
8277 (setq col (org-table-current-column))
8278 (goto-char (org-table-begin))
8279 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8280 (error "No table data"))
8281 (org-table-goto-column col)
8282 (setq beg (point))
8283 (goto-char (org-table-end))
8284 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8285 (error "No table data"))
8286 (org-table-goto-column col)
8287 (setq end (point))))
8288 (let* ((items (apply 'append (org-table-copy-region beg end)))
8289 (items1 (cond ((not nlast) items)
8290 ((>= nlast (length items)) items)
8291 (t (setq items (reverse items))
8292 (setcdr (nthcdr (1- nlast) items) nil)
8293 (nreverse items))))
8294 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8295 items1)))
8296 (res (apply '+ numbers))
8297 (sres (if (= org-timecnt 0)
8298 (format "%g" res)
8299 (setq diff (* 3600 res)
8300 h (floor (/ diff 3600)) diff (mod diff 3600)
8301 m (floor (/ diff 60)) diff (mod diff 60)
8302 s diff)
8303 (format "%d:%02d:%02d" h m s))))
8304 (kill-new sres)
8305 (if (interactive-p)
8306 (message "%s"
8307 (substitute-command-keys
8308 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8309 (length numbers) sres))))
8310 sres))))
8312 (defun org-table-get-number-for-summing (s)
8313 (let (n)
8314 (if (string-match "^ *|? *" s)
8315 (setq s (replace-match "" nil nil s)))
8316 (if (string-match " *|? *$" s)
8317 (setq s (replace-match "" nil nil s)))
8318 (setq n (string-to-number s))
8319 (cond
8320 ((and (string-match "0" s)
8321 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8322 ((string-match "\\`[ \t]+\\'" s) nil)
8323 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8324 (let ((h (string-to-number (or (match-string 1 s) "0")))
8325 (m (string-to-number (or (match-string 2 s) "0")))
8326 (s (string-to-number (or (match-string 4 s) "0"))))
8327 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8328 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8329 ((equal n 0) nil)
8330 (t n))))
8332 (defun org-table-current-field-formula (&optional key noerror)
8333 "Return the formula active for the current field.
8334 Assumes that specials are in place.
8335 If KEY is given, return the key to this formula.
8336 Otherwise return the formula preceeded with \"=\" or \":=\"."
8337 (let* ((name (car (rassoc (list (org-current-line)
8338 (org-table-current-column))
8339 org-table-named-field-locations)))
8340 (col (org-table-current-column))
8341 (scol (int-to-string col))
8342 (ref (format "@%d$%d" (org-table-current-dline) col))
8343 (stored-list (org-table-get-stored-formulas noerror))
8344 (ass (or (assoc name stored-list)
8345 (assoc ref stored-list)
8346 (assoc scol stored-list))))
8347 (if key
8348 (car ass)
8349 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8350 (cdr ass))))))
8352 (defun org-table-get-formula (&optional equation named)
8353 "Read a formula from the minibuffer, offer stored formula as default.
8354 When NAMED is non-nil, look for a named equation."
8355 (let* ((stored-list (org-table-get-stored-formulas))
8356 (name (car (rassoc (list (org-current-line)
8357 (org-table-current-column))
8358 org-table-named-field-locations)))
8359 (ref (format "@%d$%d" (org-table-current-dline)
8360 (org-table-current-column)))
8361 (refass (assoc ref stored-list))
8362 (scol (if named
8363 (if name name ref)
8364 (int-to-string (org-table-current-column))))
8365 (dummy (and (or name refass) (not named)
8366 (not (y-or-n-p "Replace field formula with column formula? " ))
8367 (error "Abort")))
8368 (name (or name ref))
8369 (org-table-may-need-update nil)
8370 (stored (cdr (assoc scol stored-list)))
8371 (eq (cond
8372 ((and stored equation (string-match "^ *=? *$" equation))
8373 stored)
8374 ((stringp equation)
8375 equation)
8376 (t (org-table-formula-from-user
8377 (read-string
8378 (org-table-formula-to-user
8379 (format "%s formula %s%s="
8380 (if named "Field" "Column")
8381 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8382 scol))
8383 (if stored (org-table-formula-to-user stored) "")
8384 'org-table-formula-history
8385 )))))
8386 mustsave)
8387 (when (not (string-match "\\S-" eq))
8388 ;; remove formula
8389 (setq stored-list (delq (assoc scol stored-list) stored-list))
8390 (org-table-store-formulas stored-list)
8391 (error "Formula removed"))
8392 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8393 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8394 (if (and name (not named))
8395 ;; We set the column equation, delete the named one.
8396 (setq stored-list (delq (assoc name stored-list) stored-list)
8397 mustsave t))
8398 (if stored
8399 (setcdr (assoc scol stored-list) eq)
8400 (setq stored-list (cons (cons scol eq) stored-list)))
8401 (if (or mustsave (not (equal stored eq)))
8402 (org-table-store-formulas stored-list))
8403 eq))
8405 (defun org-table-store-formulas (alist)
8406 "Store the list of formulas below the current table."
8407 (setq alist (sort alist 'org-table-formula-less-p))
8408 (save-excursion
8409 (goto-char (org-table-end))
8410 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8411 (progn
8412 ;; don't overwrite TBLFM, we might use text properties to store stuff
8413 (goto-char (match-beginning 2))
8414 (delete-region (match-beginning 2) (match-end 0)))
8415 (insert "#+TBLFM:"))
8416 (insert " "
8417 (mapconcat (lambda (x)
8418 (concat
8419 (if (equal (string-to-char (car x)) ?@) "" "$")
8420 (car x) "=" (cdr x)))
8421 alist "::")
8422 "\n")))
8424 (defsubst org-table-formula-make-cmp-string (a)
8425 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8426 (concat
8427 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8428 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8429 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8431 (defun org-table-formula-less-p (a b)
8432 "Compare two formulas for sorting."
8433 (let ((as (org-table-formula-make-cmp-string (car a)))
8434 (bs (org-table-formula-make-cmp-string (car b))))
8435 (and as bs (string< as bs))))
8437 (defun org-table-get-stored-formulas (&optional noerror)
8438 "Return an alist with the stored formulas directly after current table."
8439 (interactive)
8440 (let (scol eq eq-alist strings string seen)
8441 (save-excursion
8442 (goto-char (org-table-end))
8443 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8444 (setq strings (org-split-string (match-string 2) " *:: *"))
8445 (while (setq string (pop strings))
8446 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8447 (setq scol (if (match-end 2)
8448 (match-string 2 string)
8449 (match-string 1 string))
8450 eq (match-string 3 string)
8451 eq-alist (cons (cons scol eq) eq-alist))
8452 (if (member scol seen)
8453 (if noerror
8454 (progn
8455 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8456 (ding)
8457 (sit-for 2))
8458 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8459 (push scol seen))))))
8460 (nreverse eq-alist)))
8462 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8463 "Modify the equations after the table structure has been edited.
8464 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8465 For all numbers larger than LIMIT, shift them by DELTA."
8466 (save-excursion
8467 (goto-char (org-table-end))
8468 (when (looking-at "#\\+TBLFM:")
8469 (let ((re (concat key "\\([0-9]+\\)"))
8470 (re2
8471 (when remove
8472 (if (equal key "$")
8473 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8474 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8475 s n a)
8476 (when remove
8477 (while (re-search-forward re2 (point-at-eol) t)
8478 (replace-match "")))
8479 (while (re-search-forward re (point-at-eol) t)
8480 (setq s (match-string 1) n (string-to-number s))
8481 (cond
8482 ((setq a (assoc s replace))
8483 (replace-match (concat key (cdr a)) t t))
8484 ((and limit (> n limit))
8485 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8487 (defun org-table-get-specials ()
8488 "Get the column names and local parameters for this table."
8489 (save-excursion
8490 (let ((beg (org-table-begin)) (end (org-table-end))
8491 names name fields fields1 field cnt
8492 c v l line col types dlines hlines)
8493 (setq org-table-column-names nil
8494 org-table-local-parameters nil
8495 org-table-named-field-locations nil
8496 org-table-current-begin-line nil
8497 org-table-current-begin-pos nil
8498 org-table-current-line-types nil)
8499 (goto-char beg)
8500 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8501 (setq names (org-split-string (match-string 1) " *| *")
8502 cnt 1)
8503 (while (setq name (pop names))
8504 (setq cnt (1+ cnt))
8505 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8506 (push (cons name (int-to-string cnt)) org-table-column-names))))
8507 (setq org-table-column-names (nreverse org-table-column-names))
8508 (setq org-table-column-name-regexp
8509 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8510 (goto-char beg)
8511 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8512 (setq fields (org-split-string (match-string 1) " *| *"))
8513 (while (setq field (pop fields))
8514 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8515 (push (cons (match-string 1 field) (match-string 2 field))
8516 org-table-local-parameters))))
8517 (goto-char beg)
8518 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8519 (setq c (match-string 1)
8520 fields (org-split-string (match-string 2) " *| *"))
8521 (save-excursion
8522 (beginning-of-line (if (equal c "_") 2 0))
8523 (setq line (org-current-line) col 1)
8524 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8525 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8526 (while (and fields1 (setq field (pop fields)))
8527 (setq v (pop fields1) col (1+ col))
8528 (when (and (stringp field) (stringp v)
8529 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8530 (push (cons field v) org-table-local-parameters)
8531 (push (list field line col) org-table-named-field-locations))))
8532 ;; Analyse the line types
8533 (goto-char beg)
8534 (setq org-table-current-begin-line (org-current-line)
8535 org-table-current-begin-pos (point)
8536 l org-table-current-begin-line)
8537 (while (looking-at "[ \t]*|\\(-\\)?")
8538 (push (if (match-end 1) 'hline 'dline) types)
8539 (if (match-end 1) (push l hlines) (push l dlines))
8540 (beginning-of-line 2)
8541 (setq l (1+ l)))
8542 (setq org-table-current-line-types (apply 'vector (nreverse types))
8543 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8544 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8546 (defun org-table-maybe-eval-formula ()
8547 "Check if the current field starts with \"=\" or \":=\".
8548 If yes, store the formula and apply it."
8549 ;; We already know we are in a table. Get field will only return a formula
8550 ;; when appropriate. It might return a separator line, but no problem.
8551 (when org-table-formula-evaluate-inline
8552 (let* ((field (org-trim (or (org-table-get-field) "")))
8553 named eq)
8554 (when (string-match "^:?=\\(.*\\)" field)
8555 (setq named (equal (string-to-char field) ?:)
8556 eq (match-string 1 field))
8557 (if (or (fboundp 'calc-eval)
8558 (equal (substring eq 0 (min 2 (length eq))) "'("))
8559 (org-table-eval-formula (if named '(4) nil)
8560 (org-table-formula-from-user eq))
8561 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8563 (defvar org-recalc-commands nil
8564 "List of commands triggering the recalculation of a line.
8565 Will be filled automatically during use.")
8567 (defvar org-recalc-marks
8568 '((" " . "Unmarked: no special line, no automatic recalculation")
8569 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8570 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8571 ("!" . "Column name definition line. Reference in formula as $name.")
8572 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8573 ("_" . "Names for values in row below this one.")
8574 ("^" . "Names for values in row above this one.")))
8576 (defun org-table-rotate-recalc-marks (&optional newchar)
8577 "Rotate the recalculation mark in the first column.
8578 If in any row, the first field is not consistent with a mark,
8579 insert a new column for the markers.
8580 When there is an active region, change all the lines in the region,
8581 after prompting for the marking character.
8582 After each change, a message will be displayed indicating the meaning
8583 of the new mark."
8584 (interactive)
8585 (unless (org-at-table-p) (error "Not at a table"))
8586 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8587 (beg (org-table-begin))
8588 (end (org-table-end))
8589 (l (org-current-line))
8590 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8591 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8592 (have-col
8593 (save-excursion
8594 (goto-char beg)
8595 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8596 (col (org-table-current-column))
8597 (forcenew (car (assoc newchar org-recalc-marks)))
8598 epos new)
8599 (when l1
8600 (message "Change region to what mark? Type # * ! $ or SPC: ")
8601 (setq newchar (char-to-string (read-char-exclusive))
8602 forcenew (car (assoc newchar org-recalc-marks))))
8603 (if (and newchar (not forcenew))
8604 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8605 newchar))
8606 (if l1 (goto-line l1))
8607 (save-excursion
8608 (beginning-of-line 1)
8609 (unless (looking-at org-table-dataline-regexp)
8610 (error "Not at a table data line")))
8611 (unless have-col
8612 (org-table-goto-column 1)
8613 (org-table-insert-column)
8614 (org-table-goto-column (1+ col)))
8615 (setq epos (point-at-eol))
8616 (save-excursion
8617 (beginning-of-line 1)
8618 (org-table-get-field
8619 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8620 (concat " "
8621 (setq new (or forcenew
8622 (cadr (member (match-string 1) marks))))
8623 " ")
8624 " # ")))
8625 (if (and l1 l2)
8626 (progn
8627 (goto-line l1)
8628 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8629 (and (looking-at org-table-dataline-regexp)
8630 (org-table-get-field 1 (concat " " new " "))))
8631 (goto-line l1)))
8632 (if (not (= epos (point-at-eol))) (org-table-align))
8633 (goto-line l)
8634 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8636 (defun org-table-maybe-recalculate-line ()
8637 "Recompute the current line if marked for it, and if we haven't just done it."
8638 (interactive)
8639 (and org-table-allow-automatic-line-recalculation
8640 (not (and (memq last-command org-recalc-commands)
8641 (equal org-last-recalc-line (org-current-line))))
8642 (save-excursion (beginning-of-line 1)
8643 (looking-at org-table-auto-recalculate-regexp))
8644 (org-table-recalculate) t))
8646 (defvar org-table-formula-debug nil
8647 "Non-nil means, debug table formulas.
8648 When nil, simply write \"#ERROR\" in corrupted fields.")
8649 (make-variable-buffer-local 'org-table-formula-debug)
8651 (defvar modes)
8652 (defsubst org-set-calc-mode (var &optional value)
8653 (if (stringp var)
8654 (setq var (assoc var '(("D" calc-angle-mode deg)
8655 ("R" calc-angle-mode rad)
8656 ("F" calc-prefer-frac t)
8657 ("S" calc-symbolic-mode t)))
8658 value (nth 2 var) var (nth 1 var)))
8659 (if (memq var modes)
8660 (setcar (cdr (memq var modes)) value)
8661 (cons var (cons value modes)))
8662 modes)
8664 (defun org-table-eval-formula (&optional arg equation
8665 suppress-align suppress-const
8666 suppress-store suppress-analysis)
8667 "Replace the table field value at the cursor by the result of a calculation.
8669 This function makes use of Dave Gillespie's Calc package, in my view the
8670 most exciting program ever written for GNU Emacs. So you need to have Calc
8671 installed in order to use this function.
8673 In a table, this command replaces the value in the current field with the
8674 result of a formula. It also installs the formula as the \"current\" column
8675 formula, by storing it in a special line below the table. When called
8676 with a `C-u' prefix, the current field must ba a named field, and the
8677 formula is installed as valid in only this specific field.
8679 When called with two `C-u' prefixes, insert the active equation
8680 for the field back into the current field, so that it can be
8681 edited there. This is useful in order to use \\[org-table-show-reference]
8682 to check the referenced fields.
8684 When called, the command first prompts for a formula, which is read in
8685 the minibuffer. Previously entered formulas are available through the
8686 history list, and the last used formula is offered as a default.
8687 These stored formulas are adapted correctly when moving, inserting, or
8688 deleting columns with the corresponding commands.
8690 The formula can be any algebraic expression understood by the Calc package.
8691 For details, see the Org-mode manual.
8693 This function can also be called from Lisp programs and offers
8694 additional arguments: EQUATION can be the formula to apply. If this
8695 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8696 used to speed-up recursive calls by by-passing unnecessary aligns.
8697 SUPPRESS-CONST suppresses the interpretation of constants in the
8698 formula, assuming that this has been done already outside the function.
8699 SUPPRESS-STORE means the formula should not be stored, either because
8700 it is already stored, or because it is a modified equation that should
8701 not overwrite the stored one."
8702 (interactive "P")
8703 (org-table-check-inside-data-field)
8704 (or suppress-analysis (org-table-get-specials))
8705 (if (equal arg '(16))
8706 (let ((eq (org-table-current-field-formula)))
8707 (or eq (error "No equation active for current field"))
8708 (org-table-get-field nil eq)
8709 (org-table-align)
8710 (setq org-table-may-need-update t))
8711 (let* (fields
8712 (ndown (if (integerp arg) arg 1))
8713 (org-table-automatic-realign nil)
8714 (case-fold-search nil)
8715 (down (> ndown 1))
8716 (formula (if (and equation suppress-store)
8717 equation
8718 (org-table-get-formula equation (equal arg '(4)))))
8719 (n0 (org-table-current-column))
8720 (modes (copy-sequence org-calc-default-modes))
8721 (numbers nil) ; was a variable, now fixed default
8722 (keep-empty nil)
8723 n form form0 bw fmt x ev orig c lispp literal)
8724 ;; Parse the format string. Since we have a lot of modes, this is
8725 ;; a lot of work. However, I think calc still uses most of the time.
8726 (if (string-match ";" formula)
8727 (let ((tmp (org-split-string formula ";")))
8728 (setq formula (car tmp)
8729 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8730 (nth 1 tmp)))
8731 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8732 (setq c (string-to-char (match-string 1 fmt))
8733 n (string-to-number (match-string 2 fmt)))
8734 (if (= c ?p)
8735 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8736 (setq modes (org-set-calc-mode
8737 'calc-float-format
8738 (list (cdr (assoc c '((?n . float) (?f . fix)
8739 (?s . sci) (?e . eng))))
8740 n))))
8741 (setq fmt (replace-match "" t t fmt)))
8742 (if (string-match "[NT]" fmt)
8743 (setq numbers (equal (match-string 0 fmt) "N")
8744 fmt (replace-match "" t t fmt)))
8745 (if (string-match "L" fmt)
8746 (setq literal t
8747 fmt (replace-match "" t t fmt)))
8748 (if (string-match "E" fmt)
8749 (setq keep-empty t
8750 fmt (replace-match "" t t fmt)))
8751 (while (string-match "[DRFS]" fmt)
8752 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8753 (setq fmt (replace-match "" t t fmt)))
8754 (unless (string-match "\\S-" fmt)
8755 (setq fmt nil))))
8756 (if (and (not suppress-const) org-table-formula-use-constants)
8757 (setq formula (org-table-formula-substitute-names formula)))
8758 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8759 (while (> ndown 0)
8760 (setq fields (org-split-string
8761 (org-no-properties
8762 (buffer-substring (point-at-bol) (point-at-eol)))
8763 " *| *"))
8764 (if (eq numbers t)
8765 (setq fields (mapcar
8766 (lambda (x) (number-to-string (string-to-number x)))
8767 fields)))
8768 (setq ndown (1- ndown))
8769 (setq form (copy-sequence formula)
8770 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8771 (if (and lispp literal) (setq lispp 'literal))
8772 ;; Check for old vertical references
8773 (setq form (org-rewrite-old-row-references form))
8774 ;; Insert complex ranges
8775 (while (string-match org-table-range-regexp form)
8776 (setq form
8777 (replace-match
8778 (save-match-data
8779 (org-table-make-reference
8780 (org-table-get-range (match-string 0 form) nil n0)
8781 keep-empty numbers lispp))
8782 t t form)))
8783 ;; Insert simple ranges
8784 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8785 (setq form
8786 (replace-match
8787 (save-match-data
8788 (org-table-make-reference
8789 (org-sublist
8790 fields (string-to-number (match-string 1 form))
8791 (string-to-number (match-string 2 form)))
8792 keep-empty numbers lispp))
8793 t t form)))
8794 (setq form0 form)
8795 ;; Insert the references to fields in same row
8796 (while (string-match "\\$\\([0-9]+\\)" form)
8797 (setq n (string-to-number (match-string 1 form))
8798 x (nth (1- (if (= n 0) n0 n)) fields))
8799 (unless x (error "Invalid field specifier \"%s\""
8800 (match-string 0 form)))
8801 (setq form (replace-match
8802 (save-match-data
8803 (org-table-make-reference x nil numbers lispp))
8804 t t form)))
8806 (if lispp
8807 (setq ev (condition-case nil
8808 (eval (eval (read form)))
8809 (error "#ERROR"))
8810 ev (if (numberp ev) (number-to-string ev) ev))
8811 (or (fboundp 'calc-eval)
8812 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8813 (setq ev (calc-eval (cons form modes)
8814 (if numbers 'num))))
8816 (when org-table-formula-debug
8817 (with-output-to-temp-buffer "*Substitution History*"
8818 (princ (format "Substitution history of formula
8819 Orig: %s
8820 $xyz-> %s
8821 @r$c-> %s
8822 $1-> %s\n" orig formula form0 form))
8823 (if (listp ev)
8824 (princ (format " %s^\nError: %s"
8825 (make-string (car ev) ?\-) (nth 1 ev)))
8826 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8827 ev (or fmt "NONE")
8828 (if fmt (format fmt (string-to-number ev)) ev)))))
8829 (setq bw (get-buffer-window "*Substitution History*"))
8830 (shrink-window-if-larger-than-buffer bw)
8831 (unless (and (interactive-p) (not ndown))
8832 (unless (let (inhibit-redisplay)
8833 (y-or-n-p "Debugging Formula. Continue to next? "))
8834 (org-table-align)
8835 (error "Abort"))
8836 (delete-window bw)
8837 (message "")))
8838 (if (listp ev) (setq fmt nil ev "#ERROR"))
8839 (org-table-justify-field-maybe
8840 (if fmt (format fmt (string-to-number ev)) ev))
8841 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8842 (call-interactively 'org-return)
8843 (setq ndown 0)))
8844 (and down (org-table-maybe-recalculate-line))
8845 (or suppress-align (and org-table-may-need-update
8846 (org-table-align))))))
8848 (defun org-table-put-field-property (prop value)
8849 (save-excursion
8850 (put-text-property (progn (skip-chars-backward "^|") (point))
8851 (progn (skip-chars-forward "^|") (point))
8852 prop value)))
8854 (defun org-table-get-range (desc &optional tbeg col highlight)
8855 "Get a calc vector from a column, accorting to descriptor DESC.
8856 Optional arguments TBEG and COL can give the beginning of the table and
8857 the current column, to avoid unnecessary parsing.
8858 HIGHLIGHT means, just highlight the range."
8859 (if (not (equal (string-to-char desc) ?@))
8860 (setq desc (concat "@" desc)))
8861 (save-excursion
8862 (or tbeg (setq tbeg (org-table-begin)))
8863 (or col (setq col (org-table-current-column)))
8864 (let ((thisline (org-current-line))
8865 beg end c1 c2 r1 r2 rangep tmp)
8866 (unless (string-match org-table-range-regexp desc)
8867 (error "Invalid table range specifier `%s'" desc))
8868 (setq rangep (match-end 3)
8869 r1 (and (match-end 1) (match-string 1 desc))
8870 r2 (and (match-end 4) (match-string 4 desc))
8871 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8872 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8874 (and c1 (setq c1 (+ (string-to-number c1)
8875 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
8876 (and c2 (setq c2 (+ (string-to-number c2)
8877 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
8878 (if (equal r1 "") (setq r1 nil))
8879 (if (equal r2 "") (setq r2 nil))
8880 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
8881 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
8882 ; (setq r2 (or r2 r1) c2 (or c2 c1))
8883 (if (not r1) (setq r1 thisline))
8884 (if (not r2) (setq r2 thisline))
8885 (if (not c1) (setq c1 col))
8886 (if (not c2) (setq c2 col))
8887 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
8888 ;; just one field
8889 (progn
8890 (goto-line r1)
8891 (while (not (looking-at org-table-dataline-regexp))
8892 (beginning-of-line 2))
8893 (prog1 (org-trim (org-table-get-field c1))
8894 (if highlight (org-table-highlight-rectangle (point) (point)))))
8895 ;; A range, return a vector
8896 ;; First sort the numbers to get a regular ractangle
8897 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
8898 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
8899 (goto-line r1)
8900 (while (not (looking-at org-table-dataline-regexp))
8901 (beginning-of-line 2))
8902 (org-table-goto-column c1)
8903 (setq beg (point))
8904 (goto-line r2)
8905 (while (not (looking-at org-table-dataline-regexp))
8906 (beginning-of-line 0))
8907 (org-table-goto-column c2)
8908 (setq end (point))
8909 (if highlight
8910 (org-table-highlight-rectangle
8911 beg (progn (skip-chars-forward "^|\n") (point))))
8912 ;; return string representation of calc vector
8913 (mapcar 'org-trim
8914 (apply 'append (org-table-copy-region beg end)))))))
8916 (defun org-table-get-descriptor-line (desc &optional cline bline table)
8917 "Analyze descriptor DESC and retrieve the corresponding line number.
8918 The cursor is currently in line CLINE, the table begins in line BLINE,
8919 and TABLE is a vector with line types."
8920 (if (string-match "^[0-9]+$" desc)
8921 (aref org-table-dlines (string-to-number desc))
8922 (setq cline (or cline (org-current-line))
8923 bline (or bline org-table-current-begin-line)
8924 table (or table org-table-current-line-types))
8925 (if (or
8926 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8927 ;; 1 2 3 4 5 6
8928 (and (not (match-end 3)) (not (match-end 6)))
8929 (and (match-end 3) (match-end 6) (not (match-end 5))))
8930 (error "invalid row descriptor `%s'" desc))
8931 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8932 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8933 (odir (and (match-end 5) (match-string 5 desc)))
8934 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8935 (i (- cline bline))
8936 (rel (and (match-end 6)
8937 (or (and (match-end 1) (not (match-end 3)))
8938 (match-end 5)))))
8939 (if (and hn (not hdir))
8940 (progn
8941 (setq i 0 hdir "+")
8942 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8943 (if (and (not hn) on (not odir))
8944 (error "should never happen");;(aref org-table-dlines on)
8945 (if (and hn (> hn 0))
8946 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8947 (if on
8948 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8949 (+ bline i)))))
8951 (defun org-find-row-type (table i type backwards relative n)
8952 (let ((l (length table)))
8953 (while (> n 0)
8954 (while (and (setq i (+ i (if backwards -1 1)))
8955 (>= i 0) (< i l)
8956 (not (eq (aref table i) type))
8957 (if (and relative (eq (aref table i) 'hline))
8958 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8959 t)))
8960 (setq n (1- n)))
8961 (if (or (< i 0) (>= i l))
8962 (error "Row descriptior leads outside table")
8963 i)))
8965 (defun org-rewrite-old-row-references (s)
8966 (if (string-match "&[-+0-9I]" s)
8967 (error "Formula contains old &row reference, please rewrite using @-syntax")
8970 (defun org-table-make-reference (elements keep-empty numbers lispp)
8971 "Convert list ELEMENTS to something appropriate to insert into formula.
8972 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8973 NUMBERS indicates that everything should be converted to numbers.
8974 LISPP means to return something appropriate for a Lisp list."
8975 (if (stringp elements) ; just a single val
8976 (if lispp
8977 (if (eq lispp 'literal)
8978 elements
8979 (prin1-to-string (if numbers (string-to-number elements) elements)))
8980 (if (equal elements "") (setq elements "0"))
8981 (if numbers (number-to-string (string-to-number elements)) elements))
8982 (unless keep-empty
8983 (setq elements
8984 (delq nil
8985 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
8986 elements))))
8987 (setq elements (or elements '("0")))
8988 (if lispp
8989 (mapconcat
8990 (lambda (x)
8991 (if (eq lispp 'literal)
8993 (prin1-to-string (if numbers (string-to-number x) x))))
8994 elements " ")
8995 (concat "[" (mapconcat
8996 (lambda (x)
8997 (if numbers (number-to-string (string-to-number x)) x))
8998 elements
8999 ",") "]"))))
9001 (defun org-table-recalculate (&optional all noalign)
9002 "Recalculate the current table line by applying all stored formulas.
9003 With prefix arg ALL, do this for all lines in the table."
9004 (interactive "P")
9005 (or (memq this-command org-recalc-commands)
9006 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9007 (unless (org-at-table-p) (error "Not at a table"))
9008 (if (equal all '(16))
9009 (org-table-iterate)
9010 (org-table-get-specials)
9011 (let* ((eqlist (sort (org-table-get-stored-formulas)
9012 (lambda (a b) (string< (car a) (car b)))))
9013 (inhibit-redisplay (not debug-on-error))
9014 (line-re org-table-dataline-regexp)
9015 (thisline (org-current-line))
9016 (thiscol (org-table-current-column))
9017 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9018 ;; Insert constants in all formulas
9019 (setq eqlist
9020 (mapcar (lambda (x)
9021 (setcdr x (org-table-formula-substitute-names (cdr x)))
9023 eqlist))
9024 ;; Split the equation list
9025 (while (setq eq (pop eqlist))
9026 (if (<= (string-to-char (car eq)) ?9)
9027 (push eq eqlnum)
9028 (push eq eqlname)))
9029 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9030 (if all
9031 (progn
9032 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9033 (goto-char (setq beg (org-table-begin)))
9034 (if (re-search-forward org-table-calculate-mark-regexp end t)
9035 ;; This is a table with marked lines, compute selected lines
9036 (setq line-re org-table-recalculate-regexp)
9037 ;; Move forward to the first non-header line
9038 (if (and (re-search-forward org-table-dataline-regexp end t)
9039 (re-search-forward org-table-hline-regexp end t)
9040 (re-search-forward org-table-dataline-regexp end t))
9041 (setq beg (match-beginning 0))
9042 nil))) ;; just leave beg where it is
9043 (setq beg (point-at-bol)
9044 end (move-marker (make-marker) (1+ (point-at-eol)))))
9045 (goto-char beg)
9046 (and all (message "Re-applying formulas to full table..."))
9048 ;; First find the named fields, and mark them untouchanble
9049 (remove-text-properties beg end '(org-untouchable t))
9050 (while (setq eq (pop eqlname))
9051 (setq name (car eq)
9052 a (assoc name org-table-named-field-locations))
9053 (and (not a)
9054 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9055 (setq a (list name
9056 (aref org-table-dlines
9057 (string-to-number (match-string 1 name)))
9058 (string-to-number (match-string 2 name)))))
9059 (when (and a (or all (equal (nth 1 a) thisline)))
9060 (message "Re-applying formula to field: %s" name)
9061 (goto-line (nth 1 a))
9062 (org-table-goto-column (nth 2 a))
9063 (push (append a (list (cdr eq))) eqlname1)
9064 ;; FIXME (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
9065 ;; FIXME 'nostore 'noanalysis)
9066 (org-table-put-field-property :org-untouchable t)))
9068 ;; Now evauluate the column formulas, but skip fields covered by
9069 ;; field formulas
9070 (goto-char beg)
9071 (while (re-search-forward line-re end t)
9072 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9073 ;; Unprotected line, recalculate
9074 (and all (message "Re-applying formulas to full table...(line %d)"
9075 (setq cnt (1+ cnt))))
9076 (setq org-last-recalc-line (org-current-line))
9077 (setq eql eqlnum)
9078 (while (setq entry (pop eql))
9079 (goto-line org-last-recalc-line)
9080 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9081 (unless (get-text-property (point) :org-untouchable)
9082 (org-table-eval-formula nil (cdr entry)
9083 'noalign 'nocst 'nostore 'noanalysis)))))
9085 ;; Now evaluate the field formulas
9086 (while (setq eq (pop eqlname1))
9087 (message "Re-applying formula to field: %s" (car eq))
9088 (goto-line (nth 1 eq))
9089 (org-table-goto-column (nth 2 eq))
9090 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9091 'nostore 'noanalysis))
9093 (goto-line thisline)
9094 (org-table-goto-column thiscol)
9095 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9096 (or noalign (and org-table-may-need-update (org-table-align))
9097 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9099 ;; back to initial position
9100 (message "Re-applying formulas...done")
9101 (goto-line thisline)
9102 (org-table-goto-column thiscol)
9103 (or noalign (and org-table-may-need-update (org-table-align))
9104 (and all (message "Re-applying formulas...done"))))))
9106 (defun org-table-iterate (&optional arg)
9107 "Recalculate the table until it does not change anymore."
9108 (interactive "P")
9109 (let ((imax (if arg (prefix-numeric-value arg) 10))
9110 (i 0)
9111 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9112 thistbl)
9113 (catch 'exit
9114 (while (< i imax)
9115 (setq i (1+ i))
9116 (org-table-recalculate 'all)
9117 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9118 (if (not (string= lasttbl thistbl))
9119 (setq lasttbl thistbl)
9120 (if (> i 1)
9121 (message "Convergence after %d iterations" i)
9122 (message "Table was already stable"))
9123 (throw 'exit t)))
9124 (error "No convergence after %d iterations" i))))
9126 (defun org-table-formula-substitute-names (f)
9127 "Replace $const with values in string F."
9128 (let ((start 0) a (f1 f))
9129 ;; First, check for column names
9130 (while (setq start (string-match org-table-column-name-regexp f start))
9131 (setq start (1+ start))
9132 (setq a (assoc (match-string 1 f) org-table-column-names))
9133 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9134 ;; Parameters and constants
9135 (setq start 0)
9136 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9137 (setq start (1+ start))
9138 (if (setq a (save-match-data
9139 (org-table-get-constant (match-string 1 f))))
9140 (setq f (replace-match (concat "(" a ")") t t f))))
9141 (if org-table-formula-debug
9142 (put-text-property 0 (length f) :orig-formula f1 f))
9145 (defun org-table-get-constant (const)
9146 "Find the value for a parameter or constant in a formula.
9147 Parameters get priority."
9148 (or (cdr (assoc const org-table-local-parameters))
9149 (cdr (assoc const org-table-formula-constants-local))
9150 (cdr (assoc const org-table-formula-constants))
9151 (and (fboundp 'constants-get) (constants-get const))
9152 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9153 (org-entry-get nil (substring const 5) 'inherit))
9154 "#UNDEFINED_NAME"))
9156 (defvar org-table-fedit-map
9157 (let ((map (make-sparse-keymap)))
9158 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9159 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9160 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9161 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9162 (org-defkey map "\C-c?" 'org-table-show-reference)
9163 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9164 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9165 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9166 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9167 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9168 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9169 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9170 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9171 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9172 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9173 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9174 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9175 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9176 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9177 map))
9179 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9180 '("Edit-Formulas"
9181 ["Finish and Install" org-table-fedit-finish t]
9182 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9183 ["Abort" org-table-fedit-abort t]
9184 "--"
9185 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9186 ["Complete Lisp Symbol" lisp-complete-symbol t]
9187 "--"
9188 "Shift Reference at Point"
9189 ["Up" org-table-fedit-ref-up t]
9190 ["Down" org-table-fedit-ref-down t]
9191 ["Left" org-table-fedit-ref-left t]
9192 ["Right" org-table-fedit-ref-right t]
9194 "Change Test Row for Column Formulas"
9195 ["Up" org-table-fedit-line-up t]
9196 ["Down" org-table-fedit-line-down t]
9197 "--"
9198 ["Scroll Table Window" org-table-fedit-scroll t]
9199 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9200 ["Show Table Grid" org-table-fedit-toggle-coordinates
9201 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9202 org-table-overlay-coordinates)]
9203 "--"
9204 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9205 :style toggle :selected org-table-buffer-is-an]))
9207 (defvar org-pos)
9209 (defun org-table-edit-formulas ()
9210 "Edit the formulas of the current table in a separate buffer."
9211 (interactive)
9212 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9213 (beginning-of-line 0))
9214 (unless (org-at-table-p) (error "Not at a table"))
9215 (org-table-get-specials)
9216 (let ((key (org-table-current-field-formula 'key 'noerror))
9217 (eql (sort (org-table-get-stored-formulas 'noerror)
9218 'org-table-formula-less-p))
9219 (pos (move-marker (make-marker) (point)))
9220 (startline 1)
9221 (wc (current-window-configuration))
9222 (titles '((column . "# Column Formulas\n")
9223 (field . "# Field Formulas\n")
9224 (named . "# Named Field Formulas\n")))
9225 entry s type title)
9226 (switch-to-buffer-other-window "*Edit Formulas*")
9227 (erase-buffer)
9228 ;; Keep global-font-lock-mode from turning on font-lock-mode
9229 (let ((font-lock-global-modes '(not fundamental-mode)))
9230 (fundamental-mode))
9231 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9232 (org-set-local 'org-pos pos)
9233 (org-set-local 'org-window-configuration wc)
9234 (use-local-map org-table-fedit-map)
9235 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9236 (easy-menu-add org-table-fedit-menu)
9237 (setq startline (org-current-line))
9238 (while (setq entry (pop eql))
9239 (setq type (cond
9240 ((equal (string-to-char (car entry)) ?@) 'field)
9241 ((string-match "^[0-9]" (car entry)) 'column)
9242 (t 'named)))
9243 (when (setq title (assq type titles))
9244 (or (bobp) (insert "\n"))
9245 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9246 (setq titles (delq title titles)))
9247 (if (equal key (car entry)) (setq startline (org-current-line)))
9248 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9249 (car entry) " = " (cdr entry) "\n"))
9250 (remove-text-properties 0 (length s) '(face nil) s)
9251 (insert s))
9252 (if (eq org-table-use-standard-references t)
9253 (org-table-fedit-toggle-ref-type))
9254 (goto-line startline)
9255 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9257 (defun org-table-fedit-post-command ()
9258 (when (not (memq this-command '(lisp-complete-symbol)))
9259 (let ((win (selected-window)))
9260 (save-excursion
9261 (condition-case nil
9262 (org-table-show-reference)
9263 (error nil))
9264 (select-window win)))))
9266 (defun org-table-formula-to-user (s)
9267 "Convert a formula from internal to user representation."
9268 (if (eq org-table-use-standard-references t)
9269 (org-table-convert-refs-to-an s)
9272 (defun org-table-formula-from-user (s)
9273 "Convert a formula from user to internal representation."
9274 (if org-table-use-standard-references
9275 (org-table-convert-refs-to-rc s)
9278 (defun org-table-convert-refs-to-rc (s)
9279 "Convert spreadsheet references from AB7 to @7$28.
9280 Works for single references, but also for entire formulas and even the
9281 full TBLFM line."
9282 (let ((start 0))
9283 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9284 (cond
9285 ((match-end 3)
9286 ;; format match, just advance
9287 (setq start (match-end 0)))
9288 ((and (> (match-beginning 0) 0)
9289 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9290 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9291 ;; 3.e5 or something like this. FIXME: is this ok????
9292 (setq start (match-end 0)))
9294 (setq start (match-beginning 0)
9295 s (replace-match
9296 (if (equal (match-string 2 s) "&")
9297 (format "$%d" (org-letters-to-number (match-string 1 s)))
9298 (format "@%d$%d"
9299 (string-to-number (match-string 2 s))
9300 (org-letters-to-number (match-string 1 s))))
9301 t t s)))))
9304 (defun org-table-convert-refs-to-an (s)
9305 "Convert spreadsheet references from to @7$28 to AB7.
9306 Works for single references, but also for entire formulas and even the
9307 full TBLFM line."
9308 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9309 (setq s (replace-match
9310 (format "%s%d"
9311 (org-number-to-letters
9312 (string-to-number (match-string 2 s)))
9313 (string-to-number (match-string 1 s)))
9314 t t s)))
9315 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9316 (setq s (replace-match (concat "\\1"
9317 (org-number-to-letters
9318 (string-to-number (match-string 2 s))) "&")
9319 t nil s)))
9322 (defun org-letters-to-number (s)
9323 "Convert a base 26 number represented by letters into an integer.
9324 For example: AB -> 28."
9325 (let ((n 0))
9326 (setq s (upcase s))
9327 (while (> (length s) 0)
9328 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9329 s (substring s 1)))
9332 (defun org-number-to-letters (n)
9333 "Convert an integer into a base 26 number represented by letters.
9334 For example: 28 -> AB."
9335 (let ((s ""))
9336 (while (> n 0)
9337 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9338 n (/ (1- n) 26)))
9341 (defun org-table-fedit-convert-buffer (function)
9342 "Convert all references in this buffer, using FUNTION."
9343 (let ((line (org-current-line)))
9344 (goto-char (point-min))
9345 (while (not (eobp))
9346 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9347 (delete-region (point) (point-at-eol))
9348 (or (eobp) (forward-char 1)))
9349 (goto-line line)))
9351 (defun org-table-fedit-toggle-ref-type ()
9352 "Convert all references in the buffer from B3 to @3$2 and back."
9353 (interactive)
9354 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9355 (org-table-fedit-convert-buffer
9356 (if org-table-buffer-is-an
9357 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9358 (message "Reference type switched to %s"
9359 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9361 (defun org-table-fedit-ref-up ()
9362 "Shift the reference at point one row/hline up."
9363 (interactive)
9364 (org-table-fedit-shift-reference 'up))
9365 (defun org-table-fedit-ref-down ()
9366 "Shift the reference at point one row/hline down."
9367 (interactive)
9368 (org-table-fedit-shift-reference 'down))
9369 (defun org-table-fedit-ref-left ()
9370 "Shift the reference at point one field to the left."
9371 (interactive)
9372 (org-table-fedit-shift-reference 'left))
9373 (defun org-table-fedit-ref-right ()
9374 "Shift the reference at point one field to the right."
9375 (interactive)
9376 (org-table-fedit-shift-reference 'right))
9378 (defun org-table-fedit-shift-reference (dir)
9379 (cond
9380 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9381 (if (memq dir '(left right))
9382 (org-rematch-and-replace 1 (eq dir 'left))
9383 (error "Cannot shift reference in this direction")))
9384 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9385 ;; A B3-like reference
9386 (if (memq dir '(up down))
9387 (org-rematch-and-replace 2 (eq dir 'up))
9388 (org-rematch-and-replace 1 (eq dir 'left))))
9389 ((org-at-regexp-p
9390 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9391 ;; An internal reference
9392 (if (memq dir '(up down))
9393 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9394 (org-rematch-and-replace 5 (eq dir 'left))))))
9396 (defun org-rematch-and-replace (n &optional decr hline)
9397 "Re-match the group N, and replace it with the shifted refrence."
9398 (or (match-end n) (error "Cannot shift reference in this direction"))
9399 (goto-char (match-beginning n))
9400 (and (looking-at (regexp-quote (match-string n)))
9401 (replace-match (org-shift-refpart (match-string 0) decr hline)
9402 t t)))
9404 (defun org-shift-refpart (ref &optional decr hline)
9405 "Shift a refrence part REF.
9406 If DECR is set, decrease the references row/column, else increase.
9407 If HLINE is set, this may be a hline reference, it certainly is not
9408 a translation reference."
9409 (save-match-data
9410 (let* ((sign (string-match "^[-+]" ref)) n)
9412 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9413 (cond
9414 ((and hline (string-match "^I+" ref))
9415 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9416 (setq n (+ n (if decr -1 1)))
9417 (if (= n 0) (setq n (+ n (if decr -1 1))))
9418 (if sign
9419 (setq sign (if (< n 0) "-" "+") n (abs n))
9420 (setq n (max 1 n)))
9421 (concat sign (make-string n ?I)))
9423 ((string-match "^[0-9]+" ref)
9424 (setq n (string-to-number (concat sign ref)))
9425 (setq n (+ n (if decr -1 1)))
9426 (if sign
9427 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9428 (number-to-string (max 1 n))))
9430 ((string-match "^[a-zA-Z]+" ref)
9431 (org-number-to-letters
9432 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9434 (t (error "Cannot shift reference"))))))
9436 (defun org-table-fedit-toggle-coordinates ()
9437 "Toggle the display of coordinates in the refrenced table."
9438 (interactive)
9439 (let ((pos (marker-position org-pos)))
9440 (with-current-buffer (marker-buffer org-pos)
9441 (save-excursion
9442 (goto-char pos)
9443 (org-table-toggle-coordinate-overlays)))))
9445 (defun org-table-fedit-finish (&optional arg)
9446 "Parse the buffer for formula definitions and install them.
9447 With prefix ARG, apply the new formulas to the table."
9448 (interactive "P")
9449 (org-table-remove-rectangle-highlight)
9450 (if org-table-use-standard-references
9451 (progn
9452 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9453 (setq org-table-buffer-is-an nil)))
9454 (let ((pos org-pos) eql var form)
9455 (goto-char (point-min))
9456 (while (re-search-forward
9457 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9458 nil t)
9459 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9460 form (match-string 3))
9461 (setq form (org-trim form))
9462 (when (not (equal form ""))
9463 (while (string-match "[ \t]*\n[ \t]*" form)
9464 (setq form (replace-match " " t t form)))
9465 (when (assoc var eql)
9466 (error "Double formulas for %s" var))
9467 (push (cons var form) eql)))
9468 (setq org-pos nil)
9469 (set-window-configuration org-window-configuration)
9470 (select-window (get-buffer-window (marker-buffer pos)))
9471 (goto-char pos)
9472 (unless (org-at-table-p)
9473 (error "Lost table position - cannot install formulae"))
9474 (org-table-store-formulas eql)
9475 (move-marker pos nil)
9476 (kill-buffer "*Edit Formulas*")
9477 (if arg
9478 (org-table-recalculate 'all)
9479 (message "New formulas installed - press C-u C-c C-c to apply."))))
9481 (defun org-table-fedit-abort ()
9482 "Abort editing formulas, without installing the changes."
9483 (interactive)
9484 (org-table-remove-rectangle-highlight)
9485 (let ((pos org-pos))
9486 (set-window-configuration org-window-configuration)
9487 (select-window (get-buffer-window (marker-buffer pos)))
9488 (goto-char pos)
9489 (move-marker pos nil)
9490 (message "Formula editing aborted without installing changes")))
9492 (defun org-table-fedit-lisp-indent ()
9493 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9494 (interactive)
9495 (let ((pos (point)) beg end ind)
9496 (beginning-of-line 1)
9497 (cond
9498 ((looking-at "[ \t]")
9499 (goto-char pos)
9500 (call-interactively 'lisp-indent-line))
9501 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9502 ((not (fboundp 'pp-buffer))
9503 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9504 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9505 (goto-char (- (match-end 0) 2))
9506 (setq beg (point))
9507 (setq ind (make-string (current-column) ?\ ))
9508 (condition-case nil (forward-sexp 1)
9509 (error
9510 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9511 (setq end (point))
9512 (save-restriction
9513 (narrow-to-region beg end)
9514 (if (eq last-command this-command)
9515 (progn
9516 (goto-char (point-min))
9517 (setq this-command nil)
9518 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9519 (replace-match " ")))
9520 (pp-buffer)
9521 (untabify (point-min) (point-max))
9522 (goto-char (1+ (point-min)))
9523 (while (re-search-forward "^." nil t)
9524 (beginning-of-line 1)
9525 (insert ind))
9526 (goto-char (point-max))
9527 (backward-delete-char 1)))
9528 (goto-char beg))
9529 (t nil))))
9531 (defvar org-show-positions nil)
9533 (defun org-table-show-reference (&optional local)
9534 "Show the location/value of the $ expression at point."
9535 (interactive)
9536 (org-table-remove-rectangle-highlight)
9537 (catch 'exit
9538 (let ((pos (if local (point) org-pos))
9539 (face2 'highlight)
9540 (org-inhibit-highlight-removal t)
9541 (win (selected-window))
9542 (org-show-positions nil)
9543 var name e what match dest)
9544 (if local (org-table-get-specials))
9545 (setq what (cond
9546 ((or (org-at-regexp-p org-table-range-regexp2)
9547 (org-at-regexp-p org-table-translate-regexp)
9548 (org-at-regexp-p org-table-range-regexp))
9549 (setq match
9550 (save-match-data
9551 (org-table-convert-refs-to-rc (match-string 0))))
9552 'range)
9553 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9554 ((org-at-regexp-p "\\$[0-9]+") 'column)
9555 ((not local) nil)
9556 (t (error "No reference at point")))
9557 match (and what (or match (match-string 0))))
9558 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9559 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9560 'secondary-selection))
9561 (org-add-hook 'before-change-functions
9562 'org-table-remove-rectangle-highlight)
9563 (if (eq what 'name) (setq var (substring match 1)))
9564 (when (eq what 'range)
9565 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9566 (setq match (org-table-formula-substitute-names match)))
9567 (unless local
9568 (save-excursion
9569 (end-of-line 1)
9570 (re-search-backward "^\\S-" nil t)
9571 (beginning-of-line 1)
9572 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9573 (setq dest
9574 (save-match-data
9575 (org-table-convert-refs-to-rc (match-string 1))))
9576 (org-table-add-rectangle-overlay
9577 (match-beginning 1) (match-end 1) face2))))
9578 (if (and (markerp pos) (marker-buffer pos))
9579 (if (get-buffer-window (marker-buffer pos))
9580 (select-window (get-buffer-window (marker-buffer pos)))
9581 (switch-to-buffer-other-window (get-buffer-window
9582 (marker-buffer pos)))))
9583 (goto-char pos)
9584 (org-table-force-dataline)
9585 (when dest
9586 (setq name (substring dest 1))
9587 (cond
9588 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9589 (setq e (assoc name org-table-named-field-locations))
9590 (goto-line (nth 1 e))
9591 (org-table-goto-column (nth 2 e)))
9592 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9593 (let ((l (string-to-number (match-string 1 dest)))
9594 (c (string-to-number (match-string 2 dest))))
9595 (goto-line (aref org-table-dlines l))
9596 (org-table-goto-column c)))
9597 (t (org-table-goto-column (string-to-number name))))
9598 (move-marker pos (point))
9599 (org-table-highlight-rectangle nil nil face2))
9600 (cond
9601 ((equal dest match))
9602 ((not match))
9603 ((eq what 'range)
9604 (condition-case nil
9605 (save-excursion
9606 (org-table-get-range match nil nil 'highlight))
9607 (error nil)))
9608 ((setq e (assoc var org-table-named-field-locations))
9609 (goto-line (nth 1 e))
9610 (org-table-goto-column (nth 2 e))
9611 (org-table-highlight-rectangle (point) (point))
9612 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9613 ((setq e (assoc var org-table-column-names))
9614 (org-table-goto-column (string-to-number (cdr e)))
9615 (org-table-highlight-rectangle (point) (point))
9616 (goto-char (org-table-begin))
9617 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9618 (org-table-end) t)
9619 (progn
9620 (goto-char (match-beginning 1))
9621 (org-table-highlight-rectangle)
9622 (message "Named column (column %s)" (cdr e)))
9623 (error "Column name not found")))
9624 ((eq what 'column)
9625 ;; column number
9626 (org-table-goto-column (string-to-number (substring match 1)))
9627 (org-table-highlight-rectangle (point) (point))
9628 (message "Column %s" (substring match 1)))
9629 ((setq e (assoc var org-table-local-parameters))
9630 (goto-char (org-table-begin))
9631 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9632 (progn
9633 (goto-char (match-beginning 1))
9634 (org-table-highlight-rectangle)
9635 (message "Local parameter."))
9636 (error "Parameter not found")))
9638 (cond
9639 ((not var) (error "No reference at point"))
9640 ((setq e (assoc var org-table-formula-constants-local))
9641 (message "Local Constant: $%s=%s in #+CONSTANTS line."
9642 var (cdr e)))
9643 ((setq e (assoc var org-table-formula-constants))
9644 (message "Constant: $%s=%s in `org-table-formula-constants'."
9645 var (cdr e)))
9646 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9647 (message "Constant: $%s=%s, from `constants.el'%s."
9648 var e (format " (%s units)" constants-unit-system)))
9649 (t (error "Undefined name $%s" var)))))
9650 (goto-char pos)
9651 (when (and org-show-positions
9652 (not (memq this-command '(org-table-fedit-scroll
9653 org-table-fedit-scroll-down))))
9654 (push pos org-show-positions)
9655 (push org-table-current-begin-pos org-show-positions)
9656 (let ((min (apply 'min org-show-positions))
9657 (max (apply 'max org-show-positions)))
9658 (goto-char min) (recenter 0)
9659 (goto-char max)
9660 (or (pos-visible-in-window-p max) (recenter -1))))
9661 (select-window win))))
9663 (defun org-table-force-dataline ()
9664 "Make sure the cursor is in a dataline in a table."
9665 (unless (save-excursion
9666 (beginning-of-line 1)
9667 (looking-at org-table-dataline-regexp))
9668 (let* ((re org-table-dataline-regexp)
9669 (p1 (save-excursion (re-search-forward re nil 'move)))
9670 (p2 (save-excursion (re-search-backward re nil 'move))))
9671 (cond ((and p1 p2)
9672 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9673 p1 p2)))
9674 ((or p1 p2) (goto-char (or p1 p2)))
9675 (t (error "No table dataline around here"))))))
9677 (defun org-table-fedit-line-up ()
9678 "Move cursor one line up in the window showing the table."
9679 (interactive)
9680 (org-table-fedit-move 'previous-line))
9682 (defun org-table-fedit-line-down ()
9683 "Move cursor one line down in the window showing the table."
9684 (interactive)
9685 (org-table-fedit-move 'next-line))
9687 (defun org-table-fedit-move (command)
9688 "Move the cursor in the window shoinw the table.
9689 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9690 (let ((org-table-allow-automatic-line-recalculation nil)
9691 (pos org-pos) (win (selected-window)) p)
9692 (select-window (get-buffer-window (marker-buffer org-pos)))
9693 (setq p (point))
9694 (call-interactively command)
9695 (while (and (org-at-table-p)
9696 (org-at-table-hline-p))
9697 (call-interactively command))
9698 (or (org-at-table-p) (goto-char p))
9699 (move-marker pos (point))
9700 (select-window win)))
9702 (defun org-table-fedit-scroll (N)
9703 (interactive "p")
9704 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9705 (scroll-other-window N)))
9707 (defun org-table-fedit-scroll-down (N)
9708 (interactive "p")
9709 (org-table-fedit-scroll (- N)))
9711 (defvar org-table-rectangle-overlays nil)
9713 (defun org-table-add-rectangle-overlay (beg end &optional face)
9714 "Add a new overlay."
9715 (let ((ov (org-make-overlay beg end)))
9716 (org-overlay-put ov 'face (or face 'secondary-selection))
9717 (push ov org-table-rectangle-overlays)))
9719 (defun org-table-highlight-rectangle (&optional beg end face)
9720 "Highlight rectangular region in a table."
9721 (setq beg (or beg (point)) end (or end (point)))
9722 (let ((b (min beg end))
9723 (e (max beg end))
9724 l1 c1 l2 c2 tmp)
9725 (and (boundp 'org-show-positions)
9726 (setq org-show-positions (cons b (cons e org-show-positions))))
9727 (goto-char (min beg end))
9728 (setq l1 (org-current-line)
9729 c1 (org-table-current-column))
9730 (goto-char (max beg end))
9731 (setq l2 (org-current-line)
9732 c2 (org-table-current-column))
9733 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9734 (goto-line l1)
9735 (beginning-of-line 1)
9736 (loop for line from l1 to l2 do
9737 (when (looking-at org-table-dataline-regexp)
9738 (org-table-goto-column c1)
9739 (skip-chars-backward "^|\n") (setq beg (point))
9740 (org-table-goto-column c2)
9741 (skip-chars-forward "^|\n") (setq end (point))
9742 (org-table-add-rectangle-overlay beg end face))
9743 (beginning-of-line 2))
9744 (goto-char b))
9745 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9747 (defun org-table-remove-rectangle-highlight (&rest ignore)
9748 "Remove the rectangle overlays."
9749 (unless org-inhibit-highlight-removal
9750 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9751 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9752 (setq org-table-rectangle-overlays nil)))
9754 (defvar org-table-coordinate-overlays nil
9755 "Collects the cooordinate grid overlays, so that they can be removed.")
9756 (make-variable-buffer-local 'org-table-coordinate-overlays)
9758 (defun org-table-overlay-coordinates ()
9759 "Add overlays to the table at point, to show row/column coordinates."
9760 (interactive)
9761 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9762 (setq org-table-coordinate-overlays nil)
9763 (save-excursion
9764 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9765 (goto-char (org-table-begin))
9766 (while (org-at-table-p)
9767 (setq eol (point-at-eol))
9768 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9769 (push ov org-table-coordinate-overlays)
9770 (setq hline (looking-at org-table-hline-regexp))
9771 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9772 (format "%4d" (setq id (1+ id)))))
9773 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9774 (when hline
9775 (setq ic 0)
9776 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9777 (setq beg (1+ (match-beginning 0))
9778 ic (1+ ic)
9779 s1 (concat "$" (int-to-string ic))
9780 s2 (org-number-to-letters ic)
9781 str (if (eq org-table-use-standard-references t) s2 s1))
9782 (setq ov (org-make-overlay beg (+ beg (length str))))
9783 (push ov org-table-coordinate-overlays)
9784 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9785 (beginning-of-line 2)))))
9787 (defun org-table-toggle-coordinate-overlays ()
9788 "Toggle the display of Row/Column numbers in tables."
9789 (interactive)
9790 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9791 (message "Row/Column number display turned %s"
9792 (if org-table-overlay-coordinates "on" "off"))
9793 (if (and (org-at-table-p) org-table-overlay-coordinates)
9794 (org-table-align))
9795 (unless org-table-overlay-coordinates
9796 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9797 (setq org-table-coordinate-overlays nil)))
9799 (defun org-table-toggle-formula-debugger ()
9800 "Toggle the formula debugger in tables."
9801 (interactive)
9802 (setq org-table-formula-debug (not org-table-formula-debug))
9803 (message "Formula debugging has been turned %s"
9804 (if org-table-formula-debug "on" "off")))
9806 ;;; The orgtbl minor mode
9808 ;; Define a minor mode which can be used in other modes in order to
9809 ;; integrate the org-mode table editor.
9811 ;; This is really a hack, because the org-mode table editor uses several
9812 ;; keys which normally belong to the major mode, for example the TAB and
9813 ;; RET keys. Here is how it works: The minor mode defines all the keys
9814 ;; necessary to operate the table editor, but wraps the commands into a
9815 ;; function which tests if the cursor is currently inside a table. If that
9816 ;; is the case, the table editor command is executed. However, when any of
9817 ;; those keys is used outside a table, the function uses `key-binding' to
9818 ;; look up if the key has an associated command in another currently active
9819 ;; keymap (minor modes, major mode, global), and executes that command.
9820 ;; There might be problems if any of the keys used by the table editor is
9821 ;; otherwise used as a prefix key.
9823 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9824 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9825 ;; addresses this by checking explicitly for both bindings.
9827 ;; The optimized version (see variable `orgtbl-optimized') takes over
9828 ;; all keys which are bound to `self-insert-command' in the *global map*.
9829 ;; Some modes bind other commands to simple characters, for example
9830 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9831 ;; active, this binding is ignored inside tables and replaced with a
9832 ;; modified self-insert.
9834 (defvar orgtbl-mode nil
9835 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9836 table editor in arbitrary modes.")
9837 (make-variable-buffer-local 'orgtbl-mode)
9839 (defvar orgtbl-mode-map (make-keymap)
9840 "Keymap for `orgtbl-mode'.")
9842 ;;;###autoload
9843 (defun turn-on-orgtbl ()
9844 "Unconditionally turn on `orgtbl-mode'."
9845 (orgtbl-mode 1))
9847 (defvar org-old-auto-fill-inhibit-regexp nil
9848 "Local variable used by `orgtbl-mode'")
9850 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9851 "Matches a line belonging to an orgtbl.")
9853 (defconst orgtbl-extra-font-lock-keywords
9854 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9855 0 (quote 'org-table) 'prepend))
9856 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9858 ;;;###autoload
9859 (defun orgtbl-mode (&optional arg)
9860 "The `org-mode' table editor as a minor mode for use in other modes."
9861 (interactive)
9862 (if (org-mode-p)
9863 ;; Exit without error, in case some hook functions calls this
9864 ;; by accident in org-mode.
9865 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9866 (setq orgtbl-mode
9867 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9868 (if orgtbl-mode
9869 (progn
9870 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9871 ;; Make sure we are first in minor-mode-map-alist
9872 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9873 (and c (setq minor-mode-map-alist
9874 (cons c (delq c minor-mode-map-alist)))))
9875 (org-set-local (quote org-table-may-need-update) t)
9876 (org-add-hook 'before-change-functions 'org-before-change-function
9877 nil 'local)
9878 (org-set-local 'org-old-auto-fill-inhibit-regexp
9879 auto-fill-inhibit-regexp)
9880 (org-set-local 'auto-fill-inhibit-regexp
9881 (if auto-fill-inhibit-regexp
9882 (concat orgtbl-line-start-regexp "\\|"
9883 auto-fill-inhibit-regexp)
9884 orgtbl-line-start-regexp))
9885 (org-add-to-invisibility-spec '(org-cwidth))
9886 (when (fboundp 'font-lock-add-keywords)
9887 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
9888 (org-restart-font-lock))
9889 (easy-menu-add orgtbl-mode-menu)
9890 (run-hooks 'orgtbl-mode-hook))
9891 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9892 (org-cleanup-narrow-column-properties)
9893 (org-remove-from-invisibility-spec '(org-cwidth))
9894 (remove-hook 'before-change-functions 'org-before-change-function t)
9895 (when (fboundp 'font-lock-remove-keywords)
9896 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
9897 (org-restart-font-lock))
9898 (easy-menu-remove orgtbl-mode-menu)
9899 (force-mode-line-update 'all))))
9901 (defun org-cleanup-narrow-column-properties ()
9902 "Remove all properties related to narrow-column invisibility."
9903 (let ((s 1))
9904 (while (setq s (text-property-any s (point-max)
9905 'display org-narrow-column-arrow))
9906 (remove-text-properties s (1+ s) '(display t)))
9907 (setq s 1)
9908 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
9909 (remove-text-properties s (1+ s) '(org-cwidth t)))
9910 (setq s 1)
9911 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
9912 (remove-text-properties s (1+ s) '(invisible t)))))
9914 ;; Install it as a minor mode.
9915 (put 'orgtbl-mode :included t)
9916 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9917 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9919 (defun orgtbl-make-binding (fun n &rest keys)
9920 "Create a function for binding in the table minor mode.
9921 FUN is the command to call inside a table. N is used to create a unique
9922 command name. KEYS are keys that should be checked in for a command
9923 to execute outside of tables."
9924 (eval
9925 (list 'defun
9926 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9927 '(arg)
9928 (concat "In tables, run `" (symbol-name fun) "'.\n"
9929 "Outside of tables, run the binding of `"
9930 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9931 "'.")
9932 '(interactive "p")
9933 (list 'if
9934 '(org-at-table-p)
9935 (list 'call-interactively (list 'quote fun))
9936 (list 'let '(orgtbl-mode)
9937 (list 'call-interactively
9938 (append '(or)
9939 (mapcar (lambda (k)
9940 (list 'key-binding k))
9941 keys)
9942 '('orgtbl-error))))))))
9944 (defun orgtbl-error ()
9945 "Error when there is no default binding for a table key."
9946 (interactive)
9947 (error "This key is has no function outside tables"))
9949 (defun orgtbl-setup ()
9950 "Setup orgtbl keymaps."
9951 (let ((nfunc 0)
9952 (bindings
9953 (list
9954 '([(meta shift left)] org-table-delete-column)
9955 '([(meta left)] org-table-move-column-left)
9956 '([(meta right)] org-table-move-column-right)
9957 '([(meta shift right)] org-table-insert-column)
9958 '([(meta shift up)] org-table-kill-row)
9959 '([(meta shift down)] org-table-insert-row)
9960 '([(meta up)] org-table-move-row-up)
9961 '([(meta down)] org-table-move-row-down)
9962 '("\C-c\C-w" org-table-cut-region)
9963 '("\C-c\M-w" org-table-copy-region)
9964 '("\C-c\C-y" org-table-paste-rectangle)
9965 '("\C-c-" org-table-insert-hline)
9966 '("\C-c}" org-table-toggle-coordinate-overlays)
9967 '("\C-c{" org-table-toggle-formula-debugger)
9968 '("\C-m" org-table-next-row)
9969 '([(shift return)] org-table-copy-down)
9970 '("\C-c\C-q" org-table-wrap-region)
9971 '("\C-c?" org-table-field-info)
9972 '("\C-c " org-table-blank-field)
9973 '("\C-c+" org-table-sum)
9974 '("\C-c=" org-table-eval-formula)
9975 '("\C-c'" org-table-edit-formulas)
9976 '("\C-c`" org-table-edit-field)
9977 '("\C-c*" org-table-recalculate)
9978 '("\C-c|" org-table-create-or-convert-from-region)
9979 '("\C-c^" org-table-sort-lines)
9980 '([(control ?#)] org-table-rotate-recalc-marks)))
9981 elt key fun cmd)
9982 (while (setq elt (pop bindings))
9983 (setq nfunc (1+ nfunc))
9984 (setq key (org-key (car elt))
9985 fun (nth 1 elt)
9986 cmd (orgtbl-make-binding fun nfunc key))
9987 (org-defkey orgtbl-mode-map key cmd))
9989 ;; Special treatment needed for TAB and RET
9990 (org-defkey orgtbl-mode-map [(return)]
9991 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9992 (org-defkey orgtbl-mode-map "\C-m"
9993 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9995 (org-defkey orgtbl-mode-map [(tab)]
9996 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9997 (org-defkey orgtbl-mode-map "\C-i"
9998 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10000 (org-defkey orgtbl-mode-map [(shift tab)]
10001 (orgtbl-make-binding 'org-table-previous-field 104
10002 [(shift tab)] [(tab)] "\C-i"))
10004 (org-defkey orgtbl-mode-map "\M-\C-m"
10005 (orgtbl-make-binding 'org-table-wrap-region 105
10006 "\M-\C-m" [(meta return)]))
10007 (org-defkey orgtbl-mode-map [(meta return)]
10008 (orgtbl-make-binding 'org-table-wrap-region 106
10009 [(meta return)] "\M-\C-m"))
10011 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10012 (when orgtbl-optimized
10013 ;; If the user wants maximum table support, we need to hijack
10014 ;; some standard editing functions
10015 (org-remap orgtbl-mode-map
10016 'self-insert-command 'orgtbl-self-insert-command
10017 'delete-char 'org-delete-char
10018 'delete-backward-char 'org-delete-backward-char)
10019 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10020 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10021 '("OrgTbl"
10022 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10023 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10024 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10025 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10026 "--"
10027 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10028 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10029 ["Copy Field from Above"
10030 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10031 "--"
10032 ("Column"
10033 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10034 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10035 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10036 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10037 ("Row"
10038 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10039 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10040 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10041 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10042 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10043 "--"
10044 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10045 ("Rectangle"
10046 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10047 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10048 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10049 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10050 "--"
10051 ("Radio tables"
10052 ["Insert table template" orgtbl-insert-radio-table
10053 (assq major-mode orgtbl-radio-table-templates)]
10054 ["Comment/uncomment table" orgtbl-toggle-comment t])
10055 "--"
10056 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10057 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10058 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10059 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10060 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10061 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10062 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10063 ["Sum Column/Rectangle" org-table-sum
10064 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10065 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10066 ["Debug Formulas"
10067 org-table-toggle-formula-debugger :active (org-at-table-p)
10068 :keys "C-c {"
10069 :style toggle :selected org-table-formula-debug]
10070 ["Show Col/Row Numbers"
10071 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10072 :keys "C-c }"
10073 :style toggle :selected org-table-overlay-coordinates]
10077 (defun orgtbl-ctrl-c-ctrl-c (arg)
10078 "If the cursor is inside a table, realign the table.
10079 It it is a table to be sent away to a receiver, do it.
10080 With prefix arg, also recompute table."
10081 (interactive "P")
10082 (let ((pos (point)) action)
10083 (save-excursion
10084 (beginning-of-line 1)
10085 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10086 ((looking-at "[ \t]*|") pos)
10087 ((looking-at "#\\+TBLFM:") 'recalc))))
10088 (cond
10089 ((integerp action)
10090 (goto-char action)
10091 (org-table-maybe-eval-formula)
10092 (if arg
10093 (call-interactively 'org-table-recalculate)
10094 (org-table-maybe-recalculate-line))
10095 (call-interactively 'org-table-align)
10096 (orgtbl-send-table 'maybe))
10097 ((eq action 'recalc)
10098 (save-excursion
10099 (beginning-of-line 1)
10100 (skip-chars-backward " \r\n\t")
10101 (if (org-at-table-p)
10102 (org-call-with-arg 'org-table-recalculate t))))
10103 (t (let (orgtbl-mode)
10104 (call-interactively (key-binding "\C-c\C-c")))))))
10106 (defun orgtbl-tab (arg)
10107 "Justification and field motion for `orgtbl-mode'."
10108 (interactive "P")
10109 (if arg (org-table-edit-field t)
10110 (org-table-justify-field-maybe)
10111 (org-table-next-field)))
10113 (defun orgtbl-ret ()
10114 "Justification and field motion for `orgtbl-mode'."
10115 (interactive)
10116 (org-table-justify-field-maybe)
10117 (org-table-next-row))
10119 (defun orgtbl-self-insert-command (N)
10120 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10121 If the cursor is in a table looking at whitespace, the whitespace is
10122 overwritten, and the table is not marked as requiring realignment."
10123 (interactive "p")
10124 (if (and (org-at-table-p)
10126 (and org-table-auto-blank-field
10127 (member last-command
10128 '(orgtbl-hijacker-command-100
10129 orgtbl-hijacker-command-101
10130 orgtbl-hijacker-command-102
10131 orgtbl-hijacker-command-103
10132 orgtbl-hijacker-command-104
10133 orgtbl-hijacker-command-105))
10134 (org-table-blank-field))
10136 (eq N 1)
10137 (looking-at "[^|\n]* +|"))
10138 (let (org-table-may-need-update)
10139 (goto-char (1- (match-end 0)))
10140 (delete-backward-char 1)
10141 (goto-char (match-beginning 0))
10142 (self-insert-command N))
10143 (setq org-table-may-need-update t)
10144 (let (orgtbl-mode)
10145 (call-interactively (key-binding (vector last-input-event))))))
10147 (defun org-force-self-insert (N)
10148 "Needed to enforce self-insert under remapping."
10149 (interactive "p")
10150 (self-insert-command N))
10152 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10153 "Regula expression matching exponentials as produced by calc.")
10155 (defvar org-table-clean-did-remove-column nil)
10157 (defun orgtbl-export (table target)
10158 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10159 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10160 org-table-last-alignment org-table-last-column-widths
10161 maxcol column)
10162 (if (not (fboundp func))
10163 (error "Cannot export orgtbl table to %s" target))
10164 (setq lines (org-table-clean-before-export lines))
10165 (setq table
10166 (mapcar
10167 (lambda (x)
10168 (if (string-match org-table-hline-regexp x)
10169 'hline
10170 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10171 lines))
10172 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10173 table)))
10174 (loop for i from (1- maxcol) downto 0 do
10175 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10176 (setq column (delq nil column))
10177 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10178 (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))
10179 (funcall func table nil)))
10181 (defun orgtbl-send-table (&optional maybe)
10182 "Send a tranformed version of this table to the receiver position.
10183 With argument MAYBE, fail quietly if no transformation is defined for
10184 this table."
10185 (interactive)
10186 (catch 'exit
10187 (unless (org-at-table-p) (error "Not at a table"))
10188 ;; when non-interactive, we assume align has just happened.
10189 (when (interactive-p) (org-table-align))
10190 (save-excursion
10191 (goto-char (org-table-begin))
10192 (beginning-of-line 0)
10193 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10194 (if maybe
10195 (throw 'exit nil)
10196 (error "Don't know how to transform this table."))))
10197 (let* ((name (match-string 1))
10199 (transform (intern (match-string 2)))
10200 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10201 (skip (plist-get params :skip))
10202 (skipcols (plist-get params :skipcols))
10203 (txt (buffer-substring-no-properties
10204 (org-table-begin) (org-table-end)))
10205 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10206 (lines (org-table-clean-before-export lines))
10207 (i0 (if org-table-clean-did-remove-column 2 1))
10208 (table (mapcar
10209 (lambda (x)
10210 (if (string-match org-table-hline-regexp x)
10211 'hline
10212 (org-remove-by-index
10213 (org-split-string (org-trim x) "\\s-*|\\s-*")
10214 skipcols i0)))
10215 lines))
10216 (fun (if (= i0 2) 'cdr 'identity))
10217 (org-table-last-alignment
10218 (org-remove-by-index (funcall fun org-table-last-alignment)
10219 skipcols i0))
10220 (org-table-last-column-widths
10221 (org-remove-by-index (funcall fun org-table-last-column-widths)
10222 skipcols i0)))
10224 (unless (fboundp transform)
10225 (error "No such transformation function %s" transform))
10226 (setq txt (funcall transform table params))
10227 ;; Find the insertion place
10228 (save-excursion
10229 (goto-char (point-min))
10230 (unless (re-search-forward
10231 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10232 (error "Don't know where to insert translated table"))
10233 (goto-char (match-beginning 0))
10234 (beginning-of-line 2)
10235 (setq beg (point))
10236 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10237 (error "Cannot find end of insertion region"))
10238 (beginning-of-line 1)
10239 (delete-region beg (point))
10240 (goto-char beg)
10241 (insert txt "\n"))
10242 (message "Table converted and installed at receiver location"))))
10244 (defun org-remove-by-index (list indices &optional i0)
10245 "Remove the elements in LIST with indices in INDICES.
10246 First element has index 0, or I0 if given."
10247 (if (not indices)
10248 list
10249 (if (integerp indices) (setq indices (list indices)))
10250 (setq i0 (1- (or i0 0)))
10251 (delq :rm (mapcar (lambda (x)
10252 (setq i0 (1+ i0))
10253 (if (memq i0 indices) :rm x))
10254 list))))
10256 (defun orgtbl-toggle-comment ()
10257 "Comment or uncomment the orgtbl at point."
10258 (interactive)
10259 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10260 (re2 (concat "^" orgtbl-line-start-regexp))
10261 (commented (save-excursion (beginning-of-line 1)
10262 (cond ((looking-at re1) t)
10263 ((looking-at re2) nil)
10264 (t (error "Not at an org table")))))
10265 (re (if commented re1 re2))
10266 beg end)
10267 (save-excursion
10268 (beginning-of-line 1)
10269 (while (looking-at re) (beginning-of-line 0))
10270 (beginning-of-line 2)
10271 (setq beg (point))
10272 (while (looking-at re) (beginning-of-line 2))
10273 (setq end (point)))
10274 (comment-region beg end (if commented '(4) nil))))
10276 (defun orgtbl-insert-radio-table ()
10277 "Insert a radio table template appropriate for this major mode."
10278 (interactive)
10279 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10280 (txt (nth 1 e))
10281 name pos)
10282 (unless e (error "No radio table setup defined for %s" major-mode))
10283 (setq name (read-string "Table name: "))
10284 (while (string-match "%n" txt)
10285 (setq txt (replace-match name t t txt)))
10286 (or (bolp) (insert "\n"))
10287 (setq pos (point))
10288 (insert txt)
10289 (goto-char pos)))
10291 (defun org-get-param (params header i sym &optional hsym)
10292 "Get parameter value for symbol SYM.
10293 If this is a header line, actually get the value for the symbol with an
10294 additional \"h\" inserted after the colon.
10295 If the value is a protperty list, get the element for the current column.
10296 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10297 (let ((val (plist-get params sym)))
10298 (and hsym header (setq val (or (plist-get params hsym) val)))
10299 (if (consp val) (plist-get val i) val)))
10301 (defun orgtbl-to-generic (table params)
10302 "Convert the orgtbl-mode TABLE to some other format.
10303 This generic routine can be used for many standard cases.
10304 TABLE is a list, each entry either the symbol `hline' for a horizontal
10305 separator line, or a list of fields for that line.
10306 PARAMS is a property list of parameters that can influence the conversion.
10307 For the generic converter, some parameters are obligatory: You need to
10308 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10309 :splice, you must have :tstart and :tend.
10311 Valid parameters are
10313 :tstart String to start the table. Ignored when :splice is t.
10314 :tend String to end the table. Ignored when :splice is t.
10316 :splice When set to t, return only table body lines, don't wrap
10317 them into :tstart and :tend. Default is nil.
10319 :hline String to be inserted on horizontal separation lines.
10320 May be nil to ignore hlines.
10322 :lstart String to start a new table line.
10323 :lend String to end a table line
10324 :sep Separator between two fields
10325 :lfmt Format for entire line, with enough %s to capture all fields.
10326 If this is present, :lstart, :lend, and :sep are ignored.
10327 :fmt A format to be used to wrap the field, should contain
10328 %s for the original field value. For example, to wrap
10329 everything in dollars, you could use :fmt \"$%s$\".
10330 This may also be a property list with column numbers and
10331 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10333 :hlstart :hlend :hlsep :hlfmt :hfmt
10334 Same as above, specific for the header lines in the table.
10335 All lines before the first hline are treated as header.
10336 If any of these is not present, the data line value is used.
10338 :efmt Use this format to print numbers with exponentials.
10339 The format should have %s twice for inserting mantissa
10340 and exponent, for example \"%s\\\\times10^{%s}\". This
10341 may also be a property list with column numbers and
10342 formats. :fmt will still be applied after :efmt.
10344 In addition to this, the parameters :skip and :skipcols are always handled
10345 directly by `orgtbl-send-table'. See manual."
10346 (interactive)
10347 (let* ((p params)
10348 (splicep (plist-get p :splice))
10349 (hline (plist-get p :hline))
10350 rtn line i fm efm lfmt h)
10352 ;; Do we have a header?
10353 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10354 (setq h t))
10356 ;; Put header
10357 (unless splicep
10358 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10360 ;; Now loop over all lines
10361 (while (setq line (pop table))
10362 (if (eq line 'hline)
10363 ;; A horizontal separator line
10364 (progn (if hline (push hline rtn))
10365 (setq h nil)) ; no longer in header
10366 ;; A normal line. Convert the fields, push line onto the result list
10367 (setq i 0)
10368 (setq line
10369 (mapcar
10370 (lambda (f)
10371 (setq i (1+ i)
10372 fm (org-get-param p h i :fmt :hfmt)
10373 efm (org-get-param p h i :efmt))
10374 (if (and efm (string-match orgtbl-exp-regexp f))
10375 (setq f (format
10376 efm (match-string 1 f) (match-string 2 f))))
10377 (if fm (setq f (format fm f)))
10379 line))
10380 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10381 (push (apply 'format lfmt line) rtn)
10382 (push (concat
10383 (org-get-param p h i :lstart :hlstart)
10384 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10385 (org-get-param p h i :lend :hlend))
10386 rtn))))
10388 (unless splicep
10389 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10391 (mapconcat 'identity (nreverse rtn) "\n")))
10393 (defun orgtbl-to-latex (table params)
10394 "Convert the orgtbl-mode TABLE to LaTeX.
10395 TABLE is a list, each entry either the symbol `hline' for a horizontal
10396 separator line, or a list of fields for that line.
10397 PARAMS is a property list of parameters that can influence the conversion.
10398 Supports all parameters from `orgtbl-to-generic'. Most important for
10399 LaTeX are:
10401 :splice When set to t, return only table body lines, don't wrap
10402 them into a tabular environment. Default is nil.
10404 :fmt A format to be used to wrap the field, should contain %s for the
10405 original field value. For example, to wrap everything in dollars,
10406 use :fmt \"$%s$\". This may also be a property list with column
10407 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10409 :efmt Format for transforming numbers with exponentials. The format
10410 should have %s twice for inserting mantissa and exponent, for
10411 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10412 This may also be a property list with column numbers and formats.
10414 The general parameters :skip and :skipcols have already been applied when
10415 this function is called."
10416 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10417 org-table-last-alignment ""))
10418 (params2
10419 (list
10420 :tstart (concat "\\begin{tabular}{" alignment "}")
10421 :tend "\\end{tabular}"
10422 :lstart "" :lend " \\\\" :sep " & "
10423 :efmt "%s\\,(%s)" :hline "\\hline")))
10424 (orgtbl-to-generic table (org-combine-plists params2 params))))
10426 (defun orgtbl-to-html (table params)
10427 "Convert the orgtbl-mode TABLE to LaTeX.
10428 TABLE is a list, each entry either the symbol `hline' for a horizontal
10429 separator line, or a list of fields for that line.
10430 PARAMS is a property list of parameters that can influence the conversion.
10431 Currently this function recognizes the following parameters:
10433 :splice When set to t, return only table body lines, don't wrap
10434 them into a <table> environment. Default is nil.
10436 The general parameters :skip and :skipcols have already been applied when
10437 this function is called. The function does *not* use `orgtbl-to-generic',
10438 so you cannot specify parameters for it."
10439 (let* ((splicep (plist-get params :splice))
10440 html)
10441 ;; Just call the formatter we already have
10442 ;; We need to make text lines for it, so put the fields back together.
10443 (setq html (org-format-org-table-html
10444 (mapcar
10445 (lambda (x)
10446 (if (eq x 'hline)
10447 "|----+----|"
10448 (concat "| " (mapconcat 'identity x " | ") " |")))
10449 table)
10450 splicep))
10451 (if (string-match "\n+\\'" html)
10452 (setq html (replace-match "" t t html)))
10453 html))
10455 (defun orgtbl-to-texinfo (table params)
10456 "Convert the orgtbl-mode TABLE to TeXInfo.
10457 TABLE is a list, each entry either the symbol `hline' for a horizontal
10458 separator line, or a list of fields for that line.
10459 PARAMS is a property list of parameters that can influence the conversion.
10460 Supports all parameters from `orgtbl-to-generic'. Most important for
10461 TeXInfo are:
10463 :splice nil/t When set to t, return only table body lines, don't wrap
10464 them into a multitable environment. Default is nil.
10466 :fmt fmt A format to be used to wrap the field, should contain
10467 %s for the original field value. For example, to wrap
10468 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10469 This may also be a property list with column numbers and
10470 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10472 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10473 are computed automatically from the width of the columns
10474 under org-mode.
10476 The general parameters :skip and :skipcols have already been applied when
10477 this function is called."
10478 (let* ((total (float (apply '+ org-table-last-column-widths)))
10479 (colfrac (or (plist-get params :cf)
10480 (mapconcat
10481 (lambda (x) (format "%.3f" (/ (float x) total)))
10482 org-table-last-column-widths " ")))
10483 (params2
10484 (list
10485 :tstart (concat "@multitable @columnfractions " colfrac)
10486 :tend "@end multitable"
10487 :lstart "@item " :lend "" :sep " @tab "
10488 :hlstart "@headitem ")))
10489 (orgtbl-to-generic table (org-combine-plists params2 params))))
10491 ;;;; Link Stuff
10493 ;;; Link abbreviations
10495 (defun org-link-expand-abbrev (link)
10496 "Apply replacements as defined in `org-link-abbrev-alist."
10497 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10498 (let* ((key (match-string 1 link))
10499 (as (or (assoc key org-link-abbrev-alist-local)
10500 (assoc key org-link-abbrev-alist)))
10501 (tag (and (match-end 2) (match-string 3 link)))
10502 rpl)
10503 (if (not as)
10504 link
10505 (setq rpl (cdr as))
10506 (cond
10507 ((symbolp rpl) (funcall rpl tag))
10508 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10509 (t (concat rpl tag)))))
10510 link))
10512 ;;; Storing and inserting links
10514 (defvar org-insert-link-history nil
10515 "Minibuffer history for links inserted with `org-insert-link'.")
10517 (defvar org-stored-links nil
10518 "Contains the links stored with `org-store-link'.")
10520 (defvar org-store-link-plist nil
10521 "Plist with info about the most recently link created with `org-store-link'.")
10523 (defvar org-link-protocols nil
10524 "Link protocols added to Org-mode using `org-add-link-type'.")
10526 (defvar org-store-link-functions nil
10527 "List of functions that are called to create and store a link.
10528 Each function will be called in turn until one returns a non-nil
10529 value. Each function should check if it is responsible for creating
10530 this link (for example by looking at the major mode).
10531 If not, it must exit and return nil.
10532 If yes, it should return a non-nil value after a calling
10533 `org-store-link-properties' with a list of properties and values.
10534 Special properties are:
10536 :type The link prefix. like \"http\". This must be given.
10537 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10538 This is obligatory as well.
10539 :description Optional default description for the second pair
10540 of brackets in an Org-mode link. The user can still change
10541 this when inserting this link into an Org-mode buffer.
10543 In addition to these, any additional properties can be specified
10544 and then used in remember templates.")
10546 (defun org-add-link-type (type &optional follow publish)
10547 "Add TYPE to the list of `org-link-types'.
10548 Re-compute all regular expressions depending on `org-link-types'
10549 FOLLOW and PUBLISH are two functions. Both take the link path as
10550 an argument.
10551 FOLLOW should do whatever is necessary to follow the link, for example
10552 to find a file or display a mail message.
10553 PUBLISH takes the path and retuns the string that should be used when
10554 this document is published."
10555 (add-to-list 'org-link-types type t)
10556 (org-make-link-regexps)
10557 (add-to-list 'org-link-protocols
10558 (list type follow publish)))
10560 (defun org-add-agenda-custom-command (entry)
10561 "Replace or add a command in `org-agenda-custom-commands'.
10562 This is mostly for hacking and trying a new command - once the command
10563 works you probably want to add it to `org-agenda-custom-commands' for good."
10564 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
10565 (if ass
10566 (setcdr ass (cdr entry))
10567 (push entry org-agenda-custom-commands))))
10569 ;;;###autoload
10570 (defun org-store-link (arg)
10571 "\\<org-mode-map>Store an org-link to the current location.
10572 This link can later be inserted into an org-buffer with
10573 \\[org-insert-link].
10574 For some link types, a prefix arg is interpreted:
10575 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10576 For file links, arg negates `org-context-in-file-links'."
10577 (interactive "P")
10578 (setq org-store-link-plist nil) ; reset
10579 (let (link cpltxt desc description search txt)
10580 (cond
10582 ((run-hook-with-args-until-success 'org-store-link-functions)
10583 (setq link (plist-get org-store-link-plist :link)
10584 desc (or (plist-get org-store-link-plist :description) link)))
10586 ((eq major-mode 'bbdb-mode)
10587 (let ((name (bbdb-record-name (bbdb-current-record)))
10588 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10589 (setq cpltxt (concat "bbdb:" (or name company))
10590 link (org-make-link cpltxt))
10591 (org-store-link-props :type "bbdb" :name name :company company)))
10593 ((eq major-mode 'Info-mode)
10594 (setq link (org-make-link "info:"
10595 (file-name-nondirectory Info-current-file)
10596 ":" Info-current-node))
10597 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10598 ":" Info-current-node))
10599 (org-store-link-props :type "info" :file Info-current-file
10600 :node Info-current-node))
10602 ((eq major-mode 'calendar-mode)
10603 (let ((cd (calendar-cursor-to-date)))
10604 (setq link
10605 (format-time-string
10606 (car org-time-stamp-formats)
10607 (apply 'encode-time
10608 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10609 nil nil nil))))
10610 (org-store-link-props :type "calendar" :date cd)))
10612 ((or (eq major-mode 'vm-summary-mode)
10613 (eq major-mode 'vm-presentation-mode))
10614 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10615 (vm-follow-summary-cursor)
10616 (save-excursion
10617 (vm-select-folder-buffer)
10618 (let* ((message (car vm-message-pointer))
10619 (folder buffer-file-name)
10620 (subject (vm-su-subject message))
10621 (to (vm-get-header-contents message "To"))
10622 (from (vm-get-header-contents message "From"))
10623 (message-id (vm-su-message-id message)))
10624 (org-store-link-props :type "vm" :from from :to to :subject subject
10625 :message-id message-id)
10626 (setq message-id (org-remove-angle-brackets message-id))
10627 (setq folder (abbreviate-file-name folder))
10628 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10629 folder)
10630 (setq folder (replace-match "" t t folder)))
10631 (setq cpltxt (org-email-link-description))
10632 (setq link (org-make-link "vm:" folder "#" message-id)))))
10634 ((eq major-mode 'wl-summary-mode)
10635 (let* ((msgnum (wl-summary-message-number))
10636 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10637 msgnum 'message-id))
10638 (wl-message-entity
10639 (if (fboundp 'elmo-message-entity)
10640 (elmo-message-entity
10641 wl-summary-buffer-elmo-folder msgnum)
10642 (elmo-msgdb-overview-get-entity
10643 msgnum (wl-summary-buffer-msgdb))))
10644 (from (wl-summary-line-from))
10645 (to (car (elmo-message-entity-field wl-message-entity 'to)))
10646 (subject (let (wl-thr-indent-string wl-parent-message-entity)
10647 (wl-summary-line-subject))))
10648 (org-store-link-props :type "wl" :from from :to to
10649 :subject subject :message-id message-id)
10650 (setq message-id (org-remove-angle-brackets message-id))
10651 (setq cpltxt (org-email-link-description))
10652 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10653 "#" message-id))))
10655 ((or (equal major-mode 'mh-folder-mode)
10656 (equal major-mode 'mh-show-mode))
10657 (let ((from (org-mhe-get-header "From:"))
10658 (to (org-mhe-get-header "To:"))
10659 (message-id (org-mhe-get-header "Message-Id:"))
10660 (subject (org-mhe-get-header "Subject:")))
10661 (org-store-link-props :type "mh" :from from :to to
10662 :subject subject :message-id message-id)
10663 (setq cpltxt (org-email-link-description))
10664 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10665 (org-remove-angle-brackets message-id)))))
10667 ((eq major-mode 'rmail-mode)
10668 (save-excursion
10669 (save-restriction
10670 (rmail-narrow-to-non-pruned-header)
10671 (let ((folder buffer-file-name)
10672 (message-id (mail-fetch-field "message-id"))
10673 (from (mail-fetch-field "from"))
10674 (to (mail-fetch-field "to"))
10675 (subject (mail-fetch-field "subject")))
10676 (org-store-link-props
10677 :type "rmail" :from from :to to
10678 :subject subject :message-id message-id)
10679 (setq message-id (org-remove-angle-brackets message-id))
10680 (setq cpltxt (org-email-link-description))
10681 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10683 ((eq major-mode 'gnus-group-mode)
10684 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10685 (gnus-group-group-name)) ; version
10686 ((fboundp 'gnus-group-name)
10687 (gnus-group-name))
10688 (t "???"))))
10689 (unless group (error "Not on a group"))
10690 (org-store-link-props :type "gnus" :group group)
10691 (setq cpltxt (concat
10692 (if (org-xor arg org-usenet-links-prefer-google)
10693 "http://groups.google.com/groups?group="
10694 "gnus:")
10695 group)
10696 link (org-make-link cpltxt))))
10698 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10699 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10700 (let* ((group gnus-newsgroup-name)
10701 (article (gnus-summary-article-number))
10702 (header (gnus-summary-article-header article))
10703 (from (mail-header-from header))
10704 (message-id (mail-header-id header))
10705 (date (mail-header-date header))
10706 (subject (gnus-summary-subject-string)))
10707 (org-store-link-props :type "gnus" :from from :subject subject
10708 :message-id message-id :group group)
10709 (setq cpltxt (org-email-link-description))
10710 (if (org-xor arg org-usenet-links-prefer-google)
10711 (setq link
10712 (concat
10713 cpltxt "\n "
10714 (format "http://groups.google.com/groups?as_umsgid=%s"
10715 (org-fixup-message-id-for-http message-id))))
10716 (setq link (org-make-link "gnus:" group
10717 "#" (number-to-string article))))))
10719 ((eq major-mode 'w3-mode)
10720 (setq cpltxt (url-view-url t)
10721 link (org-make-link cpltxt))
10722 (org-store-link-props :type "w3" :url (url-view-url t)))
10724 ((eq major-mode 'w3m-mode)
10725 (setq cpltxt (or w3m-current-title w3m-current-url)
10726 link (org-make-link w3m-current-url))
10727 (org-store-link-props :type "w3m" :url (url-view-url t)))
10729 ((setq search (run-hook-with-args-until-success
10730 'org-create-file-search-functions))
10731 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10732 "::" search))
10733 (setq cpltxt (or description link)))
10735 ((eq major-mode 'image-mode)
10736 (setq cpltxt (concat "file:"
10737 (abbreviate-file-name buffer-file-name))
10738 link (org-make-link cpltxt))
10739 (org-store-link-props :type "image" :file buffer-file-name))
10741 ((eq major-mode 'dired-mode)
10742 ;; link to the file in the current line
10743 (setq cpltxt (concat "file:"
10744 (abbreviate-file-name
10745 (expand-file-name
10746 (dired-get-filename nil t))))
10747 link (org-make-link cpltxt)))
10749 ((and buffer-file-name (org-mode-p))
10750 ;; Just link to current headline
10751 (setq cpltxt (concat "file:"
10752 (abbreviate-file-name buffer-file-name)))
10753 ;; Add a context search string
10754 (when (org-xor org-context-in-file-links arg)
10755 ;; Check if we are on a target
10756 (if (org-in-regexp "<<\\(.*?\\)>>")
10757 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10758 (setq txt (cond
10759 ((org-on-heading-p) nil)
10760 ((org-region-active-p)
10761 (buffer-substring (region-beginning) (region-end)))
10762 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10763 (when (or (null txt) (string-match "\\S-" txt))
10764 (setq cpltxt
10765 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10766 desc "NONE"))))
10767 (if (string-match "::\\'" cpltxt)
10768 (setq cpltxt (substring cpltxt 0 -2)))
10769 (setq link (org-make-link cpltxt)))
10771 (buffer-file-name
10772 ;; Just link to this file here.
10773 (setq cpltxt (concat "file:"
10774 (abbreviate-file-name buffer-file-name)))
10775 ;; Add a context string
10776 (when (org-xor org-context-in-file-links arg)
10777 (setq txt (if (org-region-active-p)
10778 (buffer-substring (region-beginning) (region-end))
10779 (buffer-substring (point-at-bol) (point-at-eol))))
10780 ;; Only use search option if there is some text.
10781 (when (string-match "\\S-" txt)
10782 (setq cpltxt
10783 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10784 desc "NONE")))
10785 (setq link (org-make-link cpltxt)))
10787 ((interactive-p)
10788 (error "Cannot link to a buffer which is not visiting a file"))
10790 (t (setq link nil)))
10792 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10793 (setq link (or link cpltxt)
10794 desc (or desc cpltxt))
10795 (if (equal desc "NONE") (setq desc nil))
10797 (if (and (interactive-p) link)
10798 (progn
10799 (setq org-stored-links
10800 (cons (list cpltxt link desc) org-stored-links))
10801 (message "Stored: %s" (or cpltxt link)))
10802 (org-make-link-string link desc))))
10804 (defun org-store-link-props (&rest plist)
10805 "Store link properties, extract names and addresses."
10806 (let (x adr)
10807 (when (setq x (plist-get plist :from))
10808 (setq adr (mail-extract-address-components x))
10809 (plist-put plist :fromname (car adr))
10810 (plist-put plist :fromaddress (nth 1 adr)))
10811 (when (setq x (plist-get plist :to))
10812 (setq adr (mail-extract-address-components x))
10813 (plist-put plist :toname (car adr))
10814 (plist-put plist :toaddress (nth 1 adr))))
10815 (let ((from (plist-get plist :from))
10816 (to (plist-get plist :to)))
10817 (when (and from to org-from-is-user-regexp)
10818 (plist-put plist :fromto
10819 (if (string-match org-from-is-user-regexp from)
10820 (concat "to %t")
10821 (concat "from %f")))))
10822 (setq org-store-link-plist plist))
10824 (defun org-email-link-description (&optional fmt)
10825 "Return the description part of an email link.
10826 This takes information from `org-store-link-plist' and formats it
10827 according to FMT (default from `org-email-link-description-format')."
10828 (setq fmt (or fmt org-email-link-description-format))
10829 (let* ((p org-store-link-plist)
10830 (to (plist-get p :toaddress))
10831 (from (plist-get p :fromaddress))
10832 (table
10833 (list
10834 (cons "%c" (plist-get p :fromto))
10835 (cons "%F" (plist-get p :from))
10836 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10837 (cons "%T" (plist-get p :to))
10838 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10839 (cons "%s" (plist-get p :subject))
10840 (cons "%m" (plist-get p :message-id)))))
10841 (when (string-match "%c" fmt)
10842 ;; Check if the user wrote this message
10843 (if (and org-from-is-user-regexp from to
10844 (save-match-data (string-match org-from-is-user-regexp from)))
10845 (setq fmt (replace-match "to %t" t t fmt))
10846 (setq fmt (replace-match "from %f" t t fmt))))
10847 (org-replace-escapes fmt table)))
10849 (defun org-make-org-heading-search-string (&optional string heading)
10850 "Make search string for STRING or current headline."
10851 (interactive)
10852 (let ((s (or string (org-get-heading))))
10853 (unless (and string (not heading))
10854 ;; We are using a headline, clean up garbage in there.
10855 (if (string-match org-todo-regexp s)
10856 (setq s (replace-match "" t t s)))
10857 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
10858 (setq s (replace-match "" t t s)))
10859 (setq s (org-trim s))
10860 (if (string-match (concat "^\\(" org-quote-string "\\|"
10861 org-comment-string "\\)") s)
10862 (setq s (replace-match "" t t s)))
10863 (while (string-match org-ts-regexp s)
10864 (setq s (replace-match "" t t s))))
10865 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10866 (setq s (replace-match " " t t s)))
10867 (or string (setq s (concat "*" s))) ; Add * for headlines
10868 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10870 (defun org-make-link (&rest strings)
10871 "Concatenate STRINGS."
10872 (apply 'concat strings))
10874 (defun org-make-link-string (link &optional description)
10875 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10876 (when (stringp description)
10877 ;; Remove brackets from the description, they are fatal.
10878 (while (string-match "\\[\\|\\]" description)
10879 (setq description (replace-match "" t t description))))
10880 (when (equal (org-link-escape link) description)
10881 ;; No description needed, it is identical
10882 (setq description nil))
10883 (when (and (not description)
10884 (not (equal link (org-link-escape link))))
10885 (setq description link))
10886 (concat "[[" (org-link-escape link) "]"
10887 (if description (concat "[" description "]") "")
10888 "]"))
10890 (defconst org-link-escape-chars
10891 '((" " . "%20") ("\340" . "%E0")
10892 ("\342" . "%E2") ("\347" . "%E7")
10893 ("\350" . "%E8") ("\351" . "%E9")
10894 ("\352" . "%EA") ("\356" . "%EE")
10895 ("\364" . "%F4") ("\371" . "%F9")
10896 ("\373" . "%FB") (";" . "%3B")
10897 ("?" . "%3F") ("=" . "%3D")
10898 ("+" . "%2B"))
10899 "Association list of escapes for some characters problematic in links.")
10901 (defun org-link-escape (text)
10902 "Escape charaters in TEXT that are problematic for links."
10903 (when text
10904 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10905 org-link-escape-chars "\\|")))
10906 (while (string-match re text)
10907 (setq text
10908 (replace-match
10909 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10910 t t text)))
10911 text)))
10913 (defun org-link-unescape (text)
10914 "Reverse the action of `org-link-escape'."
10915 (when text
10916 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10917 org-link-escape-chars "\\|")))
10918 (while (string-match re text)
10919 (setq text
10920 (replace-match
10921 (car (rassoc (match-string 0 text) org-link-escape-chars))
10922 t t text)))
10923 text)))
10925 (defun org-xor (a b)
10926 "Exclusive or."
10927 (if a (not b) b))
10929 (defun org-get-header (header)
10930 "Find a header field in the current buffer."
10931 (save-excursion
10932 (goto-char (point-min))
10933 (let ((case-fold-search t) s)
10934 (cond
10935 ((eq header 'from)
10936 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10937 (setq s (match-string 1)))
10938 (while (string-match "\"" s)
10939 (setq s (replace-match "" t t s)))
10940 (if (string-match "[<(].*" s)
10941 (setq s (replace-match "" t t s))))
10942 ((eq header 'message-id)
10943 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10944 (setq s (match-string 1))))
10945 ((eq header 'subject)
10946 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10947 (setq s (match-string 1)))))
10948 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10949 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10950 s)))
10953 (defun org-fixup-message-id-for-http (s)
10954 "Replace special characters in a message id, so it can be used in an http query."
10955 (while (string-match "<" s)
10956 (setq s (replace-match "%3C" t t s)))
10957 (while (string-match ">" s)
10958 (setq s (replace-match "%3E" t t s)))
10959 (while (string-match "@" s)
10960 (setq s (replace-match "%40" t t s)))
10963 ;;;###autoload
10964 (defun org-insert-link-global ()
10965 "Insert a link like Org-mode does.
10966 This command can be called in any mode to follow a link that has
10967 Org-mode syntax."
10968 (interactive)
10969 (org-run-like-in-org-mode 'org-insert-link))
10971 (defun org-insert-link (&optional complete-file)
10972 "Insert a link. At the prompt, enter the link.
10974 Completion can be used to select a link previously stored with
10975 `org-store-link'. When the empty string is entered (i.e. if you just
10976 press RET at the prompt), the link defaults to the most recently
10977 stored link. As SPC triggers completion in the minibuffer, you need to
10978 use M-SPC or C-q SPC to force the insertion of a space character.
10980 You will also be prompted for a description, and if one is given, it will
10981 be displayed in the buffer instead of the link.
10983 If there is already a link at point, this command will allow you to edit link
10984 and description parts.
10986 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10987 selected using completion. The path to the file will be relative to
10988 the current directory if the file is in the current directory or a
10989 subdirectory. Otherwise, the link will be the absolute path as
10990 completed in the minibuffer (i.e. normally ~/path/to/file).
10992 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10993 is in the current directory or below.
10994 With three \\[universal-argument] prefixes, negate the meaning of
10995 `org-keep-stored-link-after-insertion'."
10996 (interactive "P")
10997 (let ((wcf (current-window-configuration))
10998 (region (if (org-region-active-p)
10999 (prog1 (buffer-substring (region-beginning) (region-end))
11000 (delete-region (region-beginning) (region-end)))))
11001 tmphist ; byte-compile incorrectly complains about this
11002 link desc entry remove file)
11003 (cond
11004 ((org-in-regexp org-bracket-link-regexp 1)
11005 ;; We do have a link at point, and we are going to edit it.
11006 (setq remove (list (match-beginning 0) (match-end 0)))
11007 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11008 (setq link (read-string "Link: "
11009 (org-link-unescape
11010 (org-match-string-no-properties 1)))))
11011 ((or (org-in-regexp org-angle-link-re)
11012 (org-in-regexp org-plain-link-re))
11013 ;; Convert to bracket link
11014 (setq remove (list (match-beginning 0) (match-end 0))
11015 link (read-string "Link: "
11016 (org-remove-angle-brackets (match-string 0)))))
11017 ((equal complete-file '(4))
11018 ;; Completing read for file names.
11019 (setq file (read-file-name "File: "))
11020 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11021 (pwd1 (file-name-as-directory (abbreviate-file-name
11022 (expand-file-name ".")))))
11023 (cond
11024 ((equal complete-file '(16))
11025 (setq link (org-make-link
11026 "file:"
11027 (abbreviate-file-name (expand-file-name file)))))
11028 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11029 (setq link (org-make-link "file:" (match-string 1 file))))
11030 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11031 (expand-file-name file))
11032 (setq link (org-make-link
11033 "file:" (match-string 1 (expand-file-name file)))))
11034 (t (setq link (org-make-link "file:" file))))))
11036 ;; Read link, with completion for stored links.
11037 (with-output-to-temp-buffer "*Org Links*"
11038 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11039 (when org-stored-links
11040 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
11041 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
11042 (let ((cw (selected-window)))
11043 (select-window (get-buffer-window "*Org Links*"))
11044 (shrink-window-if-larger-than-buffer)
11045 (setq truncate-lines t)
11046 (select-window cw))
11047 ;; Fake a link history, containing the stored links.
11048 (setq tmphist (append (mapcar 'car org-stored-links)
11049 org-insert-link-history))
11050 (unwind-protect
11051 (setq link (org-completing-read
11052 "Link: "
11053 (append
11054 (mapcar (lambda (x) (list (concat (car x) ":")))
11055 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11056 (mapcar (lambda (x) (list (concat x ":")))
11057 org-link-types))
11058 nil nil nil
11059 'tmphist
11060 (or (car (car org-stored-links)))))
11061 (set-window-configuration wcf)
11062 (kill-buffer "*Org Links*"))
11063 (setq entry (assoc link org-stored-links))
11064 (or entry (push link org-insert-link-history))
11065 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11066 (not org-keep-stored-link-after-insertion))
11067 (setq org-stored-links (delq (assoc link org-stored-links)
11068 org-stored-links)))
11069 (setq link (if entry (nth 1 entry) link)
11070 desc (or region desc (nth 2 entry)))))
11072 (if (string-match org-plain-link-re link)
11073 ;; URL-like link, normalize the use of angular brackets.
11074 (setq link (org-make-link (org-remove-angle-brackets link))))
11076 ;; Check if we are linking to the current file with a search option
11077 ;; If yes, simplify the link by using only the search option.
11078 (when (and buffer-file-name
11079 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11080 (let* ((path (match-string 1 link))
11081 (case-fold-search nil)
11082 (search (match-string 2 link)))
11083 (save-match-data
11084 (if (equal (file-truename buffer-file-name) (file-truename path))
11085 ;; We are linking to this same file, with a search option
11086 (setq link search)))))
11088 ;; Check if we can/should use a relative path. If yes, simplify the link
11089 (when (string-match "\\<file:\\(.*\\)" link)
11090 (let* ((path (match-string 1 link))
11091 (case-fold-search nil))
11092 (cond
11093 ((eq org-link-file-path-type 'absolute)
11094 (setq path (abbreviate-file-name (expand-file-name path))))
11095 ((eq org-link-file-path-type 'noabbrev)
11096 (setq path (expand-file-name path)))
11097 ((eq org-link-file-path-type 'relative)
11098 (setq path (file-relative-name path)))
11100 (save-match-data
11101 (if (string-match (concat "^" (regexp-quote
11102 (file-name-as-directory
11103 (expand-file-name "."))))
11104 (expand-file-name path))
11105 ;; We are linking a file with relative path name.
11106 (setq path (substring (expand-file-name path)
11107 (match-end 0)))))))
11108 (setq link (concat "file:" path))))
11110 (setq desc (read-string "Description: " desc))
11111 (unless (string-match "\\S-" desc) (setq desc nil))
11112 (if remove (apply 'delete-region remove))
11113 (insert (org-make-link-string link desc))))
11115 (defun org-completing-read (&rest args)
11116 (let ((minibuffer-local-completion-map
11117 (copy-keymap minibuffer-local-completion-map)))
11118 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11119 (apply 'completing-read args)))
11121 ;;; Opening/following a link
11122 (defvar org-link-search-failed nil)
11124 (defun org-next-link ()
11125 "Move forward to the next link.
11126 If the link is in hidden text, expose it."
11127 (interactive)
11128 (when (and org-link-search-failed (eq this-command last-command))
11129 (goto-char (point-min))
11130 (message "Link search wrapped back to beginning of buffer"))
11131 (setq org-link-search-failed nil)
11132 (let* ((pos (point))
11133 (ct (org-context))
11134 (a (assoc :link ct)))
11135 (if a (goto-char (nth 2 a)))
11136 (if (re-search-forward org-any-link-re nil t)
11137 (progn
11138 (goto-char (match-beginning 0))
11139 (if (org-invisible-p) (org-show-context)))
11140 (goto-char pos)
11141 (setq org-link-search-failed t)
11142 (error "No further link found"))))
11144 (defun org-previous-link ()
11145 "Move backward to the previous link.
11146 If the link is in hidden text, expose it."
11147 (interactive)
11148 (when (and org-link-search-failed (eq this-command last-command))
11149 (goto-char (point-max))
11150 (message "Link search wrapped back to end of buffer"))
11151 (setq org-link-search-failed nil)
11152 (let* ((pos (point))
11153 (ct (org-context))
11154 (a (assoc :link ct)))
11155 (if a (goto-char (nth 1 a)))
11156 (if (re-search-backward org-any-link-re nil t)
11157 (progn
11158 (goto-char (match-beginning 0))
11159 (if (org-invisible-p) (org-show-context)))
11160 (goto-char pos)
11161 (setq org-link-search-failed t)
11162 (error "No further link found"))))
11164 (defun org-find-file-at-mouse (ev)
11165 "Open file link or URL at mouse."
11166 (interactive "e")
11167 (mouse-set-point ev)
11168 (org-open-at-point 'in-emacs))
11170 (defun org-open-at-mouse (ev)
11171 "Open file link or URL at mouse."
11172 (interactive "e")
11173 (mouse-set-point ev)
11174 (org-open-at-point))
11176 (defvar org-window-config-before-follow-link nil
11177 "The window configuration before following a link.
11178 This is saved in case the need arises to restore it.")
11180 (defvar org-open-link-marker (make-marker)
11181 "Marker pointing to the location where `org-open-at-point; was called.")
11183 ;;;###autoload
11184 (defun org-open-at-point-global ()
11185 "Follow a link like Org-mode does.
11186 This command can be called in any mode to follow a link that has
11187 Org-mode syntax."
11188 (interactive)
11189 (org-run-like-in-org-mode 'org-open-at-point))
11191 (defun org-open-at-point (&optional in-emacs)
11192 "Open link at or after point.
11193 If there is no link at point, this function will search forward up to
11194 the end of the current subtree.
11195 Normally, files will be opened by an appropriate application. If the
11196 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11197 (interactive "P")
11198 (move-marker org-open-link-marker (point))
11199 (setq org-window-config-before-follow-link (current-window-configuration))
11200 (org-remove-occur-highlights nil nil t)
11201 (if (org-at-timestamp-p t)
11202 (org-follow-timestamp-link)
11203 (let (type path link line search (pos (point)))
11204 (catch 'match
11205 (save-excursion
11206 (skip-chars-forward "^]\n\r")
11207 (when (org-in-regexp org-bracket-link-regexp)
11208 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11209 (while (string-match " *\n *" link)
11210 (setq link (replace-match " " t t link)))
11211 (setq link (org-link-expand-abbrev link))
11212 (if (string-match org-link-re-with-space2 link)
11213 (setq type (match-string 1 link) path (match-string 2 link))
11214 (setq type "thisfile" path link))
11215 (throw 'match t)))
11217 (when (get-text-property (point) 'org-linked-text)
11218 (setq type "thisfile"
11219 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11220 (1+ (point)) (point))
11221 path (buffer-substring
11222 (previous-single-property-change pos 'org-linked-text)
11223 (next-single-property-change pos 'org-linked-text)))
11224 (throw 'match t))
11226 (save-excursion
11227 (when (or (org-in-regexp org-angle-link-re)
11228 (org-in-regexp org-plain-link-re))
11229 (setq type (match-string 1) path (match-string 2))
11230 (throw 'match t)))
11231 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11232 (setq type "tree-match"
11233 path (match-string 1))
11234 (throw 'match t))
11235 (save-excursion
11236 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11237 (setq type "tags"
11238 path (match-string 1))
11239 (while (string-match ":" path)
11240 (setq path (replace-match "+" t t path)))
11241 (throw 'match t))))
11242 (unless path
11243 (error "No link found"))
11244 ;; Remove any trailing spaces in path
11245 (if (string-match " +\\'" path)
11246 (setq path (replace-match "" t t path)))
11248 (cond
11250 ((assoc type org-link-protocols)
11251 (funcall (nth 1 (assoc type org-link-protocols)) path))
11253 ((equal type "mailto")
11254 (let ((cmd (car org-link-mailto-program))
11255 (args (cdr org-link-mailto-program)) args1
11256 (address path) (subject "") a)
11257 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11258 (setq address (match-string 1 path)
11259 subject (org-link-escape (match-string 2 path))))
11260 (while args
11261 (cond
11262 ((not (stringp (car args))) (push (pop args) args1))
11263 (t (setq a (pop args))
11264 (if (string-match "%a" a)
11265 (setq a (replace-match address t t a)))
11266 (if (string-match "%s" a)
11267 (setq a (replace-match subject t t a)))
11268 (push a args1))))
11269 (apply cmd (nreverse args1))))
11271 ((member type '("http" "https" "ftp" "news"))
11272 (browse-url (concat type ":" path)))
11274 ((string= type "tags")
11275 (org-tags-view in-emacs path))
11276 ((string= type "thisfile")
11277 (if in-emacs
11278 (switch-to-buffer-other-window
11279 (org-get-buffer-for-internal-link (current-buffer)))
11280 (org-mark-ring-push))
11281 (let ((cmd `(org-link-search
11282 ,path
11283 ,(cond ((equal in-emacs '(4)) 'occur)
11284 ((equal in-emacs '(16)) 'org-occur)
11285 (t nil))
11286 ,pos)))
11287 (condition-case nil (eval cmd)
11288 (error (progn (widen) (eval cmd))))))
11290 ((string= type "tree-match")
11291 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11293 ((string= type "file")
11294 (if (string-match "::\\([0-9]+\\)\\'" path)
11295 (setq line (string-to-number (match-string 1 path))
11296 path (substring path 0 (match-beginning 0)))
11297 (if (string-match "::\\(.+\\)\\'" path)
11298 (setq search (match-string 1 path)
11299 path (substring path 0 (match-beginning 0)))))
11300 (org-open-file path in-emacs line search))
11302 ((string= type "news")
11303 (org-follow-gnus-link path))
11305 ((string= type "bbdb")
11306 (org-follow-bbdb-link path))
11308 ((string= type "info")
11309 (org-follow-info-link path))
11311 ((string= type "gnus")
11312 (let (group article)
11313 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11314 (error "Error in Gnus link"))
11315 (setq group (match-string 1 path)
11316 article (match-string 3 path))
11317 (org-follow-gnus-link group article)))
11319 ((string= type "vm")
11320 (let (folder article)
11321 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11322 (error "Error in VM link"))
11323 (setq folder (match-string 1 path)
11324 article (match-string 3 path))
11325 ;; in-emacs is the prefix arg, will be interpreted as read-only
11326 (org-follow-vm-link folder article in-emacs)))
11328 ((string= type "wl")
11329 (let (folder article)
11330 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11331 (error "Error in Wanderlust link"))
11332 (setq folder (match-string 1 path)
11333 article (match-string 3 path))
11334 (org-follow-wl-link folder article)))
11336 ((string= type "mhe")
11337 (let (folder article)
11338 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11339 (error "Error in MHE link"))
11340 (setq folder (match-string 1 path)
11341 article (match-string 3 path))
11342 (org-follow-mhe-link folder article)))
11344 ((string= type "rmail")
11345 (let (folder article)
11346 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11347 (error "Error in RMAIL link"))
11348 (setq folder (match-string 1 path)
11349 article (match-string 3 path))
11350 (org-follow-rmail-link folder article)))
11352 ((string= type "shell")
11353 (let ((cmd path))
11354 ;; FIXME: the following is only for backward compatibility
11355 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11356 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11357 (if (or (not org-confirm-shell-link-function)
11358 (funcall org-confirm-shell-link-function
11359 (format "Execute \"%s\" in shell? "
11360 (org-add-props cmd nil
11361 'face 'org-warning))))
11362 (progn
11363 (message "Executing %s" cmd)
11364 (shell-command cmd))
11365 (error "Abort"))))
11367 ((string= type "elisp")
11368 (let ((cmd path))
11369 (if (or (not org-confirm-elisp-link-function)
11370 (funcall org-confirm-elisp-link-function
11371 (format "Execute \"%s\" as elisp? "
11372 (org-add-props cmd nil
11373 'face 'org-warning))))
11374 (message "%s => %s" cmd (eval (read cmd)))
11375 (error "Abort"))))
11378 (browse-url-at-point)))))
11379 (move-marker org-open-link-marker nil))
11382 ;;; File search
11384 (defvar org-create-file-search-functions nil
11385 "List of functions to construct the right search string for a file link.
11386 These functions are called in turn with point at the location to
11387 which the link should point.
11389 A function in the hook should first test if it would like to
11390 handle this file type, for example by checking the major-mode or
11391 the file extension. If it decides not to handle this file, it
11392 should just return nil to give other functions a chance. If it
11393 does handle the file, it must return the search string to be used
11394 when following the link. The search string will be part of the
11395 file link, given after a double colon, and `org-open-at-point'
11396 will automatically search for it. If special measures must be
11397 taken to make the search successful, another function should be
11398 added to the companion hook `org-execute-file-search-functions',
11399 which see.
11401 A function in this hook may also use `setq' to set the variable
11402 `description' to provide a suggestion for the descriptive text to
11403 be used for this link when it gets inserted into an Org-mode
11404 buffer with \\[org-insert-link].")
11406 (defvar org-execute-file-search-functions nil
11407 "List of functions to execute a file search triggered by a link.
11409 Functions added to this hook must accept a single argument, the
11410 search string that was part of the file link, the part after the
11411 double colon. The function must first check if it would like to
11412 handle this search, for example by checking the major-mode or the
11413 file extension. If it decides not to handle this search, it
11414 should just return nil to give other functions a chance. If it
11415 does handle the search, it must return a non-nil value to keep
11416 other functions from trying.
11418 Each function can access the current prefix argument through the
11419 variable `current-prefix-argument'. Note that a single prefix is
11420 used to force opening a link in Emacs, so it may be good to only
11421 use a numeric or double prefix to guide the search function.
11423 In case this is needed, a function in this hook can also restore
11424 the window configuration before `org-open-at-point' was called using:
11426 (set-window-configuration org-window-config-before-follow-link)")
11428 (defun org-link-search (s &optional type avoid-pos)
11429 "Search for a link search option.
11430 If S is surrounded by forward slashes, it is interpreted as a
11431 regular expression. In org-mode files, this will create an `org-occur'
11432 sparse tree. In ordinary files, `occur' will be used to list matches.
11433 If the current buffer is in `dired-mode', grep will be used to search
11434 in all files. If AVOID-POS is given, ignore matches near that position."
11435 (let ((case-fold-search t)
11436 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11437 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11438 (append '(("") (" ") ("\t") ("\n"))
11439 org-emphasis-alist)
11440 "\\|") "\\)"))
11441 (pos (point))
11442 (pre "") (post "")
11443 words re0 re1 re2 re3 re4 re5 re2a reall)
11444 (cond
11445 ;; First check if there are any special
11446 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11447 ;; Now try the builtin stuff
11448 ((save-excursion
11449 (goto-char (point-min))
11450 (and
11451 (re-search-forward
11452 (concat "<<" (regexp-quote s0) ">>") nil t)
11453 (setq pos (match-beginning 0))))
11454 ;; There is an exact target for this
11455 (goto-char pos))
11456 ((string-match "^/\\(.*\\)/$" s)
11457 ;; A regular expression
11458 (cond
11459 ((org-mode-p)
11460 (org-occur (match-string 1 s)))
11461 ;;((eq major-mode 'dired-mode)
11462 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11463 (t (org-do-occur (match-string 1 s)))))
11465 ;; A normal search strings
11466 (when (equal (string-to-char s) ?*)
11467 ;; Anchor on headlines, post may include tags.
11468 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11469 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11470 s (substring s 1)))
11471 (remove-text-properties
11472 0 (length s)
11473 '(face nil mouse-face nil keymap nil fontified nil) s)
11474 ;; Make a series of regular expressions to find a match
11475 (setq words (org-split-string s "[ \n\r\t]+")
11476 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11477 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11478 "\\)" markers)
11479 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11480 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11481 re1 (concat pre re2 post)
11482 re3 (concat pre re4 post)
11483 re5 (concat pre ".*" re4)
11484 re2 (concat pre re2)
11485 re2a (concat pre re2a)
11486 re4 (concat pre re4)
11487 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11488 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11489 re5 "\\)"
11491 (cond
11492 ((eq type 'org-occur) (org-occur reall))
11493 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11494 (t (goto-char (point-min))
11495 (if (or (org-search-not-self 1 re0 nil t)
11496 (org-search-not-self 1 re1 nil t)
11497 (org-search-not-self 1 re2 nil t)
11498 (org-search-not-self 1 re2a nil t)
11499 (org-search-not-self 1 re3 nil t)
11500 (org-search-not-self 1 re4 nil t)
11501 (org-search-not-self 1 re5 nil t)
11503 (goto-char (match-beginning 1))
11504 (goto-char pos)
11505 (error "No match")))))
11507 ;; Normal string-search
11508 (goto-char (point-min))
11509 (if (search-forward s nil t)
11510 (goto-char (match-beginning 0))
11511 (error "No match"))))
11512 (and (org-mode-p) (org-show-context 'link-search))))
11514 (defun org-search-not-self (group &rest args)
11515 "Execute `re-search-forward', but only accept matches that do not
11516 enclose the position of `org-open-link-marker'."
11517 (let ((m org-open-link-marker))
11518 (catch 'exit
11519 (while (apply 're-search-forward args)
11520 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11521 (goto-char (match-end group))
11522 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11523 (> (match-beginning 0) (marker-position m))
11524 (< (match-end 0) (marker-position m)))
11525 (save-match-data
11526 (or (not (org-in-regexp
11527 org-bracket-link-analytic-regexp 1))
11528 (not (match-end 4)) ; no description
11529 (and (<= (match-beginning 4) (point))
11530 (>= (match-end 4) (point))))))
11531 (throw 'exit (point))))))))
11533 (defun org-get-buffer-for-internal-link (buffer)
11534 "Return a buffer to be used for displaying the link target of internal links."
11535 (cond
11536 ((not org-display-internal-link-with-indirect-buffer)
11537 buffer)
11538 ((string-match "(Clone)$" (buffer-name buffer))
11539 (message "Buffer is already a clone, not making another one")
11540 ;; we also do not modify visibility in this case
11541 buffer)
11542 (t ; make a new indirect buffer for displaying the link
11543 (let* ((bn (buffer-name buffer))
11544 (ibn (concat bn "(Clone)"))
11545 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11546 (with-current-buffer ib (org-overview))
11547 ib))))
11549 (defun org-do-occur (regexp &optional cleanup)
11550 "Call the Emacs command `occur'.
11551 If CLEANUP is non-nil, remove the printout of the regular expression
11552 in the *Occur* buffer. This is useful if the regex is long and not useful
11553 to read."
11554 (occur regexp)
11555 (when cleanup
11556 (let ((cwin (selected-window)) win beg end)
11557 (when (setq win (get-buffer-window "*Occur*"))
11558 (select-window win))
11559 (goto-char (point-min))
11560 (when (re-search-forward "match[a-z]+" nil t)
11561 (setq beg (match-end 0))
11562 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11563 (setq end (1- (match-beginning 0)))))
11564 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11565 (goto-char (point-min))
11566 (select-window cwin))))
11568 ;;; The mark ring for links jumps
11570 (defvar org-mark-ring nil
11571 "Mark ring for positions before jumps in Org-mode.")
11572 (defvar org-mark-ring-last-goto nil
11573 "Last position in the mark ring used to go back.")
11574 ;; Fill and close the ring
11575 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11576 (loop for i from 1 to org-mark-ring-length do
11577 (push (make-marker) org-mark-ring))
11578 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11579 org-mark-ring)
11581 (defun org-mark-ring-push (&optional pos buffer)
11582 "Put the current position or POS into the mark ring and rotate it."
11583 (interactive)
11584 (setq pos (or pos (point)))
11585 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11586 (move-marker (car org-mark-ring)
11587 (or pos (point))
11588 (or buffer (current-buffer)))
11589 (message
11590 (substitute-command-keys
11591 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11593 (defun org-mark-ring-goto (&optional n)
11594 "Jump to the previous position in the mark ring.
11595 With prefix arg N, jump back that many stored positions. When
11596 called several times in succession, walk through the entire ring.
11597 Org-mode commands jumping to a different position in the current file,
11598 or to another Org-mode file, automatically push the old position
11599 onto the ring."
11600 (interactive "p")
11601 (let (p m)
11602 (if (eq last-command this-command)
11603 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11604 (setq p org-mark-ring))
11605 (setq org-mark-ring-last-goto p)
11606 (setq m (car p))
11607 (switch-to-buffer (marker-buffer m))
11608 (goto-char m)
11609 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11611 (defun org-remove-angle-brackets (s)
11612 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11613 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11615 (defun org-add-angle-brackets (s)
11616 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11617 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11620 ;;; Following specific links
11622 (defun org-follow-timestamp-link ()
11623 (cond
11624 ((org-at-date-range-p t)
11625 (let ((org-agenda-start-on-weekday)
11626 (t1 (match-string 1))
11627 (t2 (match-string 2)))
11628 (setq t1 (time-to-days (org-time-string-to-time t1))
11629 t2 (time-to-days (org-time-string-to-time t2)))
11630 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11631 ((org-at-timestamp-p t)
11632 (org-agenda-list nil (time-to-days (org-time-string-to-time
11633 (substring (match-string 1) 0 10)))
11635 (t (error "This should not happen"))))
11638 (defun org-follow-bbdb-link (name)
11639 "Follow a BBDB link to NAME."
11640 (require 'bbdb)
11641 (let ((inhibit-redisplay (not debug-on-error))
11642 (bbdb-electric-p nil))
11643 (catch 'exit
11644 ;; Exact match on name
11645 (bbdb-name (concat "\\`" name "\\'") nil)
11646 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11647 ;; Exact match on name
11648 (bbdb-company (concat "\\`" name "\\'") nil)
11649 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11650 ;; Partial match on name
11651 (bbdb-name name nil)
11652 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11653 ;; Partial match on company
11654 (bbdb-company name nil)
11655 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11656 ;; General match including network address and notes
11657 (bbdb name nil)
11658 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11659 (delete-window (get-buffer-window "*BBDB*"))
11660 (error "No matching BBDB record")))))
11662 (defun org-follow-info-link (name)
11663 "Follow an info file & node link to NAME."
11664 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11665 (string-match "\\(.*\\)" name))
11666 (progn
11667 (require 'info)
11668 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11669 (Info-find-node (match-string 1 name) (match-string 2 name))
11670 (Info-find-node (match-string 1 name) "Top")))
11671 (message (concat "Could not open: " name))))
11673 (defun org-follow-gnus-link (&optional group article)
11674 "Follow a Gnus link to GROUP and ARTICLE."
11675 (require 'gnus)
11676 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11677 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11678 (cond ((and group article)
11679 (gnus-group-read-group 1 nil group)
11680 (gnus-summary-goto-article (string-to-number article) nil t))
11681 (group (gnus-group-jump-to-group group))))
11683 (defun org-follow-vm-link (&optional folder article readonly)
11684 "Follow a VM link to FOLDER and ARTICLE."
11685 (require 'vm)
11686 (setq article (org-add-angle-brackets article))
11687 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11688 ;; ange-ftp or efs or tramp access
11689 (let ((user (or (match-string 1 folder) (user-login-name)))
11690 (host (match-string 2 folder))
11691 (file (match-string 3 folder)))
11692 (cond
11693 ((featurep 'tramp)
11694 ;; use tramp to access the file
11695 (if (featurep 'xemacs)
11696 (setq folder (format "[%s@%s]%s" user host file))
11697 (setq folder (format "/%s@%s:%s" user host file))))
11699 ;; use ange-ftp or efs
11700 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11701 (setq folder (format "/%s@%s:%s" user host file))))))
11702 (when folder
11703 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11704 (sit-for 0.1)
11705 (when article
11706 (vm-select-folder-buffer)
11707 (widen)
11708 (let ((case-fold-search t))
11709 (goto-char (point-min))
11710 (if (not (re-search-forward
11711 (concat "^" "message-id: *" (regexp-quote article))))
11712 (error "Could not find the specified message in this folder"))
11713 (vm-isearch-update)
11714 (vm-isearch-narrow)
11715 (vm-beginning-of-message)
11716 (vm-summarize)))))
11718 (defun org-follow-wl-link (folder article)
11719 "Follow a Wanderlust link to FOLDER and ARTICLE."
11720 (if (and (string= folder "%")
11721 article
11722 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11723 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11724 ;; Thus, we recompose folder and article ids.
11725 (setq folder (format "%s#%s" folder (match-string 1 article))
11726 article (match-string 3 article)))
11727 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11728 (error "No such folder: %s" folder))
11729 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11730 (and article
11731 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11732 (wl-summary-redisplay)))
11734 (defun org-follow-rmail-link (folder article)
11735 "Follow an RMAIL link to FOLDER and ARTICLE."
11736 (setq article (org-add-angle-brackets article))
11737 (let (message-number)
11738 (save-excursion
11739 (save-window-excursion
11740 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11741 (setq message-number
11742 (save-restriction
11743 (widen)
11744 (goto-char (point-max))
11745 (if (re-search-backward
11746 (concat "^Message-ID:\\s-+" (regexp-quote
11747 (or article "")))
11748 nil t)
11749 (rmail-what-message))))))
11750 (if message-number
11751 (progn
11752 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11753 (rmail-show-message message-number)
11754 message-number)
11755 (error "Message not found"))))
11757 ;;; mh-e integration based on planner-mode
11758 (defun org-mhe-get-message-real-folder ()
11759 "Return the name of the current message real folder, so if you use
11760 sequences, it will now work."
11761 (save-excursion
11762 (let* ((folder
11763 (if (equal major-mode 'mh-folder-mode)
11764 mh-current-folder
11765 ;; Refer to the show buffer
11766 mh-show-folder-buffer))
11767 (end-index
11768 (if (boundp 'mh-index-folder)
11769 (min (length mh-index-folder) (length folder))))
11771 ;; a simple test on mh-index-data does not work, because
11772 ;; mh-index-data is always nil in a show buffer.
11773 (if (and (boundp 'mh-index-folder)
11774 (string= mh-index-folder (substring folder 0 end-index)))
11775 (if (equal major-mode 'mh-show-mode)
11776 (save-window-excursion
11777 (when (buffer-live-p (get-buffer folder))
11778 (progn
11779 (pop-to-buffer folder)
11780 (org-mhe-get-message-folder-from-index)
11783 (org-mhe-get-message-folder-from-index)
11785 folder
11789 (defun org-mhe-get-message-folder-from-index ()
11790 "Returns the name of the message folder in a index folder buffer."
11791 (save-excursion
11792 (mh-index-previous-folder)
11793 (re-search-forward "^\\(+.*\\)$" nil t)
11794 (message (match-string 1))))
11796 (defun org-mhe-get-message-folder ()
11797 "Return the name of the current message folder. Be careful if you
11798 use sequences."
11799 (save-excursion
11800 (if (equal major-mode 'mh-folder-mode)
11801 mh-current-folder
11802 ;; Refer to the show buffer
11803 mh-show-folder-buffer)))
11805 (defun org-mhe-get-message-num ()
11806 "Return the number of the current message. Be careful if you
11807 use sequences."
11808 (save-excursion
11809 (if (equal major-mode 'mh-folder-mode)
11810 (mh-get-msg-num nil)
11811 ;; Refer to the show buffer
11812 (mh-show-buffer-message-number))))
11814 (defun org-mhe-get-header (header)
11815 "Return a header of the message in folder mode. This will create a
11816 show buffer for the corresponding message. If you have a more clever
11817 idea..."
11818 (let* ((folder (org-mhe-get-message-folder))
11819 (num (org-mhe-get-message-num))
11820 (buffer (get-buffer-create (concat "show-" folder)))
11821 (header-field))
11822 (with-current-buffer buffer
11823 (mh-display-msg num folder)
11824 (if (equal major-mode 'mh-folder-mode)
11825 (mh-header-display)
11826 (mh-show-header-display))
11827 (set-buffer buffer)
11828 (setq header-field (mh-get-header-field header))
11829 (if (equal major-mode 'mh-folder-mode)
11830 (mh-show)
11831 (mh-show-show))
11832 header-field)))
11834 (defun org-follow-mhe-link (folder article)
11835 "Follow an MHE link to FOLDER and ARTICLE.
11836 If ARTICLE is nil FOLDER is shown. If the configuration variable
11837 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11838 ARTICLE is searched in all folders. Indexed searches (swish++,
11839 namazu, and others supported by MH-E) will always search in all
11840 folders."
11841 (require 'mh-e)
11842 (require 'mh-search)
11843 (require 'mh-utils)
11844 (mh-find-path)
11845 (if (not article)
11846 (mh-visit-folder (mh-normalize-folder-name folder))
11847 (setq article (org-add-angle-brackets article))
11848 (mh-search-choose)
11849 (if (equal mh-searcher 'pick)
11850 (progn
11851 (mh-search folder (list "--message-id" article))
11852 (when (and org-mhe-search-all-folders
11853 (not (org-mhe-get-message-real-folder)))
11854 (kill-this-buffer)
11855 (mh-search "+" (list "--message-id" article))))
11856 (mh-search "+" article))
11857 (if (org-mhe-get-message-real-folder)
11858 (mh-show-msg 1)
11859 (kill-this-buffer)
11860 (error "Message not found"))))
11862 ;;; BibTeX links
11864 ;; Use the custom search meachnism to construct and use search strings for
11865 ;; file links to BibTeX database entries.
11867 (defun org-create-file-search-in-bibtex ()
11868 "Create the search string and description for a BibTeX database entry."
11869 (when (eq major-mode 'bibtex-mode)
11870 ;; yes, we want to construct this search string.
11871 ;; Make a good description for this entry, using names, year and the title
11872 ;; Put it into the `description' variable which is dynamically scoped.
11873 (let ((bibtex-autokey-names 1)
11874 (bibtex-autokey-names-stretch 1)
11875 (bibtex-autokey-name-case-convert-function 'identity)
11876 (bibtex-autokey-name-separator " & ")
11877 (bibtex-autokey-additional-names " et al.")
11878 (bibtex-autokey-year-length 4)
11879 (bibtex-autokey-name-year-separator " ")
11880 (bibtex-autokey-titlewords 3)
11881 (bibtex-autokey-titleword-separator " ")
11882 (bibtex-autokey-titleword-case-convert-function 'identity)
11883 (bibtex-autokey-titleword-length 'infty)
11884 (bibtex-autokey-year-title-separator ": "))
11885 (setq description (bibtex-generate-autokey)))
11886 ;; Now parse the entry, get the key and return it.
11887 (save-excursion
11888 (bibtex-beginning-of-entry)
11889 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11891 (defun org-execute-file-search-in-bibtex (s)
11892 "Find the link search string S as a key for a database entry."
11893 (when (eq major-mode 'bibtex-mode)
11894 ;; Yes, we want to do the search in this file.
11895 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11896 (goto-char (point-min))
11897 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11898 (regexp-quote s) "[ \t\n]*,") nil t)
11899 (goto-char (match-beginning 0)))
11900 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11901 ;; Use double prefix to indicate that any web link should be browsed
11902 (let ((b (current-buffer)) (p (point)))
11903 ;; Restore the window configuration because we just use the web link
11904 (set-window-configuration org-window-config-before-follow-link)
11905 (save-excursion (set-buffer b) (goto-char p)
11906 (bibtex-url)))
11907 (recenter 0)) ; Move entry start to beginning of window
11908 ;; return t to indicate that the search is done.
11911 ;; Finally add the functions to the right hooks.
11912 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11913 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11915 ;; end of Bibtex link setup
11917 ;;; Following file links
11919 (defun org-open-file (path &optional in-emacs line search)
11920 "Open the file at PATH.
11921 First, this expands any special file name abbreviations. Then the
11922 configuration variable `org-file-apps' is checked if it contains an
11923 entry for this file type, and if yes, the corresponding command is launched.
11924 If no application is found, Emacs simply visits the file.
11925 With optional argument IN-EMACS, Emacs will visit the file.
11926 Optional LINE specifies a line to go to, optional SEARCH a string to
11927 search for. If LINE or SEARCH is given, the file will always be
11928 opened in Emacs.
11929 If the file does not exist, an error is thrown."
11930 (setq in-emacs (or in-emacs line search))
11931 (let* ((file (if (equal path "")
11932 buffer-file-name
11933 (substitute-in-file-name (expand-file-name path))))
11934 (apps (append org-file-apps (org-default-apps)))
11935 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11936 (dirp (if remp nil (file-directory-p file)))
11937 (dfile (downcase file))
11938 (old-buffer (current-buffer))
11939 (old-pos (point))
11940 (old-mode major-mode)
11941 ext cmd)
11942 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11943 (setq ext (match-string 1 dfile))
11944 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11945 (setq ext (match-string 1 dfile))))
11946 (if in-emacs
11947 (setq cmd 'emacs)
11948 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11949 (and dirp (cdr (assoc 'directory apps)))
11950 (cdr (assoc ext apps))
11951 (cdr (assoc t apps)))))
11952 (when (eq cmd 'mailcap)
11953 (require 'mailcap)
11954 (mailcap-parse-mailcaps)
11955 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11956 (command (mailcap-mime-info mime-type)))
11957 (if (stringp command)
11958 (setq cmd command)
11959 (setq cmd 'emacs))))
11960 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11961 (not (file-exists-p file))
11962 (not org-open-non-existing-files))
11963 (error "No such file: %s" file))
11964 (cond
11965 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11966 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11967 (if (string-match "['\"]%s['\"]" cmd)
11968 (setq cmd (replace-match "%s" t t cmd)))
11969 (setq cmd (format cmd (shell-quote-argument file)))
11970 (save-window-excursion
11971 (shell-command (concat cmd " &"))))
11972 ((or (stringp cmd)
11973 (eq cmd 'emacs))
11974 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11975 (widen)
11976 (if line (goto-line line)
11977 (if search (org-link-search search))))
11978 ((consp cmd)
11979 (eval cmd))
11980 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11981 (and (org-mode-p) (eq old-mode 'org-mode)
11982 (or (not (equal old-buffer (current-buffer)))
11983 (not (equal old-pos (point))))
11984 (org-mark-ring-push old-pos old-buffer))))
11986 (defun org-default-apps ()
11987 "Return the default applications for this operating system."
11988 (cond
11989 ((eq system-type 'darwin)
11990 org-file-apps-defaults-macosx)
11991 ((eq system-type 'windows-nt)
11992 org-file-apps-defaults-windowsnt)
11993 (t org-file-apps-defaults-gnu)))
11995 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11996 (defun org-file-remote-p (file)
11997 "Test whether FILE specifies a location on a remote system.
11998 Return non-nil if the location is indeed remote.
12000 For example, the filename \"/user@host:/foo\" specifies a location
12001 on the system \"/user@host:\"."
12002 (cond ((fboundp 'file-remote-p)
12003 (file-remote-p file))
12004 ((fboundp 'tramp-handle-file-remote-p)
12005 (tramp-handle-file-remote-p file))
12006 ((and (boundp 'ange-ftp-name-format)
12007 (string-match (car ange-ftp-name-format) file))
12009 (t nil)))
12012 ;;;; Hooks for remember.el
12014 ;;;###autoload
12015 (defun org-remember-annotation ()
12016 "Return a link to the current location as an annotation for remember.el.
12017 If you are using Org-mode files as target for data storage with
12018 remember.el, then the annotations should include a link compatible with the
12019 conventions in Org-mode. This function returns such a link."
12020 (org-store-link nil))
12022 (defconst org-remember-help
12023 "Select a destination location for the note.
12024 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12025 RET at beg-of-buf -> Append to file as level 2 headline
12026 RET on headline -> Store as sublevel entry to current headline
12027 <left>/<right> -> before/after current headline, same headings level")
12029 ;;;###autoload
12030 (defun org-remember-apply-template (&optional use-char skip-interactive)
12031 "Initialize *remember* buffer with template, invoke `org-mode'.
12032 This function should be placed into `remember-mode-hook' and in fact requires
12033 to be run from that hook to fucntion properly."
12034 (if org-remember-templates
12036 (let* ((char (or use-char
12037 (if (= (length org-remember-templates) 1)
12038 (caar org-remember-templates)
12039 (message "Select template: %s"
12040 (mapconcat
12041 (lambda (x) (char-to-string (car x)))
12042 org-remember-templates " "))
12043 (read-char-exclusive))))
12044 (entry (cdr (assoc char org-remember-templates)))
12045 (tpl (car entry))
12046 (plist-p (if org-store-link-plist t nil))
12047 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12048 (string-match "\\S-" (nth 1 entry)))
12049 (nth 1 entry)
12050 org-default-notes-file))
12051 (headline (nth 2 entry))
12052 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12053 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12054 (v-u (concat "[" (substring v-t 1 -1) "]"))
12055 (v-U (concat "[" (substring v-T 1 -1) "]"))
12056 (v-i initial) ; defined in `remember-mode'
12057 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
12058 (v-n user-full-name)
12059 (org-startup-folded nil)
12060 org-time-was-given org-end-time-was-given x prompt char time)
12061 (setq org-store-link-plist
12062 (append (list :annotation v-a :initial v-i)
12063 org-store-link-plist))
12064 (unless tpl (setq tpl "") (message "No template") (ding))
12065 (erase-buffer)
12066 (insert (substitute-command-keys
12067 (format
12068 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
12069 ## Target file \"%s\", headline \"%s\"
12070 ## To switch templates, use `\\[org-remember]'.\n\n"
12071 (abbreviate-file-name (or file org-default-notes-file))
12072 (or headline ""))))
12073 (insert tpl) (goto-char (point-min))
12074 ;; Simple %-escapes
12075 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
12076 (when (and initial (equal (match-string 0) "%i"))
12077 (save-match-data
12078 (let* ((lead (buffer-substring
12079 (point-at-bol) (match-beginning 0))))
12080 (setq v-i (mapconcat 'identity
12081 (org-split-string initial "\n")
12082 (concat "\n" lead))))))
12083 (replace-match
12084 (or (eval (intern (concat "v-" (match-string 1)))) "")
12085 t t))
12086 ;; From the property list
12087 (when plist-p
12088 (goto-char (point-min))
12089 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12090 (and (setq x (plist-get org-store-link-plist
12091 (intern (match-string 1))))
12092 (replace-match x t t))))
12093 ;; Turn on org-mode in the remember buffer, set local variables
12094 (org-mode)
12095 (org-set-local 'org-finish-function 'remember-buffer)
12096 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12097 (org-set-local 'org-default-notes-file file))
12098 (if (and headline (stringp headline) (string-match "\\S-" headline))
12099 (org-set-local 'org-remember-default-headline headline))
12100 ;; Interactive template entries
12101 (goto-char (point-min))
12102 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12103 (setq char (if (match-end 3) (match-string 3))
12104 prompt (if (match-end 2) (match-string 2)))
12105 (goto-char (match-beginning 0))
12106 (replace-match "")
12107 (cond
12108 ((member char '("G" "g"))
12109 (let* ((org-last-tags-completion-table
12110 (org-global-tags-completion-table
12111 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12112 (org-add-colon-after-tag-completion t)
12113 (ins (completing-read
12114 (if prompt (concat prompt ": ") "Tags: ")
12115 'org-tags-completion-function nil nil nil
12116 'org-tags-history)))
12117 (setq ins (mapconcat 'identity
12118 (org-split-string ins (org-re "[^[:alnum:]]+"))
12119 ":"))
12120 (when (string-match "\\S-" ins)
12121 (or (equal (char-before) ?:) (insert ":"))
12122 (insert ins)
12123 (or (equal (char-after) ?:) (insert ":")))))
12124 (char
12125 (setq org-time-was-given (equal (upcase char) char))
12126 (setq time (org-read-date (equal (upcase char) "U") t nil
12127 prompt))
12128 (org-insert-time-stamp time org-time-was-given
12129 (member char '("u" "U"))
12130 nil nil (list org-end-time-was-given)))
12132 (insert (read-string
12133 (if prompt (concat prompt ": ") "Enter string"))))))
12134 (goto-char (point-min))
12135 (if (re-search-forward "%\\?" nil t)
12136 (replace-match "")
12137 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12138 (org-mode)
12139 (org-set-local 'org-finish-function 'remember-buffer)))
12141 ;;;###autoload
12142 (defun org-remember ()
12143 "Call `remember'. If this is already a remember buffer, re-apply template.
12144 If there is an active region, make sure remember uses it as initial content
12145 of the remember buffer."
12146 (interactive)
12147 (if (eq org-finish-function 'remember-buffer)
12148 (progn
12149 (when (< (length org-remember-templates) 2)
12150 (error "No other template available"))
12151 (erase-buffer)
12152 (let ((annotation (plist-get org-store-link-plist :annotation))
12153 (initial (plist-get org-store-link-plist :initial)))
12154 (org-remember-apply-template))
12155 (message "Press C-c C-c to remember data"))
12156 (if (org-region-active-p)
12157 (remember (buffer-substring (point) (mark)))
12158 (call-interactively 'remember))))
12160 ;;;###autoload
12161 (defun org-remember-handler ()
12162 "Store stuff from remember.el into an org file.
12163 First prompts for an org file. If the user just presses return, the value
12164 of `org-default-notes-file' is used.
12165 Then the command offers the headings tree of the selected file in order to
12166 file the text at a specific location.
12167 You can either immediately press RET to get the note appended to the
12168 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12169 find a better place. Then press RET or <left> or <right> in insert the note.
12171 Key Cursor position Note gets inserted
12172 -----------------------------------------------------------------------------
12173 RET buffer-start as level 2 heading at end of file
12174 RET on headline as sublevel of the heading at cursor
12175 RET no heading at cursor position, level taken from context.
12176 Or use prefix arg to specify level manually.
12177 <left> on headline as same level, before current heading
12178 <right> on headline as same level, after current heading
12180 So the fastest way to store the note is to press RET RET to append it to
12181 the default file. This way your current train of thought is not
12182 interrupted, in accordance with the principles of remember.el.
12183 You can also get the fast execution without prompting by using
12184 C-u C-c C-c to exit the remember buffer. See also the variable
12185 `org-remember-store-without-prompt'.
12187 Before being stored away, the function ensures that the text has a
12188 headline, i.e. a first line that starts with a \"*\". If not, a headline
12189 is constructed from the current date and some additional data.
12191 If the variable `org-adapt-indentation' is non-nil, the entire text is
12192 also indented so that it starts in the same column as the headline
12193 \(i.e. after the stars).
12195 See also the variable `org-reverse-note-order'."
12196 (goto-char (point-min))
12197 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12198 (replace-match ""))
12199 (catch 'quit
12200 (let* ((txt (buffer-substring (point-min) (point-max)))
12201 (fastp (org-xor (equal current-prefix-arg '(4))
12202 org-remember-store-without-prompt))
12203 (file (if fastp org-default-notes-file (org-get-org-file)))
12204 (heading org-remember-default-headline)
12205 (visiting (org-find-base-buffer-visiting file))
12206 (org-startup-folded nil)
12207 (org-startup-align-all-tables nil)
12208 (org-goto-start-pos 1)
12209 spos level indent reversed)
12210 (setq current-prefix-arg nil)
12211 ;; Modify text so that it becomes a nice subtree which can be inserted
12212 ;; into an org tree.
12213 (let* ((lines (split-string txt "\n"))
12214 first)
12215 (setq first (car lines) lines (cdr lines))
12216 (if (string-match "^\\*+ " first)
12217 ;; Is already a headline
12218 (setq indent nil)
12219 ;; We need to add a headline: Use time and first buffer line
12220 (setq lines (cons first lines)
12221 first (concat "* " (current-time-string)
12222 " (" (remember-buffer-desc) ")")
12223 indent " "))
12224 (if (and org-adapt-indentation indent)
12225 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12226 (setq txt (concat first "\n"
12227 (mapconcat 'identity lines "\n"))))
12228 ;; Find the file
12229 (if (not visiting) (find-file-noselect file))
12230 (with-current-buffer (or visiting (get-file-buffer file))
12231 (save-excursion
12232 (save-restriction
12233 (widen)
12234 (and (goto-char (point-min))
12235 (not (re-search-forward "^\\* " nil t))
12236 (insert "\n* Notes\n"))
12237 (setq reversed (org-notes-order-reversed-p))
12239 ;; Find the default location
12240 (when (and heading (stringp heading) (string-match "\\S-" heading))
12241 (goto-char (point-min))
12242 (if (re-search-forward
12243 (concat "^\\*+[ \t]+" (regexp-quote heading)
12244 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12245 nil t)
12246 (setq org-goto-start-pos (match-beginning 0))))
12248 ;; Ask the User for a location
12249 (setq spos (if fastp
12250 org-goto-start-pos
12251 (org-get-location (current-buffer) org-remember-help)))
12252 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12253 ; not handle this note
12254 (goto-char spos)
12255 (cond ((and (bobp) (not reversed))
12256 ;; Put it at the end, one level below level 1
12257 (save-restriction
12258 (widen)
12259 (goto-char (point-max))
12260 (if (not (bolp)) (newline))
12261 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12262 ((and (bobp) reversed)
12263 ;; Put it at the start, as level 1
12264 (save-restriction
12265 (widen)
12266 (goto-char (point-min))
12267 (re-search-forward "^\\*+ " nil t)
12268 (beginning-of-line 1)
12269 (org-paste-subtree 1 txt)))
12270 ((and (org-on-heading-p t) (not current-prefix-arg))
12271 ;; Put it below this entry, at the beg/end of the subtree
12272 (org-back-to-heading t)
12273 (setq level (funcall outline-level))
12274 (if reversed
12275 (outline-next-heading)
12276 (org-end-of-subtree t))
12277 (if (not (bolp)) (newline))
12278 (beginning-of-line 1)
12279 (org-paste-subtree (org-get-legal-level level 1) txt))
12281 ;; Put it right there, with automatic level determined by
12282 ;; org-paste-subtree or from prefix arg
12283 (org-paste-subtree
12284 (if (numberp current-prefix-arg) current-prefix-arg)
12285 txt)))
12286 (when remember-save-after-remembering
12287 (save-buffer)
12288 (if (not visiting) (kill-buffer (current-buffer)))))))))
12289 t) ;; return t to indicate that we took care of this note.
12291 (defun org-get-org-file ()
12292 "Read a filename, with default directory `org-directory'."
12293 (let ((default (or org-default-notes-file remember-data-file)))
12294 (read-file-name (format "File name [%s]: " default)
12295 (file-name-as-directory org-directory)
12296 default)))
12298 (defun org-notes-order-reversed-p ()
12299 "Check if the current file should receive notes in reversed order."
12300 (cond
12301 ((not org-reverse-note-order) nil)
12302 ((eq t org-reverse-note-order) t)
12303 ((not (listp org-reverse-note-order)) nil)
12304 (t (catch 'exit
12305 (let ((all org-reverse-note-order)
12306 entry)
12307 (while (setq entry (pop all))
12308 (if (string-match (car entry) buffer-file-name)
12309 (throw 'exit (cdr entry))))
12310 nil)))))
12312 ;;;; Dynamic blocks
12314 (defun org-find-dblock (name)
12315 "Find the first dynamic block with name NAME in the buffer.
12316 If not found, stay at current position and return nil."
12317 (let (pos)
12318 (save-excursion
12319 (goto-char (point-min))
12320 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12321 nil t)
12322 (match-beginning 0))))
12323 (if pos (goto-char pos))
12324 pos))
12326 (defconst org-dblock-start-re
12327 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12328 "Matches the startline of a dynamic block, with parameters.")
12330 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12331 "Matches the end of a dyhamic block.")
12333 (defun org-create-dblock (plist)
12334 "Create a dynamic block section, with parameters taken from PLIST.
12335 PLIST must containe a :name entry which is used as name of the block."
12336 (unless (bolp) (newline))
12337 (let ((name (plist-get plist :name)))
12338 (insert "#+BEGIN: " name)
12339 (while plist
12340 (if (eq (car plist) :name)
12341 (setq plist (cddr plist))
12342 (insert " " (prin1-to-string (pop plist)))))
12343 (insert "\n\n#+END:\n")
12344 (beginning-of-line -2)))
12346 (defun org-prepare-dblock ()
12347 "Prepare dynamic block for refresh.
12348 This empties the block, puts the cursor at the insert position and returns
12349 the property list including an extra property :name with the block name."
12350 (unless (looking-at org-dblock-start-re)
12351 (error "Not at a dynamic block"))
12352 (let* ((begdel (1+ (match-end 0)))
12353 (name (match-string 1))
12354 (params (append (list :name name)
12355 (read (concat "(" (match-string 3) ")")))))
12356 (unless (re-search-forward org-dblock-end-re nil t)
12357 (error "Dynamic block not terminated"))
12358 (delete-region begdel (match-beginning 0))
12359 (goto-char begdel)
12360 (open-line 1)
12361 params))
12363 (defun org-map-dblocks (&optional command)
12364 "Apply COMMAND to all dynamic blocks in the current buffer.
12365 If COMMAND is not given, use `org-update-dblock'."
12366 (let ((cmd (or command 'org-update-dblock))
12367 pos)
12368 (save-excursion
12369 (goto-char (point-min))
12370 (while (re-search-forward org-dblock-start-re nil t)
12371 (goto-char (setq pos (match-beginning 0)))
12372 (condition-case nil
12373 (funcall cmd)
12374 (error (message "Error during update of dynamic block")))
12375 (goto-char pos)
12376 (unless (re-search-forward org-dblock-end-re nil t)
12377 (error "Dynamic block not terminated"))))))
12379 (defun org-dblock-update (&optional arg)
12380 "User command for updating dynamic blocks.
12381 Update the dynamic block at point. With prefix ARG, update all dynamic
12382 blocks in the buffer."
12383 (interactive "P")
12384 (if arg
12385 (org-update-all-dblocks)
12386 (or (looking-at org-dblock-start-re)
12387 (org-beginning-of-dblock))
12388 (org-update-dblock)))
12390 (defun org-update-dblock ()
12391 "Update the dynamic block at point
12392 This means to empty the block, parse for parameters and then call
12393 the correct writing function."
12394 (let* ((pos (point))
12395 (params (org-prepare-dblock))
12396 (name (plist-get params :name))
12397 (cmd (intern (concat "org-dblock-write:" name))))
12398 (funcall cmd params)
12399 (goto-char pos)))
12401 (defun org-beginning-of-dblock ()
12402 "Find the beginning of the dynamic block at point.
12403 Error if there is no scuh block at point."
12404 (let ((pos (point))
12405 beg)
12406 (end-of-line 1)
12407 (if (and (re-search-backward org-dblock-start-re nil t)
12408 (setq beg (match-beginning 0))
12409 (re-search-forward org-dblock-end-re nil t)
12410 (> (match-end 0) pos))
12411 (goto-char beg)
12412 (goto-char pos)
12413 (error "Not in a dynamic block"))))
12415 (defun org-update-all-dblocks ()
12416 "Update all dynamic blocks in the buffer.
12417 This function can be used in a hook."
12418 (when (org-mode-p)
12419 (org-map-dblocks 'org-update-dblock)))
12422 ;;;; Completion
12424 (defun org-complete (&optional arg)
12425 "Perform completion on word at point.
12426 At the beginning of a headline, this completes TODO keywords as given in
12427 `org-todo-keywords'.
12428 If the current word is preceded by a backslash, completes the TeX symbols
12429 that are supported for HTML support.
12430 If the current word is preceded by \"#+\", completes special words for
12431 setting file options.
12432 In the line after \"#+STARTUP:, complete valid keywords.\"
12433 At all other locations, this simply calls `ispell-complete-word'."
12434 (interactive "P")
12435 (catch 'exit
12436 (let* ((end (point))
12437 (beg1 (save-excursion
12438 (skip-chars-backward (org-re "[:alnum:]_@"))
12439 (point)))
12440 (beg (save-excursion
12441 (skip-chars-backward "a-zA-Z0-9_:$")
12442 (point)))
12443 (confirm (lambda (x) (stringp (car x))))
12444 (searchhead (equal (char-before beg) ?*))
12445 (tag (and (equal (char-before beg1) ?:)
12446 (equal (char-after (point-at-bol)) ?*)))
12447 (prop (and (equal (char-before beg1) ?:)
12448 (not (equal (char-after (point-at-bol)) ?*))))
12449 (texp (equal (char-before beg) ?\\))
12450 (link (equal (char-before beg) ?\[))
12451 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12452 beg)
12453 "#+"))
12454 (startup (string-match "^#\\+STARTUP:.*"
12455 (buffer-substring (point-at-bol) (point))))
12456 (completion-ignore-case opt)
12457 (type nil)
12458 (tbl nil)
12459 (table (cond
12460 (opt
12461 (setq type :opt)
12462 (mapcar (lambda (x)
12463 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12464 (cons (match-string 2 x) (match-string 1 x)))
12465 (org-split-string (org-get-current-options) "\n")))
12466 (startup
12467 (setq type :startup)
12468 org-startup-options)
12469 (link (append org-link-abbrev-alist-local
12470 org-link-abbrev-alist))
12471 (texp
12472 (setq type :tex)
12473 org-html-entities)
12474 ((string-match "\\`\\*+[ \t]+\\'"
12475 (buffer-substring (point-at-bol) beg))
12476 (setq type :todo)
12477 (mapcar 'list org-todo-keywords-1))
12478 (searchhead
12479 (setq type :searchhead)
12480 (save-excursion
12481 (goto-char (point-min))
12482 (while (re-search-forward org-todo-line-regexp nil t)
12483 (push (list
12484 (org-make-org-heading-search-string
12485 (match-string 3) t))
12486 tbl)))
12487 tbl)
12488 (tag (setq type :tag beg beg1)
12489 (or org-tag-alist (org-get-buffer-tags)))
12490 (prop (setq type :prop beg beg1)
12491 (mapcar 'list (org-buffer-property-keys)))
12492 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
12493 (pattern (buffer-substring-no-properties beg end))
12494 (completion (try-completion pattern table confirm)))
12495 (cond ((eq completion t)
12496 (if (equal type :opt)
12497 (insert (substring (cdr (assoc (upcase pattern) table))
12498 (length pattern)))
12499 (if (memq type '(:tag :prop)) (insert ":"))))
12500 ((null completion)
12501 (message "Can't find completion for \"%s\"" pattern)
12502 (ding))
12503 ((not (string= pattern completion))
12504 (delete-region beg end)
12505 (if (string-match " +$" completion)
12506 (setq completion (replace-match "" t t completion)))
12507 (insert completion)
12508 (if (get-buffer-window "*Completions*")
12509 (delete-window (get-buffer-window "*Completions*")))
12510 (if (assoc completion table)
12511 (if (eq type :todo) (insert " ")
12512 (if (memq type '(:tag :prop)) (insert ":"))))
12513 (if (and (equal type :opt) (assoc completion table))
12514 (message "%s" (substitute-command-keys
12515 "Press \\[org-complete] again to insert example settings"))))
12517 (message "Making completion list...")
12518 (let ((list (sort (all-completions pattern table confirm)
12519 'string<)))
12520 (with-output-to-temp-buffer "*Completions*"
12521 (condition-case nil
12522 ;; Protection needed for XEmacs and emacs 21
12523 (display-completion-list list pattern)
12524 (error (display-completion-list list)))))
12525 (message "Making completion list...%s" "done"))))))
12527 ;;;; TODO, DEADLINE, Comments
12529 (defun org-toggle-comment ()
12530 "Change the COMMENT state of an entry."
12531 (interactive)
12532 (save-excursion
12533 (org-back-to-heading)
12534 (if (looking-at (concat outline-regexp
12535 "\\( *\\<" org-comment-string "\\>\\)"))
12536 (replace-match "" t t nil 1)
12537 (if (looking-at outline-regexp)
12538 (progn
12539 (goto-char (match-end 0))
12540 (insert org-comment-string " "))))))
12542 (defvar org-last-todo-state-is-todo nil
12543 "This is non-nil when the last TODO state change led to a TODO state.
12544 If the last change removed the TODO tag or switched to DONE, then
12545 this is nil.")
12547 (defun org-todo (&optional arg)
12548 "Change the TODO state of an item.
12549 The state of an item is given by a keyword at the start of the heading,
12550 like
12551 *** TODO Write paper
12552 *** DONE Call mom
12554 The different keywords are specified in the variable `org-todo-keywords'.
12555 By default the available states are \"TODO\" and \"DONE\".
12556 So for this example: when the item starts with TODO, it is changed to DONE.
12557 When it starts with DONE, the DONE is removed. And when neither TODO nor
12558 DONE are present, add TODO at the beginning of the heading.
12560 With C-u prefix arg, use completion to determine the new state.
12561 With numeric prefix arg, switch to that state.
12563 For calling through lisp, arg is also interpreted in the following way:
12564 'none -> empty state
12565 \"\"(empty string) -> switch to empty state
12566 'done -> switch to DONE
12567 'nextset -> switch to the next set of keywords
12568 'previousset -> switch to the previous set of keywords
12569 \"WAITING\" -> switch to the specified keyword, but only if it
12570 really is a member of `org-todo-keywords'."
12571 (interactive "P")
12572 (save-excursion
12573 (org-back-to-heading)
12574 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
12575 (or (looking-at (concat " +" org-todo-regexp " *"))
12576 (looking-at " *"))
12577 (let* ((this (match-string 1))
12578 (head (org-get-todo-sequence-head this))
12579 (ass (assoc head org-todo-kwd-alist))
12580 (interpret (nth 1 ass))
12581 (done-word (nth 3 ass))
12582 (final-done-word (nth 4 ass))
12583 (last-state (or this ""))
12584 (completion-ignore-case t)
12585 (member (member this org-todo-keywords-1))
12586 (tail (cdr member))
12587 (state (cond
12588 ((equal arg '(4))
12589 ;; Read a state with completion
12590 (completing-read "State: " (mapcar (lambda(x) (list x))
12591 org-todo-keywords-1)
12592 nil t))
12593 ((eq arg 'right)
12594 (if this
12595 (if tail (car tail) nil)
12596 (car org-todo-keywords-1)))
12597 ((eq arg 'left)
12598 (if (equal member org-todo-keywords-1)
12600 (if this
12601 (nth (- (length org-todo-keywords-1) (length tail) 2)
12602 org-todo-keywords-1)
12603 (org-last org-todo-keywords-1))))
12604 (arg
12605 ;; user or caller requests a specific state
12606 (cond
12607 ((equal arg "") nil)
12608 ((eq arg 'none) nil)
12609 ((eq arg 'done) (or done-word (car org-done-keywords)))
12610 ((eq arg 'nextset)
12611 (or (car (cdr (member head org-todo-heads)))
12612 (car org-todo-heads)))
12613 ((eq arg 'previousset)
12614 (let ((org-todo-heads (reverse org-todo-heads)))
12615 (or (car (cdr (member head org-todo-heads)))
12616 (car org-todo-heads))))
12617 ((car (member arg org-todo-keywords-1)))
12618 ((nth (1- (prefix-numeric-value arg))
12619 org-todo-keywords-1))))
12620 ((null member) (or head (car org-todo-keywords-1)))
12621 ((equal this final-done-word) nil) ;; -> make empty
12622 ((null tail) nil) ;; -> first entry
12623 ((eq interpret 'sequence)
12624 (car tail))
12625 ((memq interpret '(type priority))
12626 (if (eq this-command last-command)
12627 (car tail)
12628 (if (> (length tail) 0)
12629 (or done-word (car org-done-keywords))
12630 nil)))
12631 (t nil)))
12632 (next (if state (concat " " state " ") " "))
12633 dostates)
12634 (replace-match next t t)
12635 (unless head
12636 (setq head (org-get-todo-sequence-head state)
12637 ass (assoc head org-todo-kwd-alist)
12638 interpret (nth 1 ass)
12639 done-word (nth 3 ass)
12640 final-done-word (nth 4 ass)))
12641 (when (memq arg '(nextset previousset))
12642 (message "Keyword-Set %d/%d: %s"
12643 (- (length org-todo-sets) -1
12644 (length (memq (assoc state org-todo-sets) org-todo-sets)))
12645 (length org-todo-sets)
12646 (mapconcat 'identity (assoc state org-todo-sets) " ")))
12647 (setq org-last-todo-state-is-todo
12648 (not (member state org-done-keywords)))
12649 (when (and org-log-done (not (memq arg '(nextset previousset))))
12650 (setq dostates (and (eq interpret 'sequence)
12651 (listp org-log-done) (memq 'state org-log-done)))
12652 (cond
12653 ((and state (not this))
12654 ;; FIXME: should we remove CLOSED already then state is nil?
12655 (org-add-planning-info nil nil 'closed)
12656 (and dostates (org-add-log-maybe 'state state 'findpos)))
12657 ((and state dostates)
12658 (org-add-log-maybe 'state state 'findpos))
12659 ((member state org-done-keywords)
12660 ;; Planning info calls the note-setting command.
12661 (org-add-planning-info 'closed (org-current-time)
12662 (if (org-get-repeat) nil 'scheduled))
12663 (org-add-log-maybe 'done state 'findpos))))
12664 ;; Fixup tag positioning
12665 (and org-auto-align-tags (org-set-tags nil t))
12666 (run-hooks 'org-after-todo-state-change-hook)
12667 (and (member state org-done-keywords) (org-auto-repeat-maybe))
12668 (if (and arg (not (member state org-done-keywords)))
12669 (setq head (org-get-todo-sequence-head state)))
12670 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
12671 ;; Fixup cursor location if close to the keyword
12672 (if (and (outline-on-heading-p)
12673 (not (bolp))
12674 (save-excursion (beginning-of-line 1)
12675 (looking-at org-todo-line-regexp))
12676 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12677 (progn
12678 (goto-char (or (match-end 2) (match-end 1)))
12679 (just-one-space))))
12681 (defun org-get-todo-sequence-head (kwd)
12682 "Return the head of the TODO sequence to which KWD belongs.
12683 If KWD is not set, check if there is a text property remembering the
12684 right sequence."
12685 (let (p)
12686 (cond
12687 ((not kwd)
12688 (or (get-text-property (point-at-bol) 'org-todo-head)
12689 (progn
12690 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12691 nil (point-at-eol)))
12692 (get-text-property p 'org-todo-head))))
12693 ((not (member kwd org-todo-keywords-1))
12694 (car org-todo-keywords-1))
12695 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12697 (defun org-get-repeat ()
12698 "Check if tere is a deadline/schedule with repeater in this entry."
12699 (save-match-data
12700 (save-excursion
12701 (org-back-to-heading t)
12702 (if (re-search-forward
12703 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
12704 (match-string 1)))))
12706 (defvar org-last-changed-timestamp)
12707 (defvar org-log-post-message)
12708 (defun org-auto-repeat-maybe ()
12709 "Check if the current headline contains a repeated deadline/schedule.
12710 If yes, set TODO state back to what it was and change the base date
12711 of repeating deadline/scheduled time stamps to new date.
12712 This function should be run in the `org-after-todo-state-change-hook'."
12713 ;; last-state is dynamically scoped into this function
12714 (let* ((repeat (org-get-repeat))
12715 (aa (assoc last-state org-todo-kwd-alist))
12716 (interpret (nth 1 aa))
12717 (head (nth 2 aa))
12718 (done-word (nth 3 aa))
12719 (whata '(("d" . day) ("m" . month) ("y" . year)))
12720 (msg "Entry repeats: ")
12721 (org-log-done)
12722 re type n what ts)
12723 (when repeat
12724 (org-todo (if (eq interpret 'type) last-state head))
12725 (when (and org-log-repeat
12726 (not (memq 'org-add-log-note
12727 (default-value 'post-command-hook))))
12728 ;; Make sure a note is taken
12729 (let ((org-log-done '(done)))
12730 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12731 'findpos)))
12732 (org-back-to-heading t)
12733 (org-add-planning-info nil nil 'closed)
12734 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12735 org-deadline-time-regexp "\\)"))
12736 (while (re-search-forward
12737 re (save-excursion (outline-next-heading) (point)) t)
12738 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12739 ts (match-string (if (match-end 2) 2 4)))
12740 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12741 (setq n (string-to-number (match-string 1 ts))
12742 what (match-string 2 ts))
12743 (if (equal what "w") (setq n (* n 7) what "d"))
12744 (org-timestamp-change n (cdr (assoc what whata))))
12745 (setq msg (concat msg type org-last-changed-timestamp " ")))
12746 (setq org-log-post-message msg)
12747 (message msg))))
12749 (defun org-show-todo-tree (arg)
12750 "Make a compact tree which shows all headlines marked with TODO.
12751 The tree will show the lines where the regexp matches, and all higher
12752 headlines above the match.
12753 With \\[universal-argument] prefix, also show the DONE entries.
12754 With a numeric prefix N, construct a sparse tree for the Nth element
12755 of `org-todo-keywords-1'."
12756 (interactive "P")
12757 (let ((case-fold-search nil)
12758 (kwd-re
12759 (cond ((null arg) org-not-done-regexp)
12760 ((equal arg '(4))
12761 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12762 (mapcar 'list org-todo-keywords-1))))
12763 (concat "\\("
12764 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12765 "\\)\\>")))
12766 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12767 (regexp-quote (nth (1- (prefix-numeric-value arg))
12768 org-todo-keywords-1)))
12769 (t (error "Invalid prefix argument: %s" arg)))))
12770 (message "%d TODO entries found"
12771 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
12773 (defun org-deadline ()
12774 "Insert the DEADLINE: string to make a deadline.
12775 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12776 to modify it to the correct date."
12777 (interactive)
12778 (org-add-planning-info 'deadline nil 'closed))
12780 (defun org-schedule ()
12781 "Insert the SCHEDULED: string to schedule a TODO item.
12782 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12783 to modify it to the correct date."
12784 (interactive)
12785 (org-add-planning-info 'scheduled nil 'closed))
12787 (defun org-add-planning-info (what &optional time &rest remove)
12788 "Insert new timestamp with keyword in the line directly after the headline.
12789 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12790 If non is given, the user is prompted for a date.
12791 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12792 be removed."
12793 (interactive)
12794 (let (org-time-was-given org-end-time-was-given)
12795 (when what (setq time (or time (org-read-date nil 'to-time))))
12796 (when (and org-insert-labeled-timestamps-at-point
12797 (member what '(scheduled deadline)))
12798 (insert
12799 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12800 (org-insert-time-stamp time org-time-was-given
12801 nil nil nil (list org-end-time-was-given))
12802 (setq what nil))
12803 (save-excursion
12804 (save-restriction
12805 (let (col list elt ts buffer-invisibility-spec)
12806 (org-back-to-heading t)
12807 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12808 (goto-char (match-end 1))
12809 (setq col (current-column))
12810 (goto-char (match-end 0))
12811 (if (eobp) (insert "\n"))
12812 (forward-char 1)
12813 (when (and (not org-insert-labeled-timestamps-before-properties-drawer)
12814 (looking-at "[ \t]*:PROPERTIES:[ \t]*$"))
12815 (goto-char (match-end 0))
12816 (if (eobp) (insert "\n"))
12817 (forward-char 1))
12818 (if (and (not (looking-at outline-regexp))
12819 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12820 "[^\r\n]*"))
12821 (not (equal (match-string 1) org-clock-string)))
12822 (narrow-to-region (match-beginning 0) (match-end 0))
12823 (insert-before-markers "\n")
12824 (backward-char 1)
12825 (narrow-to-region (point) (point))
12826 (indent-to-column col))
12827 ;; Check if we have to remove something.
12828 (setq list (cons what remove))
12829 (while list
12830 (setq elt (pop list))
12831 (goto-char (point-min))
12832 (when (or (and (eq elt 'scheduled)
12833 (re-search-forward org-scheduled-time-regexp nil t))
12834 (and (eq elt 'deadline)
12835 (re-search-forward org-deadline-time-regexp nil t))
12836 (and (eq elt 'closed)
12837 (re-search-forward org-closed-time-regexp nil t)))
12838 (replace-match "")
12839 (if (looking-at "--+<[^>]+>") (replace-match ""))
12840 (if (looking-at " +") (replace-match ""))))
12841 (goto-char (point-max))
12842 (when what
12843 (insert
12844 (if (not (equal (char-before) ?\ )) " " "")
12845 (cond ((eq what 'scheduled) org-scheduled-string)
12846 ((eq what 'deadline) org-deadline-string)
12847 ((eq what 'closed) org-closed-string)
12848 ((eq what 'archived) org-archived-string))
12849 " ")
12850 (org-insert-time-stamp
12851 time
12852 (or org-time-was-given
12853 (and (eq what 'closed) org-log-done-with-time))
12854 (eq what 'closed)
12855 nil nil (list org-end-time-was-given))
12856 (end-of-line 1))
12857 (goto-char (point-min))
12858 (widen)
12859 (if (looking-at "[ \t]+\r?\n")
12860 (replace-match ""))
12861 ts)))))
12863 (defvar org-log-note-marker (make-marker))
12864 (defvar org-log-note-purpose nil)
12865 (defvar org-log-note-state nil)
12866 (defvar org-log-note-window-configuration nil)
12867 (defvar org-log-note-return-to (make-marker))
12868 (defvar org-log-post-message nil
12869 "Message to be displayed after a log note has been stored.
12870 The auto-repeater uses this.")
12872 (defun org-add-log-maybe (&optional purpose state findpos)
12873 "Set up the post command hook to take a note."
12874 (save-excursion
12875 (when (and (listp org-log-done)
12876 (memq purpose org-log-done))
12877 (when findpos
12878 (org-back-to-heading t)
12879 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
12880 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12881 "[^\r\n]*\\)?"))
12882 (goto-char (match-end 0))
12883 (unless org-log-states-order-reversed
12884 (if (looking-at "\n[ \t]*- State") (forward-char 1))
12885 (while (looking-at "[ \t]*- State")
12886 (condition-case nil
12887 (org-next-item)
12888 (error (org-end-of-item))))
12889 (skip-chars-backward " \t\n\r")))
12890 (move-marker org-log-note-marker (point))
12891 (setq org-log-note-purpose purpose)
12892 (setq org-log-note-state state)
12893 (add-hook 'post-command-hook 'org-add-log-note 'append))))
12895 (defun org-add-log-note (&optional purpose)
12896 "Pop up a window for taking a note, and add this note later at point."
12897 (remove-hook 'post-command-hook 'org-add-log-note)
12898 (setq org-log-note-window-configuration (current-window-configuration))
12899 (delete-other-windows)
12900 (move-marker org-log-note-return-to (point))
12901 (switch-to-buffer (marker-buffer org-log-note-marker))
12902 (goto-char org-log-note-marker)
12903 (switch-to-buffer-other-window "*Org Note*")
12904 (erase-buffer)
12905 (let ((org-inhibit-startup t)) (org-mode))
12906 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
12907 (cond
12908 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12909 ((eq org-log-note-purpose 'done) "closed todo item")
12910 ((eq org-log-note-purpose 'state) "state change")
12911 (t (error "This should not happen")))))
12912 (org-set-local 'org-finish-function 'org-store-log-note))
12914 (defun org-store-log-note ()
12915 "Finish taking a log note, and insert it to where it belongs."
12916 (let ((txt (buffer-string))
12917 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12918 lines ind)
12919 (kill-buffer (current-buffer))
12920 (if (string-match "^#.*\n[ \t\n]*" txt)
12921 (setq txt (replace-match "" t t txt)))
12922 (if (string-match "\\s-+\\'" txt)
12923 (setq txt (replace-match "" t t txt)))
12924 (setq lines (org-split-string txt "\n"))
12925 (when (and note (string-match "\\S-" note))
12926 (setq note
12927 (org-replace-escapes
12928 note
12929 (list (cons "%u" (user-login-name))
12930 (cons "%U" user-full-name)
12931 (cons "%t" (format-time-string
12932 (org-time-stamp-format 'long 'inactive)
12933 (current-time)))
12934 (cons "%s" (if org-log-note-state
12935 (concat "\"" org-log-note-state "\"")
12936 "")))))
12937 (if lines (setq note (concat note " \\\\")))
12938 (push note lines))
12939 (when lines
12940 (save-excursion
12941 (set-buffer (marker-buffer org-log-note-marker))
12942 (save-excursion
12943 (goto-char org-log-note-marker)
12944 (move-marker org-log-note-marker nil)
12945 (end-of-line 1)
12946 (if (not (bolp)) (insert "\n")) (indent-relative nil)
12947 (insert " - " (pop lines))
12948 (org-indent-line-function)
12949 (beginning-of-line 1)
12950 (looking-at "[ \t]*")
12951 (setq ind (concat (match-string 0) " "))
12952 (end-of-line 1)
12953 (while lines (insert "\n" ind (pop lines)))))))
12954 (set-window-configuration org-log-note-window-configuration)
12955 (with-current-buffer (marker-buffer org-log-note-return-to)
12956 (goto-char org-log-note-return-to))
12957 (move-marker org-log-note-return-to nil)
12958 (and org-log-post-message (message org-log-post-message)))
12960 (defvar org-occur-highlights nil)
12961 (make-variable-buffer-local 'org-occur-highlights)
12963 (defun org-occur (regexp &optional keep-previous callback)
12964 "Make a compact tree which shows all matches of REGEXP.
12965 The tree will show the lines where the regexp matches, and all higher
12966 headlines above the match. It will also show the heading after the match,
12967 to make sure editing the matching entry is easy.
12968 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12969 call to `org-occur' will be kept, to allow stacking of calls to this
12970 command.
12971 If CALLBACK is non-nil, it is a function which is called to confirm
12972 that the match should indeed be shown."
12973 (interactive "sRegexp: \nP")
12974 (or keep-previous (org-remove-occur-highlights nil nil t))
12975 (let ((cnt 0))
12976 (save-excursion
12977 (goto-char (point-min))
12978 (if (or (not keep-previous) ; do not want to keep
12979 (not org-occur-highlights)) ; no previous matches
12980 ;; hide everything
12981 (org-overview))
12982 (while (re-search-forward regexp nil t)
12983 (when (or (not callback)
12984 (save-match-data (funcall callback)))
12985 (setq cnt (1+ cnt))
12986 (when org-highlight-sparse-tree-matches
12987 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12988 (org-show-context 'occur-tree))))
12989 (when org-remove-highlights-with-change
12990 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12991 nil 'local))
12992 (unless org-sparse-tree-open-archived-trees
12993 (org-hide-archived-subtrees (point-min) (point-max)))
12994 (run-hooks 'org-occur-hook)
12995 (if (interactive-p)
12996 (message "%d match(es) for regexp %s" cnt regexp))
12997 cnt))
12999 (defun org-show-context (&optional key)
13000 "Make sure point and context and visible.
13001 How much context is shown depends upon the variables
13002 `org-show-hierarchy-above', `org-show-following-heading'. and
13003 `org-show-siblings'."
13004 (let ((heading-p (org-on-heading-p t))
13005 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13006 (following-p (org-get-alist-option org-show-following-heading key))
13007 (siblings-p (org-get-alist-option org-show-siblings key)))
13008 (catch 'exit
13009 ;; Show heading or entry text
13010 (if heading-p
13011 (org-flag-heading nil) ; only show the heading
13012 (and (or (org-invisible-p) (org-invisible-p2))
13013 (org-show-hidden-entry))) ; show entire entry
13014 (when following-p
13015 ;; Show next sibling, or heading below text
13016 (save-excursion
13017 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13018 (org-flag-heading nil))))
13019 (when siblings-p (org-show-siblings))
13020 (when hierarchy-p
13021 ;; show all higher headings, possibly with siblings
13022 (save-excursion
13023 (while (and (condition-case nil
13024 (progn (org-up-heading-all 1) t)
13025 (error nil))
13026 (not (bobp)))
13027 (org-flag-heading nil)
13028 (when siblings-p (org-show-siblings))))))))
13030 (defun org-reveal (&optional siblings)
13031 "Show current entry, hierarchy above it, and the following headline.
13032 This can be used to show a consistent set of context around locations
13033 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13034 not t for the search context.
13036 With optional argument SIBLINGS, on each level of the hierarchy all
13037 siblings are shown. This repairs the tree structure to what it would
13038 look like when opened with hierarchical calls to `org-cycle'."
13039 (interactive "P")
13040 (let ((org-show-hierarchy-above t)
13041 (org-show-following-heading t)
13042 (org-show-siblings (if siblings t org-show-siblings)))
13043 (org-show-context nil)))
13045 (defun org-highlight-new-match (beg end)
13046 "Highlight from BEG to END and mark the highlight is an occur headline."
13047 (let ((ov (org-make-overlay beg end)))
13048 (org-overlay-put ov 'face 'secondary-selection)
13049 (push ov org-occur-highlights)))
13051 (defun org-remove-occur-highlights (&optional beg end noremove)
13052 "Remove the occur highlights from the buffer.
13053 BEG and END are ignored. If NOREMOVE is nil, remove this function
13054 from the `before-change-functions' in the current buffer."
13055 (interactive)
13056 (unless org-inhibit-highlight-removal
13057 (mapc 'org-delete-overlay org-occur-highlights)
13058 (setq org-occur-highlights nil)
13059 (unless noremove
13060 (remove-hook 'before-change-functions
13061 'org-remove-occur-highlights 'local))))
13063 ;;;; Priorities
13065 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13066 "Regular expression matching the priority indicator.")
13068 (defvar org-remove-priority-next-time nil)
13070 (defun org-priority-up ()
13071 "Increase the priority of the current item."
13072 (interactive)
13073 (org-priority 'up))
13075 (defun org-priority-down ()
13076 "Decrease the priority of the current item."
13077 (interactive)
13078 (org-priority 'down))
13080 (defun org-priority (&optional action)
13081 "Change the priority of an item by ARG.
13082 ACTION can be `set', `up', `down', or a character."
13083 (interactive)
13084 (setq action (or action 'set))
13085 (let (current new news have remove)
13086 (save-excursion
13087 (org-back-to-heading)
13088 (if (looking-at org-priority-regexp)
13089 (setq current (string-to-char (match-string 2))
13090 have t)
13091 (setq current org-default-priority))
13092 (cond
13093 ((or (eq action 'set) (integerp action))
13094 (if (integerp action)
13095 (setq new action)
13096 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13097 (setq new (read-char-exclusive)))
13098 (cond ((equal new ?\ ) (setq remove t))
13099 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13100 (error "Priority must be between `%c' and `%c'"
13101 org-highest-priority org-lowest-priority))))
13102 ((eq action 'up)
13103 (setq new (1- current)))
13104 ((eq action 'down)
13105 (setq new (1+ current)))
13106 (t (error "Invalid action")))
13107 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
13108 (setq news (format "%c" new))
13109 (if have
13110 (if remove
13111 (replace-match "" t t nil 1)
13112 (replace-match news t t nil 2))
13113 (if remove
13114 (error "No priority cookie found in line")
13115 (looking-at org-todo-line-regexp)
13116 (if (match-end 2)
13117 (progn
13118 (goto-char (match-end 2))
13119 (insert " [#" news "]"))
13120 (goto-char (match-beginning 3))
13121 (insert "[#" news "] ")))))
13122 (org-preserve-lc (org-set-tags nil 'align))
13123 (if remove
13124 (message "Priority removed")
13125 (message "Priority of current item set to %s" news))))
13128 (defun org-get-priority (s)
13129 "Find priority cookie and return priority."
13130 (save-match-data
13131 (if (not (string-match org-priority-regexp s))
13132 (* 1000 (- org-lowest-priority org-default-priority))
13133 (* 1000 (- org-lowest-priority
13134 (string-to-char (match-string 2 s)))))))
13136 ;;;; Tags
13138 (defun org-scan-tags (action matcher &optional todo-only)
13139 "Scan headline tags with inheritance and produce output ACTION.
13140 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13141 evaluated, testing if a given set of tags qualifies a headline for
13142 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13143 are included in the output."
13144 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13145 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13146 (org-re
13147 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13148 (props (list 'face nil
13149 'done-face 'org-done
13150 'undone-face nil
13151 'mouse-face 'highlight
13152 'org-not-done-regexp org-not-done-regexp
13153 'org-todo-regexp org-todo-regexp
13154 'keymap org-agenda-keymap
13155 'help-echo
13156 (format "mouse-2 or RET jump to org file %s"
13157 (abbreviate-file-name buffer-file-name))))
13158 (case-fold-search nil)
13159 lspos
13160 tags tags-list tags-alist (llast 0) rtn level category i txt
13161 todo marker entry priority)
13162 (save-excursion
13163 (goto-char (point-min))
13164 (when (eq action 'sparse-tree) (org-overview))
13165 (while (re-search-forward re nil t)
13166 (catch :skip
13167 (setq todo (if (match-end 1) (match-string 2))
13168 tags (if (match-end 4) (match-string 4)))
13169 (goto-char (setq lspos (1+ (match-beginning 0))))
13170 (setq level (org-reduced-level (funcall outline-level))
13171 category (org-get-category))
13172 (setq i llast llast level)
13173 ;; remove tag lists from same and sublevels
13174 (while (>= i level)
13175 (when (setq entry (assoc i tags-alist))
13176 (setq tags-alist (delete entry tags-alist)))
13177 (setq i (1- i)))
13178 ;; add the nex tags
13179 (when tags
13180 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13181 tags-alist
13182 (cons (cons level tags) tags-alist)))
13183 ;; compile tags for current headline
13184 (setq tags-list
13185 (if org-use-tag-inheritance
13186 (apply 'append (mapcar 'cdr tags-alist))
13187 tags))
13188 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13189 (eval matcher)
13190 (or (not org-agenda-skip-archived-trees)
13191 (not (member org-archive-tag tags-list))))
13192 (and (eq action 'agenda) (org-agenda-skip))
13193 ;; list this headline
13194 (if (eq action 'sparse-tree)
13195 (progn
13196 (org-show-context 'tags-tree))
13197 (setq txt (org-format-agenda-item
13199 (concat
13200 (if org-tags-match-list-sublevels
13201 (make-string (1- level) ?.) "")
13202 (org-get-heading))
13203 category tags-list)
13204 priority (org-get-priority txt))
13205 (goto-char lspos)
13206 (setq marker (org-agenda-new-marker))
13207 (org-add-props txt props
13208 'org-marker marker 'org-hd-marker marker 'org-category category
13209 'priority priority 'type "tagsmatch")
13210 (push txt rtn))
13211 ;; if we are to skip sublevels, jump to end of subtree
13212 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13213 (when (and (eq action 'sparse-tree)
13214 (not org-sparse-tree-open-archived-trees))
13215 (org-hide-archived-subtrees (point-min) (point-max)))
13216 (nreverse rtn)))
13218 (defvar todo-only) ;; dynamically scoped
13220 (defun org-tags-sparse-tree (&optional todo-only match)
13221 "Create a sparse tree according to tags string MATCH.
13222 MATCH can contain positive and negative selection of tags, like
13223 \"+WORK+URGENT-WITHBOSS\".
13224 If optional argument TODO_ONLY is non-nil, only select lines that are
13225 also TODO lines."
13226 (interactive "P")
13227 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13229 (defvar org-cached-props nil)
13230 (defun org-cached-entry-get (pom property)
13231 (cdr (assoc property (or org-cached-props
13232 (setq org-cached-props
13233 (org-entry-properties pom))))))
13235 (defun org-global-tags-completion-table (&optional files)
13236 "Return the list of all tags in all agenda buffer/files."
13237 (save-excursion
13238 (org-uniquify
13239 (apply 'append
13240 (mapcar
13241 (lambda (file)
13242 (set-buffer (find-file-noselect file))
13243 (org-get-buffer-tags))
13244 (if (and files (car files))
13245 files
13246 (org-agenda-files)))))))
13248 (defun org-make-tags-matcher (match)
13249 "Create the TAGS//TODO matcher form for the selection string MATCH."
13250 ;; todo-only is scoped dynamically into this function, and the function
13251 ;; may change it it the matcher asksk for it.
13252 (unless match
13253 ;; Get a new match request, with completion
13254 (let ((org-last-tags-completion-table
13255 (org-global-tags-completion-table)))
13256 (setq match (completing-read
13257 "Match: " 'org-tags-completion-function nil nil nil
13258 'org-tags-history))))
13260 ;; Parse the string and create a lisp form
13261 (let ((match0 match)
13262 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13263 minus tag mm
13264 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13265 orterms term orlist re-p level-p prop-p pn pv)
13266 (if (string-match "/+" match)
13267 ;; match contains also a todo-matching request
13268 (progn
13269 (setq tagsmatch (substring match 0 (match-beginning 0))
13270 todomatch (substring match (match-end 0)))
13271 (if (string-match "^!" todomatch)
13272 (setq todo-only t todomatch (substring todomatch 1)))
13273 (if (string-match "^\\s-*$" todomatch)
13274 (setq todomatch nil)))
13275 ;; only matching tags
13276 (setq tagsmatch match todomatch nil))
13278 ;; Make the tags matcher
13279 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13280 (setq tagsmatcher t)
13281 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13282 (while (setq term (pop orterms))
13283 (while (and (equal (substring term -1) "\\") orterms)
13284 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13285 (while (string-match re term)
13286 (setq minus (and (match-end 1)
13287 (equal (match-string 1 term) "-"))
13288 tag (match-string 2 term)
13289 re-p (equal (string-to-char tag) ?{)
13290 level-p (match-end 3)
13291 prop-p (match-end 4)
13292 mm (cond
13293 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13294 (level-p `(= level ,(string-to-number
13295 (match-string 3 term))))
13296 (prop-p
13297 (setq pn (match-string 4 term)
13298 pv (match-string 5 term)
13299 re-p (equal (string-to-char pv) ?{)
13300 pv (substring pv 1 -1))
13301 (if re-p
13302 `(string-match ,pv (org-cached-entry-get nil ,pn))
13303 `(equal ,pv (org-cached-entry-get nil ,pn))))
13304 (t `(member ,(downcase tag) tags-list)))
13305 mm (if minus (list 'not mm) mm)
13306 term (substring term (match-end 0)))
13307 (push mm tagsmatcher))
13308 (push (if (> (length tagsmatcher) 1)
13309 (cons 'and tagsmatcher)
13310 (car tagsmatcher))
13311 orlist)
13312 (setq tagsmatcher nil))
13313 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13314 (setq tagsmatcher
13315 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13317 ;; Make the todo matcher
13318 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13319 (setq todomatcher t)
13320 (setq orterms (org-split-string todomatch "|") orlist nil)
13321 (while (setq term (pop orterms))
13322 (while (string-match re term)
13323 (setq minus (and (match-end 1)
13324 (equal (match-string 1 term) "-"))
13325 kwd (match-string 2 term)
13326 re-p (equal (string-to-char kwd) ?{)
13327 term (substring term (match-end 0))
13328 mm (if re-p
13329 `(string-match ,(substring kwd 1 -1) todo)
13330 (list 'equal 'todo kwd))
13331 mm (if minus (list 'not mm) mm))
13332 (push mm todomatcher))
13333 (push (if (> (length todomatcher) 1)
13334 (cons 'and todomatcher)
13335 (car todomatcher))
13336 orlist)
13337 (setq todomatcher nil))
13338 (setq todomatcher (if (> (length orlist) 1)
13339 (cons 'or orlist) (car orlist))))
13341 ;; Return the string and lisp forms of the matcher
13342 (setq matcher (if todomatcher
13343 (list 'and tagsmatcher todomatcher)
13344 tagsmatcher))
13345 (cons match0 matcher)))
13347 (defun org-match-any-p (re list)
13348 "Does re match any element of list?"
13349 (setq list (mapcar (lambda (x) (string-match re x)) list))
13350 (delq nil list))
13352 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13353 (defvar org-tags-overlay (org-make-overlay 1 1))
13354 (org-detach-overlay org-tags-overlay)
13356 (defun org-align-tags-here (to-col)
13357 ;; Assumes that this is a headline
13358 (let ((pos (point)) (col (current-column)) tags)
13359 (beginning-of-line 1)
13360 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13361 (< pos (match-beginning 2)))
13362 (progn
13363 (setq tags (match-string 2))
13364 (goto-char (match-beginning 1))
13365 (insert " ")
13366 (delete-region (point) (1+ (match-end 0)))
13367 (backward-char 1)
13368 (move-to-column
13369 (max (1+ (current-column))
13370 (1+ col)
13371 (if (> to-col 0)
13372 to-col
13373 (- (abs to-col) (length tags))))
13375 (insert tags)
13376 (move-to-column (min (current-column) col) t))
13377 (goto-char pos))))
13379 (defun org-set-tags (&optional arg just-align)
13380 "Set the tags for the current headline.
13381 With prefix ARG, realign all tags in headings in the current buffer."
13382 (interactive "P")
13383 (let* ((re (concat "^" outline-regexp))
13384 (current (org-get-tags))
13385 table current-tags inherited-tags ; computed below when needed
13386 tags p0 c0 c1 rpl)
13387 (if arg
13388 (save-excursion
13389 (goto-char (point-min))
13390 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13391 (while (re-search-forward re nil t)
13392 (org-set-tags nil t)
13393 (end-of-line 1)))
13394 (message "All tags realigned to column %d" org-tags-column))
13395 (if just-align
13396 (setq tags current)
13397 ;; Get a new set of tags from the user
13398 (save-excursion
13399 (setq table (or org-tag-alist (org-get-buffer-tags))
13400 org-last-tags-completion-table table
13401 current-tags (org-split-string current ":")
13402 inherited-tags (nreverse
13403 (nthcdr (length current-tags)
13404 (nreverse (org-get-tags-at))))
13405 tags
13406 (if (or (eq t org-use-fast-tag-selection)
13407 (and org-use-fast-tag-selection
13408 (delq nil (mapcar 'cdr table))))
13409 (org-fast-tag-selection current-tags inherited-tags table)
13410 (let ((org-add-colon-after-tag-completion t))
13411 (org-trim
13412 (completing-read "Tags: " 'org-tags-completion-function
13413 nil nil current 'org-tags-history))))))
13414 (while (string-match "[-+&]+" tags)
13415 ;; No boolean logic, just a list
13416 (setq tags (replace-match ":" t t tags))))
13418 (if (string-match "\\`[\t ]*\\'" tags)
13419 (setq tags "")
13420 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13421 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13423 ;; Insert new tags at the correct column
13424 (beginning-of-line 1)
13425 (cond
13426 ((and (equal current "") (equal tags "")))
13427 ((re-search-forward
13428 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13429 (point-at-eol) t)
13430 (if (equal tags "")
13431 (setq rpl "")
13432 (goto-char (match-beginning 0))
13433 (setq c0 (current-column) p0 (point)
13434 c1 (max (1+ c0) (if (> org-tags-column 0)
13435 org-tags-column
13436 (- (- org-tags-column) (length tags))))
13437 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13438 (replace-match rpl t t)
13439 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
13440 tags)
13441 (t (error "Tags alignment failed"))))))
13443 (defun org-tags-completion-function (string predicate &optional flag)
13444 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13445 (confirm (lambda (x) (stringp (car x)))))
13446 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
13447 (setq s1 (match-string 1 string)
13448 s2 (match-string 2 string))
13449 (setq s1 "" s2 string))
13450 (cond
13451 ((eq flag nil)
13452 ;; try completion
13453 (setq rtn (try-completion s2 ctable confirm))
13454 (if (stringp rtn)
13455 (setq rtn
13456 (concat s1 s2 (substring rtn (length s2))
13457 (if (and org-add-colon-after-tag-completion
13458 (assoc rtn ctable))
13459 ":" ""))))
13460 rtn)
13461 ((eq flag t)
13462 ;; all-completions
13463 (all-completions s2 ctable confirm)
13465 ((eq flag 'lambda)
13466 ;; exact match?
13467 (assoc s2 ctable)))
13470 (defun org-fast-tag-insert (kwd tags face &optional end)
13471 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
13472 (insert (format "%-12s" (concat kwd ":"))
13473 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13474 (or end "")))
13476 (defun org-fast-tag-show-exit (flag)
13477 (save-excursion
13478 (goto-line 3)
13479 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13480 (replace-match ""))
13481 (when flag
13482 (end-of-line 1)
13483 (move-to-column (- (window-width) 19) t)
13484 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13486 (defun org-set-current-tags-overlay (current prefix)
13487 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13488 (if (featurep 'xemacs)
13489 (org-overlay-display org-tags-overlay (concat prefix s)
13490 'secondary-selection)
13491 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13492 (org-overlay-display org-tags-overlay (concat prefix s)))))
13494 (defun org-fast-tag-selection (current inherited table)
13495 "Fast tag selection with single keys.
13496 CURRENT is the current list of tags in the headline, INHERITED is the
13497 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13498 possibly with grouping information.
13499 If the keys are nil, a-z are automatically assigned.
13500 Returns the new tags string, or nil to not change the current settings."
13501 (let* ((maxlen (apply 'max (mapcar
13502 (lambda (x)
13503 (if (stringp (car x)) (string-width (car x)) 0))
13504 table)))
13505 (buf (current-buffer))
13506 (expert (eq org-fast-tag-selection-single-key 'expert))
13507 (buffer-tags nil)
13508 (fwidth (+ maxlen 3 1 3))
13509 (ncol (/ (- (window-width) 4) fwidth))
13510 (i-face 'org-done)
13511 (c-face 'org-todo)
13512 tg cnt e c char c1 c2 ntable tbl rtn
13513 ov-start ov-end ov-prefix
13514 (exit-after-next org-fast-tag-selection-single-key)
13515 groups ingroup)
13516 (save-excursion
13517 (beginning-of-line 1)
13518 (if (looking-at
13519 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13520 (setq ov-start (match-beginning 1)
13521 ov-end (match-end 1)
13522 ov-prefix "")
13523 (setq ov-start (1- (point-at-eol))
13524 ov-end (1+ ov-start))
13525 (skip-chars-forward "^\n\r")
13526 (setq ov-prefix
13527 (concat
13528 (buffer-substring (1- (point)) (point))
13529 (if (> (current-column) org-tags-column)
13531 (make-string (- org-tags-column (current-column)) ?\ ))))))
13532 (org-move-overlay org-tags-overlay ov-start ov-end)
13533 (save-window-excursion
13534 (if expert
13535 (set-buffer (get-buffer-create " *Org tags*"))
13536 (delete-other-windows)
13537 (split-window-vertically)
13538 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13539 (erase-buffer)
13540 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13541 (org-fast-tag-insert "Current" current c-face "\n\n")
13542 (org-fast-tag-show-exit exit-after-next)
13543 (org-set-current-tags-overlay current ov-prefix)
13544 (setq tbl table char ?a cnt 0)
13545 (while (setq e (pop tbl))
13546 (cond
13547 ((equal e '(:startgroup))
13548 (push '() groups) (setq ingroup t)
13549 (when (not (= cnt 0))
13550 (setq cnt 0)
13551 (insert "\n"))
13552 (insert "{ "))
13553 ((equal e '(:endgroup))
13554 (setq ingroup nil cnt 0)
13555 (insert "}\n"))
13557 (setq tg (car e) c2 nil)
13558 (if (cdr e)
13559 (setq c (cdr e))
13560 ;; automatically assign a character.
13561 (setq c1 (string-to-char
13562 (downcase (substring
13563 tg (if (= (string-to-char tg) ?@) 1 0)))))
13564 (if (or (rassoc c1 ntable) (rassoc c1 table))
13565 (while (or (rassoc char ntable) (rassoc char table))
13566 (setq char (1+ char)))
13567 (setq c2 c1))
13568 (setq c (or c2 char)))
13569 (if ingroup (push tg (car groups)))
13570 (setq tg (org-add-props tg nil 'face
13571 (cond
13572 ((member tg current) c-face)
13573 ((member tg inherited) i-face)
13574 (t nil))))
13575 (if (and (= cnt 0) (not ingroup)) (insert " "))
13576 (insert "[" c "] " tg (make-string
13577 (- fwidth 4 (length tg)) ?\ ))
13578 (push (cons tg c) ntable)
13579 (when (= (setq cnt (1+ cnt)) ncol)
13580 (insert "\n")
13581 (if ingroup (insert " "))
13582 (setq cnt 0)))))
13583 (setq ntable (nreverse ntable))
13584 (insert "\n")
13585 (goto-char (point-min))
13586 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13587 (fit-window-to-buffer))
13588 (setq rtn
13589 (catch 'exit
13590 (while t
13591 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
13592 (if groups " [!] no groups" " [!]groups")
13593 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13594 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13595 (cond
13596 ((= c ?\r) (throw 'exit t))
13597 ((= c ?!)
13598 (setq groups (not groups))
13599 (goto-char (point-min))
13600 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13601 ((= c ?\C-c)
13602 (if (not expert)
13603 (org-fast-tag-show-exit
13604 (setq exit-after-next (not exit-after-next)))
13605 (setq expert nil)
13606 (delete-other-windows)
13607 (split-window-vertically)
13608 (switch-to-buffer-other-window " *Org tags*")
13609 (and (fboundp 'fit-window-to-buffer)
13610 (fit-window-to-buffer))))
13611 ((or (= c ?\C-g)
13612 (and (= c ?q) (not (rassoc c ntable))))
13613 (org-detach-overlay org-tags-overlay)
13614 (setq quit-flag t))
13615 ((= c ?\ )
13616 (setq current nil)
13617 (if exit-after-next (setq exit-after-next 'now)))
13618 ((= c ?\t)
13619 (condition-case nil
13620 (setq tg (completing-read
13621 "Tag: "
13622 (or buffer-tags
13623 (with-current-buffer buf
13624 (org-get-buffer-tags)))))
13625 (quit (setq tg "")))
13626 (when (string-match "\\S-" tg)
13627 (add-to-list 'buffer-tags (list tg))
13628 (if (member tg current)
13629 (setq current (delete tg current))
13630 (push tg current)))
13631 (if exit-after-next (setq exit-after-next 'now)))
13632 ((setq e (rassoc c ntable) tg (car e))
13633 (if (member tg current)
13634 (setq current (delete tg current))
13635 (loop for g in groups do
13636 (if (member tg g)
13637 (mapcar (lambda (x)
13638 (setq current (delete x current)))
13639 g)))
13640 (push tg current))
13641 (if exit-after-next (setq exit-after-next 'now))))
13643 ;; Create a sorted list
13644 (setq current
13645 (sort current
13646 (lambda (a b)
13647 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13648 (if (eq exit-after-next 'now) (throw 'exit t))
13649 (goto-char (point-min))
13650 (beginning-of-line 2)
13651 (delete-region (point) (point-at-eol))
13652 (org-fast-tag-insert "Current" current c-face)
13653 (org-set-current-tags-overlay current ov-prefix)
13654 (while (re-search-forward
13655 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13656 (setq tg (match-string 1))
13657 (add-text-properties (match-beginning 1) (match-end 1)
13658 (list 'face
13659 (cond
13660 ((member tg current) c-face)
13661 ((member tg inherited) i-face)
13662 (t nil)))))
13663 (goto-char (point-min)))))
13664 (org-detach-overlay org-tags-overlay)
13665 (if rtn
13666 (mapconcat 'identity current ":")
13667 nil))))
13669 (defun org-get-tags ()
13670 "Get the TAGS string in the current headline."
13671 (unless (org-on-heading-p t)
13672 (error "Not on a heading"))
13673 (save-excursion
13674 (beginning-of-line 1)
13675 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13676 (org-match-string-no-properties 1)
13677 "")))
13679 (defun org-get-buffer-tags ()
13680 "Get a table of all tags used in the buffer, for completion."
13681 (let (tags)
13682 (save-excursion
13683 (goto-char (point-min))
13684 (while (re-search-forward
13685 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13686 (when (equal (char-after (point-at-bol 0)) ?*)
13687 (mapc (lambda (x) (add-to-list 'tags x))
13688 (org-split-string (org-match-string-no-properties 1) ":")))))
13689 (mapcar 'list tags)))
13692 ;;;; Properties
13694 ;;; Setting and retrieving properties
13696 (defconst org-special-properties
13697 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED"
13698 "CLOCK" "PRIORITY")
13699 "The special properties valid in Org-mode.
13701 These are properties that are not defined in the property drawer,
13702 but in some other way.")
13704 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13705 "Regular expression matching the first line of a property drawer.")
13707 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13708 "Regular expression matching the first line of a property drawer.")
13710 (defun org-property-action ()
13711 "Do an action on properties."
13712 (interactive)
13713 (let (c prop)
13714 (org-at-property-p)
13715 (setq prop (match-string 2))
13716 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13717 (setq c (read-char-exclusive))
13718 (cond
13719 ((equal c ?s)
13720 (call-interactively 'org-set-property))
13721 ((equal c ?d)
13722 (call-interactively 'org-delete-property))
13723 ((equal c ?D)
13724 (call-interactively 'org-delete-property-globally))
13725 ((equal c ?c)
13726 (call-interactively 'org-compute-property-at-point))
13727 (t (error "No such property action %c" c)))))
13729 (defun org-at-property-p ()
13730 "Is the cursor in a property line?"
13731 ;; FIXME: Does not check if we are actually in the drawer.
13732 ;; FIXME: also returns true on any drawers.....
13733 ;; This is used by C-c C-c for property action.
13734 (save-excursion
13735 (beginning-of-line 1)
13736 (looking-at "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(.*\\)")))
13738 (defmacro org-with-point-at (pom &rest body)
13739 "Move to buffer and point of point-or-marker POM for the duration of BODY."
13740 (declare (indent 1) (debug t))
13741 `(save-excursion
13742 (if (markerp pom) (set-buffer (marker-buffer pom)))
13743 (save-excursion
13744 (goto-char (or pom (point)))
13745 ,@body)))
13747 (defun org-get-property-block (&optional beg end force)
13748 "Return the (beg . end) range of the body of the property drawer.
13749 BEG and END can be beginning and end of subtree, if not given
13750 they will be found.
13751 If the drawer does not exist and FORCE is non-nil, create the drawer."
13752 (catch 'exit
13753 (save-excursion
13754 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13755 (end (or end (progn (outline-next-heading) (point)))))
13756 (goto-char beg)
13757 (if (re-search-forward org-property-start-re end t)
13758 (setq beg (1+ (match-end 0)))
13759 (if force
13760 (save-excursion
13761 (org-insert-property-drawer)
13762 (setq end (progn (outline-next-heading) (point))))
13763 (throw 'exit nil))
13764 (goto-char beg)
13765 (if (re-search-forward org-property-start-re end t)
13766 (setq beg (1+ (match-end 0)))))
13767 (if (re-search-forward org-property-end-re end t)
13768 (setq end (match-beginning 0))
13769 (or force (throw 'exit nil))
13770 (goto-char beg)
13771 (setq end beg)
13772 (org-indent-line-function)
13773 (insert ":END:\n"))
13774 (cons beg end)))))
13776 (defun org-entry-properties (&optional pom which)
13777 "Get all properties of the entry at point-or-marker POM.
13778 This includes the TODO keyword, the tags, time strings for deadline,
13779 scheduled, and clocking, and any additional properties defined in the
13780 entry. The return value is an alist, keys may occur multiple times
13781 if the property key was used several times.
13782 POM may also be nil, in which case the current entry is used.
13783 If WHICH is nil or `all', get all properties. If WHICH is
13784 `special' or `standard', only get that subclass."
13785 (setq which (or which 'all))
13786 (org-with-point-at pom
13787 (let ((clockstr (substring org-clock-string 0 -1))
13788 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
13789 beg end range props sum-props key value)
13790 (save-excursion
13791 (when (condition-case nil (org-back-to-heading t) (error nil))
13792 (setq beg (point))
13793 (setq sum-props (get-text-property (point) 'org-summaries))
13794 (outline-next-heading)
13795 (setq end (point))
13796 (when (memq which '(all special))
13797 ;; Get the special properties, like TODO and tags
13798 (goto-char beg)
13799 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13800 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13801 (when (looking-at org-priority-regexp)
13802 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13803 (when (and (setq value (org-get-tags)) (string-match "\\S-" value))
13804 (push (cons "TAGS" value) props))
13805 (when (setq value (org-get-tags-at))
13806 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
13807 props))
13808 (while (re-search-forward org-keyword-time-regexp end t)
13809 (setq key (substring (org-match-string-no-properties 1) 0 -1))
13810 (unless (member key excluded) (push key excluded))
13811 (push (cons key
13812 (if (equal key clockstr)
13813 (org-no-properties
13814 (org-trim
13815 (buffer-substring
13816 (match-beginning 2) (point-at-eol))))
13817 (org-match-string-no-properties 2)))
13818 props)))
13819 (when (memq which '(all standard))
13820 ;; Get the standard properties, like :PORP: ...
13821 (setq range (org-get-property-block beg end))
13822 (when range
13823 (goto-char (car range))
13824 (while (re-search-forward
13825 "^[ \t]*:\\([a-zA-Z][a-zA-Z_0-9]*\\):[ \t]*\\(\\S-.*\\)?"
13826 (cdr range) t)
13827 (setq key (org-match-string-no-properties 1)
13828 value (org-trim (or (org-match-string-no-properties 2) "")))
13829 (unless (member key excluded)
13830 (push (cons key (or value "")) props)))))
13831 (append sum-props (nreverse props)))))))
13833 (defun org-entry-get (pom property &optional inherit)
13834 "Get value of PROPERTY for entry at point-or-marker POM.
13835 If INHERIT is non-nil and the entry does not have the property,
13836 then also check higher levels of the hierarchy.
13837 If the property is present but empty, the return value is the empty string.
13838 If the property is not present at all, nil is returned."
13839 (org-with-point-at pom
13840 (if inherit
13841 (org-entry-get-with-inheritance property)
13842 (if (member property org-special-properties)
13843 ;; We need a special property. Use brute force, get all properties.
13844 (cdr (assoc property (org-entry-properties nil 'special)))
13845 (let ((range (org-get-property-block)))
13846 (if (and range
13847 (goto-char (car range))
13848 (re-search-forward
13849 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
13850 (cdr range) t))
13851 ;; Found the property, return it.
13852 (if (match-end 1)
13853 (org-match-string-no-properties 1)
13854 "")))))))
13856 (defun org-entry-delete (pom property)
13857 "Delete the property PROPERTY from entry at point-or-marker POM."
13858 (org-with-point-at pom
13859 (if (member property org-special-properties)
13860 nil ; cannot delete these properties.
13861 (let ((range (org-get-property-block)))
13862 (if (and range
13863 (goto-char (car range))
13864 (re-search-forward
13865 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
13866 (cdr range) t))
13867 (progn
13868 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13870 nil)))))
13872 (defvar org-entry-property-inherited-from (make-marker))
13874 (defun org-entry-get-with-inheritance (property)
13875 "Get entry property, and search higher levels if not present."
13876 (let (tmp)
13877 (save-excursion
13878 (catch 'ex
13879 (while t
13880 (when (setq tmp (org-entry-get nil property))
13881 (org-back-to-heading t)
13882 (move-marker org-entry-property-inherited-from (point))
13883 (throw 'ex tmp))
13884 (condition-case nil
13885 (org-up-heading-all 1)
13886 (error (throw 'ex nil))))))
13887 (or tmp (cdr (assoc property org-local-properties))
13888 (cdr (assoc property org-global-properties)))))
13890 (defun org-entry-put (pom property value)
13891 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13892 (org-with-point-at pom
13893 (org-back-to-heading t)
13894 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13895 range)
13896 (cond
13897 ((equal property "TODO")
13898 (when (and (stringp value) (string-match "\\S-" value)
13899 (not (member value org-todo-keywords-1)))
13900 (error "\"%s\" is not a valid TODO state" value))
13901 (if (or (not value)
13902 (not (string-match "\\S-" value)))
13903 (setq value 'none))
13904 (org-todo value)
13905 (org-set-tags nil 'align))
13906 ((equal property "PRIORITY")
13907 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13908 (string-to-char value) ?\ ))
13909 (org-set-tags nil 'align))
13910 ((equal property "SCHEDULED")
13911 (if (re-search-forward org-scheduled-time-regexp end t)
13912 (cond
13913 ((eq value 'earlier) (org-timestamp-change -1 'day))
13914 ((eq value 'later) (org-timestamp-change 1 'day))
13915 (t (call-interactively 'org-schedule)))
13916 (call-interactively 'org-schedule)))
13917 ((equal property "DEADLINE")
13918 (if (re-search-forward org-deadline-time-regexp end t)
13919 (cond
13920 ((eq value 'earlier) (org-timestamp-change -1 'day))
13921 ((eq value 'later) (org-timestamp-change 1 'day))
13922 (t (call-interactively 'org-deadline)))
13923 (call-interactively 'org-deadline)))
13924 ((member property org-special-properties)
13925 (error "The %s property can not yet be set with `org-entry-put'"
13926 property))
13927 (t ; a non-special property
13928 (setq range (org-get-property-block beg end 'force))
13929 (goto-char (car range))
13930 (if (re-search-forward
13931 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13932 (progn
13933 (delete-region (match-beginning 1) (match-end 1))
13934 (goto-char (match-beginning 1)))
13935 (goto-char (cdr range))
13936 (insert "\n")
13937 (backward-char 1)
13938 (org-indent-line-function)
13939 (insert ":" property ":"))
13940 (and value (insert " " value))
13941 (org-indent-line-function))))))
13943 (defun org-buffer-property-keys (&optional include-specials)
13944 "Get all property keys in the current buffer."
13945 (let (rtn range)
13946 (save-excursion
13947 (save-restriction
13948 (widen)
13949 (goto-char (point-min))
13950 (while (re-search-forward org-property-start-re nil t)
13951 (setq range (org-get-property-block))
13952 (goto-char (car range))
13953 (while (re-search-forward "^[ \t]*:\\([a-zA-Z0-9]+\\):" (cdr range) t)
13954 (add-to-list 'rtn (org-match-string-no-properties 1)))
13955 (outline-next-heading))))
13956 (when include-specials
13957 (setq rtn (append org-special-properties rtn)))
13958 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13960 (defun org-insert-property-drawer ()
13961 "Insert a property drawer into the current entry."
13962 (interactive)
13963 (org-back-to-heading t)
13964 (let ((beg (point))
13965 (re (concat "^[ \t]*" org-keyword-time-regexp))
13966 end hiddenp)
13967 (outline-next-heading)
13968 (setq end (point))
13969 (goto-char beg)
13970 (while (re-search-forward re end t))
13971 (setq hiddenp (org-invisible-p))
13972 (end-of-line 1)
13973 (insert "\n:PROPERTIES:\n:END:")
13974 (beginning-of-line 0)
13975 (org-indent-line-function)
13976 (beginning-of-line 2)
13977 (org-indent-line-function)
13978 (beginning-of-line 0)
13979 (if hiddenp
13980 (save-excursion
13981 (org-back-to-heading t)
13982 (hide-entry))
13983 (org-flag-drawer t))))
13985 (defun org-set-property (property value)
13986 "In the current entry, set PROPERTY to VALUE."
13987 (interactive
13988 (let* ((prop (completing-read "Property: "
13989 (mapcar 'list (org-buffer-property-keys))))
13990 (cur (org-entry-get nil prop))
13991 (allowed (org-property-get-allowed-values nil prop 'table))
13992 (val (if allowed
13993 (completing-read "Value: " allowed nil 'req-match)
13994 (read-string
13995 (concat "Value" (if (and cur (string-match "\\S-" cur))
13996 (concat "[" cur "]") "")
13997 ": ")
13998 "" cur))))
13999 (list prop (if (equal val "") cur val))))
14000 (unless (equal (org-entry-get nil property) value)
14001 (org-entry-put nil property value)))
14003 (defun org-delete-property (property)
14004 "In the current entry, delete PROPERTY."
14005 (interactive
14006 (let* ((prop (completing-read
14007 "Property: " (org-entry-properties nil 'standard))))
14008 (list prop)))
14009 (message (concat "Property " property
14010 (if (org-entry-delete nil property)
14011 " deleted"
14012 " was not present in the entry"))))
14014 (defun org-delete-property-globally (property)
14015 "Remove PROPERTY globally, from all entries."
14016 (interactive
14017 (let* ((prop (completing-read
14018 "Globally remove property: "
14019 (mapcar 'list (org-buffer-property-keys)))))
14020 (list prop)))
14021 (save-excursion
14022 (save-restriction
14023 (widen)
14024 (goto-char (point-min))
14025 (let ((cnt 0))
14026 (while (re-search-forward
14027 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14028 nil t)
14029 (setq cnt (1+ cnt))
14030 (replace-match ""))
14031 (message "Property \"%s\" removed from %d entries" property cnt)))))
14033 (defvar org-columns-current-fmt-compiled) ; defined below
14035 (defun org-compute-property-at-point ()
14036 "FIXME:"
14037 (interactive)
14038 (unless (org-at-property-p)
14039 (error "Not at a property"))
14040 (let ((prop (org-match-string-no-properties 2)))
14041 (org-columns-get-format-and-top-level)
14042 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14043 (error "No operator defined for property %s" prop))
14044 (org-columns-compute prop)))
14046 (defun org-property-get-allowed-values (pom property &optional table)
14047 "Get allowed values for the property PROPERTY.
14048 When TABLE is non-nil, return an alist that can directly be used for
14049 completion."
14050 (let (vals)
14051 (cond
14052 ((equal property "TODO")
14053 (setq vals (org-with-point-at pom
14054 (append org-todo-keywords-1 '("")))))
14055 ((equal property "PRIORITY")
14056 (let ((n org-lowest-priority))
14057 (while (>= n org-highest-priority)
14058 (push (char-to-string n) vals)
14059 (setq n (1- n)))))
14060 ((member property org-special-properties))
14062 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14064 (when (and vals (string-match "\\S-" vals))
14065 (setq vals (car (read-from-string (concat "(" vals ")"))))
14066 (setq vals (mapcar (lambda (x)
14067 (cond ((stringp x) x)
14068 ((numberp x) (number-to-string x))
14069 ((symbolp x) (symbol-name x))
14070 (t "???")))
14071 vals)))))
14072 (if table (mapcar 'list vals) vals)))
14074 (defun org-property-previous-allowed-value (&optional previous)
14075 "Switch to the next allowed value for this property."
14076 (interactive)
14077 (org-property-next-allowed-value t))
14079 (defun org-property-next-allowed-value (&optional previous)
14080 "Switch to the next allowed value for this property."
14081 (interactive)
14082 (unless (org-at-property-p)
14083 (error "Not at a property"))
14084 (let* ((key (match-string 2))
14085 (value (match-string 3))
14086 (allowed (or (org-property-get-allowed-values (point) key)
14087 (and (member value '("[ ]" "[-]" "[X]"))
14088 '("[ ]" "[X]"))))
14089 nval)
14090 (unless allowed
14091 (error "Allowed values for this property have not been defined"))
14092 (if previous (setq allowed (reverse allowed)))
14093 (if (member value allowed)
14094 (setq nval (car (cdr (member value allowed)))))
14095 (setq nval (or nval (car allowed)))
14096 (if (equal nval value)
14097 (error "Only one allowed value for this property"))
14098 (org-at-property-p)
14099 (replace-match (concat " :" key ": " nval) t t)
14100 (org-indent-line-function)
14101 (beginning-of-line 1)
14102 (skip-chars-forward " \t")))
14104 ;;; Column View
14106 (defvar org-columns-overlays nil
14107 "Holds the list of current column overlays.")
14109 (defvar org-columns-current-fmt nil
14110 "Local variable, holds the currently active column format.")
14111 (defvar org-columns-current-fmt-compiled nil
14112 "Local variable, holds the currently active column format.
14113 This is the compiled version of the format.")
14114 (defvar org-columns-current-maxwidths nil
14115 "Loval variable, holds the currently active maximum column widths.")
14116 (defvar org-columns-begin-marker (make-marker)
14117 "Points to the position where last a column creation command was called.")
14118 (defvar org-columns-top-level-marker (make-marker)
14119 "Points to the position where current columns region starts.")
14121 (defvar org-columns-map (make-sparse-keymap)
14122 "The keymap valid in column display.")
14124 (defun org-columns-content ()
14125 "Switch to contents view while in columns view."
14126 (interactive)
14127 (org-overview)
14128 (org-content))
14130 (org-defkey org-columns-map "c" 'org-columns-content)
14131 (org-defkey org-columns-map "o" 'org-overview)
14132 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14133 (org-defkey org-columns-map "v" 'org-columns-show-value)
14134 (org-defkey org-columns-map "q" 'org-columns-quit)
14135 (org-defkey org-columns-map "r" 'org-columns-redo)
14136 (org-defkey org-columns-map [left] 'backward-char)
14137 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14138 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14139 (org-defkey org-columns-map [right] 'forward-char)
14140 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14141 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14142 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14143 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14144 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14145 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14146 (org-defkey org-columns-map "<" 'org-columns-narrow)
14147 (org-defkey org-columns-map ">" 'org-columns-widen)
14148 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14149 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14150 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14151 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14153 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14154 '("Column"
14155 ["Edit property" org-columns-edit-value t]
14156 ["Next allowed value" org-columns-next-allowed-value t]
14157 ["Previous allowed value" org-columns-previous-allowed-value t]
14158 ["Show full value" org-columns-show-value t]
14159 ["Edit allowed" org-columns-edit-allowed t]
14160 "--"
14161 ["Edit column attributes" org-columns-edit-attributes t]
14162 ["Increase column width" org-columns-widen t]
14163 ["Decrease column width" org-columns-narrow t]
14164 "--"
14165 ["Move column right" org-columns-move-right t]
14166 ["Move column left" org-columns-move-left t]
14167 ["Add column" org-columns-new t]
14168 ["Delete column" org-columns-delete t]
14169 "--"
14170 ["CONTENTS" org-columns-content t]
14171 ["OVERVIEW" org-overview t]
14172 ["Refresh columns display" org-columns-redo t]
14173 "--"
14174 ["Quit" org-columns-quit t]))
14176 (defun org-columns-new-overlay (beg end &optional string face)
14177 "Create a new column overlay and add it to the list."
14178 (let ((ov (org-make-overlay beg end)))
14179 (org-overlay-put ov 'face (or face 'secondary-selection))
14180 (org-overlay-display ov string face)
14181 (push ov org-columns-overlays)
14182 ov))
14184 (defun org-columns-display-here (&optional props)
14185 "Overlay the current line with column display."
14186 (interactive)
14187 (let* ((fmt org-columns-current-fmt-compiled)
14188 (beg (point-at-bol))
14189 (level-face (save-excursion
14190 (beginning-of-line 1)
14191 (looking-at "\\(\\**\\)\\(\\* \\)")
14192 (org-get-level-face 2)))
14193 (color (list :foreground
14194 (face-attribute (or level-face 'default) :foreground)))
14195 props pom property ass width f string ov column)
14196 ;; Check if the entry is in another buffer.
14197 (unless props
14198 (if (eq major-mode 'org-agenda-mode)
14199 (setq pom (or (get-text-property (point) 'org-hd-marker)
14200 (get-text-property (point) 'org-marker))
14201 props (if pom (org-entry-properties pom) nil))
14202 (setq props (org-entry-properties nil))))
14203 ;; Walk the format
14204 (while (setq column (pop fmt))
14205 (setq property (car column)
14206 ass (if (equal property "ITEM")
14207 (cons "ITEM"
14208 (save-match-data
14209 (org-no-properties
14210 (org-remove-tabs
14211 (buffer-substring-no-properties
14212 (point-at-bol) (point-at-eol))))))
14213 (assoc property props))
14214 width (or (cdr (assoc property org-columns-current-maxwidths))
14215 (nth 2 column))
14216 f (format "%%-%d.%ds | " width width)
14217 string (format f (or (cdr ass) "")))
14218 ;; Create the overlay
14219 (org-unmodified
14220 (setq ov (org-columns-new-overlay
14221 beg (setq beg (1+ beg)) string
14222 (list color 'org-column)))
14223 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14224 (org-overlay-put ov 'keymap org-columns-map)
14225 (org-overlay-put ov 'org-columns-key property)
14226 (org-overlay-put ov 'org-columns-value (cdr ass))
14227 (org-overlay-put ov 'org-columns-pom pom)
14228 (org-overlay-put ov 'org-columns-format f))
14229 (if (or (not (char-after beg))
14230 (equal (char-after beg) ?\n))
14231 (let ((inhibit-read-only t))
14232 (save-excursion
14233 (goto-char beg)
14234 (insert " ")))))
14235 ;; Make the rest of the line disappear.
14236 (org-unmodified
14237 (setq ov (org-columns-new-overlay beg (point-at-eol)))
14238 (org-overlay-put ov 'invisible t)
14239 (org-overlay-put ov 'keymap org-columns-map)
14240 (org-overlay-put ov 'intangible t)
14241 (push ov org-columns-overlays)
14242 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
14243 (org-overlay-put ov 'keymap org-columns-map)
14244 (push ov org-columns-overlays)
14245 (let ((inhibit-read-only t))
14246 (put-text-property (max (point-min) (1- (point-at-bol)))
14247 (min (point-max) (1+ (point-at-eol)))
14248 'read-only "Type `e' to edit property")))))
14250 (defvar org-previous-header-line-format nil
14251 "The header line format before column view was turned on.")
14252 (defvar org-columns-inhibit-recalculation nil
14253 "Inhibit recomputing of columns on column view startup.")
14255 (defvar header-line-format)
14256 (defun org-columns-display-here-title ()
14257 "Overlay the newline before the current line with the table title."
14258 (interactive)
14259 (let ((fmt org-columns-current-fmt-compiled)
14260 string (title "")
14261 property width f column str)
14262 (while (setq column (pop fmt))
14263 (setq property (car column)
14264 str (or (nth 1 column) property)
14265 width (or (cdr (assoc property org-columns-current-maxwidths))
14266 (nth 2 column))
14267 f (format "%%-%d.%ds | " width width)
14268 string (format f str)
14269 title (concat title string)))
14270 (setq title (concat
14271 (org-add-props " " nil 'display '(space :align-to 0))
14272 (org-add-props title nil 'face '(:weight bold :underline t))))
14273 (org-set-local 'org-previous-header-line-format header-line-format)
14274 (setq header-line-format title)))
14276 (defun org-columns-remove-overlays ()
14277 "Remove all currently active column overlays."
14278 (interactive)
14279 (when (marker-buffer org-columns-begin-marker)
14280 (with-current-buffer (marker-buffer org-columns-begin-marker)
14281 (when (local-variable-p 'org-previous-header-line-format)
14282 (setq header-line-format org-previous-header-line-format)
14283 (kill-local-variable 'org-previous-header-line-format))
14284 (move-marker org-columns-begin-marker nil)
14285 (move-marker org-columns-top-level-marker nil)
14286 (org-unmodified
14287 (mapc 'org-delete-overlay org-columns-overlays)
14288 (setq org-columns-overlays nil)
14289 (let ((inhibit-read-only t))
14290 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
14292 (defun org-columns-show-value ()
14293 "Show the full value of the property."
14294 (interactive)
14295 (let ((value (get-char-property (point) 'org-columns-value)))
14296 (message "Value is: %s" (or value ""))))
14298 (defun org-columns-quit ()
14299 "Remove the column overlays and in this way exit column editing."
14300 (interactive)
14301 (org-unmodified
14302 (org-columns-remove-overlays)
14303 (let ((inhibit-read-only t))
14304 ;; FIXME: is this safe???
14305 ;; or are there other reasons why there may be a read-only property????
14306 (remove-text-properties (point-min) (point-max) '(read-only t))))
14307 (when (eq major-mode 'org-agenda-mode)
14308 (message "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
14310 (defun org-columns-edit-value ()
14311 "Edit the value of the property at point in column view.
14312 Where possible, use the standard interface for changing this line."
14313 (interactive)
14314 (let* ((col (current-column))
14315 (key (get-char-property (point) 'org-columns-key))
14316 (value (get-char-property (point) 'org-columns-value))
14317 (bol (point-at-bol)) (eol (point-at-eol))
14318 (pom (or (get-text-property bol 'org-hd-marker)
14319 (point))) ; keep despite of compiler waring
14320 (line-overlays
14321 (delq nil (mapcar (lambda (x)
14322 (and (eq (overlay-buffer x) (current-buffer))
14323 (>= (overlay-start x) bol)
14324 (<= (overlay-start x) eol)
14326 org-columns-overlays)))
14327 nval eval allowed)
14328 (when (equal key "ITEM")
14329 (error "Cannot edit item headline from here"))
14331 (cond
14332 ((equal key "TODO")
14333 (setq eval '(org-with-point-at pom
14334 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14335 ((equal key "PRIORITY")
14336 (setq eval '(org-with-point-at pom
14337 (call-interactively 'org-priority))))
14338 ((equal key "TAGS")
14339 (setq eval '(org-with-point-at pom
14340 (let ((org-fast-tag-selection-single-key
14341 (if (eq org-fast-tag-selection-single-key 'expert)
14342 t org-fast-tag-selection-single-key)))
14343 (call-interactively 'org-set-tags)))))
14344 ((equal key "DEADLINE")
14345 (setq eval '(org-with-point-at pom
14346 (call-interactively 'org-deadline))))
14347 ((equal key "SCHEDULED")
14348 (setq eval '(org-with-point-at pom
14349 (call-interactively 'org-schedule))))
14351 (setq allowed (org-property-get-allowed-values pom key 'table))
14352 (if allowed
14353 (setq nval (completing-read "Value: " allowed nil t))
14354 (setq nval (read-string "Edit: " value)))
14355 (setq nval (org-trim nval))
14356 (when (not (equal nval value))
14357 (setq eval '(org-entry-put pom key nval)))))
14358 (when eval
14359 (let ((inhibit-read-only t))
14360 (remove-text-properties (1- bol) eol '(read-only t))
14361 (unwind-protect
14362 (progn
14363 (setq org-columns-overlays
14364 (org-delete-all line-overlays org-columns-overlays))
14365 (mapc 'org-delete-overlay line-overlays)
14366 (org-columns-eval eval))
14367 (org-columns-display-here))))
14368 (move-to-column col)
14369 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14370 (org-columns-update key))))
14372 (defun org-columns-edit-allowed ()
14373 "Edit the list of allowed values for the current property."
14374 (interactive)
14375 (let* ((col (current-column))
14376 (key (get-char-property (point) 'org-columns-key))
14377 (key1 (concat key "_ALL"))
14378 (value (get-char-property (point) 'org-columns-value))
14379 (allowed (org-entry-get (point) key1 t))
14380 nval)
14381 (setq nval (read-string "Allowed: " allowed))
14382 (org-entry-put
14383 (cond ((marker-position org-entry-property-inherited-from)
14384 org-entry-property-inherited-from)
14385 ((marker-position org-columns-top-level-marker)
14386 org-columns-top-level-marker))
14387 key1 nval)))
14389 (defun org-columns-eval (form)
14390 (let (hidep)
14391 (save-excursion
14392 (beginning-of-line 1)
14393 (next-line 1)
14394 (setq hidep (org-on-heading-p 1)))
14395 (eval form)
14396 (and hidep (hide-entry))))
14398 (defun org-columns-previous-allowed-value ()
14399 "Switch to the previous allowed value for this column."
14400 (interactive)
14401 (org-columns-next-allowed-value t))
14403 (defun org-columns-next-allowed-value (&optional previous)
14404 "Switch to the next allowed value for this column."
14405 (interactive)
14406 (let* ((col (current-column))
14407 (key (get-char-property (point) 'org-columns-key))
14408 (value (get-char-property (point) 'org-columns-value))
14409 (bol (point-at-bol)) (eol (point-at-eol))
14410 (pom (or (get-text-property bol 'org-hd-marker)
14411 (point))) ; keep despite of compiler waring
14412 (line-overlays
14413 (delq nil (mapcar (lambda (x)
14414 (and (eq (overlay-buffer x) (current-buffer))
14415 (>= (overlay-start x) bol)
14416 (<= (overlay-start x) eol)
14418 org-columns-overlays)))
14419 (allowed (or (org-property-get-allowed-values pom key)
14420 (and (equal
14421 (nth 4 (assoc key org-columns-current-fmt-compiled))
14422 'checkbox) '("[ ]" "[X]"))))
14423 nval)
14424 (when (equal key "ITEM")
14425 (error "Cannot edit item headline from here"))
14426 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
14427 (error "Allowed values for this property have not been defined"))
14428 (if (member key '("SCHEDULED" "DEADLINE"))
14429 (setq nval (if previous 'earlier 'later))
14430 (if previous (setq allowed (reverse allowed)))
14431 (if (member value allowed)
14432 (setq nval (car (cdr (member value allowed)))))
14433 (setq nval (or nval (car allowed)))
14434 (if (equal nval value)
14435 (error "Only one allowed value for this property")))
14436 (let ((inhibit-read-only t))
14437 (remove-text-properties (1- bol) eol '(read-only t))
14438 (unwind-protect
14439 (progn
14440 (setq org-columns-overlays
14441 (org-delete-all line-overlays org-columns-overlays))
14442 (mapc 'org-delete-overlay line-overlays)
14443 (org-columns-eval '(org-entry-put pom key nval)))
14444 (org-columns-display-here)))
14445 (move-to-column col)
14446 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14447 (org-columns-update key))))
14449 (defun org-verify-version (task)
14450 (cond
14451 ((eq task 'columns)
14452 (if (or (featurep 'xemacs)
14453 (< emacs-major-version 22))
14454 (error "Emacs 22 is required for the columns feature")))))
14456 (defun org-columns-get-format-and-top-level ()
14457 (let (fmt)
14458 (when (condition-case nil (org-back-to-heading) (error nil))
14459 (move-marker org-entry-property-inherited-from nil)
14460 (setq fmt (org-entry-get nil "COLUMNS" t)))
14461 (setq fmt (or fmt org-columns-default-format))
14462 (org-set-local 'org-columns-current-fmt fmt)
14463 (org-columns-compile-format fmt)
14464 (if (marker-position org-entry-property-inherited-from)
14465 (move-marker org-columns-top-level-marker
14466 org-entry-property-inherited-from)
14467 (move-marker org-columns-top-level-marker (point)))
14468 fmt))
14470 (defun org-columns ()
14471 "Turn on column view on an org-mode file."
14472 (interactive)
14473 (org-verify-version 'columns)
14474 (org-columns-remove-overlays)
14475 (move-marker org-columns-begin-marker (point))
14476 (let (beg end fmt cache maxwidths)
14477 (setq fmt (org-columns-get-format-and-top-level))
14478 (save-excursion
14479 (goto-char org-columns-top-level-marker)
14480 (setq beg (point))
14481 (unless org-columns-inhibit-recalculation
14482 (org-columns-compute-all))
14483 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
14484 (point-max)))
14485 (goto-char beg)
14486 ;; Get and cache the properties
14487 (while (re-search-forward (concat "^" outline-regexp) end t)
14488 (push (cons (org-current-line) (org-entry-properties)) cache))
14489 (when cache
14490 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14491 (org-set-local 'org-columns-current-maxwidths maxwidths)
14492 (org-columns-display-here-title)
14493 (mapc (lambda (x)
14494 (goto-line (car x))
14495 (org-columns-display-here (cdr x)))
14496 cache)))))
14498 (defun org-columns-new (&optional prop title width op fmt)
14499 "Insert a new column, to the leeft o the current column."
14500 (interactive)
14501 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
14502 cell)
14503 (setq prop (completing-read
14504 "Property: " (mapcar 'list (org-buffer-property-keys t))
14505 nil nil prop))
14506 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
14507 (setq width (read-string "Column width: " (if width (number-to-string width))))
14508 (if (string-match "\\S-" width)
14509 (setq width (string-to-number width))
14510 (setq width nil))
14511 (setq fmt (completing-read "Summary [none]: "
14512 '(("none") ("add_numbers") ("add_times") ("checkbox"))
14513 nil t))
14514 (if (string-match "\\S-" fmt)
14515 (setq fmt (intern fmt))
14516 (setq fmt nil))
14517 (if (eq fmt 'none) (setq fmt nil))
14518 (if editp
14519 (progn
14520 (setcar editp prop)
14521 (setcdr editp (list title width nil fmt)))
14522 (setq cell (nthcdr (1- (current-column))
14523 org-columns-current-fmt-compiled))
14524 (setcdr cell (cons (list prop title width nil fmt)
14525 (cdr cell))))
14526 (org-columns-store-format)
14527 (org-columns-redo)))
14529 (defun org-columns-delete ()
14530 "Delete the column at point from columns view."
14531 (interactive)
14532 (let* ((n (current-column))
14533 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
14534 (when (y-or-n-p
14535 (format "Are you sure you want to remove column \"%s\"? " title))
14536 (setq org-columns-current-fmt-compiled
14537 (delq (nth n org-columns-current-fmt-compiled)
14538 org-columns-current-fmt-compiled))
14539 (org-columns-store-format)
14540 (org-columns-redo)
14541 (if (>= (current-column) (length org-columns-current-fmt-compiled))
14542 (backward-char 1)))))
14544 (defun org-columns-edit-attributes ()
14545 "Edit the attributes of the current column."
14546 (interactive)
14547 (let* ((n (current-column))
14548 (info (nth n org-columns-current-fmt-compiled)))
14549 (apply 'org-columns-new info)))
14551 (defun org-columns-widen (arg)
14552 "Make the column wider by ARG characters."
14553 (interactive "p")
14554 (let* ((n (current-column))
14555 (entry (nth n org-columns-current-fmt-compiled))
14556 (width (or (nth 2 entry)
14557 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
14558 (setq width (max 1 (+ width arg)))
14559 (setcar (nthcdr 2 entry) width)
14560 (org-columns-store-format)
14561 (org-columns-redo)))
14563 (defun org-columns-narrow (arg)
14564 "Make the column nrrower by ARG characters."
14565 (interactive "p")
14566 (org-columns-widen (- arg)))
14568 (defun org-columns-move-right ()
14569 "Swap this column with the one to the right."
14570 (interactive)
14571 (let* ((n (current-column))
14572 (cell (nthcdr n org-columns-current-fmt-compiled))
14574 (when (>= n (1- (length org-columns-current-fmt-compiled)))
14575 (error "Cannot shift this column further to the right"))
14576 (setq e (car cell))
14577 (setcar cell (car (cdr cell)))
14578 (setcdr cell (cons e (cdr (cdr cell))))
14579 (org-columns-store-format)
14580 (org-columns-redo)
14581 (forward-char 1)))
14583 (defun org-columns-move-left ()
14584 "Swap this column with the one to the left."
14585 (interactive)
14586 (let* ((n (current-column)))
14587 (when (= n 0)
14588 (error "Cannot shift this column further to the left"))
14589 (backward-char 1)
14590 (org-columns-move-right)
14591 (backward-char 1)))
14593 (defun org-columns-store-format ()
14594 "Store the text version of the current columns format in appropriate place.
14595 This is either in the COLUMNS property of the node starting the current column
14596 display, or in the #+COLUMNS line of the current buffer."
14597 (let (fmt)
14598 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
14599 (if (marker-position org-columns-top-level-marker)
14600 (save-excursion
14601 (goto-char org-columns-top-level-marker)
14602 (if (org-entry-get nil "COLUMNS")
14603 (org-entry-put nil "COLUMNS" fmt)
14604 (goto-char (point-min))
14605 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
14606 (replace-match (concat "#+COLUMNS: " fmt t t)))))
14607 (setq org-columns-current-fmt fmt))))
14609 (defvar org-overriding-columns-format nil
14610 "When set, overrides any other definition.")
14611 (defvar org-agenda-view-columns-initially nil
14612 "When set, switch to columns view immediately after creating the agenda.")
14614 (defun org-agenda-columns ()
14615 "Turn on column view in the agenda."
14616 (interactive)
14617 (org-verify-version 'columns)
14618 (org-columns-remove-overlays)
14619 (move-marker org-columns-begin-marker (point))
14620 (let (fmt cache maxwidths m)
14621 (cond
14622 ((and (local-variable-p 'org-overriding-columns-format)
14623 org-overriding-columns-format)
14624 (setq fmt org-overriding-columns-format))
14625 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
14626 (setq fmt (org-entry-get m "COLUMNS" t)))
14627 ((and (boundp 'org-columns-current-fmt)
14628 (local-variable-p 'org-columns-current-fmt)
14629 org-columns-current-fmt)
14630 (setq fmt org-columns-current-fmt))
14631 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
14632 (setq m (get-text-property m 'org-hd-marker))
14633 (setq fmt (org-entry-get m "COLUMNS" t))))
14634 (setq fmt (or fmt org-columns-default-format))
14635 (org-set-local 'org-columns-current-fmt fmt)
14636 (org-columns-compile-format fmt)
14637 (save-excursion
14638 ;; Get and cache the properties
14639 (goto-char (point-min))
14640 (while (not (eobp))
14641 (when (setq m (or (get-text-property (point) 'org-hd-marker)
14642 (get-text-property (point) 'org-marker)))
14643 (push (cons (org-current-line) (org-entry-properties m)) cache))
14644 (beginning-of-line 2))
14645 (when cache
14646 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14647 (org-set-local 'org-columns-current-maxwidths maxwidths)
14648 (org-columns-display-here-title)
14649 (mapc (lambda (x)
14650 (goto-line (car x))
14651 (org-columns-display-here (cdr x)))
14652 cache)))))
14654 (defun org-columns-get-autowidth-alist (s cache)
14655 "Derive the maximum column widths from the format and the cache."
14656 (let ((start 0) rtn)
14657 (while (string-match "%\\([a-zA-Z]\\S-*\\)" s start)
14658 (push (cons (match-string 1 s) 1) rtn)
14659 (setq start (match-end 0)))
14660 (mapc (lambda (x)
14661 (setcdr x (apply 'max
14662 (mapcar
14663 (lambda (y)
14664 (length (or (cdr (assoc (car x) (cdr y))) " ")))
14665 cache))))
14666 rtn)
14667 rtn))
14669 (defun org-columns-compute-all ()
14670 "Compute all columns that have operators defined."
14671 (org-unmodified
14672 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
14673 (let ((columns org-columns-current-fmt-compiled) col)
14674 (while (setq col (pop columns))
14675 (when (nth 3 col)
14676 (save-excursion
14677 (org-columns-compute (car col)))))))
14679 (defun org-columns-update (property)
14680 "Recompute PROPERTY, and update the columns display for it."
14681 (org-columns-compute property)
14682 (let (fmt val pos)
14683 (save-excursion
14684 (mapc (lambda (ov)
14685 (when (equal (org-overlay-get ov 'org-columns-key) property)
14686 (setq pos (org-overlay-start ov))
14687 (goto-char pos)
14688 (when (setq val (cdr (assoc property
14689 (get-text-property (point-at-bol) 'org-summaries))))
14690 (setq fmt (org-overlay-get ov 'org-columns-format))
14691 (org-overlay-put ov 'display (format fmt val)))))
14692 org-columns-overlays))))
14694 (defun org-columns-compute (property)
14695 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
14696 (interactive)
14697 (let* ((re (concat "^" outline-regexp))
14698 (lmax 30) ; Does anyone use deeper levels???
14699 (lsum (make-vector lmax 0))
14700 (level 0)
14701 (ass (assoc property org-columns-current-fmt-compiled))
14702 (format (nth 4 ass))
14703 (beg org-columns-top-level-marker)
14704 last-level val end sumpos sum-alist sum str)
14705 (save-excursion
14706 ;; Find the region to compute
14707 (goto-char beg)
14708 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
14709 (goto-char end)
14710 ;; Walk the tree from the back and do the computations
14711 (while (re-search-backward re beg t)
14712 (setq sumpos (match-beginning 0)
14713 last-level level
14714 level (org-outline-level)
14715 val (org-entry-get nil property))
14716 (cond
14717 ((< level last-level)
14718 ;; put the sum of lower levels here as a property
14719 (setq sum (aref lsum last-level)
14720 str (org-column-number-to-string sum format)
14721 sum-alist (get-text-property sumpos 'org-summaries))
14722 (if (assoc property sum-alist)
14723 (setcdr (assoc property sum-alist) str)
14724 (push (cons property str) sum-alist)
14725 (org-unmodified
14726 (add-text-properties sumpos (1+ sumpos)
14727 (list 'org-summaries sum-alist))))
14728 (when val ;?????????????????????????????????? and force?????
14729 (org-entry-put nil property str))
14730 ;; add current to current level accumulator
14731 (aset lsum level (+ (aref lsum level) sum))
14732 ;; clear accumulators for deeper levels
14733 (loop for l from (1+ level) to (1- lmax) do (aset lsum l 0)))
14734 ((>= level last-level)
14735 ;; add what we have here to the accumulator for this level
14736 (aset lsum level (+ (aref lsum level)
14737 (org-column-string-to-number (or val "0") format))))
14738 (t (error "This should not happen")))))))
14740 (defun org-columns-redo ()
14741 "Construct the column display again."
14742 (interactive)
14743 (message "Recomputing columns...")
14744 (save-excursion
14745 (if (marker-position org-columns-begin-marker)
14746 (goto-char org-columns-begin-marker))
14747 (org-columns-remove-overlays)
14748 (if (org-mode-p)
14749 (call-interactively 'org-columns)
14750 (call-interactively 'org-agenda-columns)))
14751 (message "Recomputing columns...done"))
14753 (defun org-columns-not-in-agenda ()
14754 (if (eq major-mode 'org-agenda-mode)
14755 (error "This command is only allowed in Org-mode buffers")))
14758 (defun org-string-to-number (s)
14759 "Convert string to number, and interpret hh:mm:ss."
14760 (if (not (string-match ":" s))
14761 (string-to-number s)
14762 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14763 (while l
14764 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14765 sum)))
14767 (defun org-column-number-to-string (n fmt)
14768 "Convert a computed column number to a string value, according to FMT."
14769 (cond
14770 ((eq fmt 'add_times)
14771 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
14772 (format "%d:%02d" h m)))
14773 ((eq fmt 'checkbox)
14774 (cond ((= n (floor n)) "[X]")
14775 ((> n 1.) "[-]")
14776 (t "[ ]")))
14777 (t (number-to-string n))))
14779 (defun org-column-string-to-number (s fmt)
14780 "Convert a column value to a number that can be used for column computing."
14781 (cond
14782 ((string-match ":" s)
14783 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14784 (while l
14785 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14786 sum))
14787 ((eq fmt 'checkbox)
14788 (if (equal s "[X]") 1. 0.000001))
14789 (t (string-to-number s))))
14791 (defun org-columns-uncompile-format (cfmt)
14792 "Turn the compiled columns format back into a string representation."
14793 (let ((rtn "") e s prop title op width fmt)
14794 (while (setq e (pop cfmt))
14795 (setq prop (car e)
14796 title (nth 1 e)
14797 width (nth 2 e)
14798 op (nth 3 e)
14799 fmt (nth 4 e))
14800 (cond
14801 ((eq fmt 'add_times) (setq op ":"))
14802 ((eq fmt 'checkbox) (setq op "X"))
14803 ((eq fmt 'add_numbers) (setq op "+")))
14804 (if (equal title prop) (setq title nil))
14805 (setq s (concat "%" (if width (number-to-string width))
14806 prop
14807 (if title (concat "(" title ")"))
14808 (if op (concat "{" op "}"))))
14809 (setq rtn (concat rtn " " s)))
14810 (org-trim rtn)))
14812 (defun org-columns-compile-format (fmt)
14813 "FIXME"
14814 (let ((start 0) width prop title op f)
14815 (setq org-columns-current-fmt-compiled nil)
14816 (while (string-match "%\\([0-9]+\\)?\\([a-zA-Z_0-9]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*"
14817 fmt start)
14818 (setq start (match-end 0)
14819 width (match-string 1 fmt)
14820 prop (match-string 2 fmt)
14821 title (or (match-string 3 fmt) prop)
14822 op (match-string 4 fmt)
14823 f nil)
14824 (if width (setq width (string-to-number width)))
14825 (cond
14826 ((equal op "+") (setq f 'add_numbers))
14827 ((equal op ":") (setq f 'add_times))
14828 ((equal op "X") (setq f 'checkbox)))
14829 (push (list prop title width op f) org-columns-current-fmt-compiled))
14830 (setq org-columns-current-fmt-compiled
14831 (nreverse org-columns-current-fmt-compiled))))
14833 ;;;; Timestamps
14835 (defvar org-last-changed-timestamp nil)
14836 (defvar org-time-was-given) ; dynamically scoped parameter
14837 (defvar org-end-time-was-given) ; dynamically scoped parameter
14838 (defvar org-ts-what) ; dynamically scoped parameter
14840 (defun org-time-stamp (arg)
14841 "Prompt for a date/time and insert a time stamp.
14842 If the user specifies a time like HH:MM, or if this command is called
14843 with a prefix argument, the time stamp will contain date and time.
14844 Otherwise, only the date will be included. All parts of a date not
14845 specified by the user will be filled in from the current date/time.
14846 So if you press just return without typing anything, the time stamp
14847 will represent the current date/time. If there is already a timestamp
14848 at the cursor, it will be modified."
14849 (interactive "P")
14850 (let (org-time-was-given org-end-time-was-given time)
14851 (cond
14852 ((and (org-at-timestamp-p)
14853 (eq last-command 'org-time-stamp)
14854 (eq this-command 'org-time-stamp))
14855 (insert "--")
14856 (setq time (let ((this-command this-command))
14857 (org-read-date arg 'totime)))
14858 (org-insert-time-stamp time (or org-time-was-given arg)))
14859 ((org-at-timestamp-p)
14860 (setq time (let ((this-command this-command))
14861 (org-read-date arg 'totime)))
14862 (when (org-at-timestamp-p) ; just to get the match data
14863 (replace-match "")
14864 (setq org-last-changed-timestamp
14865 (org-insert-time-stamp
14866 time (or org-time-was-given arg)
14867 nil nil nil (list org-end-time-was-given))))
14868 (message "Timestamp updated"))
14870 (setq time (let ((this-command this-command))
14871 (org-read-date arg 'totime)))
14872 (org-insert-time-stamp time (or org-time-was-given arg)
14873 nil nil nil (list org-end-time-was-given))))))
14875 (defun org-time-stamp-inactive (&optional arg)
14876 "Insert an inactive time stamp.
14877 An inactive time stamp is enclosed in square brackets instead of angle
14878 brackets. It is inactive in the sense that it does not trigger agenda entries,
14879 does not link to the calendar and cannot be changed with the S-cursor keys.
14880 So these are more for recording a certain time/date."
14881 (interactive "P")
14882 (let (org-time-was-given org-end-time-was-given time)
14883 (setq time (org-read-date arg 'totime))
14884 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
14885 nil nil (list org-end-time-was-given))))
14887 (defvar org-date-ovl (org-make-overlay 1 1))
14888 (org-overlay-put org-date-ovl 'face 'org-warning)
14889 (org-detach-overlay org-date-ovl)
14891 (defvar org-ans1) ; dynamically scoped parameter
14892 (defvar org-ans2) ; dynamically scoped parameter
14894 (defvar org-plain-time-of-day-regexp) ; defined below
14895 (defun org-read-date (&optional with-time to-time from-string prompt)
14896 "Read a date and make things smooth for the user.
14897 The prompt will suggest to enter an ISO date, but you can also enter anything
14898 which will at least partially be understood by `parse-time-string'.
14899 Unrecognized parts of the date will default to the current day, month, year,
14900 hour and minute. For example,
14901 3-2-5 --> 2003-02-05
14902 feb 15 --> currentyear-02-15
14903 sep 12 9 --> 2009-09-12
14904 12:45 --> today 12:45
14905 22 sept 0:34 --> currentyear-09-22 0:34
14906 12 --> currentyear-currentmonth-12
14907 Fri --> nearest Friday (today or later)
14908 +4 --> four days from today (only if +N is the only thing given)
14909 etc.
14910 The function understands only English month and weekday abbreviations,
14911 but this can be configured with the variables `parse-time-months' and
14912 `parse-time-weekdays'.
14914 While prompting, a calendar is popped up - you can also select the
14915 date with the mouse (button 1). The calendar shows a period of three
14916 months. To scroll it to other months, use the keys `>' and `<'.
14917 If you don't like the calendar, turn it off with
14918 \(setq org-popup-calendar-for-date-prompt nil)
14920 With optional argument TO-TIME, the date will immediately be converted
14921 to an internal time.
14922 With an optional argument WITH-TIME, the prompt will suggest to also
14923 insert a time. Note that when WITH-TIME is not set, you can still
14924 enter a time, and this function will inform the calling routine about
14925 this change. The calling routine may then choose to change the format
14926 used to insert the time stamp into the buffer to include the time."
14927 (require 'parse-time)
14928 (let* ((org-time-stamp-rounding-minutes
14929 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
14930 (ct (org-current-time))
14931 (default-time
14932 ;; Default time is either today, or, when entering a range,
14933 ;; the range start.
14934 (if (save-excursion
14935 (re-search-backward
14936 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14937 (- (point) 20) t))
14938 (apply
14939 'encode-time
14940 (mapcar (lambda(x) (or x 0))
14941 (parse-time-string (match-string 1))))
14942 ct))
14943 (calendar-move-hook nil)
14944 (view-diary-entries-initially nil)
14945 (view-calendar-holidays-initially nil)
14946 (timestr (format-time-string
14947 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
14948 (prompt (concat (if prompt (concat prompt " ") "")
14949 (format "Date and/or time (default [%s]): " timestr)))
14950 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
14951 second minute hour day month year tl wday wday1 pm)
14953 (cond
14954 (from-string (setq ans from-string))
14955 (org-popup-calendar-for-date-prompt
14956 (save-excursion
14957 (save-window-excursion
14958 (calendar)
14959 (calendar-forward-day (- (time-to-days default-time)
14960 (calendar-absolute-from-gregorian
14961 (calendar-current-date))))
14962 (org-eval-in-calendar nil t)
14963 (let* ((old-map (current-local-map))
14964 (map (copy-keymap calendar-mode-map))
14965 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14966 (org-defkey map (kbd "RET") 'org-calendar-select)
14967 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
14968 'org-calendar-select-mouse)
14969 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
14970 'org-calendar-select-mouse)
14971 (org-defkey minibuffer-local-map [(meta shift left)]
14972 (lambda () (interactive)
14973 (org-eval-in-calendar '(calendar-backward-month 1))))
14974 (org-defkey minibuffer-local-map [(meta shift right)]
14975 (lambda () (interactive)
14976 (org-eval-in-calendar '(calendar-forward-month 1))))
14977 (org-defkey minibuffer-local-map [(shift up)]
14978 (lambda () (interactive)
14979 (org-eval-in-calendar '(calendar-backward-week 1))))
14980 (org-defkey minibuffer-local-map [(shift down)]
14981 (lambda () (interactive)
14982 (org-eval-in-calendar '(calendar-forward-week 1))))
14983 (org-defkey minibuffer-local-map [(shift left)]
14984 (lambda () (interactive)
14985 (org-eval-in-calendar '(calendar-backward-day 1))))
14986 (org-defkey minibuffer-local-map [(shift right)]
14987 (lambda () (interactive)
14988 (org-eval-in-calendar '(calendar-forward-day 1))))
14989 (org-defkey minibuffer-local-map ">"
14990 (lambda () (interactive)
14991 (org-eval-in-calendar '(scroll-calendar-left 1))))
14992 (org-defkey minibuffer-local-map "<"
14993 (lambda () (interactive)
14994 (org-eval-in-calendar '(scroll-calendar-right 1))))
14995 (unwind-protect
14996 (progn
14997 (use-local-map map)
14998 (setq org-ans0 (read-string prompt "" nil nil))
14999 ;; org-ans0: from prompt
15000 ;; org-ans1: from mouse click
15001 ;; org-ans2: from calendar motion
15002 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15003 (use-local-map old-map))))))
15004 (t ; Naked prompt only
15005 (setq ans (read-string prompt "" nil timestr))))
15006 (org-detach-overlay org-date-ovl)
15008 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
15009 (setq deltadays (string-to-number ans) ans ""))
15011 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15012 (when (string-match
15013 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15014 (setq year (if (match-end 2)
15015 (string-to-number (match-string 2 ans))
15016 (string-to-number (format-time-string "%Y")))
15017 month (string-to-number (match-string 3 ans))
15018 day (string-to-number (match-string 4 ans)))
15019 (if (< year 100) (setq year (+ 2000 year)))
15020 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15021 t nil ans)))
15022 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15023 ;; If there is a time with am/pm, and *no* time without it, we convert
15024 ;; so that matching will be successful.
15025 ;; FIXME: make this replace twice, so that we catch the end time.
15026 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15027 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15028 (setq hour (string-to-number (match-string 1 ans))
15029 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
15030 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
15031 (if (and (= hour 12) (not pm))
15032 (setq hour 0)
15033 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15034 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
15036 ;; Check if there is a time range
15037 (when (and (boundp 'org-end-time-was-given)
15038 (string-match org-plain-time-of-day-regexp ans)
15039 (match-end 8))
15040 (setq org-end-time-was-given (match-string 8 ans))
15041 (setq ans (concat (substring ans 0 (match-beginning 7))
15042 (substring ans (match-end 7)))))
15044 (setq tl (parse-time-string ans)
15045 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
15046 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
15047 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
15048 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
15049 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
15050 second (or (nth 0 tl) 0)
15051 wday (nth 6 tl))
15052 (setq day (+ day deltadays))
15053 (when (and wday (not (nth 3 tl)))
15054 ;; Weekday was given, but no day, so pick that day in the week
15055 ;; on or after the derived date.
15056 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15057 (unless (equal wday wday1)
15058 (setq day (+ day (% (- wday wday1 -7) 7)))))
15059 (if (and (boundp 'org-time-was-given)
15060 (nth 2 tl))
15061 (setq org-time-was-given t))
15062 (if (< year 100) (setq year (+ 2000 year)))
15063 (if to-time
15064 (encode-time second minute hour day month year)
15065 (if (or (nth 1 tl) (nth 2 tl))
15066 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15067 (format "%04d-%02d-%02d" year month day)))))
15069 (defun org-eval-in-calendar (form &optional keepdate)
15070 "Eval FORM in the calendar window and return to current window.
15071 Also, store the cursor date in variable org-ans2."
15072 (let ((sw (selected-window)))
15073 (select-window (get-buffer-window "*Calendar*"))
15074 (eval form)
15075 (when (and (not keepdate) (calendar-cursor-to-date))
15076 (let* ((date (calendar-cursor-to-date))
15077 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15078 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15079 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15080 (select-window sw)
15081 ;; Update the prompt to show new default date
15082 (save-excursion
15083 (goto-char (point-min))
15084 (when (and org-ans2
15085 (re-search-forward "\\[[-0-9]+\\]" nil t)
15086 (get-text-property (match-end 0) 'field))
15087 (let ((inhibit-read-only t))
15088 (replace-match (concat "[" org-ans2 "]") t t)
15089 (add-text-properties (point-min) (1+ (match-end 0))
15090 (text-properties-at (1+ (point-min)))))))))
15092 (defun org-calendar-select ()
15093 "Return to `org-read-date' with the date currently selected.
15094 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15095 (interactive)
15096 (when (calendar-cursor-to-date)
15097 (let* ((date (calendar-cursor-to-date))
15098 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15099 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15100 (if (active-minibuffer-window) (exit-minibuffer))))
15102 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15103 "Insert a date stamp for the date given by the internal TIME.
15104 WITH-HM means, use the stamp format that includes the time of the day.
15105 INACTIVE means use square brackets instead of angular ones, so that the
15106 stamp will not contribute to the agenda.
15107 PRE and POST are optional strings to be inserted before and after the
15108 stamp.
15109 The command returns the inserted time stamp."
15110 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15111 stamp)
15112 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15113 (insert (or pre ""))
15114 (insert (setq stamp (format-time-string fmt time)))
15115 (when (listp extra)
15116 (setq extra (car extra))
15117 (if (and (stringp extra)
15118 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15119 (setq extra (format "-%02d:%02d"
15120 (string-to-number (match-string 1 extra))
15121 (string-to-number (match-string 2 extra))))
15122 (setq extra nil)))
15123 (when extra
15124 (backward-char 1)
15125 (insert extra)
15126 (forward-char 1))
15127 (insert (or post ""))
15128 stamp))
15130 (defun org-toggle-time-stamp-overlays ()
15131 "Toggle the use of custom time stamp formats."
15132 (interactive)
15133 (setq org-display-custom-times (not org-display-custom-times))
15134 (unless org-display-custom-times
15135 (let ((p (point-min)) (bmp (buffer-modified-p)))
15136 (while (setq p (next-single-property-change p 'display))
15137 (if (and (get-text-property p 'display)
15138 (eq (get-text-property p 'face) 'org-date))
15139 (remove-text-properties
15140 p (setq p (next-single-property-change p 'display))
15141 '(display t))))
15142 (set-buffer-modified-p bmp)))
15143 (if (featurep 'xemacs)
15144 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15145 (org-restart-font-lock)
15146 (setq org-table-may-need-update t)
15147 (if org-display-custom-times
15148 (message "Time stamps are overlayed with custom format")
15149 (message "Time stamp overlays removed")))
15151 (defun org-display-custom-time (beg end)
15152 "Overlay modified time stamp format over timestamp between BED and END."
15153 (let* ((ts (buffer-substring beg end))
15154 t1 w1 with-hm tf time str w2 (off 0))
15155 (save-match-data
15156 (setq t1 (org-parse-time-string ts t))
15157 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
15158 (setq off (- (match-end 0) (match-beginning 0)))))
15159 (setq end (- end off))
15160 (setq w1 (- end beg)
15161 with-hm (and (nth 1 t1) (nth 2 t1))
15162 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15163 time (org-fix-decoded-time t1)
15164 str (org-add-props
15165 (format-time-string
15166 (substring tf 1 -1) (apply 'encode-time time))
15167 nil 'mouse-face 'highlight)
15168 w2 (length str))
15169 (if (not (= w2 w1))
15170 (add-text-properties (1+ beg) (+ 2 beg)
15171 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15172 (if (featurep 'xemacs)
15173 (progn
15174 (put-text-property beg end 'invisible t)
15175 (put-text-property beg end 'end-glyph (make-glyph str)))
15176 (put-text-property beg end 'display str))))
15178 (defun org-translate-time (string)
15179 "Translate all timestamps in STRING to custom format.
15180 But do this only if the variable `org-display-custom-times' is set."
15181 (when org-display-custom-times
15182 (save-match-data
15183 (let* ((start 0)
15184 (re org-ts-regexp-both)
15185 t1 with-hm inactive tf time str beg end)
15186 (while (setq start (string-match re string start))
15187 (setq beg (match-beginning 0)
15188 end (match-end 0)
15189 t1 (save-match-data
15190 (org-parse-time-string (substring string beg end) t))
15191 with-hm (and (nth 1 t1) (nth 2 t1))
15192 inactive (equal (substring string beg (1+ beg)) "[")
15193 tf (funcall (if with-hm 'cdr 'car)
15194 org-time-stamp-custom-formats)
15195 time (org-fix-decoded-time t1)
15196 str (format-time-string
15197 (concat
15198 (if inactive "[" "<") (substring tf 1 -1)
15199 (if inactive "]" ">"))
15200 (apply 'encode-time time))
15201 string (replace-match str t t string)
15202 start (+ start (length str)))))))
15203 string)
15205 (defun org-fix-decoded-time (time)
15206 "Set 0 instead of nil for the first 6 elements of time.
15207 Don't touch the rest."
15208 (let ((n 0))
15209 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15211 (defun org-days-to-time (timestamp-string)
15212 "Difference between TIMESTAMP-STRING and now in days."
15213 (- (time-to-days (org-time-string-to-time timestamp-string))
15214 (time-to-days (current-time))))
15216 (defun org-deadline-close (timestamp-string &optional ndays)
15217 "Is the time in TIMESTAMP-STRING close to the current date?"
15218 (and (< (org-days-to-time timestamp-string)
15219 (or ndays org-deadline-warning-days))
15220 (not (org-entry-is-done-p))))
15222 (defun org-calendar-select-mouse (ev)
15223 "Return to `org-read-date' with the date currently selected.
15224 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15225 (interactive "e")
15226 (mouse-set-point ev)
15227 (when (calendar-cursor-to-date)
15228 (let* ((date (calendar-cursor-to-date))
15229 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15230 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15231 (if (active-minibuffer-window) (exit-minibuffer))))
15233 (defun org-check-deadlines (ndays)
15234 "Check if there are any deadlines due or past due.
15235 A deadline is considered due if it happens within `org-deadline-warning-days'
15236 days from today's date. If the deadline appears in an entry marked DONE,
15237 it is not shown. The prefix arg NDAYS can be used to test that many
15238 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15239 (interactive "P")
15240 (let* ((org-warn-days
15241 (cond
15242 ((equal ndays '(4)) 100000)
15243 (ndays (prefix-numeric-value ndays))
15244 (t org-deadline-warning-days)))
15245 (case-fold-search nil)
15246 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15247 (callback
15248 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15250 (message "%d deadlines past-due or due within %d days"
15251 (org-occur regexp nil callback)
15252 org-warn-days)))
15254 (defun org-evaluate-time-range (&optional to-buffer)
15255 "Evaluate a time range by computing the difference between start and end.
15256 Normally the result is just printed in the echo area, but with prefix arg
15257 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15258 If the time range is actually in a table, the result is inserted into the
15259 next column.
15260 For time difference computation, a year is assumed to be exactly 365
15261 days in order to avoid rounding problems."
15262 (interactive "P")
15264 (org-clock-update-time-maybe)
15265 (save-excursion
15266 (unless (org-at-date-range-p)
15267 (goto-char (point-at-bol))
15268 (re-search-forward org-tr-regexp (point-at-eol) t))
15269 (if (not (org-at-date-range-p))
15270 (error "Not at a time-stamp range, and none found in current line")))
15271 (let* ((ts1 (match-string 1))
15272 (ts2 (match-string 2))
15273 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15274 (match-end (match-end 0))
15275 (time1 (org-time-string-to-time ts1))
15276 (time2 (org-time-string-to-time ts2))
15277 (t1 (time-to-seconds time1))
15278 (t2 (time-to-seconds time2))
15279 (diff (abs (- t2 t1)))
15280 (negative (< (- t2 t1) 0))
15281 ;; (ys (floor (* 365 24 60 60)))
15282 (ds (* 24 60 60))
15283 (hs (* 60 60))
15284 (fy "%dy %dd %02d:%02d")
15285 (fy1 "%dy %dd")
15286 (fd "%dd %02d:%02d")
15287 (fd1 "%dd")
15288 (fh "%02d:%02d")
15289 y d h m align)
15290 (if havetime
15291 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15293 d (floor (/ diff ds)) diff (mod diff ds)
15294 h (floor (/ diff hs)) diff (mod diff hs)
15295 m (floor (/ diff 60)))
15296 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15298 d (floor (+ (/ diff ds) 0.5))
15299 h 0 m 0))
15300 (if (not to-buffer)
15301 (message (org-make-tdiff-string y d h m))
15302 (when (org-at-table-p)
15303 (goto-char match-end)
15304 (setq align t)
15305 (and (looking-at " *|") (goto-char (match-end 0))))
15306 (if (looking-at
15307 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15308 (replace-match ""))
15309 (if negative (insert " -"))
15310 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15311 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15312 (insert " " (format fh h m))))
15313 (if align (org-table-align))
15314 (message "Time difference inserted")))))
15316 (defun org-make-tdiff-string (y d h m)
15317 (let ((fmt "")
15318 (l nil))
15319 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15320 l (push y l)))
15321 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15322 l (push d l)))
15323 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15324 l (push h l)))
15325 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15326 l (push m l)))
15327 (apply 'format fmt (nreverse l))))
15329 (defun org-time-string-to-time (s)
15330 (apply 'encode-time (org-parse-time-string s)))
15332 (defun org-time-string-to-absolute (s &optional daynr)
15333 "Convert a time stamp to an absolute day number.
15334 If there is a specifyer for a cyclic time stamp, get the closest date to
15335 DAYNR."
15336 (cond
15337 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15338 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15339 daynr
15340 (+ daynr 1000)))
15341 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15342 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15343 (time-to-days (current-time))) (match-string 0 s)))
15344 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15346 (defun org-calendar-holiday ()
15347 "List of holidays, for Diary display in Org-mode."
15348 (let ((hl (check-calendar-holidays date)))
15349 (if hl (mapconcat 'identity hl "; "))))
15351 (defun org-diary-sexp-entry (sexp entry date)
15352 "Process a SEXP diary ENTRY for DATE."
15353 (require 'diary-lib)
15354 (let ((result (if calendar-debug-sexp
15355 (let ((stack-trace-on-error t))
15356 (eval (car (read-from-string sexp))))
15357 (condition-case nil
15358 (eval (car (read-from-string sexp)))
15359 (error
15360 (beep)
15361 (message "Bad sexp at line %d in %s: %s"
15362 (org-current-line)
15363 (buffer-file-name) sexp)
15364 (sleep-for 2))))))
15365 (cond ((stringp result) result)
15366 ((and (consp result)
15367 (stringp (cdr result))) (cdr result))
15368 (result entry)
15369 (t nil))))
15371 (defun org-diary-to-ical-string (frombuf)
15372 "FIXME"
15373 (let* ((tmpdir (if (featurep 'xemacs)
15374 (temp-directory)
15375 temporary-file-directory))
15376 (tmpfile (make-temp-name
15377 (expand-file-name "orgics" tmpdir)))
15378 buf rtn b e)
15379 (save-excursion
15380 (set-buffer frombuf)
15381 (icalendar-export-region (point-min) (point-max) tmpfile)
15382 (setq buf (find-buffer-visiting tmpfile))
15383 (set-buffer buf)
15384 (goto-char (point-min))
15385 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15386 (setq b (match-beginning 0)))
15387 (goto-char (point-max))
15388 (if (re-search-backward "^END:VEVENT" nil t)
15389 (setq e (match-end 0)))
15390 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15391 (kill-buffer buf)
15392 (kill-buffer frombuf)
15393 (delete-file tmpfile)
15394 rtn))
15396 (defun org-closest-date (start current change)
15397 "Find the date closest to CURRENT that is consistent with START and CHANGE."
15398 ;; Make the proper lists from the dates
15399 (catch 'exit
15400 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15401 dn dw sday cday n1 n2
15402 d m y y1 y2 date1 date2 nmonths nm ny m2)
15404 (setq start (org-date-to-gregorian start)
15405 current (org-date-to-gregorian
15406 (if org-agenda-repeating-timestamp-show-all
15407 current
15408 (time-to-days (current-time))))
15409 sday (calendar-absolute-from-gregorian start)
15410 cday (calendar-absolute-from-gregorian current))
15412 (if (<= cday sday) (throw 'exit sday))
15414 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15415 (setq dn (string-to-number (match-string 1 change))
15416 dw (cdr (assoc (match-string 2 change) a1)))
15417 (error "Invalid change specifyer: %s" change))
15418 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15419 (cond
15420 ((eq dw 'day)
15421 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15422 n2 (+ n1 dn)))
15423 ((eq dw 'year)
15424 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15425 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15426 (setq date1 (list m d y1)
15427 n1 (calendar-absolute-from-gregorian date1)
15428 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15429 n2 (calendar-absolute-from-gregorian date2)))
15430 ((eq dw 'month)
15431 ;; approx number of month between the tow dates
15432 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15433 ;; How often does dn fit in there?
15434 (setq d (nth 1 start) m (car start) y (nth 2 start)
15435 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15436 m (+ m nm)
15437 ny (floor (/ m 12))
15438 y (+ y ny)
15439 m (- m (* ny 12)))
15440 (while (> m 12) (setq m (- m 12) y (1+ y)))
15441 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15442 (setq m2 (+ m dn) y2 y)
15443 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15444 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15445 (while (< n2 cday)
15446 (setq n1 n2 m m2 y y2)
15447 (setq m2 (+ m dn) y2 y)
15448 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15449 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15451 (if org-agenda-repeating-timestamp-show-all
15452 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
15453 (if (= cday n1) n1 n2)))))
15455 (defun org-date-to-gregorian (date)
15456 "Turn any specification of DATE into a gregorian date for the calendar."
15457 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15458 ((and (listp date) (= (length date) 3)) date)
15459 ((stringp date)
15460 (setq date (org-parse-time-string date))
15461 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15462 ((listp date)
15463 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15465 (defun org-parse-time-string (s &optional nodefault)
15466 "Parse the standard Org-mode time string.
15467 This should be a lot faster than the normal `parse-time-string'.
15468 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15469 hour and minute fields will be nil if not given."
15470 (if (string-match org-ts-regexp0 s)
15471 (list 0
15472 (if (or (match-beginning 8) (not nodefault))
15473 (string-to-number (or (match-string 8 s) "0")))
15474 (if (or (match-beginning 7) (not nodefault))
15475 (string-to-number (or (match-string 7 s) "0")))
15476 (string-to-number (match-string 4 s))
15477 (string-to-number (match-string 3 s))
15478 (string-to-number (match-string 2 s))
15479 nil nil nil)
15480 (make-list 9 0)))
15482 (defun org-timestamp-up (&optional arg)
15483 "Increase the date item at the cursor by one.
15484 If the cursor is on the year, change the year. If it is on the month or
15485 the day, change that.
15486 With prefix ARG, change by that many units."
15487 (interactive "p")
15488 (org-timestamp-change (prefix-numeric-value arg)))
15490 (defun org-timestamp-down (&optional arg)
15491 "Decrease the date item at the cursor by one.
15492 If the cursor is on the year, change the year. If it is on the month or
15493 the day, change that.
15494 With prefix ARG, change by that many units."
15495 (interactive "p")
15496 (org-timestamp-change (- (prefix-numeric-value arg))))
15498 (defun org-timestamp-up-day (&optional arg)
15499 "Increase the date in the time stamp by one day.
15500 With prefix ARG, change that many days."
15501 (interactive "p")
15502 (if (and (not (org-at-timestamp-p t))
15503 (org-on-heading-p))
15504 (org-todo 'up)
15505 (org-timestamp-change (prefix-numeric-value arg) 'day)))
15507 (defun org-timestamp-down-day (&optional arg)
15508 "Decrease the date in the time stamp by one day.
15509 With prefix ARG, change that many days."
15510 (interactive "p")
15511 (if (and (not (org-at-timestamp-p t))
15512 (org-on-heading-p))
15513 (org-todo 'down)
15514 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
15516 (defsubst org-pos-in-match-range (pos n)
15517 (and (match-beginning n)
15518 (<= (match-beginning n) pos)
15519 (>= (match-end n) pos)))
15521 (defun org-at-timestamp-p (&optional inactive-ok)
15522 "Determine if the cursor is in or at a timestamp."
15523 (interactive)
15524 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15525 (pos (point))
15526 (ans (or (looking-at tsr)
15527 (save-excursion
15528 (skip-chars-backward "^[<\n\r\t")
15529 (if (> (point) 1) (backward-char 1))
15530 (and (looking-at tsr)
15531 (> (- (match-end 0) pos) -1))))))
15532 (and (boundp 'org-ts-what)
15533 (setq org-ts-what
15534 (cond
15535 ((org-pos-in-match-range pos 2) 'year)
15536 ((org-pos-in-match-range pos 3) 'month)
15537 ((org-pos-in-match-range pos 7) 'hour)
15538 ((org-pos-in-match-range pos 8) 'minute)
15539 ((or (org-pos-in-match-range pos 4)
15540 (org-pos-in-match-range pos 5)) 'day)
15541 ((and (> pos (or (match-end 8) (match-end 5)))
15542 (< pos (match-end 0)))
15543 (- pos (or (match-end 8) (match-end 5))))
15544 (t 'day))))
15545 ans))
15547 (defun org-timestamp-change (n &optional what)
15548 "Change the date in the time stamp at point.
15549 The date will be changed by N times WHAT. WHAT can be `day', `month',
15550 `year', `minute', `second'. If WHAT is not given, the cursor position
15551 in the timestamp determines what will be changed."
15552 (let ((pos (point))
15553 with-hm inactive
15554 org-ts-what
15555 extra
15556 ts time time0)
15557 (if (not (org-at-timestamp-p t))
15558 (error "Not at a timestamp"))
15559 (if (and (not what) (not (eq org-ts-what 'day))
15560 org-display-custom-times
15561 (get-text-property (point) 'display)
15562 (not (get-text-property (1- (point)) 'display)))
15563 (setq org-ts-what 'day))
15564 (setq org-ts-what (or what org-ts-what)
15565 inactive (= (char-after (match-beginning 0)) ?\[)
15566 ts (match-string 0))
15567 (replace-match "")
15568 (if (string-match
15569 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
15571 (setq extra (match-string 1 ts)))
15572 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15573 (setq with-hm t))
15574 (setq time0 (org-parse-time-string ts))
15575 (setq time
15576 (apply 'encode-time
15577 (append
15578 (list (or (car time0) 0))
15579 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
15580 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
15581 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
15582 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
15583 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
15584 (nthcdr 6 time0))))
15585 (when (integerp org-ts-what)
15586 (setq extra (org-modify-ts-extra extra org-ts-what n)))
15587 (if (eq what 'calendar)
15588 (let ((cal-date
15589 (save-excursion
15590 (save-match-data
15591 (set-buffer "*Calendar*")
15592 (calendar-cursor-to-date)))))
15593 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15594 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15595 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15596 (setcar time0 (or (car time0) 0))
15597 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15598 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
15599 (setq time (apply 'encode-time time0))))
15600 (setq org-last-changed-timestamp
15601 (org-insert-time-stamp time with-hm inactive nil nil extra))
15602 (org-clock-update-time-maybe)
15603 (goto-char pos)
15604 ;; Try to recenter the calendar window, if any
15605 (if (and org-calendar-follow-timestamp-change
15606 (get-buffer-window "*Calendar*" t)
15607 (memq org-ts-what '(day month year)))
15608 (org-recenter-calendar (time-to-days time)))))
15610 (defun org-modify-ts-extra (s pos n)
15611 "FIXME"
15612 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15613 ng h m new)
15614 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15615 (cond
15616 ((or (org-pos-in-match-range pos 2)
15617 (org-pos-in-match-range pos 3))
15618 (setq m (string-to-number (match-string 3 s))
15619 h (string-to-number (match-string 2 s)))
15620 (if (org-pos-in-match-range pos 2)
15621 (setq h (+ h n))
15622 (setq m (+ m n)))
15623 (if (< m 0) (setq m (+ m 60) h (1- h)))
15624 (if (> m 59) (setq m (- m 60) h (1+ h)))
15625 (setq h (min 24 (max 0 h)))
15626 (setq ng 1 new (format "-%02d:%02d" h m)))
15627 ((org-pos-in-match-range pos 6)
15628 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15629 ((org-pos-in-match-range pos 5)
15630 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
15632 (when ng
15633 (setq s (concat
15634 (substring s 0 (match-beginning ng))
15636 (substring s (match-end ng))))))
15639 (defun org-recenter-calendar (date)
15640 "If the calendar is visible, recenter it to DATE."
15641 (let* ((win (selected-window))
15642 (cwin (get-buffer-window "*Calendar*" t))
15643 (calendar-move-hook nil))
15644 (when cwin
15645 (select-window cwin)
15646 (calendar-goto-date (if (listp date) date
15647 (calendar-gregorian-from-absolute date)))
15648 (select-window win))))
15650 (defun org-goto-calendar (&optional arg)
15651 "Go to the Emacs calendar at the current date.
15652 If there is a time stamp in the current line, go to that date.
15653 A prefix ARG can be used to force the current date."
15654 (interactive "P")
15655 (let ((tsr org-ts-regexp) diff
15656 (calendar-move-hook nil)
15657 (view-calendar-holidays-initially nil)
15658 (view-diary-entries-initially nil))
15659 (if (or (org-at-timestamp-p)
15660 (save-excursion
15661 (beginning-of-line 1)
15662 (looking-at (concat ".*" tsr))))
15663 (let ((d1 (time-to-days (current-time)))
15664 (d2 (time-to-days
15665 (org-time-string-to-time (match-string 1)))))
15666 (setq diff (- d2 d1))))
15667 (calendar)
15668 (calendar-goto-today)
15669 (if (and diff (not arg)) (calendar-forward-day diff))))
15671 (defun org-date-from-calendar ()
15672 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15673 If there is already a time stamp at the cursor position, update it."
15674 (interactive)
15675 (org-timestamp-change 0 'calendar))
15677 ;;; The clock for measuring work time.
15679 (defvar org-mode-line-string "")
15680 (put 'org-mode-line-string 'risky-local-variable t)
15682 (defvar org-mode-line-timer nil)
15683 (defvar org-clock-heading "")
15684 (defvar org-clock-start-time "")
15686 (defun org-update-mode-line ()
15687 (let* ((delta (- (time-to-seconds (current-time))
15688 (time-to-seconds org-clock-start-time)))
15689 (h (floor delta 3600))
15690 (m (floor (- delta (* 3600 h)) 60)))
15691 (setq org-mode-line-string
15692 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
15693 'help-echo "Org-mode clock is running"))
15694 (force-mode-line-update)))
15696 (defvar org-clock-marker (make-marker)
15697 "Marker recording the last clock-in.")
15698 (defvar org-clock-mode-line-entry nil
15699 "Information for the modeline about the running clock.")
15701 (defun org-clock-in ()
15702 "Start the clock on the current item.
15703 If necessary, clock-out of the currently active clock."
15704 (interactive)
15705 (org-clock-out t)
15706 (let (ts)
15707 (save-excursion
15708 (org-back-to-heading t)
15709 (if (looking-at org-todo-line-regexp)
15710 (setq org-clock-heading (match-string 3))
15711 (setq org-clock-heading "???"))
15712 (setq org-clock-heading (propertize org-clock-heading 'face nil))
15713 (beginning-of-line 2)
15714 (while
15715 (or (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15716 (not (equal (match-string 1) org-clock-string)))
15717 (and (looking-at "[ \t]*:PROPERTIES:")
15718 (not org-insert-labeled-timestamps-before-properties-drawer)))
15719 ;; Scheduling info, or properties drawer, move one line further
15720 (beginning-of-line 2)
15721 (or (bolp) (newline)))
15722 (insert "\n") (backward-char 1)
15723 (indent-relative)
15724 (insert org-clock-string " ")
15725 (setq org-clock-start-time (current-time))
15726 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15727 (move-marker org-clock-marker (point) (buffer-base-buffer))
15728 (or global-mode-string (setq global-mode-string '("")))
15729 (or (memq 'org-mode-line-string global-mode-string)
15730 (setq global-mode-string
15731 (append global-mode-string '(org-mode-line-string))))
15732 (org-update-mode-line)
15733 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
15734 (message "Clock started at %s" ts))))
15736 (defun org-clock-out (&optional fail-quietly)
15737 "Stop the currently running clock.
15738 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
15739 (interactive)
15740 (catch 'exit
15741 (if (not (marker-buffer org-clock-marker))
15742 (if fail-quietly (throw 'exit t) (error "No active clock")))
15743 (let (ts te s h m)
15744 (save-excursion
15745 (set-buffer (marker-buffer org-clock-marker))
15746 (goto-char org-clock-marker)
15747 (beginning-of-line 1)
15748 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15749 (equal (match-string 1) org-clock-string))
15750 (setq ts (match-string 2))
15751 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
15752 (goto-char (match-end 0))
15753 (delete-region (point) (point-at-eol))
15754 (insert "--")
15755 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15756 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
15757 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
15758 h (floor (/ s 3600))
15759 s (- s (* 3600 h))
15760 m (floor (/ s 60))
15761 s (- s (* 60 s)))
15762 (insert " => " (format "%2d:%02d" h m))
15763 (move-marker org-clock-marker nil)
15764 (org-add-log-maybe 'clock-out)
15765 (when org-mode-line-timer
15766 (cancel-timer org-mode-line-timer)
15767 (setq org-mode-line-timer nil))
15768 (setq global-mode-string
15769 (delq 'org-mode-line-string global-mode-string))
15770 (force-mode-line-update)
15771 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
15773 (defun org-clock-cancel ()
15774 "Cancel the running clock be removing the start timestamp."
15775 (interactive)
15776 (if (not (marker-buffer org-clock-marker))
15777 (error "No active clock"))
15778 (save-excursion
15779 (set-buffer (marker-buffer org-clock-marker))
15780 (goto-char org-clock-marker)
15781 (delete-region (1- (point-at-bol)) (point-at-eol)))
15782 (message "Clock canceled"))
15784 (defvar org-clock-file-total-minutes nil
15785 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
15786 (make-variable-buffer-local 'org-clock-file-total-minutes)
15788 (defun org-clock-sum (&optional tstart tend)
15789 "Sum the times for each subtree.
15790 Puts the resulting times in minutes as a text property on each headline."
15791 (interactive)
15792 (let* ((bmp (buffer-modified-p))
15793 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
15794 org-clock-string
15795 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
15796 (lmax 30)
15797 (ltimes (make-vector lmax 0))
15798 (t1 0)
15799 (level 0)
15800 ts te dt
15801 time)
15802 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
15803 (save-excursion
15804 (goto-char (point-max))
15805 (while (re-search-backward re nil t)
15806 (cond
15807 ((match-end 2)
15808 ;; Two time stamps
15809 (setq ts (match-string 2)
15810 te (match-string 3)
15811 ts (time-to-seconds
15812 (apply 'encode-time (org-parse-time-string ts)))
15813 te (time-to-seconds
15814 (apply 'encode-time (org-parse-time-string te)))
15815 ts (if tstart (max ts tstart) ts)
15816 te (if tend (min te tend) te)
15817 dt (- te ts)
15818 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
15819 ((match-end 4)
15820 ;; A naket time
15821 (setq t1 (+ t1 (string-to-number (match-string 5))
15822 (* 60 (string-to-number (match-string 4))))))
15823 (t ;; A headline
15824 (setq level (- (match-end 1) (match-beginning 1)))
15825 (when (or (> t1 0) (> (aref ltimes level) 0))
15826 (loop for l from 0 to level do
15827 (aset ltimes l (+ (aref ltimes l) t1)))
15828 (setq t1 0 time (aref ltimes level))
15829 (loop for l from level to (1- lmax) do
15830 (aset ltimes l 0))
15831 (goto-char (match-beginning 0))
15832 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
15833 (setq org-clock-file-total-minutes (aref ltimes 0)))
15834 (set-buffer-modified-p bmp)))
15836 (defun org-clock-display (&optional total-only)
15837 "Show subtree times in the entire buffer.
15838 If TOTAL-ONLY is non-nil, only show the total time for the entire file
15839 in the echo area."
15840 (interactive)
15841 (org-remove-clock-overlays)
15842 (let (time h m p)
15843 (org-clock-sum)
15844 (unless total-only
15845 (save-excursion
15846 (goto-char (point-min))
15847 (while (setq p (next-single-property-change (point) :org-clock-minutes))
15848 (goto-char p)
15849 (when (setq time (get-text-property p :org-clock-minutes))
15850 (org-put-clock-overlay time (funcall outline-level))))
15851 (setq h (/ org-clock-file-total-minutes 60)
15852 m (- org-clock-file-total-minutes (* 60 h)))
15853 ;; Arrange to remove the overlays upon next change.
15854 (when org-remove-highlights-with-change
15855 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
15856 nil 'local))))
15857 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
15859 (defvar org-clock-overlays nil)
15860 (make-variable-buffer-local 'org-clock-overlays)
15862 (defun org-put-clock-overlay (time &optional level)
15863 "Put an overlays on the current line, displaying TIME.
15864 If LEVEL is given, prefix time with a corresponding number of stars.
15865 This creates a new overlay and stores it in `org-clock-overlays', so that it
15866 will be easy to remove."
15867 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
15868 (l (if level (org-get-legal-level level 0) 0))
15869 (off 0)
15870 ov tx)
15871 (move-to-column c)
15872 (unless (eolp) (skip-chars-backward "^ \t"))
15873 (skip-chars-backward " \t")
15874 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
15875 tx (concat (buffer-substring (1- (point)) (point))
15876 (make-string (+ off (max 0 (- c (current-column)))) ?.)
15877 (org-add-props (format "%s %2d:%02d%s"
15878 (make-string l ?*) h m
15879 (make-string (- 10 l) ?\ ))
15880 '(face secondary-selection))
15881 ""))
15882 (if (not (featurep 'xemacs))
15883 (org-overlay-put ov 'display tx)
15884 (org-overlay-put ov 'invisible t)
15885 (org-overlay-put ov 'end-glyph (make-glyph tx)))
15886 (push ov org-clock-overlays)))
15888 (defun org-remove-clock-overlays (&optional beg end noremove)
15889 "Remove the occur highlights from the buffer.
15890 BEG and END are ignored. If NOREMOVE is nil, remove this function
15891 from the `before-change-functions' in the current buffer."
15892 (interactive)
15893 (unless org-inhibit-highlight-removal
15894 (mapc 'org-delete-overlay org-clock-overlays)
15895 (setq org-clock-overlays nil)
15896 (unless noremove
15897 (remove-hook 'before-change-functions
15898 'org-remove-clock-overlays 'local))))
15900 (defun org-clock-out-if-current ()
15901 "Clock out if the current entry contains the running clock.
15902 This is used to stop the clock after a TODO entry is marked DONE,
15903 and is only done if the variable `org-clock-out-when-done' is not nil."
15904 (when (and org-clock-out-when-done
15905 (member state org-done-keywords)
15906 (equal (marker-buffer org-clock-marker) (current-buffer))
15907 (< (point) org-clock-marker)
15908 (> (save-excursion (outline-next-heading) (point))
15909 org-clock-marker))
15910 ;; Clock out, but don't accept a logging message for this.
15911 (let ((org-log-done (if (and (listp org-log-done)
15912 (member 'clock-out org-log-done))
15913 '(done)
15914 org-log-done)))
15915 (org-clock-out))))
15917 (add-hook 'org-after-todo-state-change-hook
15918 'org-clock-out-if-current)
15920 (defun org-check-running-clock ()
15921 "Check if the current buffer contains the running clock.
15922 If yes, offer to stop it and to save the buffer with the changes."
15923 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
15924 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
15925 (buffer-name))))
15926 (org-clock-out)
15927 (when (y-or-n-p "Save changed buffer?")
15928 (save-buffer))))
15930 (defun org-clock-report ()
15931 "Create a table containing a report about clocked time.
15932 If the buffer contains lines
15933 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
15935 #+END: clocktable
15936 then the table will be inserted between these lines, replacing whatever
15937 is was there before. If these lines are not in the buffer, the table
15938 is inserted at point, surrounded by the special lines.
15939 The BEGIN line can contain parameters. Allowed are:
15940 :maxlevel The maximum level to be included in the table. Default is 3.
15941 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
15942 (interactive)
15943 (org-remove-clock-overlays)
15944 (unless (org-find-dblock "clocktable")
15945 (org-create-dblock (list :name "clocktable"
15946 :maxlevel 2 :emphasize nil)))
15947 (org-update-dblock))
15949 (defun org-clock-update-time-maybe ()
15950 "If this is a CLOCK line, update it and return t.
15951 Otherwise, return nil."
15952 (interactive)
15953 (save-excursion
15954 (beginning-of-line 1)
15955 (skip-chars-forward " \t")
15956 (when (looking-at org-clock-string)
15957 (let ((re (concat "[ \t]*" org-clock-string
15958 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
15959 "\\([ \t]*=>.*\\)?"))
15960 ts te h m s)
15961 (if (not (looking-at re))
15963 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
15964 (end-of-line 1)
15965 (setq ts (match-string 1)
15966 te (match-string 2))
15967 (setq s (- (time-to-seconds
15968 (apply 'encode-time (org-parse-time-string te)))
15969 (time-to-seconds
15970 (apply 'encode-time (org-parse-time-string ts))))
15971 h (floor (/ s 3600))
15972 s (- s (* 3600 h))
15973 m (floor (/ s 60))
15974 s (- s (* 60 s)))
15975 (insert " => " (format "%2d:%02d" h m))
15976 t)))))
15978 (defun org-clock-special-range (key &optional time as-strings)
15979 "Return two times bordering a special time range.
15980 Key is a symbol specifying the range and can be one of `today', `yesterday',
15981 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
15982 A week starts Monday 0:00 and ends Sunday 24:00.
15983 The range is determined relative to TIME. TIME defaults to the current time.
15984 The return value is a cons cell with two internal times like the ones
15985 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
15986 the returned times will be formatted strings."
15987 (let* ((tm (decode-time (or time (current-time))))
15988 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
15989 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
15990 (dow (nth 6 tm))
15991 s1 m1 h1 d1 month1 y1 diff ts te fm)
15992 (cond
15993 ((eq key 'today)
15994 (setq h 0 m 0 h1 24 m1 0))
15995 ((eq key 'yesterday)
15996 (setq d (1- d) h 0 m 0 h1 24 m1 0))
15997 ((eq key 'thisweek)
15998 (setq diff (if (= dow 0) 6 (1- dow))
15999 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16000 ((eq key 'lastweek)
16001 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16002 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16003 ((eq key 'thismonth)
16004 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16005 ((eq key 'lastmonth)
16006 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16007 ((eq key 'thisyear)
16008 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16009 ((eq key 'lastyear)
16010 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
16011 (t (error "No such time block %s" key)))
16012 (setq ts (encode-time s m h d month y)
16013 te (encode-time (or s1 s) (or m1 m) (or h1 h)
16014 (or d1 d) (or month1 month) (or y1 y)))
16015 (setq fm (cdr org-time-stamp-formats))
16016 (if as-strings
16017 (cons (format-time-string fm ts) (format-time-string fm te))
16018 (cons ts te))))
16020 (defun org-dblock-write:clocktable (params)
16021 "Write the standard clocktable."
16022 (let ((hlchars '((1 . "*") (2 . ?/)))
16023 (emph nil)
16024 (ins (make-marker))
16025 ipos time h m p level hlc hdl maxlevel
16026 ts te cc block)
16027 (setq maxlevel (or (plist-get params :maxlevel) 3)
16028 emph (plist-get params :emphasize)
16029 ts (plist-get params :tstart)
16030 te (plist-get params :tend)
16031 block (plist-get params :block))
16032 (when block
16033 (setq cc (org-clock-special-range block nil t)
16034 ts (car cc) te (cdr cc)))
16035 (if ts (setq ts (time-to-seconds
16036 (apply 'encode-time (org-parse-time-string ts)))))
16037 (if te (setq te (time-to-seconds
16038 (apply 'encode-time (org-parse-time-string te)))))
16039 (move-marker ins (point))
16040 (setq ipos (point))
16041 (insert-before-markers "Clock summary at ["
16042 (substring
16043 (format-time-string (cdr org-time-stamp-formats))
16044 1 -1)
16045 "]."
16046 (if block
16047 (format " Considered range is /%s/." block)
16049 "\n\n|L|Headline|Time|\n")
16050 (org-clock-sum ts te)
16051 (setq h (/ org-clock-file-total-minutes 60)
16052 m (- org-clock-file-total-minutes (* 60 h)))
16053 (insert-before-markers "|-\n|0|" "*Total file time*| "
16054 (format "*%d:%02d*" h m)
16055 "|\n")
16056 (goto-char (point-min))
16057 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16058 (goto-char p)
16059 (when (setq time (get-text-property p :org-clock-minutes))
16060 (save-excursion
16061 (beginning-of-line 1)
16062 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
16063 (setq level (- (match-end 1) (match-beginning 1)))
16064 (<= level maxlevel))
16065 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
16066 hdl (match-string 2)
16067 h (/ time 60)
16068 m (- time (* 60 h)))
16069 (goto-char ins)
16070 (if (= level 1) (insert-before-markers "|-\n"))
16071 (insert-before-markers
16072 "| " (int-to-string level) "|" hlc hdl hlc " |"
16073 (make-string (1- level) ?|)
16075 (format "%d:%02d" h m)
16077 " |\n")))))
16078 (goto-char ins)
16079 (backward-delete-char 1)
16080 (goto-char ipos)
16081 (skip-chars-forward "^|")
16082 (org-table-align)))
16084 ;; FIXME: I don't think anybody uses this, ask David
16085 (defun org-collect-clock-time-entries ()
16086 "Return an internal list with clocking information.
16087 This list has one entry for each CLOCK interval.
16088 FIXME: describe the elements."
16089 (interactive)
16090 (let ((re (concat "^[ \t]*" org-clock-string
16091 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
16092 rtn beg end next cont level title total closedp leafp
16093 clockpos titlepos h m donep)
16094 (save-excursion
16095 (org-clock-sum)
16096 (goto-char (point-min))
16097 (while (re-search-forward re nil t)
16098 (setq clockpos (match-beginning 0)
16099 beg (match-string 1) end (match-string 2)
16100 cont (match-end 0))
16101 (setq beg (apply 'encode-time (org-parse-time-string beg))
16102 end (apply 'encode-time (org-parse-time-string end)))
16103 (org-back-to-heading t)
16104 (setq donep (org-entry-is-done-p))
16105 (setq titlepos (point)
16106 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
16107 h (/ total 60) m (- total (* 60 h))
16108 total (cons h m))
16109 (looking-at "\\(\\*+\\) +\\(.*\\)")
16110 (setq level (- (match-end 1) (match-beginning 1))
16111 title (org-match-string-no-properties 2))
16112 (save-excursion (outline-next-heading) (setq next (point)))
16113 (setq closedp (re-search-forward org-closed-time-regexp next t))
16114 (goto-char next)
16115 (setq leafp (and (looking-at "^\\*+ ")
16116 (<= (- (match-end 0) (point)) level)))
16117 (push (list beg end clockpos closedp donep
16118 total title titlepos level leafp)
16119 rtn)
16120 (goto-char cont)))
16121 (nreverse rtn)))
16123 ;;;; Agenda, and Diary Integration
16125 ;;; Define the Org-agenda-mode
16127 (defvar org-agenda-mode-map (make-sparse-keymap)
16128 "Keymap for `org-agenda-mode'.")
16130 (defvar org-agenda-menu) ; defined later in this file.
16131 (defvar org-agenda-follow-mode nil)
16132 (defvar org-agenda-show-log nil)
16133 (defvar org-agenda-redo-command nil)
16134 (defvar org-agenda-mode-hook nil)
16135 (defvar org-agenda-type nil)
16136 (defvar org-agenda-force-single-file nil)
16138 (defun org-agenda-mode ()
16139 "Mode for time-sorted view on action items in Org-mode files.
16141 The following commands are available:
16143 \\{org-agenda-mode-map}"
16144 (interactive)
16145 (kill-all-local-variables)
16146 (setq org-agenda-undo-list nil
16147 org-agenda-pending-undo-list nil)
16148 (setq major-mode 'org-agenda-mode)
16149 ;; Keep global-font-lock-mode from turning on font-lock-mode
16150 (org-set-local 'font-lock-global-modes (list 'not major-mode))
16151 (setq mode-name "Org-Agenda")
16152 (use-local-map org-agenda-mode-map)
16153 (easy-menu-add org-agenda-menu)
16154 (if org-startup-truncated (setq truncate-lines t))
16155 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
16156 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
16157 ;; Make sure properties are removed when copying text
16158 (when (boundp 'buffer-substring-filters)
16159 (org-set-local 'buffer-substring-filters
16160 (cons (lambda (x)
16161 (set-text-properties 0 (length x) nil x) x)
16162 buffer-substring-filters)))
16163 (unless org-agenda-keep-modes
16164 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
16165 org-agenda-show-log nil))
16166 (easy-menu-change
16167 '("Agenda") "Agenda Files"
16168 (append
16169 (list
16170 (vector
16171 (if (get 'org-agenda-files 'org-restrict)
16172 "Restricted to single file"
16173 "Edit File List")
16174 '(org-edit-agenda-file-list)
16175 (not (get 'org-agenda-files 'org-restrict)))
16176 "--")
16177 (mapcar 'org-file-menu-entry (org-agenda-files))))
16178 (org-agenda-set-mode-name)
16179 (apply
16180 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
16181 (list 'org-agenda-mode-hook)))
16183 (substitute-key-definition 'undo 'org-agenda-undo
16184 org-agenda-mode-map global-map)
16185 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
16186 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
16187 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
16188 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
16189 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
16190 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
16191 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
16192 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
16193 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
16194 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
16195 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
16196 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
16197 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
16198 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
16199 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
16200 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
16201 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
16202 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
16203 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
16204 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
16205 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
16206 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
16207 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
16208 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
16209 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
16210 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
16211 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
16212 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
16213 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
16215 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
16216 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
16217 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
16218 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
16219 (while l (org-defkey org-agenda-mode-map
16220 (int-to-string (pop l)) 'digit-argument)))
16222 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
16223 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
16224 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
16225 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
16226 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
16227 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
16228 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
16229 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
16230 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
16231 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
16232 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
16233 (org-defkey org-agenda-mode-map "n" 'next-line)
16234 (org-defkey org-agenda-mode-map "p" 'previous-line)
16235 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
16236 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
16237 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
16238 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
16239 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
16240 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
16241 (eval-after-load "calendar"
16242 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
16243 'org-calendar-goto-agenda))
16244 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
16245 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
16246 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
16247 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
16248 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
16249 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
16250 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
16251 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
16252 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
16253 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
16254 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
16255 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
16256 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
16257 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
16258 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
16259 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
16260 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
16262 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
16263 "Local keymap for agenda entries from Org-mode.")
16265 (org-defkey org-agenda-keymap
16266 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
16267 (org-defkey org-agenda-keymap
16268 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
16269 (when org-agenda-mouse-1-follows-link
16270 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
16271 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
16272 '("Agenda"
16273 ("Agenda Files")
16274 "--"
16275 ["Show" org-agenda-show t]
16276 ["Go To (other window)" org-agenda-goto t]
16277 ["Go To (this window)" org-agenda-switch-to t]
16278 ["Follow Mode" org-agenda-follow-mode
16279 :style toggle :selected org-agenda-follow-mode :active t]
16280 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
16281 "--"
16282 ["Cycle TODO" org-agenda-todo t]
16283 ["Archive subtree" org-agenda-archive t]
16284 ["Delete subtree" org-agenda-kill t]
16285 "--"
16286 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
16287 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
16288 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
16289 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
16290 "--"
16291 ("Tags and Properties"
16292 ["Show all Tags" org-agenda-show-tags t]
16293 ["Set Tags" org-agenda-set-tags t]
16294 "--"
16295 ["Column View" org-columns t])
16296 ("Date/Schedule"
16297 ["Schedule" org-agenda-schedule t]
16298 ["Set Deadline" org-agenda-deadline t]
16299 "--"
16300 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
16301 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
16302 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
16303 ("Priority"
16304 ["Set Priority" org-agenda-priority t]
16305 ["Increase Priority" org-agenda-priority-up t]
16306 ["Decrease Priority" org-agenda-priority-down t]
16307 ["Show Priority" org-agenda-show-priority t])
16308 ("Calendar/Diary"
16309 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
16310 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
16311 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
16312 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
16313 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
16314 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
16315 "--"
16316 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
16317 "--"
16318 ("View"
16319 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
16320 :style radio :selected (equal org-agenda-ndays 1)]
16321 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
16322 :style radio :selected (equal org-agenda-ndays 7)]
16323 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
16324 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
16325 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
16326 :style radio :selected (member org-agenda-ndays '(365 366))]
16327 "--"
16328 ["Show Logbook entries" org-agenda-log-mode
16329 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
16330 ["Include Diary" org-agenda-toggle-diary
16331 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
16332 ["Use Time Grid" org-agenda-toggle-time-grid
16333 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
16334 ["Write view to file" org-write-agenda t]
16335 ["Rebuild buffer" org-agenda-redo t]
16336 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
16337 "--"
16338 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
16339 "--"
16340 ["Quit" org-agenda-quit t]
16341 ["Exit and Release Buffers" org-agenda-exit t]
16344 ;;; Agenda undo
16346 (defvar org-agenda-allow-remote-undo t
16347 "Non-nil means, allow remote undo from the agenda buffer.")
16348 (defvar org-agenda-undo-list nil
16349 "List of undoable operations in the agenda since last refresh.")
16350 (defvar org-agenda-undo-has-started-in nil
16351 "Buffers that have already seen `undo-start' in the current undo sequence.")
16352 (defvar org-agenda-pending-undo-list nil
16353 "In a series of undo commands, this is the list of remaning undo items.")
16355 (defmacro org-if-unprotected (&rest body)
16356 "Execute BODY if there is no `org-protected' text property at point."
16357 (declare (debug t))
16358 `(unless (get-text-property (point) 'org-protected)
16359 ,@body))
16361 (defmacro org-with-remote-undo (_buffer &rest _body)
16362 "Execute BODY while recording undo information in two buffers."
16363 (declare (indent 1) (debug t))
16364 `(let ((_cline (org-current-line))
16365 (_cmd this-command)
16366 (_buf1 (current-buffer))
16367 (_buf2 ,_buffer)
16368 (_undo1 buffer-undo-list)
16369 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
16370 _c1 _c2)
16371 ,@_body
16372 (when org-agenda-allow-remote-undo
16373 (setq _c1 (org-verify-change-for-undo
16374 _undo1 (with-current-buffer _buf1 buffer-undo-list))
16375 _c2 (org-verify-change-for-undo
16376 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
16377 (when (or _c1 _c2)
16378 ;; make sure there are undo boundaries
16379 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
16380 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
16381 ;; remember which buffer to undo
16382 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
16383 org-agenda-undo-list)))))
16385 (defun org-agenda-undo ()
16386 "Undo a remote editing step in the agenda.
16387 This undoes changes both in the agenda buffer and in the remote buffer
16388 that have been changed along."
16389 (interactive)
16390 (or org-agenda-allow-remote-undo
16391 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
16392 (if (not (eq this-command last-command))
16393 (setq org-agenda-undo-has-started-in nil
16394 org-agenda-pending-undo-list org-agenda-undo-list))
16395 (if (not org-agenda-pending-undo-list)
16396 (error "No further undo information"))
16397 (let* ((entry (pop org-agenda-pending-undo-list))
16398 buf line cmd rembuf)
16399 (setq cmd (pop entry) line (pop entry))
16400 (setq rembuf (nth 2 entry))
16401 (org-with-remote-undo rembuf
16402 (while (bufferp (setq buf (pop entry)))
16403 (if (pop entry)
16404 (with-current-buffer buf
16405 (let ((last-undo-buffer buf)
16406 (inhibit-read-only t))
16407 (unless (memq buf org-agenda-undo-has-started-in)
16408 (push buf org-agenda-undo-has-started-in)
16409 (make-local-variable 'pending-undo-list)
16410 (undo-start))
16411 (while (and pending-undo-list
16412 (listp pending-undo-list)
16413 (not (car pending-undo-list)))
16414 (pop pending-undo-list))
16415 (undo-more 1))))))
16416 (goto-line line)
16417 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
16419 (defun org-verify-change-for-undo (l1 l2)
16420 "Verify that a real change occurred between the undo lists L1 and L2."
16421 (while (and l1 (listp l1) (null (car l1))) (pop l1))
16422 (while (and l2 (listp l2) (null (car l2))) (pop l2))
16423 (not (eq l1 l2)))
16425 ;;; Agenda dispatch
16427 (defvar org-agenda-restrict nil)
16428 (defvar org-agenda-restrict-begin (make-marker))
16429 (defvar org-agenda-restrict-end (make-marker))
16430 (defvar org-agenda-last-dispatch-buffer nil)
16432 ;;;###autoload
16433 (defun org-agenda (arg)
16434 "Dispatch agenda commands to collect entries to the agenda buffer.
16435 Prompts for a character to select a command. Any prefix arg will be passed
16436 on to the selected command. The default selections are:
16438 a Call `org-agenda-list' to display the agenda for current day or week.
16439 t Call `org-todo-list' to display the global todo list.
16440 T Call `org-todo-list' to display the global todo list, select only
16441 entries with a specific TODO keyword (the user gets a prompt).
16442 m Call `org-tags-view' to display headlines with tags matching
16443 a condition (the user is prompted for the condition).
16444 M Like `m', but select only TODO entries, no ordinary headlines.
16445 L Create a timeline for the current buffer.
16446 e Export views to associated files.
16448 More commands can be added by configuring the variable
16449 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
16450 searches can be pre-defined in this way.
16452 If the current buffer is in Org-mode and visiting a file, you can also
16453 first press `1' to indicate that the agenda should be temporarily (until the
16454 next use of \\[org-agenda]) restricted to the current file."
16455 (interactive "P")
16456 (catch 'exit
16457 (let* ((buf (current-buffer))
16458 (bfn (buffer-file-name (buffer-base-buffer)))
16459 (restrict-ok (and bfn (org-mode-p)))
16460 (custom org-agenda-custom-commands)
16461 c entry key type match lprops)
16462 ;; Turn off restriction
16463 (put 'org-agenda-files 'org-restrict nil)
16464 (setq org-agenda-restrict nil)
16465 (move-marker org-agenda-restrict-begin nil)
16466 (move-marker org-agenda-restrict-end nil)
16467 ;; Delete old local properties
16468 (put 'org-agenda-redo-command 'org-lprops nil)
16469 ;; Remember where this call originated
16470 (setq org-agenda-last-dispatch-buffer (current-buffer))
16471 (save-window-excursion
16472 (delete-other-windows)
16473 (switch-to-buffer-other-window " *Agenda Commands*")
16474 (erase-buffer)
16475 (insert (eval-when-compile
16476 (let ((header
16477 "Press key for an agenda command:
16478 -------------------------------- C Configure custom agenda commands
16479 a Agenda for current week or day e Export agenda views
16480 t List of all TODO entries T Entries with special TODO kwd
16481 m Match a TAGS query M Like m, but only TODO entries
16482 L Timeline for current buffer # List stuck projects (!=configure)
16484 (start 0))
16485 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
16486 (setq start (match-end 0))
16487 (add-text-properties (match-beginning 2) (match-end 2)
16488 '(face bold) header))
16489 header)))
16490 (while (setq entry (pop custom))
16491 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
16492 (insert (format "\n%-4s%-14s: %s"
16493 (org-add-props (copy-sequence key)
16494 '(face bold))
16495 (cond
16496 ((stringp type) type)
16497 ((eq type 'agenda) "Agenda for current week or day")
16498 ((eq type 'alltodo) "List of all TODO entries")
16499 ((eq type 'stuck) "List of stuck projects")
16500 ((eq type 'todo) "TODO keyword")
16501 ((eq type 'tags) "Tags query")
16502 ((eq type 'tags-todo) "Tags (TODO)")
16503 ((eq type 'tags-tree) "Tags tree")
16504 ((eq type 'todo-tree) "TODO kwd tree")
16505 ((eq type 'occur-tree) "Occur tree")
16506 ((functionp type) (symbol-name type))
16507 (t "???"))
16508 (if (stringp match)
16509 (org-add-props match nil 'face 'org-warning)
16510 (format "set of %d commands" (length match))))))
16511 (if restrict-ok
16512 (insert "\n"
16513 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
16514 (goto-char (point-min))
16515 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
16516 (message "Press key for agenda command%s"
16517 (if restrict-ok ", or [1] or [0] to restrict" ""))
16518 (setq c (read-char-exclusive))
16519 (message "")
16520 (when (memq c '(?L ?1 ?0))
16521 (if restrict-ok
16522 (put 'org-agenda-files 'org-restrict (list bfn))
16523 (error "Cannot restrict agenda to current buffer"))
16524 (with-current-buffer " *Agenda Commands*"
16525 (goto-char (point-max))
16526 (delete-region (point-at-bol) (point))
16527 (goto-char (point-min)))
16528 (when (eq c ?0)
16529 (setq org-agenda-restrict t)
16530 (with-current-buffer buf
16531 (if (org-region-active-p)
16532 (progn
16533 (move-marker org-agenda-restrict-begin (region-beginning))
16534 (move-marker org-agenda-restrict-end (region-end)))
16535 (save-excursion
16536 (org-back-to-heading t)
16537 (move-marker org-agenda-restrict-begin (point))
16538 (move-marker org-agenda-restrict-end
16539 (progn (org-end-of-subtree t)))))))
16540 (unless (eq c ?L)
16541 (message "Press key for agenda command%s"
16542 (if restrict-ok " (restricted to current file)" ""))
16543 (setq c (read-char-exclusive)))
16544 (message "")))
16545 (require 'calendar) ; FIXME: can we avoid this for some commands?
16546 ;; For example the todo list should not need it (but does...)
16547 (cond
16548 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
16549 (if (symbolp (nth 1 entry))
16550 (progn
16551 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
16552 lprops (nth 3 entry))
16553 (put 'org-agenda-redo-command 'org-lprops lprops)
16554 (cond
16555 ((eq type 'agenda)
16556 (org-let lprops '(org-agenda-list current-prefix-arg)))
16557 ((eq type 'alltodo)
16558 (org-let lprops '(org-todo-list current-prefix-arg)))
16559 ((eq type 'stuck)
16560 (org-let lprops '(org-agenda-list-stuck-projects
16561 current-prefix-arg)))
16562 ((eq type 'tags)
16563 (org-let lprops '(org-tags-view current-prefix-arg match)))
16564 ((eq type 'tags-todo)
16565 (org-let lprops '(org-tags-view '(4) match)))
16566 ((eq type 'todo)
16567 (org-let lprops '(org-todo-list match)))
16568 ((eq type 'tags-tree)
16569 (org-check-for-org-mode)
16570 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
16571 ((eq type 'todo-tree)
16572 (org-check-for-org-mode)
16573 (org-let lprops
16574 '(org-occur (concat "^" outline-regexp "[ \t]*"
16575 (regexp-quote match) "\\>"))))
16576 ((eq type 'occur-tree)
16577 (org-check-for-org-mode)
16578 (org-let lprops '(org-occur match)))
16579 ((fboundp type)
16580 (org-let lprops '(funcall type match)))
16581 (t (error "Invalid custom agenda command type %s" type))))
16582 (org-run-agenda-series (nth 1 entry) (cddr entry))))
16583 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
16584 ((equal c ?a) (call-interactively 'org-agenda-list))
16585 ((equal c ?t) (call-interactively 'org-todo-list))
16586 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
16587 ((equal c ?m) (call-interactively 'org-tags-view))
16588 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
16589 ((equal c ?e) (call-interactively 'org-store-agenda-views))
16590 ((equal c ?L)
16591 (unless restrict-ok
16592 (error "This is not an Org-mode file"))
16593 (org-call-with-arg 'org-timeline arg))
16594 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
16595 ((equal c ?!) (customize-variable 'org-stuck-projects))
16596 (t (error "Invalid key"))))))
16598 (defun org-run-agenda-series (name series)
16599 (org-prepare-agenda name)
16600 (let* ((org-agenda-multi t)
16601 (redo (list 'org-run-agenda-series name (list 'quote series)))
16602 (cmds (car series))
16603 (gprops (nth 1 series))
16604 match ;; The byte compiler incorrectly complains about this. Keep it!
16605 cmd type lprops)
16606 (while (setq cmd (pop cmds))
16607 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
16608 (cond
16609 ((eq type 'agenda)
16610 (org-let2 gprops lprops
16611 '(call-interactively 'org-agenda-list)))
16612 ((eq type 'alltodo)
16613 (org-let2 gprops lprops
16614 '(call-interactively 'org-todo-list)))
16615 ((eq type 'stuck)
16616 (org-let2 gprops lprops
16617 '(call-interactively 'org-agenda-list-stuck-projects)))
16618 ((eq type 'tags)
16619 (org-let2 gprops lprops
16620 '(org-tags-view current-prefix-arg match)))
16621 ((eq type 'tags-todo)
16622 (org-let2 gprops lprops
16623 '(org-tags-view '(4) match)))
16624 ((eq type 'todo)
16625 (org-let2 gprops lprops
16626 '(org-todo-list match)))
16627 ((fboundp type)
16628 (org-let2 gprops lprops
16629 '(funcall type match)))
16630 (t (error "Invalid type in command series"))))
16631 (widen)
16632 (setq org-agenda-redo-command redo)
16633 (goto-char (point-min)))
16634 (org-finalize-agenda))
16636 ;;;###autoload
16637 (defmacro org-batch-agenda (cmd-key &rest parameters)
16638 "Run an agenda command in batch mode and send the result to STDOUT.
16639 If CMD-KEY is a string of length 1, it is used as a key in
16640 `org-agenda-custom-commands' and triggers this command. If it is a
16641 longer string is is used as a tags/todo match string.
16642 Paramters are alternating variable names and values that will be bound
16643 before running the agenda command."
16644 (let (pars)
16645 (while parameters
16646 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16647 (if (> (length cmd-key) 1)
16648 (eval (list 'let (nreverse pars)
16649 (list 'org-tags-view nil cmd-key)))
16650 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16651 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16652 (set-buffer "*Org Agenda*")
16653 (princ (org-encode-for-stdout (buffer-string)))))
16655 (defun org-encode-for-stdout (string)
16656 (if (fboundp 'encode-coding-string)
16657 (encode-coding-string string buffer-file-coding-system)
16658 string))
16660 (defvar org-agenda-info nil)
16662 ;;;###autoload
16663 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
16664 "Run an agenda command in batch mode and send the result to STDOUT.
16665 If CMD-KEY is a string of length 1, it is used as a key in
16666 `org-agenda-custom-commands' and triggers this command. If it is a
16667 longer string is is used as a tags/todo match string.
16668 Paramters are alternating variable names and values that will be bound
16669 before running the agenda command.
16671 The output gives a line for each selected agenda item. Each
16672 item is a list of comma-separated values, like this:
16674 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
16676 category The category of the item
16677 head The headline, without TODO kwd, TAGS and PRIORITY
16678 type The type of the agenda entry, can be
16679 todo selected in TODO match
16680 tagsmatch selected in tags match
16681 diary imported from diary
16682 deadline a deadline on given date
16683 scheduled scheduled on given date
16684 timestamp entry has timestamp on given date
16685 closed entry was closed on given date
16686 upcoming-deadline warning about deadline
16687 past-scheduled forwarded scheduled item
16688 block entry has date block including g. date
16689 todo The todo keyword, if any
16690 tags All tags including inherited ones, separated by colons
16691 date The relevant date, like 2007-2-14
16692 time The time, like 15:00-16:50
16693 extra Sting with extra planning info
16694 priority-l The priority letter if any was given
16695 priority-n The computed numerical priority
16696 agenda-day The day in the agenda where this is listed"
16698 (let (pars)
16699 (while parameters
16700 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16701 (push (list 'org-agenda-remove-tags t) pars)
16702 (if (> (length cmd-key) 1)
16703 (eval (list 'let (nreverse pars)
16704 (list 'org-tags-view nil cmd-key)))
16705 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16706 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16707 (set-buffer "*Org Agenda*")
16708 (let* ((lines (org-split-string (buffer-string) "\n"))
16709 line)
16710 (while (setq line (pop lines))
16711 (catch 'next
16712 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
16713 (setq org-agenda-info
16714 (org-fix-agenda-info (text-properties-at 0 line)))
16715 (princ
16716 (org-encode-for-stdout
16717 (mapconcat 'org-agenda-export-csv-mapper
16718 '(org-category txt type todo tags date time-of-day extra
16719 priority-letter priority agenda-day)
16720 ",")))
16721 (princ "\n"))))))
16723 (defun org-fix-agenda-info (props)
16724 "FIXME"
16725 (let (tmp re)
16726 (when (setq tmp (plist-get props 'tags))
16727 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
16728 (when (setq tmp (plist-get props 'date))
16729 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16730 (let ((calendar-date-display-form '(year "-" month "-" day)))
16731 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
16733 (setq tmp (calendar-date-string tmp)))
16734 (setq props (plist-put props 'date tmp)))
16735 (when (setq tmp (plist-get props 'day))
16736 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16737 (let ((calendar-date-display-form '(year "-" month "-" day)))
16738 (setq tmp (calendar-date-string tmp)))
16739 (setq props (plist-put props 'day tmp))
16740 (setq props (plist-put props 'agenda-day tmp)))
16741 (when (setq tmp (plist-get props 'txt))
16742 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
16743 (plist-put props 'priority-letter (match-string 1 tmp))
16744 (setq tmp (replace-match "" t t tmp)))
16745 (when (and (setq re (plist-get props 'org-todo-regexp))
16746 (setq re (concat "\\`\\.*" re " ?"))
16747 (string-match re tmp))
16748 (plist-put props 'todo (match-string 1 tmp))
16749 (setq tmp (replace-match "" t t tmp)))
16750 (plist-put props 'txt tmp)))
16751 props)
16753 (defun org-agenda-export-csv-mapper (prop)
16754 (let ((res (plist-get org-agenda-info prop)))
16755 (setq res
16756 (cond
16757 ((not res) "")
16758 ((stringp res) res)
16759 (t (prin1-to-string res))))
16760 (while (string-match "," res)
16761 (setq res (replace-match ";" t t res)))
16762 (org-trim res)))
16765 ;;;###autoload
16766 (defun org-store-agenda-views (&rest parameters)
16767 (interactive)
16768 (eval (list 'org-batch-store-agenda-views)))
16770 (defvar org-agenda-buffer-name)
16772 ;; FIXME, why is this a macro?????
16773 ;;;###autoload
16774 (defmacro org-batch-store-agenda-views (&rest parameters)
16775 "Run all custom agenda commands that have a file argument."
16776 (let ((cmds org-agenda-custom-commands)
16777 (dir default-directory)
16778 pars cmd thiscmdkey files opts)
16779 (while parameters
16780 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16781 (setq pars (reverse pars))
16782 (save-window-excursion
16783 (while cmds
16784 (setq cmd (pop cmds)
16785 thiscmdkey (car cmd)
16786 opts (nth 3 cmd)
16787 files (org-last cmd))
16788 (if (stringp files) (setq files (list files)))
16789 (when files
16790 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
16791 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16792 '(org-agenda nil))))
16793 (set-buffer "*Org Agenda*")
16794 (while files
16795 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16796 (list 'org-write-agenda
16797 (expand-file-name (pop files) dir) t)))))
16798 (kill-buffer org-agenda-buffer-name)))))
16800 (defun org-write-agenda (file &optional nosettings)
16801 "Write the current buffer (an agenda view) as a file.
16802 Depending on the extension of the file name, plain text (.txt),
16803 HTML (.html or .htm) or Postscript (.ps) is produced.
16804 If NOSETTINGS is given, do not scope the settings of
16805 `org-agenda-exporter-settings' into the export commands. This is used when
16806 the settings have already been scoped and we do not wish to overrule other,
16807 higher priority settings."
16808 (interactive "FWrite agenda to file: ")
16809 (if (not (file-writable-p file))
16810 (error "Cannot write agenda to file %s" file))
16811 (cond
16812 ((string-match "\\.html?\\'" file) (require 'htmlize))
16813 ((string-match "\\.ps\\'" file) (require 'ps-print)))
16814 (org-let (if nosettings nil org-agenda-exporter-settings)
16815 '(save-excursion
16816 (save-window-excursion
16817 (cond
16818 ((string-match "\\.html?\\'" file)
16819 (set-buffer (htmlize-buffer (current-buffer)))
16821 (when (and org-agenda-export-html-style
16822 (string-match "<style>" org-agenda-export-html-style))
16823 ;; replace <style> section with org-agenda-export-html-style
16824 (goto-char (point-min))
16825 (kill-region (- (search-forward "<style") 6)
16826 (search-forward "</style>"))
16827 (insert org-agenda-export-html-style))
16828 (write-file file)
16829 (kill-buffer (current-buffer))
16830 (message "HTML written to %s" file))
16831 ((string-match "\\.ps\\'" file)
16832 (ps-print-buffer-with-faces file)
16833 (message "Postscript written to %s" file))
16835 (let ((bs (buffer-string)))
16836 (find-file file)
16837 (insert bs)
16838 (save-buffer 0)
16839 (kill-buffer (current-buffer))
16840 (message "Plain text written to %s" file))))))
16841 (set-buffer org-agenda-buffer-name)))
16843 (defmacro org-no-read-only (&rest body)
16844 "Inhibit read-only for BODY."
16845 `(let ((inhibit-read-only t)) ,@body))
16847 (defun org-check-for-org-mode ()
16848 "Make sure current buffer is in org-mode. Error if not."
16849 (or (org-mode-p)
16850 (error "Cannot execute org-mode agenda command on buffer in %s."
16851 major-mode)))
16853 (defun org-fit-agenda-window ()
16854 "Fit the window to the buffer size."
16855 (and (memq org-agenda-window-setup '(reorganize-frame))
16856 (fboundp 'fit-window-to-buffer)
16857 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
16858 (/ (frame-height) 2))))
16860 ;;; Agenda file list
16862 (defun org-agenda-files (&optional unrestricted)
16863 "Get the list of agenda files.
16864 Optional UNRESTRICTED means return the full list even if a restriction
16865 is currently in place."
16866 (cond
16867 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16868 ((stringp org-agenda-files) (org-read-agenda-file-list))
16869 ((listp org-agenda-files) org-agenda-files)
16870 (t (error "Invalid value of `org-agenda-files'"))))
16872 (defun org-edit-agenda-file-list ()
16873 "Edit the list of agenda files.
16874 Depending on setup, this either uses customize to edit the variable
16875 `org-agenda-files', or it visits the file that is holding the list. In the
16876 latter case, the buffer is set up in a way that saving it automatically kills
16877 the buffer and restores the previous window configuration."
16878 (interactive)
16879 (if (stringp org-agenda-files)
16880 (let ((cw (current-window-configuration)))
16881 (find-file org-agenda-files)
16882 (org-set-local 'org-window-configuration cw)
16883 (org-add-hook 'after-save-hook
16884 (lambda ()
16885 (set-window-configuration
16886 (prog1 org-window-configuration
16887 (kill-buffer (current-buffer))))
16888 (org-install-agenda-files-menu)
16889 (message "New agenda file list installed"))
16890 nil 'local)
16891 (message (substitute-command-keys
16892 "Edit list and finish with \\[save-buffer]")))
16893 (customize-variable 'org-agenda-files)))
16895 (defun org-store-new-agenda-file-list (list)
16896 "Set new value for the agenda file list and save it correcly."
16897 (if (stringp org-agenda-files)
16898 (let ((f org-agenda-files) b)
16899 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
16900 (with-temp-file f
16901 (insert (mapconcat 'identity list "\n") "\n")))
16902 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
16903 (setq org-agenda-files list)
16904 (customize-save-variable 'org-agenda-files org-agenda-files))))
16906 (defun org-read-agenda-file-list ()
16907 "Read the list of agenda files from a file."
16908 (when (stringp org-agenda-files)
16909 (with-temp-buffer
16910 (insert-file-contents org-agenda-files)
16911 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
16914 ;;;###autoload
16915 (defun org-cycle-agenda-files ()
16916 "Cycle through the files in `org-agenda-files'.
16917 If the current buffer visits an agenda file, find the next one in the list.
16918 If the current buffer does not, find the first agenda file."
16919 (interactive)
16920 (let* ((fs (org-agenda-files t))
16921 (files (append fs (list (car fs))))
16922 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16923 file)
16924 (unless files (error "No agenda files"))
16925 (catch 'exit
16926 (while (setq file (pop files))
16927 (if (equal (file-truename file) tcf)
16928 (when (car files)
16929 (find-file (car files))
16930 (throw 'exit t))))
16931 (find-file (car fs)))
16932 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
16934 (defun org-agenda-file-to-front (&optional to-end)
16935 "Move/add the current file to the top of the agenda file list.
16936 If the file is not present in the list, it is added to the front. If it is
16937 present, it is moved there. With optional argument TO-END, add/move to the
16938 end of the list."
16939 (interactive "P")
16940 (let ((file-alist (mapcar (lambda (x)
16941 (cons (file-truename x) x))
16942 (org-agenda-files t)))
16943 (ctf (file-truename buffer-file-name))
16944 x had)
16945 (setq x (assoc ctf file-alist) had x)
16947 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16948 (if to-end
16949 (setq file-alist (append (delq x file-alist) (list x)))
16950 (setq file-alist (cons x (delq x file-alist))))
16951 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16952 (org-install-agenda-files-menu)
16953 (message "File %s to %s of agenda file list"
16954 (if had "moved" "added") (if to-end "end" "front"))))
16956 (defun org-remove-file (&optional file)
16957 "Remove current file from the list of files in variable `org-agenda-files'.
16958 These are the files which are being checked for agenda entries.
16959 Optional argument FILE means, use this file instead of the current."
16960 (interactive)
16961 (let* ((file (or file buffer-file-name))
16962 (true-file (file-truename file))
16963 (afile (abbreviate-file-name file))
16964 (files (delq nil (mapcar
16965 (lambda (x)
16966 (if (equal true-file
16967 (file-truename x))
16968 nil x))
16969 (org-agenda-files t)))))
16970 (if (not (= (length files) (length (org-agenda-files t))))
16971 (progn
16972 (org-store-new-agenda-file-list files)
16973 (org-install-agenda-files-menu)
16974 (message "Removed file: %s" afile))
16975 (message "File was not in list: %s" afile))))
16977 (defun org-file-menu-entry (file)
16978 (vector file (list 'find-file file) t))
16980 (defun org-check-agenda-file (file)
16981 "Make sure FILE exists. If not, ask user what to do."
16982 (when (not (file-exists-p file))
16983 (message "non-existent file %s. [R]emove from list or [A]bort?"
16984 (abbreviate-file-name file))
16985 (let ((r (downcase (read-char-exclusive))))
16986 (cond
16987 ((equal r ?r)
16988 (org-remove-file file)
16989 (throw 'nextfile t))
16990 (t (error "Abort"))))))
16992 ;;; Agenda prepare and finalize
16994 (defvar org-agenda-multi nil) ; dynammically scoped
16995 (defvar org-agenda-buffer-name "*Org Agenda*")
16996 (defvar org-pre-agenda-window-conf nil)
16997 (defvar org-agenda-name nil)
16998 (defun org-prepare-agenda (&optional name)
16999 (setq org-todo-keywords-for-agenda nil)
17000 (setq org-done-keywords-for-agenda nil)
17001 (if org-agenda-multi
17002 (progn
17003 (setq buffer-read-only nil)
17004 (goto-char (point-max))
17005 (unless (bobp)
17006 (insert "\n" (make-string (window-width) ?=) "\n"))
17007 (narrow-to-region (point) (point-max)))
17008 (org-agenda-maybe-reset-markers 'force)
17009 (org-prepare-agenda-buffers (org-agenda-files))
17010 (setq org-todo-keywords-for-agenda
17011 (org-uniquify org-todo-keywords-for-agenda))
17012 (setq org-done-keywords-for-agenda
17013 (org-uniquify org-done-keywords-for-agenda))
17014 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
17015 (awin (get-buffer-window abuf)))
17016 (cond
17017 ((equal (current-buffer) abuf) nil)
17018 (awin (select-window awin))
17019 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
17020 ((equal org-agenda-window-setup 'current-window)
17021 (switch-to-buffer abuf))
17022 ((equal org-agenda-window-setup 'other-window)
17023 (switch-to-buffer-other-window abuf))
17024 ((equal org-agenda-window-setup 'other-frame)
17025 (switch-to-buffer-other-frame abuf))
17026 ((equal org-agenda-window-setup 'reorganize-frame)
17027 (delete-other-windows)
17028 (switch-to-buffer-other-window abuf))))
17029 (setq buffer-read-only nil)
17030 (erase-buffer)
17031 (org-agenda-mode)
17032 (and name (not org-agenda-name)
17033 (org-set-local 'org-agenda-name name)))
17034 (setq buffer-read-only nil))
17036 (defun org-finalize-agenda ()
17037 "Finishing touch for the agenda buffer, called just before displaying it."
17038 (unless org-agenda-multi
17039 (save-excursion
17040 (let ((inhibit-read-only t))
17041 (goto-char (point-min))
17042 (while (org-activate-bracket-links (point-max))
17043 (add-text-properties (match-beginning 0) (match-end 0)
17044 '(face org-link)))
17045 (org-agenda-align-tags)
17046 (unless org-agenda-with-colors
17047 (remove-text-properties (point-min) (point-max) '(face nil))))
17048 (if (and (boundp 'org-overriding-columns-format)
17049 org-overriding-columns-format)
17050 (org-set-local 'org-overriding-columns-format
17051 org-overriding-columns-format))
17052 (if (and (boundp 'org-agenda-view-columns-initially)
17053 org-agenda-view-columns-initially)
17054 (org-agenda-columns))
17055 (run-hooks 'org-finalize-agenda-hook))))
17057 (defun org-prepare-agenda-buffers (files)
17058 "Create buffers for all agenda files, protect archived trees and comments."
17059 (interactive)
17060 (let ((pa '(:org-archived t))
17061 (pc '(:org-comment t))
17062 (pall '(:org-archived t :org-comment t))
17063 (inhibit-read-only t)
17064 (rea (concat ":" org-archive-tag ":"))
17065 bmp file re)
17066 (save-excursion
17067 (save-restriction
17068 (while (setq file (pop files))
17069 (org-check-agenda-file file)
17070 (set-buffer (org-get-agenda-file-buffer file))
17071 (widen)
17072 (setq bmp (buffer-modified-p))
17073 (setq org-todo-keywords-for-agenda
17074 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17075 (setq org-done-keywords-for-agenda
17076 (append org-done-keywords-for-agenda org-done-keywords))
17077 (save-excursion
17078 (remove-text-properties (point-min) (point-max) pall)
17079 (when org-agenda-skip-archived-trees
17080 (goto-char (point-min))
17081 (while (re-search-forward rea nil t)
17082 (if (org-on-heading-p t)
17083 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17084 (goto-char (point-min))
17085 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
17086 (while (re-search-forward re nil t)
17087 (add-text-properties
17088 (match-beginning 0) (org-end-of-subtree t) pc)))
17089 (set-buffer-modified-p bmp))))))
17091 (defvar org-agenda-skip-function nil
17092 "Function to be called at each match during agenda construction.
17093 If this function returns nil, the current match should not be skipped.
17094 Otherwise, the function must return a position from where the search
17095 should be continued.
17096 This may also be a Lisp form, it will be evaluated.
17097 Never set this variable using `setq' or so, because then it will apply
17098 to all future agenda commands. Instead, bind it with `let' to scope
17099 it dynamically into the agenda-constructing command. A good way to set
17100 it is through options in org-agenda-custom-commands.")
17102 (defun org-agenda-skip ()
17103 "Throw to `:skip' in places that should be skipped.
17104 Also moves point to the end of the skipped region, so that search can
17105 continue from there."
17106 (let ((p (point-at-bol)) to fp)
17107 (and org-agenda-skip-archived-trees
17108 (get-text-property p :org-archived)
17109 (org-end-of-subtree t)
17110 (throw :skip t))
17111 (and (get-text-property p :org-comment)
17112 (org-end-of-subtree t)
17113 (throw :skip t))
17114 (if (equal (char-after p) ?#) (throw :skip t))
17115 (when (and (or (setq fp (functionp org-agenda-skip-function))
17116 (consp org-agenda-skip-function))
17117 (setq to (save-excursion
17118 (save-match-data
17119 (if fp
17120 (funcall org-agenda-skip-function)
17121 (eval org-agenda-skip-function))))))
17122 (goto-char to)
17123 (throw :skip t))))
17125 (defvar org-agenda-markers nil
17126 "List of all currently active markers created by `org-agenda'.")
17127 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
17128 "Creation time of the last agenda marker.")
17130 (defun org-agenda-new-marker (&optional pos)
17131 "Return a new agenda marker.
17132 Org-mode keeps a list of these markers and resets them when they are
17133 no longer in use."
17134 (let ((m (copy-marker (or pos (point)))))
17135 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
17136 (push m org-agenda-markers)
17139 (defun org-agenda-maybe-reset-markers (&optional force)
17140 "Reset markers created by `org-agenda'. But only if they are old enough."
17141 (if (or (and force (not org-agenda-multi))
17142 (> (- (time-to-seconds (current-time))
17143 org-agenda-last-marker-time)
17145 (while org-agenda-markers
17146 (move-marker (pop org-agenda-markers) nil))))
17148 (defvar org-agenda-new-buffers nil
17149 "Buffers created to visit agenda files.")
17151 (defun org-get-agenda-file-buffer (file)
17152 "Get a buffer visiting FILE. If the buffer needs to be created, add
17153 it to the list of buffers which might be released later."
17154 (let ((buf (org-find-base-buffer-visiting file)))
17155 (if buf
17156 buf ; just return it
17157 ;; Make a new buffer and remember it
17158 (setq buf (find-file-noselect file))
17159 (if buf (push buf org-agenda-new-buffers))
17160 buf)))
17162 (defun org-release-buffers (blist)
17163 "Release all buffers in list, asking the user for confirmation when needed.
17164 When a buffer is unmodified, it is just killed. When modified, it is saved
17165 \(if the user agrees) and then killed."
17166 (let (buf file)
17167 (while (setq buf (pop blist))
17168 (setq file (buffer-file-name buf))
17169 (when (and (buffer-modified-p buf)
17170 file
17171 (y-or-n-p (format "Save file %s? " file)))
17172 (with-current-buffer buf (save-buffer)))
17173 (kill-buffer buf))))
17175 (defvar org-category-table nil)
17176 (defun org-get-category-table ()
17177 "Get the table of categories and positions in current buffer."
17178 (let (tbl)
17179 (save-excursion
17180 (save-restriction
17181 (widen)
17182 (goto-char (point-min))
17183 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
17184 nil t)
17185 (push (cons (match-beginning 1)
17186 (org-trim (match-string 1))) tbl))))
17187 tbl))
17189 (defun org-get-category (&optional pos)
17190 "Get the category applying to position POS."
17191 (if (not org-category-table)
17192 (cond
17193 ((null org-category)
17194 (setq org-category
17195 (if buffer-file-name
17196 (file-name-sans-extension
17197 (file-name-nondirectory buffer-file-name))
17198 "???")))
17199 ((symbolp org-category) (symbol-name org-category))
17200 (t org-category))
17201 (let ((tbl org-category-table)
17202 (pos (or pos (point))))
17203 (while (and tbl (> (caar tbl) pos))
17204 (pop tbl))
17205 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
17206 org-category-table))))))
17207 ;;; Agenda timeline
17209 (defun org-timeline (&optional include-all)
17210 "Show a time-sorted view of the entries in the current org file.
17211 Only entries with a time stamp of today or later will be listed. With
17212 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
17213 under the current date.
17214 If the buffer contains an active region, only check the region for
17215 dates."
17216 (interactive "P")
17217 (require 'calendar)
17218 (org-compile-prefix-format 'timeline)
17219 (org-set-sorting-strategy 'timeline)
17220 (let* ((dopast t)
17221 (dotodo include-all)
17222 (doclosed org-agenda-show-log)
17223 (entry buffer-file-name)
17224 (date (calendar-current-date))
17225 (beg (if (org-region-active-p) (region-beginning) (point-min)))
17226 (end (if (org-region-active-p) (region-end) (point-max)))
17227 (day-numbers (org-get-all-dates beg end 'no-ranges
17228 t doclosed ; always include today
17229 org-timeline-show-empty-dates))
17230 (today (time-to-days (current-time)))
17231 (past t)
17232 args
17233 s e rtn d emptyp)
17234 (setq org-agenda-redo-command
17235 (list 'progn
17236 (list 'switch-to-buffer-other-window (current-buffer))
17237 (list 'org-timeline (list 'quote include-all))))
17238 (if (not dopast)
17239 ;; Remove past dates from the list of dates.
17240 (setq day-numbers (delq nil (mapcar (lambda(x)
17241 (if (>= x today) x nil))
17242 day-numbers))))
17243 (org-prepare-agenda (concat "Timeline "
17244 (file-name-nondirectory buffer-file-name)))
17245 (if doclosed (push :closed args))
17246 (push :timestamp args)
17247 (push :sexp args)
17248 (if dotodo (push :todo args))
17249 (while (setq d (pop day-numbers))
17250 (if (and (listp d) (eq (car d) :omitted))
17251 (progn
17252 (setq s (point))
17253 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
17254 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
17255 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
17256 (if (and (>= d today)
17257 dopast
17258 past)
17259 (progn
17260 (setq past nil)
17261 (insert (make-string 79 ?-) "\n")))
17262 (setq date (calendar-gregorian-from-absolute d))
17263 (setq s (point))
17264 (setq rtn (and (not emptyp)
17265 (apply 'org-agenda-get-day-entries
17266 entry date args)))
17267 (if (or rtn (equal d today) org-timeline-show-empty-dates)
17268 (progn
17269 (insert (calendar-day-name date) " "
17270 (number-to-string (extract-calendar-day date)) " "
17271 (calendar-month-name (extract-calendar-month date)) " "
17272 (number-to-string (extract-calendar-year date)) "\n")
17273 ; FIXME: this gives a timezone problem
17274 ; (insert (format-time-string org-agenda-date-format
17275 ; (calendar-time-from-absolute d 0))
17276 ; "\n")
17277 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17278 (put-text-property s (1- (point)) 'org-date-line t)
17279 (if (equal d today)
17280 (put-text-property s (1- (point)) 'org-today t))
17281 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
17282 (put-text-property s (1- (point)) 'day d)))))
17283 (goto-char (point-min))
17284 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
17285 (point-min)))
17286 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
17287 (org-finalize-agenda)
17288 (setq buffer-read-only t)))
17290 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
17291 "Return a list of all relevant day numbers from BEG to END buffer positions.
17292 If NO-RANGES is non-nil, include only the start and end dates of a range,
17293 not every single day in the range. If FORCE-TODAY is non-nil, make
17294 sure that TODAY is included in the list. If INACTIVE is non-nil, also
17295 inactive time stamps (those in square brackets) are included.
17296 When EMPTY is non-nil, also include days without any entries."
17297 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
17298 dates dates1 date day day1 day2 ts1 ts2)
17299 (if force-today
17300 (setq dates (list (time-to-days (current-time)))))
17301 (save-excursion
17302 (goto-char beg)
17303 (while (re-search-forward re end t)
17304 (setq day (time-to-days (org-time-string-to-time
17305 (substring (match-string 1) 0 10))))
17306 (or (memq day dates) (push day dates)))
17307 (unless no-ranges
17308 (goto-char beg)
17309 (while (re-search-forward org-tr-regexp end t)
17310 (setq ts1 (substring (match-string 1) 0 10)
17311 ts2 (substring (match-string 2) 0 10)
17312 day1 (time-to-days (org-time-string-to-time ts1))
17313 day2 (time-to-days (org-time-string-to-time ts2)))
17314 (while (< (setq day1 (1+ day1)) day2)
17315 (or (memq day1 dates) (push day1 dates)))))
17316 (setq dates (sort dates '<))
17317 (when empty
17318 (while (setq day (pop dates))
17319 (setq day2 (car dates))
17320 (push day dates1)
17321 (when (and day2 empty)
17322 (if (or (eq empty t)
17323 (and (numberp empty) (<= (- day2 day) empty)))
17324 (while (< (setq day (1+ day)) day2)
17325 (push (list day) dates1))
17326 (push (cons :omitted (- day2 day)) dates1))))
17327 (setq dates (nreverse dates1)))
17328 dates)))
17330 ;;; Agenda Daily/Weekly
17332 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
17333 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
17334 (defvar org-agenda-last-arguments nil
17335 "The arguments of the previous call to org-agenda")
17336 (defvar org-starting-day nil) ; local variable in the agenda buffer
17337 (defvar org-agenda-span nil) ; local variable in the agenda buffer
17338 (defvar org-include-all-loc nil) ; local variable
17341 ;;;###autoload
17342 (defun org-agenda-list (&optional include-all start-day ndays)
17343 "Produce a weekly view from all files in variable `org-agenda-files'.
17344 The view will be for the current week, but from the overview buffer you
17345 will be able to go to other weeks.
17346 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
17347 also be shown, under the current date.
17348 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
17349 on the days are also shown. See the variable `org-log-done' for how
17350 to turn on logging.
17351 START-DAY defaults to TODAY, or to the most recent match for the weekday
17352 given in `org-agenda-start-on-weekday'.
17353 NDAYS defaults to `org-agenda-ndays'."
17354 (interactive "P")
17355 (setq ndays (or ndays org-agenda-ndays)
17356 start-day (or start-day org-agenda-start-day))
17357 (if org-agenda-overriding-arguments
17358 (setq include-all (car org-agenda-overriding-arguments)
17359 start-day (nth 1 org-agenda-overriding-arguments)
17360 ndays (nth 2 org-agenda-overriding-arguments)))
17361 (if (stringp start-day)
17362 ;; Convert to an absolute day number
17363 (setq start-day (time-to-days (org-read-date nil t start-day))))
17364 (setq org-agenda-last-arguments (list include-all start-day ndays))
17365 (org-compile-prefix-format 'agenda)
17366 (org-set-sorting-strategy 'agenda)
17367 (require 'calendar)
17368 (let* ((org-agenda-start-on-weekday
17369 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
17370 org-agenda-start-on-weekday nil))
17371 (thefiles (org-agenda-files))
17372 (files thefiles)
17373 (today (time-to-days (current-time)))
17374 (sd (or start-day today))
17375 (start (if (or (null org-agenda-start-on-weekday)
17376 (< org-agenda-ndays 7))
17378 (let* ((nt (calendar-day-of-week
17379 (calendar-gregorian-from-absolute sd)))
17380 (n1 org-agenda-start-on-weekday)
17381 (d (- nt n1)))
17382 (- sd (+ (if (< d 0) 7 0) d)))))
17383 (day-numbers (list start))
17384 (inhibit-redisplay (not debug-on-error))
17385 s e rtn rtnall file date d start-pos end-pos todayp nd)
17386 (setq org-agenda-redo-command
17387 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
17388 ;; Make the list of days
17389 (setq ndays (or ndays org-agenda-ndays)
17390 nd ndays)
17391 (while (> ndays 1)
17392 (push (1+ (car day-numbers)) day-numbers)
17393 (setq ndays (1- ndays)))
17394 (setq day-numbers (nreverse day-numbers))
17395 (org-prepare-agenda "Day/Week")
17396 (org-set-local 'org-starting-day (car day-numbers))
17397 (org-set-local 'org-include-all-loc include-all)
17398 (org-set-local 'org-agenda-span
17399 (org-agenda-ndays-to-span nd))
17400 (when (and (or include-all org-agenda-include-all-todo)
17401 (member today day-numbers))
17402 (setq files thefiles
17403 rtnall nil)
17404 (while (setq file (pop files))
17405 (catch 'nextfile
17406 (org-check-agenda-file file)
17407 (setq date (calendar-gregorian-from-absolute today)
17408 rtn (org-agenda-get-day-entries
17409 file date :todo))
17410 (setq rtnall (append rtnall rtn))))
17411 (when rtnall
17412 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
17413 (add-text-properties (point-min) (1- (point))
17414 (list 'face 'org-agenda-structure))
17415 (insert (org-finalize-agenda-entries rtnall) "\n")))
17416 (setq s (point))
17417 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
17418 "-agenda:\n")
17419 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
17420 'org-date-line t))
17421 (while (setq d (pop day-numbers))
17422 (setq date (calendar-gregorian-from-absolute d)
17423 s (point))
17424 (if (or (setq todayp (= d today))
17425 (and (not start-pos) (= d sd)))
17426 (setq start-pos (point))
17427 (if (and start-pos (not end-pos))
17428 (setq end-pos (point))))
17429 (setq files thefiles
17430 rtnall nil)
17431 (while (setq file (pop files))
17432 (catch 'nextfile
17433 (org-check-agenda-file file)
17434 (if org-agenda-show-log
17435 (setq rtn (org-agenda-get-day-entries
17436 file date
17437 :deadline :scheduled :timestamp :sexp :closed))
17438 (setq rtn (org-agenda-get-day-entries
17439 file date
17440 :deadline :scheduled :sexp :timestamp)))
17441 (setq rtnall (append rtnall rtn))))
17442 (if org-agenda-include-diary
17443 (progn
17444 (require 'diary-lib)
17445 (setq rtn (org-get-entries-from-diary date))
17446 (setq rtnall (append rtnall rtn))))
17447 (if (or rtnall org-agenda-show-all-dates)
17448 (progn
17449 (insert (format "%-9s %2d %s %4d\n"
17450 (calendar-day-name date)
17451 (extract-calendar-day date)
17452 (calendar-month-name (extract-calendar-month date))
17453 (extract-calendar-year date)))
17454 ; FIXME: this gives a timezone problem
17455 ; (insert (format-time-string org-agenda-date-format
17456 ; (calendar-time-from-absolute d 0)) "\n")
17457 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17458 (put-text-property s (1- (point)) 'org-date-line t)
17459 (if todayp (put-text-property s (1- (point)) 'org-today t))
17460 (if rtnall (insert
17461 (org-finalize-agenda-entries
17462 (org-agenda-add-time-grid-maybe
17463 rtnall nd todayp))
17464 "\n"))
17465 (put-text-property s (1- (point)) 'day d))))
17466 (goto-char (point-min))
17467 (org-fit-agenda-window)
17468 (unless (and (pos-visible-in-window-p (point-min))
17469 (pos-visible-in-window-p (point-max)))
17470 (goto-char (1- (point-max)))
17471 (recenter -1)
17472 (if (not (pos-visible-in-window-p (or start-pos 1)))
17473 (progn
17474 (goto-char (or start-pos 1))
17475 (recenter 1))))
17476 (goto-char (or start-pos 1))
17477 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
17478 (org-finalize-agenda)
17479 (setq buffer-read-only t)
17480 (message "")))
17482 (defun org-agenda-ndays-to-span (n)
17483 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
17485 ;;; Agenda TODO list
17487 (defvar org-select-this-todo-keyword nil)
17488 (defvar org-last-arg nil)
17490 ;;;###autoload
17491 (defun org-todo-list (arg)
17492 "Show all TODO entries from all agenda file in a single list.
17493 The prefix arg can be used to select a specific TODO keyword and limit
17494 the list to these. When using \\[universal-argument], you will be prompted
17495 for a keyword. A numeric prefix directly selects the Nth keyword in
17496 `org-todo-keywords-1'."
17497 (interactive "P")
17498 (require 'calendar)
17499 (org-compile-prefix-format 'todo)
17500 (org-set-sorting-strategy 'todo)
17501 (org-prepare-agenda "TODO")
17502 (let* ((today (time-to-days (current-time)))
17503 (date (calendar-gregorian-from-absolute today))
17504 (kwds org-todo-keywords-for-agenda)
17505 (completion-ignore-case t)
17506 (org-select-this-todo-keyword
17507 (if (stringp arg) arg
17508 (and arg (integerp arg) (> arg 0)
17509 (nth (1- arg) kwds))))
17510 rtn rtnall files file pos)
17511 (when (equal arg '(4))
17512 (setq org-select-this-todo-keyword
17513 (completing-read "Keyword (or KWD1|K2D2|...): "
17514 (mapcar 'list kwds) nil nil)))
17515 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
17516 (org-set-local 'org-last-arg arg)
17517 (setq org-agenda-redo-command
17518 '(org-todo-list (or current-prefix-arg org-last-arg)))
17519 (setq files (org-agenda-files)
17520 rtnall nil)
17521 (while (setq file (pop files))
17522 (catch 'nextfile
17523 (org-check-agenda-file file)
17524 (setq rtn (org-agenda-get-day-entries file date :todo))
17525 (setq rtnall (append rtnall rtn))))
17526 (if org-agenda-overriding-header
17527 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17528 nil 'face 'org-agenda-structure) "\n")
17529 (insert "Global list of TODO items of type: ")
17530 (add-text-properties (point-min) (1- (point))
17531 (list 'face 'org-agenda-structure))
17532 (setq pos (point))
17533 (insert (or org-select-this-todo-keyword "ALL") "\n")
17534 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17535 (setq pos (point))
17536 (unless org-agenda-multi
17537 (insert "Available with `N r': (0)ALL")
17538 (let ((n 0) s)
17539 (mapc (lambda (x)
17540 (setq s (format "(%d)%s" (setq n (1+ n)) x))
17541 (if (> (+ (current-column) (string-width s) 1) (frame-width))
17542 (insert "\n "))
17543 (insert " " s))
17544 kwds))
17545 (insert "\n"))
17546 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17547 (when rtnall
17548 (insert (org-finalize-agenda-entries rtnall) "\n"))
17549 (goto-char (point-min))
17550 (org-fit-agenda-window)
17551 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
17552 (org-finalize-agenda)
17553 (setq buffer-read-only t)))
17555 ;;; Agenda tags match
17557 ;;;###autoload
17558 (defun org-tags-view (&optional todo-only match)
17559 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
17560 The prefix arg TODO-ONLY limits the search to TODO entries."
17561 (interactive "P")
17562 (org-compile-prefix-format 'tags)
17563 (org-set-sorting-strategy 'tags)
17564 (let* ((org-tags-match-list-sublevels
17565 (if todo-only t org-tags-match-list-sublevels))
17566 (completion-ignore-case t)
17567 rtn rtnall files file pos matcher
17568 buffer)
17569 (setq matcher (org-make-tags-matcher match)
17570 match (car matcher) matcher (cdr matcher))
17571 (org-prepare-agenda (concat "TAGS " match))
17572 (setq org-agenda-redo-command
17573 (list 'org-tags-view (list 'quote todo-only)
17574 (list 'if 'current-prefix-arg nil match)))
17575 (setq files (org-agenda-files)
17576 rtnall nil)
17577 (while (setq file (pop files))
17578 (catch 'nextfile
17579 (org-check-agenda-file file)
17580 (setq buffer (if (file-exists-p file)
17581 (org-get-agenda-file-buffer file)
17582 (error "No such file %s" file)))
17583 (if (not buffer)
17584 ;; If file does not exist, merror message to agenda
17585 (setq rtn (list
17586 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17587 rtnall (append rtnall rtn))
17588 (with-current-buffer buffer
17589 (unless (org-mode-p)
17590 (error "Agenda file %s is not in `org-mode'" file))
17591 (setq org-category-table (org-get-category-table))
17592 (save-excursion
17593 (save-restriction
17594 (if org-agenda-restrict
17595 (narrow-to-region org-agenda-restrict-begin
17596 org-agenda-restrict-end)
17597 (widen))
17598 (setq rtn (org-scan-tags 'agenda matcher todo-only))
17599 (setq rtnall (append rtnall rtn))))))))
17600 (if org-agenda-overriding-header
17601 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17602 nil 'face 'org-agenda-structure) "\n")
17603 (insert "Headlines with TAGS match: ")
17604 (add-text-properties (point-min) (1- (point))
17605 (list 'face 'org-agenda-structure))
17606 (setq pos (point))
17607 (insert match "\n")
17608 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17609 (setq pos (point))
17610 (unless org-agenda-multi
17611 (insert "Press `C-u r' to search again with new search string\n"))
17612 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17613 (when rtnall
17614 (insert (org-finalize-agenda-entries rtnall) "\n"))
17615 (goto-char (point-min))
17616 (org-fit-agenda-window)
17617 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
17618 (org-finalize-agenda)
17619 (setq buffer-read-only t)))
17621 ;;; Agenda Finding stuck projects
17623 (defvar org-agenda-skip-regexp nil
17624 "Regular expression used in skipping subtrees for the agenda.
17625 This is basically a temporary global variable that can be set and then
17626 used by user-defined selections using `org-agenda-skip-function'.")
17628 (defvar org-agenda-overriding-header nil
17629 "When this is set during todo and tags searches, will replace header.")
17631 (defun org-agenda-skip-subtree-when-regexp-matches ()
17632 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
17633 If yes, it returns the end position of this tree, causing agenda commands
17634 to skip this subtree. This is a function that can be put into
17635 `org-agenda-skip-function' for the duration of a command."
17636 (let ((end (save-excursion (org-end-of-subtree t)))
17637 skip)
17638 (save-excursion
17639 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
17640 (and skip end)))
17642 (defun org-agenda-skip-entry-if (&rest conditions)
17643 "Skip entry is any of CONDITIONS is true.
17644 See `org-agenda-skip-if for details."
17645 (org-agenda-skip-if nil conditions))
17646 (defun org-agenda-skip-subtree-if (&rest conditions)
17647 "Skip entry is any of CONDITIONS is true.
17648 See `org-agenda-skip-if for details."
17649 (org-agenda-skip-if t conditions))
17651 (defun org-agenda-skip-if (subtree conditions)
17652 "Checks current entity for CONDITIONS.
17653 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
17654 the entry, i.e. the text before the next heading is checked.
17656 CONDITIONS is a list of symbols, boolean OR is used to combine the results
17657 from different tests. Valid conditions are:
17659 scheduled Check if there is a scheduled cookie
17660 notscheduled Check if there is no scheduled cookie
17661 deadline Check if there is a deadline
17662 notdeadline Check if there is no deadline
17663 regexp Check if regexp matches
17664 notregexp Check if regexp does not match.
17666 The regexp is taken from the conditions list, it must com right after the
17667 `regexp' of `notregexp' element.
17669 If any of these conditions is met, this function returns the end point of
17670 the entity, causing the search to continue from there. This is a function
17671 that can be put into `org-agenda-skip-function' for the duration of a command."
17672 (let (beg end m r)
17673 (org-back-to-heading t)
17674 (setq beg (point)
17675 end (if subtree
17676 (progn (org-end-of-subtree t) (point))
17677 (progn (outline-next-heading) (1- (point)))))
17678 (goto-char beg)
17679 (and
17681 (and (memq 'scheduled conditions)
17682 (re-search-forward org-scheduled-time-regexp end t))
17683 (and (memq 'notscheduled conditions)
17684 (not (re-search-forward org-scheduled-time-regexp end t)))
17685 (and (memq 'deadline conditions)
17686 (re-search-forward org-deadline-time-regexp end t))
17687 (and (memq 'notdeadline conditions)
17688 (not (re-search-forward org-deadline-time-regexp end t)))
17689 (and (setq m (memq 'regexp conditions))
17690 (stringp (setq r (nth 1 m)))
17691 (re-search-forward m end t))
17692 (and (setq m (memq 'notregexp conditions))
17693 (stringp (setq r (nth 1 m)))
17694 (not (re-search-forward m end t))))
17695 end)))
17697 (defun org-agenda-list-stuck-projects (&rest ignore)
17698 "Create agenda view for projects that are stuck.
17699 Stuck projects are project that have no next actions. For the definitions
17700 of what a project is and how to check if it stuck, customize the variable
17701 `org-stuck-projects'.
17702 MATCH is being ignored."
17703 (interactive)
17704 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
17705 ;; FIXME: we could have used org-agenda-skip-if here.
17706 (org-agenda-overriding-header "List of stuck projects: ")
17707 (matcher (nth 0 org-stuck-projects))
17708 (todo (nth 1 org-stuck-projects))
17709 (todo-wds (if (member "*" todo)
17710 (progn
17711 (org-prepare-agenda-buffers (org-agenda-files))
17712 (org-delete-all
17713 org-done-keywords-for-agenda
17714 (copy-sequence org-todo-keywords-for-agenda)))
17715 todo))
17716 (todo-re (concat "^\\*+[ \t]+\\("
17717 (mapconcat 'identity todo-wds "\\|")
17718 "\\)\\>"))
17719 (tags (nth 2 org-stuck-projects))
17720 (tags-re (if (member "*" tags)
17721 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
17722 (concat "^\\*+ .*:\\("
17723 (mapconcat 'identity tags "\\|")
17724 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
17725 (gen-re (nth 3 org-stuck-projects))
17726 (re-list
17727 (delq nil
17728 (list
17729 (if todo todo-re)
17730 (if tags tags-re)
17731 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
17732 gen-re)))))
17733 (setq org-agenda-skip-regexp
17734 (if re-list
17735 (mapconcat 'identity re-list "\\|")
17736 (error "No information how to identify unstuck projects")))
17737 (org-tags-view nil matcher)
17738 (with-current-buffer org-agenda-buffer-name
17739 (setq org-agenda-redo-command
17740 '(org-agenda-list-stuck-projects
17741 (or current-prefix-arg org-last-arg))))))
17743 ;;; Diary integration
17745 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
17747 (defun org-get-entries-from-diary (date)
17748 "Get the (Emacs Calendar) diary entries for DATE."
17749 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
17750 (diary-display-hook '(fancy-diary-display))
17751 (list-diary-entries-hook
17752 (cons 'org-diary-default-entry list-diary-entries-hook))
17753 (diary-file-name-prefix-function nil) ; turn this feature off
17754 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
17755 entries
17756 (org-disable-agenda-to-diary t))
17757 (save-excursion
17758 (save-window-excursion
17759 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
17760 (if (not (get-buffer fancy-diary-buffer))
17761 (setq entries nil)
17762 (with-current-buffer fancy-diary-buffer
17763 (setq buffer-read-only nil)
17764 (if (zerop (buffer-size))
17765 ;; No entries
17766 (setq entries nil)
17767 ;; Omit the date and other unnecessary stuff
17768 (org-agenda-cleanup-fancy-diary)
17769 ;; Add prefix to each line and extend the text properties
17770 (if (zerop (buffer-size))
17771 (setq entries nil)
17772 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
17773 (set-buffer-modified-p nil)
17774 (kill-buffer fancy-diary-buffer)))
17775 (when entries
17776 (setq entries (org-split-string entries "\n"))
17777 (setq entries
17778 (mapcar
17779 (lambda (x)
17780 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
17781 ;; Extend the text properties to the beginning of the line
17782 (org-add-props x (text-properties-at (1- (length x)) x)
17783 'type "diary" 'date date))
17784 entries)))))
17786 (defun org-agenda-cleanup-fancy-diary ()
17787 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
17788 This gets rid of the date, the underline under the date, and
17789 the dummy entry installed by `org-mode' to ensure non-empty diary for each
17790 date. It also removes lines that contain only whitespace."
17791 (goto-char (point-min))
17792 (if (looking-at ".*?:[ \t]*")
17793 (progn
17794 (replace-match "")
17795 (re-search-forward "\n=+$" nil t)
17796 (replace-match "")
17797 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
17798 (re-search-forward "\n=+$" nil t)
17799 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
17800 (goto-char (point-min))
17801 (while (re-search-forward "^ +\n" nil t)
17802 (replace-match ""))
17803 (goto-char (point-min))
17804 (if (re-search-forward "^Org-mode dummy\n?" nil t)
17805 (replace-match "")))
17807 ;; Make sure entries from the diary have the right text properties.
17808 (eval-after-load "diary-lib"
17809 '(if (boundp 'diary-modify-entry-list-string-function)
17810 ;; We can rely on the hook, nothing to do
17812 ;; Hook not avaiable, must use advice to make this work
17813 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
17814 "Make the position visible."
17815 (if (and org-disable-agenda-to-diary ;; called from org-agenda
17816 (stringp string)
17817 buffer-file-name)
17818 (setq string (org-modify-diary-entry-string string))))))
17820 (defun org-modify-diary-entry-string (string)
17821 "Add text properties to string, allowing org-mode to act on it."
17822 (org-add-props string nil
17823 'mouse-face 'highlight
17824 'keymap org-agenda-keymap
17825 'help-echo (if buffer-file-name
17826 (format "mouse-2 or RET jump to diary file %s"
17827 (abbreviate-file-name buffer-file-name))
17829 'org-agenda-diary-link t
17830 'org-marker (org-agenda-new-marker (point-at-bol))))
17832 (defun org-diary-default-entry ()
17833 "Add a dummy entry to the diary.
17834 Needed to avoid empty dates which mess up holiday display."
17835 ;; Catch the error if dealing with the new add-to-diary-alist
17836 (when org-disable-agenda-to-diary
17837 (condition-case nil
17838 (add-to-diary-list original-date "Org-mode dummy" "")
17839 (error
17840 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
17842 ;;;###autoload
17843 (defun org-diary (&rest args)
17844 "Return diary information from org-files.
17845 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
17846 It accesses org files and extracts information from those files to be
17847 listed in the diary. The function accepts arguments specifying what
17848 items should be listed. The following arguments are allowed:
17850 :timestamp List the headlines of items containing a date stamp or
17851 date range matching the selected date. Deadlines will
17852 also be listed, on the expiration day.
17854 :sexp FIXME
17856 :deadline List any deadlines past due, or due within
17857 `org-deadline-warning-days'. The listing occurs only
17858 in the diary for *today*, not at any other date. If
17859 an entry is marked DONE, it is no longer listed.
17861 :scheduled List all items which are scheduled for the given date.
17862 The diary for *today* also contains items which were
17863 scheduled earlier and are not yet marked DONE.
17865 :todo List all TODO items from the org-file. This may be a
17866 long list - so this is not turned on by default.
17867 Like deadlines, these entries only show up in the
17868 diary for *today*, not at any other date.
17870 The call in the diary file should look like this:
17872 &%%(org-diary) ~/path/to/some/orgfile.org
17874 Use a separate line for each org file to check. Or, if you omit the file name,
17875 all files listed in `org-agenda-files' will be checked automatically:
17877 &%%(org-diary)
17879 If you don't give any arguments (as in the example above), the default
17880 arguments (:deadline :scheduled :timestamp :sexp) are used.
17881 So the example above may also be written as
17883 &%%(org-diary :deadline :timestamp :sexp :scheduled)
17885 The function expects the lisp variables `entry' and `date' to be provided
17886 by the caller, because this is how the calendar works. Don't use this
17887 function from a program - use `org-agenda-get-day-entries' instead."
17888 (org-agenda-maybe-reset-markers)
17889 (org-compile-prefix-format 'agenda)
17890 (org-set-sorting-strategy 'agenda)
17891 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17892 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
17893 (list entry)
17894 (org-agenda-files t)))
17895 file rtn results)
17896 (org-prepare-agenda-buffers files)
17897 ;; If this is called during org-agenda, don't return any entries to
17898 ;; the calendar. Org Agenda will list these entries itself.
17899 (if org-disable-agenda-to-diary (setq files nil))
17900 (while (setq file (pop files))
17901 (setq rtn (apply 'org-agenda-get-day-entries file date args))
17902 (setq results (append results rtn)))
17903 (if results
17904 (concat (org-finalize-agenda-entries results) "\n"))))
17906 ;;; Agenda entry finders
17908 (defun org-agenda-get-day-entries (file date &rest args)
17909 "Does the work for `org-diary' and `org-agenda'.
17910 FILE is the path to a file to be checked for entries. DATE is date like
17911 the one returned by `calendar-current-date'. ARGS are symbols indicating
17912 which kind of entries should be extracted. For details about these, see
17913 the documentation of `org-diary'."
17914 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17915 (let* ((org-startup-folded nil)
17916 (org-startup-align-all-tables nil)
17917 (buffer (if (file-exists-p file)
17918 (org-get-agenda-file-buffer file)
17919 (error "No such file %s" file)))
17920 arg results rtn)
17921 (if (not buffer)
17922 ;; If file does not exist, make sure an error message ends up in diary
17923 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17924 (with-current-buffer buffer
17925 (unless (org-mode-p)
17926 (error "Agenda file %s is not in `org-mode'" file))
17927 (setq org-category-table (org-get-category-table))
17928 (let ((case-fold-search nil))
17929 (save-excursion
17930 (save-restriction
17931 (if org-agenda-restrict
17932 (narrow-to-region org-agenda-restrict-begin
17933 org-agenda-restrict-end)
17934 (widen))
17935 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
17936 (while (setq arg (pop args))
17937 (cond
17938 ((and (eq arg :todo)
17939 (equal date (calendar-current-date)))
17940 (setq rtn (org-agenda-get-todos))
17941 (setq results (append results rtn)))
17942 ((eq arg :timestamp)
17943 (setq rtn (org-agenda-get-blocks))
17944 (setq results (append results rtn))
17945 (setq rtn (org-agenda-get-timestamps))
17946 (setq results (append results rtn)))
17947 ((eq arg :sexp)
17948 (setq rtn (org-agenda-get-sexps))
17949 (setq results (append results rtn)))
17950 ((eq arg :scheduled)
17951 (setq rtn (org-agenda-get-scheduled))
17952 (setq results (append results rtn)))
17953 ((eq arg :closed)
17954 (setq rtn (org-agenda-get-closed))
17955 (setq results (append results rtn)))
17956 ((eq arg :deadline)
17957 (setq rtn (org-agenda-get-deadlines))
17958 (setq results (append results rtn))))))))
17959 results))))
17961 ;; FIXME: this works only if the cursor is not at the
17962 ;; beginning of the entry
17963 (defun org-entry-is-done-p ()
17964 "Is the current entry marked DONE?"
17965 (save-excursion
17966 (and (re-search-backward "[\r\n]\\*+ " nil t)
17967 (looking-at org-nl-done-regexp))))
17969 (defun org-at-date-range-p (&optional inactive-ok)
17970 "Is the cursor inside a date range?"
17971 (interactive)
17972 (save-excursion
17973 (catch 'exit
17974 (let ((pos (point)))
17975 (skip-chars-backward "^[<\r\n")
17976 (skip-chars-backward "<[")
17977 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
17978 (>= (match-end 0) pos)
17979 (throw 'exit t))
17980 (skip-chars-backward "^<[\r\n")
17981 (skip-chars-backward "<[")
17982 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
17983 (>= (match-end 0) pos)
17984 (throw 'exit t)))
17985 nil)))
17987 (defun org-agenda-get-todos ()
17988 "Return the TODO information for agenda display."
17989 (let* ((props (list 'face nil
17990 'done-face 'org-done
17991 'org-not-done-regexp org-not-done-regexp
17992 'org-todo-regexp org-todo-regexp
17993 'mouse-face 'highlight
17994 'keymap org-agenda-keymap
17995 'help-echo
17996 (format "mouse-2 or RET jump to org file %s"
17997 (abbreviate-file-name buffer-file-name))))
17998 ;; FIXME: get rid of the \n at some point but watch out
17999 (regexp (concat "^\\*+[ \t]+\\("
18000 (if org-select-this-todo-keyword
18001 (if (equal org-select-this-todo-keyword "*")
18002 org-todo-regexp
18003 (concat "\\<\\("
18004 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
18005 "\\)\\>"))
18006 org-not-done-regexp)
18007 "[^\n\r]*\\)"))
18008 marker priority category tags
18009 ee txt beg end)
18010 (goto-char (point-min))
18011 (while (re-search-forward regexp nil t)
18012 (catch :skip
18013 (save-match-data
18014 (beginning-of-line)
18015 (setq beg (point) end (progn (outline-next-heading) (point)))
18016 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
18017 (re-search-forward org-scheduled-time-regexp end t))
18018 (and org-agenda-todo-ignore-deadlines (goto-char beg)
18019 (re-search-forward org-deadline-time-regexp end t)
18020 (org-deadline-close (match-string 1))))
18021 (goto-char beg)
18022 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
18023 (throw :skip nil)))
18024 (goto-char beg)
18025 (org-agenda-skip)
18026 (goto-char (match-beginning 1))
18027 (setq marker (org-agenda-new-marker (match-beginning 0))
18028 category (org-get-category)
18029 tags (org-get-tags-at (point))
18030 txt (org-format-agenda-item "" (match-string 1) category tags)
18031 priority (1+ (org-get-priority txt)))
18032 (org-add-props txt props
18033 'org-marker marker 'org-hd-marker marker
18034 'priority priority 'org-category category
18035 'type "todo")
18036 (push txt ee)
18037 (if org-agenda-todo-list-sublevels
18038 (goto-char (match-end 1))
18039 (org-end-of-subtree 'invisible))))
18040 (nreverse ee)))
18042 (defconst org-agenda-no-heading-message
18043 "No heading for this item in buffer or region.")
18045 (defun org-agenda-get-timestamps ()
18046 "Return the date stamp information for agenda display."
18047 (let* ((props (list 'face nil
18048 'org-not-done-regexp org-not-done-regexp
18049 'org-todo-regexp org-todo-regexp
18050 'mouse-face 'highlight
18051 'keymap org-agenda-keymap
18052 'help-echo
18053 (format "mouse-2 or RET jump to org file %s"
18054 (abbreviate-file-name buffer-file-name))))
18055 (d1 (calendar-absolute-from-gregorian date))
18056 (regexp
18057 (concat
18058 (regexp-quote
18059 (substring
18060 (format-time-string
18061 (car org-time-stamp-formats)
18062 (apply 'encode-time ; DATE bound by calendar
18063 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18064 0 11))
18065 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
18066 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
18067 marker hdmarker deadlinep scheduledp donep tmp priority category
18068 ee txt timestr tags b0 b3 e3)
18069 (goto-char (point-min))
18070 (while (re-search-forward regexp nil t)
18071 (setq b0 (match-beginning 0)
18072 b3 (match-beginning 3) e3 (match-end 3))
18073 (catch :skip
18074 (and (org-at-date-range-p) (throw :skip nil))
18075 (org-agenda-skip)
18076 (if (and (match-end 1)
18077 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
18078 (throw :skip nil))
18079 (if (and e3
18080 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
18081 (throw :skip nil))
18082 (setq marker (org-agenda-new-marker b0)
18083 category (org-get-category b0)
18084 tmp (buffer-substring (max (point-min)
18085 (- b0 org-ds-keyword-length))
18087 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
18088 deadlinep (string-match org-deadline-regexp tmp)
18089 scheduledp (string-match org-scheduled-regexp tmp)
18090 donep (org-entry-is-done-p))
18091 (if (or scheduledp deadlinep) (throw :skip t))
18092 (if (string-match ">" timestr)
18093 ;; substring should only run to end of time stamp
18094 (setq timestr (substring timestr 0 (match-end 0))))
18095 (save-excursion
18096 (if (re-search-backward "^\\*+ " nil t)
18097 (progn
18098 (goto-char (match-beginning 0))
18099 (setq hdmarker (org-agenda-new-marker)
18100 tags (org-get-tags-at))
18101 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18102 (setq txt (org-format-agenda-item
18103 nil (match-string 1) category tags timestr)))
18104 (setq txt org-agenda-no-heading-message))
18105 (setq priority (org-get-priority txt))
18106 (org-add-props txt props
18107 'org-marker marker 'org-hd-marker hdmarker)
18108 (org-add-props txt nil 'priority priority
18109 'org-category category 'date date
18110 'type "timestamp")
18111 (push txt ee))
18112 (outline-next-heading)))
18113 (nreverse ee)))
18115 (defun org-agenda-get-sexps ()
18116 "Return the sexp information for agenda display."
18117 (require 'diary-lib)
18118 (let* ((props (list 'face nil
18119 'mouse-face 'highlight
18120 'keymap org-agenda-keymap
18121 'help-echo
18122 (format "mouse-2 or RET jump to org file %s"
18123 (abbreviate-file-name buffer-file-name))))
18124 (regexp "^&?%%(")
18125 marker category ee txt tags entry result beg b sexp sexp-entry)
18126 (goto-char (point-min))
18127 (while (re-search-forward regexp nil t)
18128 (catch :skip
18129 (org-agenda-skip)
18130 (setq beg (match-beginning 0))
18131 (goto-char (1- (match-end 0)))
18132 (setq b (point))
18133 (forward-sexp 1)
18134 (setq sexp (buffer-substring b (point)))
18135 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
18136 (org-trim (match-string 1))
18137 ""))
18138 (setq result (org-diary-sexp-entry sexp sexp-entry date))
18139 (when result
18140 (setq marker (org-agenda-new-marker beg)
18141 category (org-get-category beg))
18143 (if (string-match "\\S-" result)
18144 (setq txt result)
18145 (setq txt "SEXP entry returned empty string"))
18147 (setq txt (org-format-agenda-item
18148 "" txt category tags 'time))
18149 (org-add-props txt props 'org-marker marker)
18150 (org-add-props txt nil
18151 'org-category category 'date date
18152 'type "sexp")
18153 (push txt ee))))
18154 (nreverse ee)))
18156 (defun org-agenda-get-closed ()
18157 "Return the logged TODO entries for agenda display."
18158 (let* ((props (list 'mouse-face 'highlight
18159 'org-not-done-regexp org-not-done-regexp
18160 'org-todo-regexp org-todo-regexp
18161 'keymap org-agenda-keymap
18162 'help-echo
18163 (format "mouse-2 or RET jump to org file %s"
18164 (abbreviate-file-name buffer-file-name))))
18165 (regexp (concat
18166 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
18167 (regexp-quote
18168 (substring
18169 (format-time-string
18170 (car org-time-stamp-formats)
18171 (apply 'encode-time ; DATE bound by calendar
18172 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18173 1 11))))
18174 marker hdmarker priority category tags closedp
18175 ee txt timestr)
18176 (goto-char (point-min))
18177 (while (re-search-forward regexp nil t)
18178 (catch :skip
18179 (org-agenda-skip)
18180 (setq marker (org-agenda-new-marker (match-beginning 0))
18181 closedp (equal (match-string 1) org-closed-string)
18182 category (org-get-category (match-beginning 0))
18183 timestr (buffer-substring (match-beginning 0) (point-at-eol))
18184 ;; donep (org-entry-is-done-p)
18186 (if (string-match "\\]" timestr)
18187 ;; substring should only run to end of time stamp
18188 (setq timestr (substring timestr 0 (match-end 0))))
18189 (save-excursion
18190 (if (re-search-backward "^\\*+ " nil t)
18191 (progn
18192 (goto-char (match-beginning 0))
18193 (setq hdmarker (org-agenda-new-marker)
18194 tags (org-get-tags-at))
18195 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18196 (setq txt (org-format-agenda-item
18197 (if closedp "Closed: " "Clocked: ")
18198 (match-string 1) category tags timestr)))
18199 (setq txt org-agenda-no-heading-message))
18200 (setq priority 100000)
18201 (org-add-props txt props
18202 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
18203 'priority priority 'org-category category
18204 'type "closed" 'date date
18205 'undone-face 'org-warning 'done-face 'org-done)
18206 (push txt ee))
18207 (outline-next-heading)))
18208 (nreverse ee)))
18210 (defun org-agenda-get-deadlines ()
18211 "Return the deadline information for agenda display."
18212 (let* ((props (list 'mouse-face 'highlight
18213 'org-not-done-regexp org-not-done-regexp
18214 'org-todo-regexp org-todo-regexp
18215 'keymap org-agenda-keymap
18216 'help-echo
18217 (format "mouse-2 or RET jump to org file %s"
18218 (abbreviate-file-name buffer-file-name))))
18219 (regexp org-deadline-time-regexp)
18220 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18221 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18222 d2 diff dfrac wdays pos pos1 category tags
18223 ee txt head face s upcomingp)
18224 (goto-char (point-min))
18225 (while (re-search-forward regexp nil t)
18226 (catch :skip
18227 (org-agenda-skip)
18228 (setq s (match-string 1)
18229 pos (1- (match-beginning 1))
18230 d2 (org-time-string-to-absolute (match-string 1) d1)
18231 diff (- d2 d1))
18232 (if (string-match "-\\([0-9]+\\)\\([dwmy]\\)\\'" s)
18233 (setq wdays
18234 (floor
18235 (* (string-to-number (match-string 1 s))
18236 (cdr (assoc (match-string 2 s)
18237 '(("d" . 1) ("w" . 7)
18238 ("m" . 30.4) ("y" . 365.25)))))))
18239 (setq wdays org-deadline-warning-days))
18240 (setq dfrac (/ (* 1.0 (- wdays diff)) wdays))
18241 (setq upcomingp (and todayp (> diff 0)))
18242 ;; When to show a deadline in the calendar:
18243 ;; If the expiration is within wdays warning time.
18244 ;; Past-due deadlines are only shown on the current date
18245 (if (or (and (<= diff wdays) todayp)
18246 (= diff 0))
18247 (save-excursion
18248 (setq category (org-get-category))
18249 (if (re-search-backward "^\\*+[ \t]+" nil t)
18250 (progn
18251 (goto-char (match-end 0))
18252 (setq pos1 (match-beginning 0))
18253 (setq tags (org-get-tags-at pos1))
18254 (setq head (buffer-substring-no-properties
18255 (point)
18256 (progn (skip-chars-forward "^\r\n")
18257 (point))))
18258 (if (and org-agenda-skip-deadline-if-done
18259 (string-match org-looking-at-done-regexp head))
18260 (setq txt nil)
18261 (setq txt (org-format-agenda-item
18262 (if (= diff 0)
18263 "Deadline: "
18264 (format "In %3d d.: " diff))
18265 head category tags))))
18266 (setq txt org-agenda-no-heading-message))
18267 (when txt
18268 (setq face (org-agenda-deadline-face dfrac))
18269 (org-add-props txt props
18270 'org-marker (org-agenda-new-marker pos)
18271 'org-hd-marker (org-agenda-new-marker pos1)
18272 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
18273 (org-get-priority txt))
18274 'org-category category
18275 'type (if upcomingp "upcoming-deadline" "deadline")
18276 'date (if upcomingp date d2)
18277 'face face 'undone-face face 'done-face 'org-done)
18278 (push txt ee))))))
18279 ee))
18281 (defun org-agenda-deadline-face (fraction)
18282 "Return the face to displaying a deadline item.
18283 FRACTION is what fraction of the head-warning time has passed."
18284 (let ((faces org-agenda-deadline-faces) f)
18285 (catch 'exit
18286 (while (setq f (pop faces))
18287 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
18289 (defun org-agenda-get-scheduled ()
18290 "Return the scheduled information for agenda display."
18291 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
18292 'org-todo-regexp org-todo-regexp
18293 'done-face 'org-done
18294 'mouse-face 'highlight
18295 'keymap org-agenda-keymap
18296 'help-echo
18297 (format "mouse-2 or RET jump to org file %s"
18298 (abbreviate-file-name buffer-file-name))))
18299 (regexp org-scheduled-time-regexp)
18300 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18301 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18302 d2 diff pos pos1 category tags
18303 ee txt head pastduep donep face)
18304 (goto-char (point-min))
18305 (while (re-search-forward regexp nil t)
18306 (catch :skip
18307 (org-agenda-skip)
18308 (setq pos (1- (match-beginning 1))
18309 d2 (org-time-string-to-absolute (match-string 1) d1)
18310 diff (- d2 d1))
18311 (setq pastduep (and todayp (< diff 0)))
18312 ;; When to show a scheduled item in the calendar:
18313 ;; If it is on or past the date.
18314 (if (or (and (< diff 0) todayp)
18315 (= diff 0))
18316 (save-excursion
18317 (setq category (org-get-category))
18318 (if (re-search-backward "^\\*+[ \t]+" nil t)
18319 (progn
18320 (goto-char (match-end 0))
18321 (setq pos1 (match-beginning 0))
18322 (setq tags (org-get-tags-at))
18323 (setq head (buffer-substring-no-properties
18324 (point)
18325 (progn (skip-chars-forward "^\r\n") (point))))
18326 (setq donep (string-match org-looking-at-done-regexp head))
18327 (if (and org-agenda-skip-scheduled-if-done donep)
18328 (setq txt nil)
18329 (setq txt (org-format-agenda-item
18330 (if (= diff 0)
18331 "Scheduled: "
18332 (format "Sched.%2dx: " (- 1 diff)))
18333 head category tags))))
18334 (setq txt org-agenda-no-heading-message))
18335 (when txt
18336 (setq face (if pastduep
18337 'org-scheduled-previously
18338 'org-scheduled-today))
18339 (org-add-props txt props
18340 'undone-face face
18341 'face (if donep 'org-done face)
18342 'org-marker (org-agenda-new-marker pos)
18343 'org-hd-marker (org-agenda-new-marker pos1)
18344 'type (if pastduep "past-scheduled" "scheduled")
18345 'date (if pastduep d2 date)
18346 'priority (+ (- 5 diff) (org-get-priority txt))
18347 'org-category category)
18348 (push txt ee))))))
18349 ee))
18351 (defun org-agenda-get-blocks ()
18352 "Return the date-range information for agenda display."
18353 (let* ((props (list 'face nil
18354 'org-not-done-regexp org-not-done-regexp
18355 'org-todo-regexp org-todo-regexp
18356 'mouse-face 'highlight
18357 'keymap org-agenda-keymap
18358 'help-echo
18359 (format "mouse-2 or RET jump to org file %s"
18360 (abbreviate-file-name buffer-file-name))))
18361 (regexp org-tr-regexp)
18362 (d0 (calendar-absolute-from-gregorian date))
18363 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
18364 (goto-char (point-min))
18365 (while (re-search-forward regexp nil t)
18366 (catch :skip
18367 (org-agenda-skip)
18368 (setq pos (point))
18369 (setq timestr (match-string 0)
18370 s1 (match-string 1)
18371 s2 (match-string 2)
18372 d1 (time-to-days (org-time-string-to-time s1))
18373 d2 (time-to-days (org-time-string-to-time s2)))
18374 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
18375 ;; Only allow days between the limits, because the normal
18376 ;; date stamps will catch the limits.
18377 (save-excursion
18378 (setq marker (org-agenda-new-marker (point)))
18379 (setq category (org-get-category))
18380 (if (re-search-backward "^\\*+ " nil t)
18381 (progn
18382 (goto-char (match-beginning 0))
18383 (setq hdmarker (org-agenda-new-marker (point)))
18384 (setq tags (org-get-tags-at))
18385 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18386 (setq txt (org-format-agenda-item
18387 (format (if (= d1 d2) "" "(%d/%d): ")
18388 (1+ (- d0 d1)) (1+ (- d2 d1)))
18389 (match-string 1) category tags
18390 (if (= d0 d1) timestr))))
18391 (setq txt org-agenda-no-heading-message))
18392 (org-add-props txt props
18393 'org-marker marker 'org-hd-marker hdmarker
18394 'type "block" 'date date
18395 'priority (org-get-priority txt) 'org-category category)
18396 (push txt ee)))
18397 (goto-char pos)))
18398 ;; Sort the entries by expiration date.
18399 (nreverse ee)))
18401 ;;; Agenda presentation and sorting
18403 (defconst org-plain-time-of-day-regexp
18404 (concat
18405 "\\(\\<[012]?[0-9]"
18406 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18407 "\\(--?"
18408 "\\(\\<[012]?[0-9]"
18409 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18410 "\\)?")
18411 "Regular expression to match a plain time or time range.
18412 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
18413 groups carry important information:
18414 0 the full match
18415 1 the first time, range or not
18416 8 the second time, if it is a range.")
18418 (defconst org-stamp-time-of-day-regexp
18419 (concat
18420 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
18421 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
18422 "\\(--?"
18423 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
18424 "Regular expression to match a timestamp time or time range.
18425 After a match, the following groups carry important information:
18426 0 the full match
18427 1 date plus weekday, for backreferencing to make sure both times on same day
18428 2 the first time, range or not
18429 4 the second time, if it is a range.")
18431 (defvar org-prefix-has-time nil
18432 "A flag, set by `org-compile-prefix-format'.
18433 The flag is set if the currently compiled format contains a `%t'.")
18434 (defvar org-prefix-has-tag nil
18435 "A flag, set by `org-compile-prefix-format'.
18436 The flag is set if the currently compiled format contains a `%T'.")
18438 (defun org-format-agenda-item (extra txt &optional category tags dotime
18439 noprefix)
18440 "Format TXT to be inserted into the agenda buffer.
18441 In particular, it adds the prefix and corresponding text properties. EXTRA
18442 must be a string and replaces the `%s' specifier in the prefix format.
18443 CATEGORY (string, symbol or nil) may be used to overrule the default
18444 category taken from local variable or file name. It will replace the `%c'
18445 specifier in the format. DOTIME, when non-nil, indicates that a
18446 time-of-day should be extracted from TXT for sorting of this entry, and for
18447 the `%t' specifier in the format. When DOTIME is a string, this string is
18448 searched for a time before TXT is. NOPREFIX is a flag and indicates that
18449 only the correctly processes TXT should be returned - this is used by
18450 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
18451 (save-match-data
18452 ;; Diary entries sometimes have extra whitespace at the beginning
18453 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
18454 (let* ((category (or category
18455 org-category
18456 (if buffer-file-name
18457 (file-name-sans-extension
18458 (file-name-nondirectory buffer-file-name))
18459 "")))
18460 (tag (if tags (nth (1- (length tags)) tags) ""))
18461 time ; time and tag are needed for the eval of the prefix format
18462 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
18463 (time-of-day (and dotime (org-get-time-of-day ts)))
18464 stamp plain s0 s1 s2 rtn srp)
18465 (when (and dotime time-of-day org-prefix-has-time)
18466 ;; Extract starting and ending time and move them to prefix
18467 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
18468 (setq plain (string-match org-plain-time-of-day-regexp ts)))
18469 (setq s0 (match-string 0 ts)
18470 srp (and stamp (match-end 3))
18471 s1 (match-string (if plain 1 2) ts)
18472 s2 (match-string (if plain 8 (if srp 4 6)) ts))
18474 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
18475 ;; them, we might want to remove them there to avoid duplication.
18476 ;; The user can turn this off with a variable.
18477 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
18478 (string-match (concat (regexp-quote s0) " *") txt)
18479 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
18480 (= (match-beginning 0) 0)
18482 (setq txt (replace-match "" nil nil txt))))
18483 ;; Normalize the time(s) to 24 hour
18484 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
18485 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
18487 (when (and s1 (not s2) org-agenda-default-appointment-duration
18488 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
18489 (let ((m (+ (string-to-number (match-string 2 s1))
18490 (* 60 (string-to-number (match-string 1 s1)))
18491 org-agenda-default-appointment-duration))
18493 (setq h (/ m 60) m (- m (* h 60)))
18494 (setq s2 (format "%02d:%02d" h m))))
18496 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
18497 txt)
18498 ;; Tags are in the string
18499 (if (or (eq org-agenda-remove-tags t)
18500 (and org-agenda-remove-tags
18501 org-prefix-has-tag))
18502 (setq txt (replace-match "" t t txt))
18503 (setq txt (replace-match
18504 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
18505 (match-string 2 txt))
18506 t t txt))))
18508 ;; Create the final string
18509 (if noprefix
18510 (setq rtn txt)
18511 ;; Prepare the variables needed in the eval of the compiled format
18512 (setq time (cond (s2 (concat s1 "-" s2))
18513 (s1 (concat s1 "......"))
18514 (t ""))
18515 extra (or extra "")
18516 category (if (symbolp category) (symbol-name category) category))
18517 ;; Evaluate the compiled format
18518 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
18520 ;; And finally add the text properties
18521 (org-add-props rtn nil
18522 'org-category (downcase category) 'tags tags
18523 'prefix-length (- (length rtn) (length txt))
18524 'time-of-day time-of-day
18525 'txt txt
18526 'time time
18527 'extra extra
18528 'dotime dotime))))
18530 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
18531 (defvar org-agenda-sorting-strategy-selected nil)
18533 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
18534 (catch 'exit
18535 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
18536 ((and todayp (member 'today (car org-agenda-time-grid))))
18537 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
18538 ((member 'weekly (car org-agenda-time-grid)))
18539 (t (throw 'exit list)))
18540 (let* ((have (delq nil (mapcar
18541 (lambda (x) (get-text-property 1 'time-of-day x))
18542 list)))
18543 (string (nth 1 org-agenda-time-grid))
18544 (gridtimes (nth 2 org-agenda-time-grid))
18545 (req (car org-agenda-time-grid))
18546 (remove (member 'remove-match req))
18547 new time)
18548 (if (and (member 'require-timed req) (not have))
18549 ;; don't show empty grid
18550 (throw 'exit list))
18551 (while (setq time (pop gridtimes))
18552 (unless (and remove (member time have))
18553 (setq time (int-to-string time))
18554 (push (org-format-agenda-item
18555 nil string "" nil
18556 (concat (substring time 0 -2) ":" (substring time -2)))
18557 new)
18558 (put-text-property
18559 1 (length (car new)) 'face 'org-time-grid (car new))))
18560 (if (member 'time-up org-agenda-sorting-strategy-selected)
18561 (append new list)
18562 (append list new)))))
18564 (defun org-compile-prefix-format (key)
18565 "Compile the prefix format into a Lisp form that can be evaluated.
18566 The resulting form is returned and stored in the variable
18567 `org-prefix-format-compiled'."
18568 (setq org-prefix-has-time nil org-prefix-has-tag nil)
18569 (let ((s (cond
18570 ((stringp org-agenda-prefix-format)
18571 org-agenda-prefix-format)
18572 ((assq key org-agenda-prefix-format)
18573 (cdr (assq key org-agenda-prefix-format)))
18574 (t " %-12:c%?-12t% s")))
18575 (start 0)
18576 varform vars var e c f opt)
18577 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
18578 s start)
18579 (setq var (cdr (assoc (match-string 4 s)
18580 '(("c" . category) ("t" . time) ("s" . extra)
18581 ("T" . tag))))
18582 c (or (match-string 3 s) "")
18583 opt (match-beginning 1)
18584 start (1+ (match-beginning 0)))
18585 (if (equal var 'time) (setq org-prefix-has-time t))
18586 (if (equal var 'tag) (setq org-prefix-has-tag t))
18587 (setq f (concat "%" (match-string 2 s) "s"))
18588 (if opt
18589 (setq varform
18590 `(if (equal "" ,var)
18592 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
18593 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
18594 (setq s (replace-match "%s" t nil s))
18595 (push varform vars))
18596 (setq vars (nreverse vars))
18597 (setq org-prefix-format-compiled `(format ,s ,@vars))))
18599 (defun org-set-sorting-strategy (key)
18600 (if (symbolp (car org-agenda-sorting-strategy))
18601 ;; the old format
18602 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
18603 (setq org-agenda-sorting-strategy-selected
18604 (or (cdr (assq key org-agenda-sorting-strategy))
18605 (cdr (assq 'agenda org-agenda-sorting-strategy))
18606 '(time-up category-keep priority-down)))))
18608 (defun org-get-time-of-day (s &optional string mod24)
18609 "Check string S for a time of day.
18610 If found, return it as a military time number between 0 and 2400.
18611 If not found, return nil.
18612 The optional STRING argument forces conversion into a 5 character wide string
18613 HH:MM."
18614 (save-match-data
18615 (when
18617 (string-match
18618 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
18619 (string-match
18620 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
18621 (let* ((h (string-to-number (match-string 1 s)))
18622 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
18623 (ampm (if (match-end 4) (downcase (match-string 4 s))))
18624 (am-p (equal ampm "am"))
18625 (h1 (cond ((not ampm) h)
18626 ((= h 12) (if am-p 0 12))
18627 (t (+ h (if am-p 0 12)))))
18628 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
18629 (mod h1 24) h1))
18630 (t0 (+ (* 100 h2) m))
18631 (t1 (concat (if (>= h1 24) "+" " ")
18632 (if (< t0 100) "0" "")
18633 (if (< t0 10) "0" "")
18634 (int-to-string t0))))
18635 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
18637 (defun org-finalize-agenda-entries (list &optional nosort)
18638 "Sort and concatenate the agenda items."
18639 (setq list (mapcar 'org-agenda-highlight-todo list))
18640 (if nosort
18641 list
18642 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
18644 (defun org-agenda-highlight-todo (x)
18645 (let (re pl)
18646 (if (eq x 'line)
18647 (save-excursion
18648 (beginning-of-line 1)
18649 (setq re (get-text-property (point) 'org-not-done-regexp))
18650 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
18651 (and (looking-at (concat "[ \t]*\\.*" re))
18652 (add-text-properties (match-beginning 0) (match-end 0)
18653 '(face org-todo))))
18654 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
18655 pl (get-text-property 0 'prefix-length x))
18656 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
18657 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
18658 '(face org-todo) x))
18659 x)))
18661 (defsubst org-cmp-priority (a b)
18662 "Compare the priorities of string A and B."
18663 (let ((pa (or (get-text-property 1 'priority a) 0))
18664 (pb (or (get-text-property 1 'priority b) 0)))
18665 (cond ((> pa pb) +1)
18666 ((< pa pb) -1)
18667 (t nil))))
18669 (defsubst org-cmp-category (a b)
18670 "Compare the string values of categories of strings A and B."
18671 (let ((ca (or (get-text-property 1 'org-category a) ""))
18672 (cb (or (get-text-property 1 'org-category b) "")))
18673 (cond ((string-lessp ca cb) -1)
18674 ((string-lessp cb ca) +1)
18675 (t nil))))
18677 (defsubst org-cmp-tag (a b)
18678 "Compare the string values of categories of strings A and B."
18679 (let ((ta (car (last (get-text-property 1 'tags a))))
18680 (tb (car (last (get-text-property 1 'tags b)))))
18681 (cond ((not ta) +1)
18682 ((not tb) -1)
18683 ((string-lessp ta tb) -1)
18684 ((string-lessp tb ta) +1)
18685 (t nil))))
18687 (defsubst org-cmp-time (a b)
18688 "Compare the time-of-day values of strings A and B."
18689 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
18690 (ta (or (get-text-property 1 'time-of-day a) def))
18691 (tb (or (get-text-property 1 'time-of-day b) def)))
18692 (cond ((< ta tb) -1)
18693 ((< tb ta) +1)
18694 (t nil))))
18696 (defun org-entries-lessp (a b)
18697 "Predicate for sorting agenda entries."
18698 ;; The following variables will be used when the form is evaluated.
18699 ;; So even though the compiler complains, keep them.
18700 (let* ((time-up (org-cmp-time a b))
18701 (time-down (if time-up (- time-up) nil))
18702 (priority-up (org-cmp-priority a b))
18703 (priority-down (if priority-up (- priority-up) nil))
18704 (category-up (org-cmp-category a b))
18705 (category-down (if category-up (- category-up) nil))
18706 (category-keep (if category-up +1 nil))
18707 (tag-up (org-cmp-tag a b))
18708 (tag-down (if tag-up (- tag-up) nil)))
18709 (cdr (assoc
18710 (eval (cons 'or org-agenda-sorting-strategy-selected))
18711 '((-1 . t) (1 . nil) (nil . nil))))))
18713 ;;; Agenda commands
18715 (defun org-agenda-check-type (error &rest types)
18716 "Check if agenda buffer is of allowed type.
18717 If ERROR is non-nil, throw an error, otherwise just return nil."
18718 (if (memq org-agenda-type types)
18720 (if error
18721 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
18722 nil)))
18724 (defun org-agenda-quit ()
18725 "Exit agenda by removing the window or the buffer."
18726 (interactive)
18727 (let ((buf (current-buffer)))
18728 (if (not (one-window-p)) (delete-window))
18729 (kill-buffer buf)
18730 (org-agenda-maybe-reset-markers 'force)
18731 (org-columns-remove-overlays))
18732 ;; Maybe restore the pre-agenda window configuration.
18733 (and org-agenda-restore-windows-after-quit
18734 (not (eq org-agenda-window-setup 'other-frame))
18735 org-pre-agenda-window-conf
18736 (set-window-configuration org-pre-agenda-window-conf)))
18738 (defun org-agenda-exit ()
18739 "Exit agenda by removing the window or the buffer.
18740 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
18741 Org-mode buffers visited directly by the user will not be touched."
18742 (interactive)
18743 (org-release-buffers org-agenda-new-buffers)
18744 (setq org-agenda-new-buffers nil)
18745 (org-agenda-quit))
18747 (defun org-save-all-org-buffers ()
18748 "Save all Org-mode buffers without user confirmation."
18749 (interactive)
18750 (message "Saving all Org-mode buffers...")
18751 (save-some-buffers t 'org-mode-p)
18752 (message "Saving all Org-mode buffers... done"))
18754 (defun org-agenda-redo ()
18755 "Rebuild Agenda.
18756 When this is the global TODO list, a prefix argument will be interpreted."
18757 (interactive)
18758 (let* ((org-agenda-keep-modes t)
18759 (line (org-current-line))
18760 (window-line (- line (org-current-line (window-start))))
18761 (lprops (get 'org-agenda-redo-command 'org-lprops)))
18762 (message "Rebuilding agenda buffer...")
18763 (org-let lprops '(eval org-agenda-redo-command))
18764 (setq org-agenda-undo-list nil
18765 org-agenda-pending-undo-list nil)
18766 (message "Rebuilding agenda buffer...done")
18767 (goto-line line)
18768 (recenter window-line)))
18770 (defun org-agenda-goto-date (date)
18771 "Jump to DATE in agenda."
18772 (interactive (list (org-read-date)))
18773 (org-agenda-list nil date))
18775 (defun org-agenda-goto-today ()
18776 "Go to today."
18777 (interactive)
18778 (org-agenda-check-type t 'timeline 'agenda)
18779 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
18780 (cond
18781 (tdpos (goto-char tdpos))
18782 ((eq org-agenda-type 'agenda)
18783 (let* ((sd (time-to-days (current-time)))
18784 (comp (org-agenda-compute-time-span sd org-agenda-span))
18785 (org-agenda-overriding-arguments org-agenda-last-arguments))
18786 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
18787 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
18788 (org-agenda-redo)
18789 (org-agenda-find-today-or-agenda)))
18790 (t (error "Cannot find today")))))
18792 (defun org-agenda-find-today-or-agenda ()
18793 (goto-char
18794 (or (text-property-any (point-min) (point-max) 'org-today t)
18795 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
18796 (point-min))))
18798 (defun org-agenda-later (arg)
18799 "Go forward in time by thee current span.
18800 With prefix ARG, go forward that many times the current span."
18801 (interactive "p")
18802 (org-agenda-check-type t 'agenda)
18803 (let* ((span org-agenda-span)
18804 (sd org-starting-day)
18805 (greg (calendar-gregorian-from-absolute sd))
18806 greg2 nd)
18807 (cond
18808 ((eq span 'day)
18809 (setq sd (+ arg sd) nd 1))
18810 ((eq span 'week)
18811 (setq sd (+ (* 7 arg) sd) nd 7))
18812 ((eq span 'month)
18813 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
18814 sd (calendar-absolute-from-gregorian greg2))
18815 (setcar greg2 (1+ (car greg2)))
18816 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
18817 ((eq span 'year)
18818 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
18819 sd (calendar-absolute-from-gregorian greg2))
18820 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
18821 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
18822 (let ((org-agenda-overriding-arguments
18823 (list (car org-agenda-last-arguments) sd nd t)))
18824 (org-agenda-redo)
18825 (org-agenda-find-today-or-agenda))))
18827 (defun org-agenda-earlier (arg)
18828 "Go backward in time by the current span.
18829 With prefix ARG, go backward that many times the current span."
18830 (interactive "p")
18831 (org-agenda-later (- arg)))
18833 (defun org-agenda-day-view ()
18834 "Switch to daily view for agenda."
18835 (interactive)
18836 (setq org-agenda-ndays 1)
18837 (org-agenda-change-time-span 'day))
18838 (defun org-agenda-week-view ()
18839 "Switch to daily view for agenda."
18840 (interactive)
18841 (setq org-agenda-ndays 7)
18842 (org-agenda-change-time-span 'week))
18843 (defun org-agenda-month-view ()
18844 "Switch to daily view for agenda."
18845 (interactive)
18846 (org-agenda-change-time-span 'month))
18847 (defun org-agenda-year-view ()
18848 "Switch to daily view for agenda."
18849 (interactive)
18850 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
18851 (org-agenda-change-time-span 'year)
18852 (error "Abort")))
18854 (defun org-agenda-change-time-span (span)
18855 "Change the agenda view to SPAN.
18856 SPAN may be `day', `week', `month', `year'."
18857 (org-agenda-check-type t 'agenda)
18858 (if (equal org-agenda-span span)
18859 (error "Viewing span is already \"%s\"" span))
18860 (let* ((sd (or (get-text-property (point) 'day)
18861 org-starting-day))
18862 (computed (org-agenda-compute-time-span sd span))
18863 (org-agenda-overriding-arguments
18864 (list (car org-agenda-last-arguments)
18865 (car computed) (cdr computed) t)))
18866 (org-agenda-redo)
18867 (org-agenda-find-today-or-agenda))
18868 (org-agenda-set-mode-name)
18869 (message "Switched to %s view" span))
18871 (defun org-agenda-compute-time-span (sd span)
18872 "Compute starting date and number of days for agenda.
18873 SPAN may be `day', `week', `month', `year'. The return value
18874 is a cons cell with the starting date and the number of days,
18875 so that the date SD will be in that range."
18876 (let* ((greg (calendar-gregorian-from-absolute sd))
18878 (cond
18879 ((eq span 'day)
18880 (setq nd 1))
18881 ((eq span 'week)
18882 (let* ((nt (calendar-day-of-week
18883 (calendar-gregorian-from-absolute sd)))
18884 (d (if org-agenda-start-on-weekday
18885 (- nt org-agenda-start-on-weekday)
18886 0)))
18887 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
18888 (setq nd 7)))
18889 ((eq span 'month)
18890 (setq sd (calendar-absolute-from-gregorian
18891 (list (car greg) 1 (nth 2 greg)))
18892 nd (- (calendar-absolute-from-gregorian
18893 (list (1+ (car greg)) 1 (nth 2 greg)))
18894 sd)))
18895 ((eq span 'year)
18896 (setq sd (calendar-absolute-from-gregorian
18897 (list 1 1 (nth 2 greg)))
18898 nd (- (calendar-absolute-from-gregorian
18899 (list 1 1 (1+ (nth 2 greg))))
18900 sd))))
18901 (cons sd nd)))
18903 ;; FIXME: this no longer works if user make date format that starts with a blank
18904 (defun org-agenda-next-date-line (&optional arg)
18905 "Jump to the next line indicating a date in agenda buffer."
18906 (interactive "p")
18907 (org-agenda-check-type t 'agenda 'timeline)
18908 (beginning-of-line 1)
18909 (if (looking-at "^\\S-") (forward-char 1))
18910 (if (not (re-search-forward "^\\S-" nil t arg))
18911 (progn
18912 (backward-char 1)
18913 (error "No next date after this line in this buffer")))
18914 (goto-char (match-beginning 0)))
18916 (defun org-agenda-previous-date-line (&optional arg)
18917 "Jump to the previous line indicating a date in agenda buffer."
18918 (interactive "p")
18919 (org-agenda-check-type t 'agenda 'timeline)
18920 (beginning-of-line 1)
18921 (if (not (re-search-backward "^\\S-" nil t arg))
18922 (error "No previous date before this line in this buffer")))
18924 ;; Initialize the highlight
18925 (defvar org-hl (org-make-overlay 1 1))
18926 (org-overlay-put org-hl 'face 'highlight)
18928 (defun org-highlight (begin end &optional buffer)
18929 "Highlight a region with overlay."
18930 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
18931 org-hl begin end (or buffer (current-buffer))))
18933 (defun org-unhighlight ()
18934 "Detach overlay INDEX."
18935 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
18937 ;; FIXME this is currently not used.
18938 (defun org-highlight-until-next-command (beg end &optional buffer)
18939 (org-highlight beg end buffer)
18940 (add-hook 'pre-command-hook 'org-unhighlight-once))
18942 (defun org-unhighlight-once ()
18943 (remove-hook 'pre-command-hook 'org-unhighlight-once)
18944 (org-unhighlight))
18946 (defun org-agenda-follow-mode ()
18947 "Toggle follow mode in an agenda buffer."
18948 (interactive)
18949 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
18950 (org-agenda-set-mode-name)
18951 (message "Follow mode is %s"
18952 (if org-agenda-follow-mode "on" "off")))
18954 (defun org-agenda-log-mode ()
18955 "Toggle log mode in an agenda buffer."
18956 (interactive)
18957 (org-agenda-check-type t 'agenda 'timeline)
18958 (setq org-agenda-show-log (not org-agenda-show-log))
18959 (org-agenda-set-mode-name)
18960 (org-agenda-redo)
18961 (message "Log mode is %s"
18962 (if org-agenda-show-log "on" "off")))
18964 (defun org-agenda-toggle-diary ()
18965 "Toggle diary inclusion in an agenda buffer."
18966 (interactive)
18967 (org-agenda-check-type t 'agenda)
18968 (setq org-agenda-include-diary (not org-agenda-include-diary))
18969 (org-agenda-redo)
18970 (org-agenda-set-mode-name)
18971 (message "Diary inclusion turned %s"
18972 (if org-agenda-include-diary "on" "off")))
18974 (defun org-agenda-toggle-time-grid ()
18975 "Toggle time grid in an agenda buffer."
18976 (interactive)
18977 (org-agenda-check-type t 'agenda)
18978 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
18979 (org-agenda-redo)
18980 (org-agenda-set-mode-name)
18981 (message "Time-grid turned %s"
18982 (if org-agenda-use-time-grid "on" "off")))
18984 (defun org-agenda-set-mode-name ()
18985 "Set the mode name to indicate all the small mode settings."
18986 (setq mode-name
18987 (concat "Org-Agenda"
18988 (if (equal org-agenda-ndays 1) " Day" "")
18989 (if (equal org-agenda-ndays 7) " Week" "")
18990 (if org-agenda-follow-mode " Follow" "")
18991 (if org-agenda-include-diary " Diary" "")
18992 (if org-agenda-use-time-grid " Grid" "")
18993 (if org-agenda-show-log " Log" "")))
18994 (force-mode-line-update))
18996 (defun org-agenda-post-command-hook ()
18997 (and (eolp) (not (bolp)) (backward-char 1))
18998 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
18999 (if (and org-agenda-follow-mode
19000 (get-text-property (point) 'org-marker))
19001 (org-agenda-show)))
19003 (defun org-agenda-show-priority ()
19004 "Show the priority of the current item.
19005 This priority is composed of the main priority given with the [#A] cookies,
19006 and by additional input from the age of a schedules or deadline entry."
19007 (interactive)
19008 (let* ((pri (get-text-property (point-at-bol) 'priority)))
19009 (message "Priority is %d" (if pri pri -1000))))
19011 (defun org-agenda-show-tags ()
19012 "Show the tags applicable to the current item."
19013 (interactive)
19014 (let* ((tags (get-text-property (point-at-bol) 'tags)))
19015 (if tags
19016 (message "Tags are :%s:"
19017 (org-no-properties (mapconcat 'identity tags ":")))
19018 (message "No tags associated with this line"))))
19020 (defun org-agenda-goto (&optional highlight)
19021 "Go to the Org-mode file which contains the item at point."
19022 (interactive)
19023 (let* ((marker (or (get-text-property (point) 'org-marker)
19024 (org-agenda-error)))
19025 (buffer (marker-buffer marker))
19026 (pos (marker-position marker)))
19027 (switch-to-buffer-other-window buffer)
19028 (widen)
19029 (goto-char pos)
19030 (when (org-mode-p)
19031 (org-show-context 'agenda)
19032 (save-excursion
19033 (and (outline-next-heading)
19034 (org-flag-heading nil)))) ; show the next heading
19035 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
19037 (defun org-agenda-kill ()
19038 "Kill the entry or subtree belonging to the current agenda entry."
19039 (interactive)
19040 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19041 (let* ((marker (or (get-text-property (point) 'org-marker)
19042 (org-agenda-error)))
19043 (buffer (marker-buffer marker))
19044 (pos (marker-position marker))
19045 (type (get-text-property (point) 'type))
19046 dbeg dend (n 0) conf)
19047 (org-with-remote-undo buffer
19048 (with-current-buffer buffer
19049 (save-excursion
19050 (goto-char pos)
19051 (if (and (org-mode-p) (not (member type '("sexp"))))
19052 (setq dbeg (progn (org-back-to-heading t) (point))
19053 dend (org-end-of-subtree t))
19054 (setq dbeg (point-at-bol)
19055 dend (min (point-max) (1+ (point-at-eol)))))
19056 (goto-char dbeg)
19057 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
19058 (setq conf (or (eq t org-agenda-confirm-kill)
19059 (and (numberp org-agenda-confirm-kill)
19060 (> n org-agenda-confirm-kill))))
19061 (and conf
19062 (not (y-or-n-p
19063 (format "Delete entry with %d lines in buffer \"%s\"? "
19064 n (buffer-name buffer))))
19065 (error "Abort"))
19066 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
19067 (with-current-buffer buffer (delete-region dbeg dend))
19068 (message "Agenda item and source killed"))))
19070 (defun org-agenda-archive ()
19071 "Kill the entry or subtree belonging to the current agenda entry."
19072 (interactive)
19073 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19074 (let* ((marker (or (get-text-property (point) 'org-marker)
19075 (org-agenda-error)))
19076 (buffer (marker-buffer marker))
19077 (pos (marker-position marker)))
19078 (org-with-remote-undo buffer
19079 (with-current-buffer buffer
19080 (if (org-mode-p)
19081 (save-excursion
19082 (goto-char pos)
19083 (org-remove-subtree-entries-from-agenda)
19084 (org-back-to-heading t)
19085 (org-archive-subtree))
19086 (error "Archiving works only in Org-mode files"))))))
19088 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
19089 "Remove all lines in the agenda that correspond to a given subtree.
19090 The subtree is the one in buffer BUF, starting at BEG and ending at END.
19091 If this information is not given, the function uses the tree at point."
19092 (let ((buf (or buf (current-buffer))) m p)
19093 (save-excursion
19094 (unless (and beg end)
19095 (org-back-to-heading t)
19096 (setq beg (point))
19097 (org-end-of-subtree t)
19098 (setq end (point)))
19099 (set-buffer (get-buffer org-agenda-buffer-name))
19100 (save-excursion
19101 (goto-char (point-max))
19102 (beginning-of-line 1)
19103 (while (not (bobp))
19104 (when (and (setq m (get-text-property (point) 'org-marker))
19105 (equal buf (marker-buffer m))
19106 (setq p (marker-position m))
19107 (>= p beg)
19108 (<= p end))
19109 (let ((inhibit-read-only t))
19110 (delete-region (point-at-bol) (1+ (point-at-eol)))))
19111 (beginning-of-line 0))))))
19113 (defun org-agenda-open-link ()
19114 "Follow the link in the current line, if any."
19115 (interactive)
19116 (let ((eol (point-at-eol)))
19117 (save-excursion
19118 (if (or (re-search-forward org-bracket-link-regexp eol t)
19119 (re-search-forward org-angle-link-re eol t)
19120 (re-search-forward org-plain-link-re eol t))
19121 (call-interactively 'org-open-at-point)
19122 (error "No link in current line")))))
19124 (defun org-agenda-switch-to (&optional delete-other-windows)
19125 "Go to the Org-mode file which contains the item at point."
19126 (interactive)
19127 (let* ((marker (or (get-text-property (point) 'org-marker)
19128 (org-agenda-error)))
19129 (buffer (marker-buffer marker))
19130 (pos (marker-position marker)))
19131 (switch-to-buffer buffer)
19132 (and delete-other-windows (delete-other-windows))
19133 (widen)
19134 (goto-char pos)
19135 (when (org-mode-p)
19136 (org-show-context 'agenda)
19137 (save-excursion
19138 (and (outline-next-heading)
19139 (org-flag-heading nil)))))) ; show the next heading
19141 (defun org-agenda-goto-mouse (ev)
19142 "Go to the Org-mode file which contains the item at the mouse click."
19143 (interactive "e")
19144 (mouse-set-point ev)
19145 (org-agenda-goto))
19147 (defun org-agenda-show ()
19148 "Display the Org-mode file which contains the item at point."
19149 (interactive)
19150 (let ((win (selected-window)))
19151 (org-agenda-goto t)
19152 (select-window win)))
19154 (defun org-agenda-recenter (arg)
19155 "Display the Org-mode file which contains the item at point and recenter."
19156 (interactive "P")
19157 (let ((win (selected-window)))
19158 (org-agenda-goto t)
19159 (recenter arg)
19160 (select-window win)))
19162 (defun org-agenda-show-mouse (ev)
19163 "Display the Org-mode file which contains the item at the mouse click."
19164 (interactive "e")
19165 (mouse-set-point ev)
19166 (org-agenda-show))
19168 (defun org-agenda-check-no-diary ()
19169 "Check if the entry is a diary link and abort if yes."
19170 (if (get-text-property (point) 'org-agenda-diary-link)
19171 (org-agenda-error)))
19173 (defun org-agenda-error ()
19174 (error "Command not allowed in this line"))
19176 (defun org-agenda-tree-to-indirect-buffer ()
19177 "Show the subtree corresponding to the current entry in an indirect buffer.
19178 This calls the command `org-tree-to-indirect-buffer' from the original
19179 Org-mode buffer.
19180 With numerical prefix arg ARG, go up to this level and then take that tree.
19181 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
19182 dedicated frame)."
19183 (interactive)
19184 (org-agenda-check-no-diary)
19185 (let* ((marker (or (get-text-property (point) 'org-marker)
19186 (org-agenda-error)))
19187 (buffer (marker-buffer marker))
19188 (pos (marker-position marker)))
19189 (with-current-buffer buffer
19190 (save-excursion
19191 (goto-char pos)
19192 (call-interactively 'org-tree-to-indirect-buffer)))))
19194 (defvar org-last-heading-marker (make-marker)
19195 "Marker pointing to the headline that last changed its TODO state
19196 by a remote command from the agenda.")
19198 (defun org-agenda-todo-nextset ()
19199 "Switch TODO entry to next sequence."
19200 (interactive)
19201 (org-agenda-todo 'nextset))
19203 (defun org-agenda-todo-previousset ()
19204 "Switch TODO entry to previous sequence."
19205 (interactive)
19206 (org-agenda-todo 'previousset))
19208 (defun org-agenda-todo (&optional arg)
19209 "Cycle TODO state of line at point, also in Org-mode file.
19210 This changes the line at point, all other lines in the agenda referring to
19211 the same tree node, and the headline of the tree node in the Org-mode file."
19212 (interactive "P")
19213 (org-agenda-check-no-diary)
19214 (let* ((col (current-column))
19215 (marker (or (get-text-property (point) 'org-marker)
19216 (org-agenda-error)))
19217 (buffer (marker-buffer marker))
19218 (pos (marker-position marker))
19219 (hdmarker (get-text-property (point) 'org-hd-marker))
19220 (inhibit-read-only t)
19221 newhead)
19222 (org-with-remote-undo buffer
19223 (with-current-buffer buffer
19224 (widen)
19225 (goto-char pos)
19226 (org-show-context 'agenda)
19227 (save-excursion
19228 (and (outline-next-heading)
19229 (org-flag-heading nil))) ; show the next heading
19230 (org-todo arg)
19231 (and (bolp) (forward-char 1))
19232 (setq newhead (org-get-heading))
19233 (save-excursion
19234 (org-back-to-heading)
19235 (move-marker org-last-heading-marker (point))))
19236 (beginning-of-line 1)
19237 (save-excursion
19238 (org-agenda-change-all-lines newhead hdmarker 'fixface))
19239 (move-to-column col))))
19241 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
19242 "Change all lines in the agenda buffer which match HDMARKER.
19243 The new content of the line will be NEWHEAD (as modified by
19244 `org-format-agenda-item'). HDMARKER is checked with
19245 `equal' against all `org-hd-marker' text properties in the file.
19246 If FIXFACE is non-nil, the face of each item is modified acording to
19247 the new TODO state."
19248 (let* ((inhibit-read-only t)
19249 props m pl undone-face done-face finish new dotime cat tags)
19250 (save-excursion
19251 (goto-char (point-max))
19252 (beginning-of-line 1)
19253 (while (not finish)
19254 (setq finish (bobp))
19255 (when (and (setq m (get-text-property (point) 'org-hd-marker))
19256 (equal m hdmarker))
19257 (setq props (text-properties-at (point))
19258 dotime (get-text-property (point) 'dotime)
19259 cat (get-text-property (point) 'org-category)
19260 tags (get-text-property (point) 'tags)
19261 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
19262 pl (get-text-property (point) 'prefix-length)
19263 undone-face (get-text-property (point) 'undone-face)
19264 done-face (get-text-property (point) 'done-face))
19265 (move-to-column pl)
19266 (cond
19267 ((equal new "")
19268 (beginning-of-line 1)
19269 (and (looking-at ".*\n?") (replace-match "")))
19270 ((looking-at ".*")
19271 (replace-match new t t)
19272 (beginning-of-line 1)
19273 (add-text-properties (point-at-bol) (point-at-eol) props)
19274 (when fixface
19275 (add-text-properties
19276 (point-at-bol) (point-at-eol)
19277 (list 'face
19278 (if org-last-todo-state-is-todo
19279 undone-face done-face))))
19280 (org-agenda-highlight-todo 'line)
19281 (beginning-of-line 1))
19282 (t (error "Line update did not work"))))
19283 (beginning-of-line 0)))
19284 (org-finalize-agenda)))
19286 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
19287 ;; See the code in set-tags for the way to do this.
19288 (defun org-agenda-align-tags (&optional line)
19289 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
19290 (let ((inhibit-read-only t))
19291 (save-excursion
19292 (goto-char (if line (point-at-bol) (point-min)))
19293 (while (re-search-forward (org-re "\\([ \t]+\\):[[:alnum:]_@:]+:[ \t]*$")
19294 (if line (point-at-eol) nil) t)
19295 (delete-region (match-beginning 1) (match-end 1))
19296 (goto-char (match-beginning 1))
19297 (insert (org-add-props
19298 (make-string (max 1 (- org-agenda-align-tags-to-column
19299 (current-column))) ?\ )
19300 (text-properties-at (point))))))))
19302 (defun org-agenda-priority-up ()
19303 "Increase the priority of line at point, also in Org-mode file."
19304 (interactive)
19305 (org-agenda-priority 'up))
19307 (defun org-agenda-priority-down ()
19308 "Decrease the priority of line at point, also in Org-mode file."
19309 (interactive)
19310 (org-agenda-priority 'down))
19312 (defun org-agenda-priority (&optional force-direction)
19313 "Set the priority of line at point, also in Org-mode file.
19314 This changes the line at point, all other lines in the agenda referring to
19315 the same tree node, and the headline of the tree node in the Org-mode file."
19316 (interactive)
19317 (org-agenda-check-no-diary)
19318 (let* ((marker (or (get-text-property (point) 'org-marker)
19319 (org-agenda-error)))
19320 (hdmarker (get-text-property (point) 'org-hd-marker))
19321 (buffer (marker-buffer hdmarker))
19322 (pos (marker-position hdmarker))
19323 (inhibit-read-only t)
19324 newhead)
19325 (org-with-remote-undo buffer
19326 (with-current-buffer buffer
19327 (widen)
19328 (goto-char pos)
19329 (org-show-context 'agenda)
19330 (save-excursion
19331 (and (outline-next-heading)
19332 (org-flag-heading nil))) ; show the next heading
19333 (funcall 'org-priority force-direction)
19334 (end-of-line 1)
19335 (setq newhead (org-get-heading)))
19336 (org-agenda-change-all-lines newhead hdmarker)
19337 (beginning-of-line 1))))
19339 (defun org-get-tags-at (&optional pos)
19340 "Get a list of all headline tags applicable at POS.
19341 POS defaults to point. If tags are inherited, the list contains
19342 the targets in the same sequence as the headlines appear, i.e.
19343 the tags of the current headline come last."
19344 (interactive)
19345 (let (tags)
19346 (save-excursion
19347 (save-restriction
19348 (widen)
19349 (goto-char (or pos (point)))
19350 (save-match-data
19351 (org-back-to-heading t)
19352 (condition-case nil
19353 (while t
19354 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
19355 (setq tags (append (org-split-string
19356 (org-match-string-no-properties 1) ":")
19357 tags)))
19358 (or org-use-tag-inheritance (error ""))
19359 (org-up-heading-all 1))
19360 (error nil))))
19361 tags)))
19363 ;; FIXME: should fix the tags property of the agenda line.
19364 (defun org-agenda-set-tags ()
19365 "Set tags for the current headline."
19366 (interactive)
19367 (org-agenda-check-no-diary)
19368 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19369 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19370 (org-agenda-error)))
19371 (buffer (marker-buffer hdmarker))
19372 (pos (marker-position hdmarker))
19373 (inhibit-read-only t)
19374 newhead)
19375 (org-with-remote-undo buffer
19376 (with-current-buffer buffer
19377 (widen)
19378 (goto-char pos)
19379 (save-excursion
19380 (org-show-context 'agenda))
19381 (save-excursion
19382 (and (outline-next-heading)
19383 (org-flag-heading nil))) ; show the next heading
19384 (goto-char pos)
19385 (call-interactively 'org-set-tags)
19386 (end-of-line 1)
19387 (setq newhead (org-get-heading)))
19388 (org-agenda-change-all-lines newhead hdmarker)
19389 (beginning-of-line 1))))
19391 (defun org-agenda-toggle-archive-tag ()
19392 "Toggle the archive tag for the current entry."
19393 (interactive)
19394 (org-agenda-check-no-diary)
19395 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19396 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19397 (org-agenda-error)))
19398 (buffer (marker-buffer hdmarker))
19399 (pos (marker-position hdmarker))
19400 (inhibit-read-only t)
19401 newhead)
19402 (org-with-remote-undo buffer
19403 (with-current-buffer buffer
19404 (widen)
19405 (goto-char pos)
19406 (org-show-context 'agenda)
19407 (save-excursion
19408 (and (outline-next-heading)
19409 (org-flag-heading nil))) ; show the next heading
19410 (call-interactively 'org-toggle-archive-tag)
19411 (end-of-line 1)
19412 (setq newhead (org-get-heading)))
19413 (org-agenda-change-all-lines newhead hdmarker)
19414 (beginning-of-line 1))))
19416 (defun org-agenda-date-later (arg &optional what)
19417 "Change the date of this item to one day later."
19418 (interactive "p")
19419 (org-agenda-check-type t 'agenda 'timeline)
19420 (org-agenda-check-no-diary)
19421 (let* ((marker (or (get-text-property (point) 'org-marker)
19422 (org-agenda-error)))
19423 (buffer (marker-buffer marker))
19424 (pos (marker-position marker)))
19425 (org-with-remote-undo buffer
19426 (with-current-buffer buffer
19427 (widen)
19428 (goto-char pos)
19429 (if (not (org-at-timestamp-p))
19430 (error "Cannot find time stamp"))
19431 (org-timestamp-change arg (or what 'day)))
19432 (org-agenda-show-new-time marker org-last-changed-timestamp))
19433 (message "Time stamp changed to %s" org-last-changed-timestamp)))
19435 (defun org-agenda-date-earlier (arg &optional what)
19436 "Change the date of this item to one day earlier."
19437 (interactive "p")
19438 (org-agenda-date-later (- arg) what))
19440 (defun org-agenda-show-new-time (marker stamp)
19441 "Show new date stamp via text properties."
19442 ;; We use text properties to make this undoable
19443 (let ((inhibit-read-only t))
19444 (setq stamp (concat " => " stamp))
19445 (save-excursion
19446 (goto-char (point-max))
19447 (while (not (bobp))
19448 (when (equal marker (get-text-property (point) 'org-marker))
19449 (move-to-column (- (window-width) (length stamp)) t)
19450 (if (featurep 'xemacs)
19451 ;; Use `duplicable' property to trigger undo recording
19452 (let ((ex (make-extent nil nil))
19453 (gl (make-glyph stamp)))
19454 (set-glyph-face gl 'secondary-selection)
19455 (set-extent-properties
19456 ex (list 'invisible t 'end-glyph gl 'duplicable t))
19457 (insert-extent ex (1- (point)) (point-at-eol)))
19458 (add-text-properties
19459 (1- (point)) (point-at-eol)
19460 (list 'display (org-add-props stamp nil
19461 'face 'secondary-selection))))
19462 (beginning-of-line 1))
19463 (beginning-of-line 0)))))
19465 (defun org-agenda-date-prompt (arg)
19466 "Change the date of this item. Date is prompted for, with default today.
19467 The prefix ARG is passed to the `org-time-stamp' command and can therefore
19468 be used to request time specification in the time stamp."
19469 (interactive "P")
19470 (org-agenda-check-type t 'agenda 'timeline)
19471 (org-agenda-check-no-diary)
19472 (let* ((marker (or (get-text-property (point) 'org-marker)
19473 (org-agenda-error)))
19474 (buffer (marker-buffer marker))
19475 (pos (marker-position marker)))
19476 (org-with-remote-undo buffer
19477 (with-current-buffer buffer
19478 (widen)
19479 (goto-char pos)
19480 (if (not (org-at-timestamp-p))
19481 (error "Cannot find time stamp"))
19482 (org-time-stamp arg)
19483 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
19485 (defun org-agenda-schedule (arg)
19486 "Schedule the item at point."
19487 (interactive "P")
19488 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19489 (org-agenda-check-no-diary)
19490 (let* ((marker (or (get-text-property (point) 'org-marker)
19491 (org-agenda-error)))
19492 (buffer (marker-buffer marker))
19493 (pos (marker-position marker))
19494 (org-insert-labeled-timestamps-at-point nil)
19496 (org-with-remote-undo buffer
19497 (with-current-buffer buffer
19498 (widen)
19499 (goto-char pos)
19500 (setq ts (org-schedule))
19501 (message "Item scheduled for %s" ts)))))
19503 (defun org-agenda-deadline (arg)
19504 "Schedule the item at point."
19505 (interactive "P")
19506 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19507 (org-agenda-check-no-diary)
19508 (let* ((marker (or (get-text-property (point) 'org-marker)
19509 (org-agenda-error)))
19510 (buffer (marker-buffer marker))
19511 (pos (marker-position marker))
19512 (org-insert-labeled-timestamps-at-point nil)
19514 (org-with-remote-undo buffer
19515 (with-current-buffer buffer
19516 (widen)
19517 (goto-char pos)
19518 (setq ts (org-deadline))
19519 (message "Deadline for this item set to %s" ts)))))
19521 (defun org-get-heading ()
19522 "Return the heading of the current entry, without the stars."
19523 (save-excursion
19524 (org-back-to-heading t)
19525 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
19527 (defun org-agenda-clock-in (&optional arg)
19528 "Start the clock on the currently selected item."
19529 (interactive "P")
19530 (org-agenda-check-no-diary)
19531 (let* ((marker (or (get-text-property (point) 'org-marker)
19532 (org-agenda-error)))
19533 (pos (marker-position marker)))
19534 (org-with-remote-undo (marker-buffer marker)
19535 (with-current-buffer (marker-buffer marker)
19536 (widen)
19537 (goto-char pos)
19538 (org-clock-in)))))
19540 (defun org-agenda-clock-out (&optional arg)
19541 "Stop the currently running clock."
19542 (interactive "P")
19543 (unless (marker-buffer org-clock-marker)
19544 (error "No running clock"))
19545 (org-with-remote-undo (marker-buffer org-clock-marker)
19546 (org-clock-out)))
19548 (defun org-agenda-clock-cancel (&optional arg)
19549 "Cancel the currently running clock."
19550 (interactive "P")
19551 (unless (marker-buffer org-clock-marker)
19552 (error "No running clock"))
19553 (org-with-remote-undo (marker-buffer org-clock-marker)
19554 (org-clock-cancel)))
19556 (defun org-agenda-diary-entry ()
19557 "Make a diary entry, like the `i' command from the calendar.
19558 All the standard commands work: block, weekly etc."
19559 (interactive)
19560 (org-agenda-check-type t 'agenda 'timeline)
19561 (require 'diary-lib)
19562 (let* ((char (progn
19563 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
19564 (read-char-exclusive)))
19565 (cmd (cdr (assoc char
19566 '((?d . insert-diary-entry)
19567 (?w . insert-weekly-diary-entry)
19568 (?m . insert-monthly-diary-entry)
19569 (?y . insert-yearly-diary-entry)
19570 (?a . insert-anniversary-diary-entry)
19571 (?b . insert-block-diary-entry)
19572 (?c . insert-cyclic-diary-entry)))))
19573 (oldf (symbol-function 'calendar-cursor-to-date))
19574 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
19575 (point (point))
19576 (mark (or (mark t) (point))))
19577 (unless cmd
19578 (error "No command associated with <%c>" char))
19579 (unless (and (get-text-property point 'day)
19580 (or (not (equal ?b char))
19581 (get-text-property mark 'day)))
19582 (error "Don't know which date to use for diary entry"))
19583 ;; We implement this by hacking the `calendar-cursor-to-date' function
19584 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
19585 (let ((calendar-mark-ring
19586 (list (calendar-gregorian-from-absolute
19587 (or (get-text-property mark 'day)
19588 (get-text-property point 'day))))))
19589 (unwind-protect
19590 (progn
19591 (fset 'calendar-cursor-to-date
19592 (lambda (&optional error)
19593 (calendar-gregorian-from-absolute
19594 (get-text-property point 'day))))
19595 (call-interactively cmd))
19596 (fset 'calendar-cursor-to-date oldf)))))
19599 (defun org-agenda-execute-calendar-command (cmd)
19600 "Execute a calendar command from the agenda, with the date associated to
19601 the cursor position."
19602 (org-agenda-check-type t 'agenda 'timeline)
19603 (require 'diary-lib)
19604 (unless (get-text-property (point) 'day)
19605 (error "Don't know which date to use for calendar command"))
19606 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
19607 (point (point))
19608 (date (calendar-gregorian-from-absolute
19609 (get-text-property point 'day)))
19610 ;; the following 3 vars are needed in the calendar
19611 (displayed-day (extract-calendar-day date))
19612 (displayed-month (extract-calendar-month date))
19613 (displayed-year (extract-calendar-year date)))
19614 (unwind-protect
19615 (progn
19616 (fset 'calendar-cursor-to-date
19617 (lambda (&optional error)
19618 (calendar-gregorian-from-absolute
19619 (get-text-property point 'day))))
19620 (call-interactively cmd))
19621 (fset 'calendar-cursor-to-date oldf))))
19623 (defun org-agenda-phases-of-moon ()
19624 "Display the phases of the moon for the 3 months around the cursor date."
19625 (interactive)
19626 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
19628 (defun org-agenda-holidays ()
19629 "Display the holidays for the 3 months around the cursor date."
19630 (interactive)
19631 (org-agenda-execute-calendar-command 'list-calendar-holidays))
19633 (defun org-agenda-sunrise-sunset (arg)
19634 "Display sunrise and sunset for the cursor date.
19635 Latitude and longitude can be specified with the variables
19636 `calendar-latitude' and `calendar-longitude'. When called with prefix
19637 argument, latitude and longitude will be prompted for."
19638 (interactive "P")
19639 (let ((calendar-longitude (if arg nil calendar-longitude))
19640 (calendar-latitude (if arg nil calendar-latitude))
19641 (calendar-location-name
19642 (if arg "the given coordinates" calendar-location-name)))
19643 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
19645 (defun org-agenda-goto-calendar ()
19646 "Open the Emacs calendar with the date at the cursor."
19647 (interactive)
19648 (org-agenda-check-type t 'agenda 'timeline)
19649 (let* ((day (or (get-text-property (point) 'day)
19650 (error "Don't know which date to open in calendar")))
19651 (date (calendar-gregorian-from-absolute day))
19652 (calendar-move-hook nil)
19653 (view-calendar-holidays-initially nil)
19654 (view-diary-entries-initially nil))
19655 (calendar)
19656 (calendar-goto-date date)))
19658 (defun org-calendar-goto-agenda ()
19659 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
19660 This is a command that has to be installed in `calendar-mode-map'."
19661 (interactive)
19662 (org-agenda-list nil (calendar-absolute-from-gregorian
19663 (calendar-cursor-to-date))
19664 nil))
19666 (defun org-agenda-convert-date ()
19667 (interactive)
19668 (org-agenda-check-type t 'agenda 'timeline)
19669 (let ((day (get-text-property (point) 'day))
19670 date s)
19671 (unless day
19672 (error "Don't know which date to convert"))
19673 (setq date (calendar-gregorian-from-absolute day))
19674 (setq s (concat
19675 "Gregorian: " (calendar-date-string date) "\n"
19676 "ISO: " (calendar-iso-date-string date) "\n"
19677 "Day of Yr: " (calendar-day-of-year-string date) "\n"
19678 "Julian: " (calendar-julian-date-string date) "\n"
19679 "Astron. JD: " (calendar-astro-date-string date)
19680 " (Julian date number at noon UTC)\n"
19681 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
19682 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
19683 "French: " (calendar-french-date-string date) "\n"
19684 "Mayan: " (calendar-mayan-date-string date) "\n"
19685 "Coptic: " (calendar-coptic-date-string date) "\n"
19686 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
19687 "Persian: " (calendar-persian-date-string date) "\n"
19688 "Chinese: " (calendar-chinese-date-string date) "\n"))
19689 (with-output-to-temp-buffer "*Dates*"
19690 (princ s))
19691 (if (fboundp 'fit-window-to-buffer)
19692 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
19695 ;;;; Embedded LaTeX
19697 (defvar org-cdlatex-mode-map (make-sparse-keymap)
19698 "Keymap for the minor `org-cdlatex-mode'.")
19700 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
19701 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
19702 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
19703 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
19704 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
19706 (defvar org-cdlatex-texmathp-advice-is-done nil
19707 "Flag remembering if we have applied the advice to texmathp already.")
19709 (define-minor-mode org-cdlatex-mode
19710 "Toggle the minor `org-cdlatex-mode'.
19711 This mode supports entering LaTeX environment and math in LaTeX fragments
19712 in Org-mode.
19713 \\{org-cdlatex-mode-map}"
19714 nil " OCDL" nil
19715 (when org-cdlatex-mode (require 'cdlatex))
19716 (unless org-cdlatex-texmathp-advice-is-done
19717 (setq org-cdlatex-texmathp-advice-is-done t)
19718 (defadvice texmathp (around org-math-always-on activate)
19719 "Always return t in org-mode buffers.
19720 This is because we want to insert math symbols without dollars even outside
19721 the LaTeX math segments. If Orgmode thinks that point is actually inside
19722 en embedded LaTeX fragement, let texmathp do its job.
19723 \\[org-cdlatex-mode-map]"
19724 (interactive)
19725 (let (p)
19726 (cond
19727 ((not (org-mode-p)) ad-do-it)
19728 ((eq this-command 'cdlatex-math-symbol)
19729 (setq ad-return-value t
19730 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
19732 (let ((p (org-inside-LaTeX-fragment-p)))
19733 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
19734 (setq ad-return-value t
19735 texmathp-why '("Org-mode embedded math" . 0))
19736 (if p ad-do-it)))))))))
19738 (defun turn-on-org-cdlatex ()
19739 "Unconditionally turn on `org-cdlatex-mode'."
19740 (org-cdlatex-mode 1))
19742 (defun org-inside-LaTeX-fragment-p ()
19743 "Test if point is inside a LaTeX fragment.
19744 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19745 sequence appearing also before point.
19746 Even though the matchers for math are configurable, this function assumes
19747 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19748 delimiters are skipped when they have been removed by customization.
19749 The return value is nil, or a cons cell with the delimiter and
19750 and the position of this delimiter.
19752 This function does a reasonably good job, but can locally be fooled by
19753 for example currency specifications. For example it will assume being in
19754 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19755 fragments that are properly closed, but during editing, we have to live
19756 with the uncertainty caused by missing closing delimiters. This function
19757 looks only before point, not after."
19758 (catch 'exit
19759 (let ((pos (point))
19760 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19761 (lim (progn
19762 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19763 (point)))
19764 dd-on str (start 0) m re)
19765 (goto-char pos)
19766 (when dodollar
19767 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19768 re (nth 1 (assoc "$" org-latex-regexps)))
19769 (while (string-match re str start)
19770 (cond
19771 ((= (match-end 0) (length str))
19772 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19773 ((= (match-end 0) (- (length str) 5))
19774 (throw 'exit nil))
19775 (t (setq start (match-end 0))))))
19776 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19777 (goto-char pos)
19778 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19779 (and (match-beginning 2) (throw 'exit nil))
19780 ;; count $$
19781 (while (re-search-backward "\\$\\$" lim t)
19782 (setq dd-on (not dd-on)))
19783 (goto-char pos)
19784 (if dd-on (cons "$$" m))))))
19787 (defun org-try-cdlatex-tab ()
19788 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
19789 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
19790 - inside a LaTeX fragment, or
19791 - after the first word in a line, where an abbreviation expansion could
19792 insert a LaTeX environment."
19793 (when org-cdlatex-mode
19794 (cond
19795 ((save-excursion
19796 (skip-chars-backward "a-zA-Z0-9*")
19797 (skip-chars-backward " \t")
19798 (bolp))
19799 (cdlatex-tab) t)
19800 ((org-inside-LaTeX-fragment-p)
19801 (cdlatex-tab) t)
19802 (t nil))))
19804 (defun org-cdlatex-underscore-caret (&optional arg)
19805 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19806 Revert to the normal definition outside of these fragments."
19807 (interactive "P")
19808 (if (org-inside-LaTeX-fragment-p)
19809 (call-interactively 'cdlatex-sub-superscript)
19810 (let (org-cdlatex-mode)
19811 (call-interactively (key-binding (vector last-input-event))))))
19813 (defun org-cdlatex-math-modify (&optional arg)
19814 "Execute `cdlatex-math-modify' in LaTeX fragments.
19815 Revert to the normal definition outside of these fragments."
19816 (interactive "P")
19817 (if (org-inside-LaTeX-fragment-p)
19818 (call-interactively 'cdlatex-math-modify)
19819 (let (org-cdlatex-mode)
19820 (call-interactively (key-binding (vector last-input-event))))))
19822 (defvar org-latex-fragment-image-overlays nil
19823 "List of overlays carrying the images of latex fragments.")
19824 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
19826 (defun org-remove-latex-fragment-image-overlays ()
19827 "Remove all overlays with LaTeX fragment images in current buffer."
19828 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
19829 (setq org-latex-fragment-image-overlays nil))
19831 (defun org-preview-latex-fragment (&optional subtree)
19832 "Preview the LaTeX fragment at point, or all locally or globally.
19833 If the cursor is in a LaTeX fragment, create the image and overlay
19834 it over the source code. If there is no fragment at point, display
19835 all fragments in the current text, from one headline to the next. With
19836 prefix SUBTREE, display all fragments in the current subtree. With a
19837 double prefix `C-u C-u', or when the cursor is before the first headline,
19838 display all fragments in the buffer.
19839 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
19840 (interactive "P")
19841 (org-remove-latex-fragment-image-overlays)
19842 (save-excursion
19843 (save-restriction
19844 (let (beg end at msg)
19845 (cond
19846 ((or (equal subtree '(16))
19847 (not (save-excursion
19848 (re-search-backward (concat "^" outline-regexp) nil t))))
19849 (setq beg (point-min) end (point-max)
19850 msg "Creating images for buffer...%s"))
19851 ((equal subtree '(4))
19852 (org-back-to-heading)
19853 (setq beg (point) end (org-end-of-subtree t)
19854 msg "Creating images for subtree...%s"))
19856 (if (setq at (org-inside-LaTeX-fragment-p))
19857 (goto-char (max (point-min) (- (cdr at) 2)))
19858 (org-back-to-heading))
19859 (setq beg (point) end (progn (outline-next-heading) (point))
19860 msg (if at "Creating image...%s"
19861 "Creating images for entry...%s"))))
19862 (message msg "")
19863 (narrow-to-region beg end)
19864 (goto-char beg)
19865 (org-format-latex
19866 (concat "ltxpng/" (file-name-sans-extension
19867 (file-name-nondirectory
19868 buffer-file-name)))
19869 default-directory 'overlays msg at 'forbuffer)
19870 (message msg "done. Use `C-c C-c' to remove images.")))))
19872 (defvar org-latex-regexps
19873 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
19874 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
19875 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
19876 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
19877 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
19878 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
19879 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
19880 "Regular expressions for matching embedded LaTeX.")
19882 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
19883 "Replace LaTeX fragments with links to an image, and produce images."
19884 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19885 (let* ((prefixnodir (file-name-nondirectory prefix))
19886 (absprefix (expand-file-name prefix dir))
19887 (todir (file-name-directory absprefix))
19888 (opt org-format-latex-options)
19889 (matchers (plist-get opt :matchers))
19890 (re-list org-latex-regexps)
19891 (cnt 0) txt link beg end re e checkdir
19892 m n block linkfile movefile ov)
19893 ;; Check if there are old images files with this prefix, and remove them
19894 (when (file-directory-p todir)
19895 (mapc 'delete-file
19896 (directory-files
19897 todir 'full
19898 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
19899 ;; Check the different regular expressions
19900 (while (setq e (pop re-list))
19901 (setq m (car e) re (nth 1 e) n (nth 2 e)
19902 block (if (nth 3 e) "\n\n" ""))
19903 (when (member m matchers)
19904 (goto-char (point-min))
19905 (while (re-search-forward re nil t)
19906 (when (or (not at) (equal (cdr at) (match-beginning n)))
19907 (setq txt (match-string n)
19908 beg (match-beginning n) end (match-end n)
19909 cnt (1+ cnt)
19910 linkfile (format "%s_%04d.png" prefix cnt)
19911 movefile (format "%s_%04d.png" absprefix cnt)
19912 link (concat block "[[file:" linkfile "]]" block))
19913 (if msg (message msg cnt))
19914 (goto-char beg)
19915 (unless checkdir ; make sure the directory exists
19916 (setq checkdir t)
19917 (or (file-directory-p todir) (make-directory todir)))
19918 (org-create-formula-image
19919 txt movefile opt forbuffer)
19920 (if overlays
19921 (progn
19922 (setq ov (org-make-overlay beg end))
19923 (if (featurep 'xemacs)
19924 (progn
19925 (org-overlay-put ov 'invisible t)
19926 (org-overlay-put
19927 ov 'end-glyph
19928 (make-glyph (vector 'png :file movefile))))
19929 (org-overlay-put
19930 ov 'display
19931 (list 'image :type 'png :file movefile :ascent 'center)))
19932 (push ov org-latex-fragment-image-overlays)
19933 (goto-char end))
19934 (delete-region beg end)
19935 (insert link))))))))
19937 ;; This function borrows from Ganesh Swami's latex2png.el
19938 (defun org-create-formula-image (string tofile options buffer)
19939 (let* ((tmpdir (if (featurep 'xemacs)
19940 (temp-directory)
19941 temporary-file-directory))
19942 (texfilebase (make-temp-name
19943 (expand-file-name "orgtex" tmpdir)))
19944 (texfile (concat texfilebase ".tex"))
19945 (dvifile (concat texfilebase ".dvi"))
19946 (pngfile (concat texfilebase ".png"))
19947 (fnh (face-attribute 'default :height nil))
19948 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19949 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
19950 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19951 "Black"))
19952 (bg (or (plist-get options (if buffer :background :html-background))
19953 "Transparent")))
19954 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
19955 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
19956 (with-temp-file texfile
19957 (insert org-format-latex-header
19958 "\n\\begin{document}\n" string "\n\\end{document}\n"))
19959 (let ((dir default-directory))
19960 (condition-case nil
19961 (progn
19962 (cd tmpdir)
19963 (call-process "latex" nil nil nil texfile))
19964 (error nil))
19965 (cd dir))
19966 (if (not (file-exists-p dvifile))
19967 (progn (message "Failed to create dvi file from %s" texfile) nil)
19968 (call-process "dvipng" nil nil nil
19969 "-E" "-fg" fg "-bg" bg
19970 "-D" dpi
19971 ;;"-x" scale "-y" scale
19972 "-T" "tight"
19973 "-o" pngfile
19974 dvifile)
19975 (if (not (file-exists-p pngfile))
19976 (progn (message "Failed to create png file from %s" texfile) nil)
19977 ;; Use the requested file name and clean up
19978 (copy-file pngfile tofile 'replace)
19979 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
19980 (delete-file (concat texfilebase e)))
19981 pngfile))))
19983 (defun org-dvipng-color (attr)
19984 "Return an rgb color specification for dvipng."
19985 (apply 'format "rgb %s %s %s"
19986 (mapcar 'org-normalize-color
19987 (color-values (face-attribute 'default attr nil)))))
19989 (defun org-normalize-color (value)
19990 "Return string to be used as color value for an RGB component."
19991 (format "%g" (/ value 65535.0)))
19993 ;;;; Exporting
19995 ;;; Variables, constants, and parameter plists
19997 (defconst org-level-max 20)
19999 (defvar org-export-html-preamble nil
20000 "Preamble, to be inserted just after <body>. Set by publishing functions.")
20001 (defvar org-export-html-postamble nil
20002 "Preamble, to be inserted just before </body>. Set by publishing functions.")
20003 (defvar org-export-html-auto-preamble t
20004 "Should default preamble be inserted? Set by publishing functions.")
20005 (defvar org-export-html-auto-postamble t
20006 "Should default postamble be inserted? Set by publishing functions.")
20007 (defvar org-current-export-file nil) ; dynamically scoped parameter
20008 (defvar org-current-export-dir nil) ; dynamically scoped parameter
20011 (defconst org-export-plist-vars
20012 '((:language . org-export-default-language)
20013 (:customtime . org-display-custom-times)
20014 (:headline-levels . org-export-headline-levels)
20015 (:section-numbers . org-export-with-section-numbers)
20016 (:table-of-contents . org-export-with-toc)
20017 (:preserve-breaks . org-export-preserve-breaks)
20018 (:archived-trees . org-export-with-archived-trees)
20019 (:emphasize . org-export-with-emphasize)
20020 (:sub-superscript . org-export-with-sub-superscripts)
20021 (:footnotes . org-export-with-footnotes)
20022 (:property-drawer . org-export-with-property-drawer)
20023 (:TeX-macros . org-export-with-TeX-macros)
20024 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
20025 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
20026 (:fixed-width . org-export-with-fixed-width)
20027 (:timestamps . org-export-with-timestamps)
20028 (:author-info . org-export-author-info)
20029 (:time-stamp-file . org-export-time-stamp-file)
20030 (:tables . org-export-with-tables)
20031 (:table-auto-headline . org-export-highlight-first-table-line)
20032 (:style . org-export-html-style)
20033 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
20034 (:convert-org-links . org-export-html-link-org-files-as-html)
20035 (:inline-images . org-export-html-inline-images)
20036 (:expand-quoted-html . org-export-html-expand)
20037 (:timestamp . org-export-html-with-timestamp)
20038 (:publishing-directory . org-export-publishing-directory)
20039 (:preamble . org-export-html-preamble)
20040 (:postamble . org-export-html-postamble)
20041 (:auto-preamble . org-export-html-auto-preamble)
20042 (:auto-postamble . org-export-html-auto-postamble)
20043 (:author . user-full-name)
20044 (:email . user-mail-address)))
20046 (defun org-default-export-plist ()
20047 "Return the property list with default settings for the export variables."
20048 (let ((l org-export-plist-vars) rtn e)
20049 (while (setq e (pop l))
20050 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
20051 rtn))
20053 (defun org-infile-export-plist ()
20054 "Return the property list with file-local settings for export."
20055 (save-excursion
20056 (goto-char 0)
20057 (let ((re (org-make-options-regexp
20058 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
20059 p key val text options)
20060 (while (re-search-forward re nil t)
20061 (setq key (org-match-string-no-properties 1)
20062 val (org-match-string-no-properties 2))
20063 (cond
20064 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
20065 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
20066 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
20067 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
20068 ((string-equal key "TEXT")
20069 (setq text (if text (concat text "\n" val) val)))
20070 ((string-equal key "OPTIONS") (setq options val))))
20071 (setq p (plist-put p :text text))
20072 (when options
20073 (let ((op '(("H" . :headline-levels)
20074 ("num" . :section-numbers)
20075 ("toc" . :table-of-contents)
20076 ("\\n" . :preserve-breaks)
20077 ("@" . :expand-quoted-html)
20078 (":" . :fixed-width)
20079 ("|" . :tables)
20080 ("^" . :sub-superscript)
20081 ("f" . :footnotes)
20082 ("p" . :property-drawer)
20083 ("*" . :emphasize)
20084 ("TeX" . :TeX-macros)
20085 ("LaTeX" . :LaTeX-fragments)
20086 ("skip" . :skip-before-1st-heading)
20087 ("author" . :author-info)
20088 ("timestamp" . :time-stamp-file)))
20090 (while (setq o (pop op))
20091 (if (string-match (concat (regexp-quote (car o))
20092 ":\\([^ \t\n\r;,.]*\\)")
20093 options)
20094 (setq p (plist-put p (cdr o)
20095 (car (read-from-string
20096 (match-string 1 options)))))))))
20097 p)))
20099 (defun org-export-directory (type plist)
20100 (let* ((val (plist-get plist :publishing-directory))
20101 (dir (if (listp val)
20102 (or (cdr (assoc type val)) ".")
20103 val)))
20104 dir))
20106 (defun org-skip-comments (lines)
20107 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
20108 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
20109 (re2 "^\\(\\*+\\)[ \t\n\r]")
20110 (case-fold-search nil)
20111 rtn line level)
20112 (while (setq line (pop lines))
20113 (cond
20114 ((and (string-match re1 line)
20115 (setq level (- (match-end 1) (match-beginning 1))))
20116 ;; Beginning of a COMMENT subtree. Skip it.
20117 (while (and (setq line (pop lines))
20118 (or (not (string-match re2 line))
20119 (> (- (match-end 1) (match-beginning 1)) level))))
20120 (setq lines (cons line lines)))
20121 ((string-match "^#" line)
20122 ;; an ordinary comment line
20124 ((and org-export-table-remove-special-lines
20125 (string-match "^[ \t]*|" line)
20126 (or (string-match "^[ \t]*| *[!_^] *|" line)
20127 (and (string-match "| *<[0-9]+> *|" line)
20128 (not (string-match "| *[^ <|]" line)))))
20129 ;; a special table line that should be removed
20131 (t (setq rtn (cons line rtn)))))
20132 (nreverse rtn)))
20134 (defun org-export (&optional arg)
20135 (interactive)
20136 (let ((help "[t] insert the export option template
20137 \[v] limit export to visible part of outline tree
20139 \[a] export as ASCII
20141 \[h] export as HTML
20142 \[H] export as HTML to temporary buffer
20143 \[R] export region as HTML
20144 \[b] export as HTML and browse immediately
20145 \[x] export as XOXO
20147 \[l] export as LaTeX
20148 \[L] export as LaTeX to temporary buffer
20150 \[i] export current file as iCalendar file
20151 \[I] export all agenda files as iCalendar files
20152 \[c] export agenda files into combined iCalendar file
20154 \[F] publish current file
20155 \[P] publish current project
20156 \[X] publish... (project will be prompted for)
20157 \[A] publish all projects")
20158 (cmds
20159 '((?t . org-insert-export-options-template)
20160 (?v . org-export-visible)
20161 (?a . org-export-as-ascii)
20162 (?h . org-export-as-html)
20163 (?b . org-export-as-html-and-open)
20164 (?H . org-export-as-html-to-buffer)
20165 (?R . org-export-region-as-html)
20166 (?x . org-export-as-xoxo)
20167 (?l . org-export-as-latex)
20168 (?L . org-export-as-latex-to-buffer)
20169 (?i . org-export-icalendar-this-file)
20170 (?I . org-export-icalendar-all-agenda-files)
20171 (?c . org-export-icalendar-combine-agenda-files)
20172 (?F . org-publish-current-file)
20173 (?P . org-publish-current-project)
20174 (?X . org-publish)
20175 (?A . org-publish-all)))
20176 r1 r2 ass)
20177 (save-window-excursion
20178 (delete-other-windows)
20179 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
20180 (princ help))
20181 (message "Select command: ")
20182 (setq r1 (read-char-exclusive)))
20183 (setq r2 (if (< r1 27) (+ r1 96) r1))
20184 (if (setq ass (assq r2 cmds))
20185 (call-interactively (cdr ass))
20186 (error "No command associated with key %c" r1))))
20188 (defconst org-html-entities
20189 '(("nbsp")
20190 ("iexcl")
20191 ("cent")
20192 ("pound")
20193 ("curren")
20194 ("yen")
20195 ("brvbar")
20196 ("vert" . "&#124;")
20197 ("sect")
20198 ("uml")
20199 ("copy")
20200 ("ordf")
20201 ("laquo")
20202 ("not")
20203 ("shy")
20204 ("reg")
20205 ("macr")
20206 ("deg")
20207 ("plusmn")
20208 ("sup2")
20209 ("sup3")
20210 ("acute")
20211 ("micro")
20212 ("para")
20213 ("middot")
20214 ("odot"."o")
20215 ("star"."*")
20216 ("cedil")
20217 ("sup1")
20218 ("ordm")
20219 ("raquo")
20220 ("frac14")
20221 ("frac12")
20222 ("frac34")
20223 ("iquest")
20224 ("Agrave")
20225 ("Aacute")
20226 ("Acirc")
20227 ("Atilde")
20228 ("Auml")
20229 ("Aring") ("AA"."&Aring;")
20230 ("AElig")
20231 ("Ccedil")
20232 ("Egrave")
20233 ("Eacute")
20234 ("Ecirc")
20235 ("Euml")
20236 ("Igrave")
20237 ("Iacute")
20238 ("Icirc")
20239 ("Iuml")
20240 ("ETH")
20241 ("Ntilde")
20242 ("Ograve")
20243 ("Oacute")
20244 ("Ocirc")
20245 ("Otilde")
20246 ("Ouml")
20247 ("times")
20248 ("Oslash")
20249 ("Ugrave")
20250 ("Uacute")
20251 ("Ucirc")
20252 ("Uuml")
20253 ("Yacute")
20254 ("THORN")
20255 ("szlig")
20256 ("agrave")
20257 ("aacute")
20258 ("acirc")
20259 ("atilde")
20260 ("auml")
20261 ("aring")
20262 ("aelig")
20263 ("ccedil")
20264 ("egrave")
20265 ("eacute")
20266 ("ecirc")
20267 ("euml")
20268 ("igrave")
20269 ("iacute")
20270 ("icirc")
20271 ("iuml")
20272 ("eth")
20273 ("ntilde")
20274 ("ograve")
20275 ("oacute")
20276 ("ocirc")
20277 ("otilde")
20278 ("ouml")
20279 ("divide")
20280 ("oslash")
20281 ("ugrave")
20282 ("uacute")
20283 ("ucirc")
20284 ("uuml")
20285 ("yacute")
20286 ("thorn")
20287 ("yuml")
20288 ("fnof")
20289 ("Alpha")
20290 ("Beta")
20291 ("Gamma")
20292 ("Delta")
20293 ("Epsilon")
20294 ("Zeta")
20295 ("Eta")
20296 ("Theta")
20297 ("Iota")
20298 ("Kappa")
20299 ("Lambda")
20300 ("Mu")
20301 ("Nu")
20302 ("Xi")
20303 ("Omicron")
20304 ("Pi")
20305 ("Rho")
20306 ("Sigma")
20307 ("Tau")
20308 ("Upsilon")
20309 ("Phi")
20310 ("Chi")
20311 ("Psi")
20312 ("Omega")
20313 ("alpha")
20314 ("beta")
20315 ("gamma")
20316 ("delta")
20317 ("epsilon")
20318 ("varepsilon"."&epsilon;")
20319 ("zeta")
20320 ("eta")
20321 ("theta")
20322 ("iota")
20323 ("kappa")
20324 ("lambda")
20325 ("mu")
20326 ("nu")
20327 ("xi")
20328 ("omicron")
20329 ("pi")
20330 ("rho")
20331 ("sigmaf") ("varsigma"."&sigmaf;")
20332 ("sigma")
20333 ("tau")
20334 ("upsilon")
20335 ("phi")
20336 ("chi")
20337 ("psi")
20338 ("omega")
20339 ("thetasym") ("vartheta"."&thetasym;")
20340 ("upsih")
20341 ("piv")
20342 ("bull") ("bullet"."&bull;")
20343 ("hellip") ("dots"."&hellip;")
20344 ("prime")
20345 ("Prime")
20346 ("oline")
20347 ("frasl")
20348 ("weierp")
20349 ("image")
20350 ("real")
20351 ("trade")
20352 ("alefsym")
20353 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
20354 ("uarr") ("uparrow"."&uarr;")
20355 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
20356 ("darr")("downarrow"."&darr;")
20357 ("harr") ("leftrightarrow"."&harr;")
20358 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
20359 ("lArr") ("Leftarrow"."&lArr;")
20360 ("uArr") ("Uparrow"."&uArr;")
20361 ("rArr") ("Rightarrow"."&rArr;")
20362 ("dArr") ("Downarrow"."&dArr;")
20363 ("hArr") ("Leftrightarrow"."&hArr;")
20364 ("forall")
20365 ("part") ("partial"."&part;")
20366 ("exist") ("exists"."&exist;")
20367 ("empty") ("emptyset"."&empty;")
20368 ("nabla")
20369 ("isin") ("in"."&isin;")
20370 ("notin")
20371 ("ni")
20372 ("prod")
20373 ("sum")
20374 ("minus")
20375 ("lowast") ("ast"."&lowast;")
20376 ("radic")
20377 ("prop") ("proptp"."&prop;")
20378 ("infin") ("infty"."&infin;")
20379 ("ang") ("angle"."&ang;")
20380 ("and") ("vee"."&and;")
20381 ("or") ("wedge"."&or;")
20382 ("cap")
20383 ("cup")
20384 ("int")
20385 ("there4")
20386 ("sim")
20387 ("cong") ("simeq"."&cong;")
20388 ("asymp")("approx"."&asymp;")
20389 ("ne") ("neq"."&ne;")
20390 ("equiv")
20391 ("le")
20392 ("ge")
20393 ("sub") ("subset"."&sub;")
20394 ("sup") ("supset"."&sup;")
20395 ("nsub")
20396 ("sube")
20397 ("supe")
20398 ("oplus")
20399 ("otimes")
20400 ("perp")
20401 ("sdot") ("cdot"."&sdot;")
20402 ("lceil")
20403 ("rceil")
20404 ("lfloor")
20405 ("rfloor")
20406 ("lang")
20407 ("rang")
20408 ("loz") ("Diamond"."&loz;")
20409 ("spades") ("spadesuit"."&spades;")
20410 ("clubs") ("clubsuit"."&clubs;")
20411 ("hearts") ("diamondsuit"."&hearts;")
20412 ("diams") ("diamondsuit"."&diams;")
20413 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
20414 ("quot")
20415 ("amp")
20416 ("lt")
20417 ("gt")
20418 ("OElig")
20419 ("oelig")
20420 ("Scaron")
20421 ("scaron")
20422 ("Yuml")
20423 ("circ")
20424 ("tilde")
20425 ("ensp")
20426 ("emsp")
20427 ("thinsp")
20428 ("zwnj")
20429 ("zwj")
20430 ("lrm")
20431 ("rlm")
20432 ("ndash")
20433 ("mdash")
20434 ("lsquo")
20435 ("rsquo")
20436 ("sbquo")
20437 ("ldquo")
20438 ("rdquo")
20439 ("bdquo")
20440 ("dagger")
20441 ("Dagger")
20442 ("permil")
20443 ("lsaquo")
20444 ("rsaquo")
20445 ("euro")
20447 ("arccos"."arccos")
20448 ("arcsin"."arcsin")
20449 ("arctan"."arctan")
20450 ("arg"."arg")
20451 ("cos"."cos")
20452 ("cosh"."cosh")
20453 ("cot"."cot")
20454 ("coth"."coth")
20455 ("csc"."csc")
20456 ("deg"."deg")
20457 ("det"."det")
20458 ("dim"."dim")
20459 ("exp"."exp")
20460 ("gcd"."gcd")
20461 ("hom"."hom")
20462 ("inf"."inf")
20463 ("ker"."ker")
20464 ("lg"."lg")
20465 ("lim"."lim")
20466 ("liminf"."liminf")
20467 ("limsup"."limsup")
20468 ("ln"."ln")
20469 ("log"."log")
20470 ("max"."max")
20471 ("min"."min")
20472 ("Pr"."Pr")
20473 ("sec"."sec")
20474 ("sin"."sin")
20475 ("sinh"."sinh")
20476 ("sup"."sup")
20477 ("tan"."tan")
20478 ("tanh"."tanh")
20480 "Entities for TeX->HTML translation.
20481 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
20482 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
20483 In that case, \"\\ent\" will be translated to \"&other;\".
20484 The list contains HTML entities for Latin-1, Greek and other symbols.
20485 It is supplemented by a number of commonly used TeX macros with appropriate
20486 translations. There is currently no way for users to extend this.")
20488 ;;; General functions for all backends
20490 (defun org-cleaned-string-for-export (string &rest parameters)
20491 "Cleanup a buffer STRING so that links can be created safely."
20492 (interactive)
20493 (let* ((re-radio (and org-target-link-regexp
20494 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
20495 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
20496 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
20497 (re-archive (concat ":" org-archive-tag ":"))
20498 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
20499 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
20500 (htmlp (plist-get parameters :for-html))
20501 (asciip (plist-get parameters :for-ascii))
20502 (latexp (plist-get parameters :for-LaTeX))
20503 (commentsp (plist-get parameters :comments))
20504 (inhibit-read-only t)
20505 (outline-regexp "\\*+ ")
20506 a b xx
20507 rtn p)
20508 (with-current-buffer (get-buffer-create " org-mode-tmp")
20509 (erase-buffer)
20510 (insert string)
20511 ;; Remove license-to-kill stuff
20512 (while (setq p (text-property-any (point-min) (point-max)
20513 :org-license-to-kill t))
20514 (delete-region p (next-single-property-change p :org-license-to-kill)))
20516 (let ((org-inhibit-startup t)) (org-mode))
20517 (untabify (point-min) (point-max))
20519 ;; Get the correct stuff before the first headline
20520 (when (plist-get parameters :skip-before-1st-heading)
20521 (goto-char (point-min))
20522 (when (re-search-forward "^\\*+[ \t]" nil t)
20523 (delete-region (point-min) (match-beginning 0))
20524 (goto-char (point-min))
20525 (insert "\n")))
20526 (when (plist-get parameters :add-text)
20527 (goto-char (point-min))
20528 (insert (plist-get parameters :add-text) "\n"))
20530 ;; Get rid of archived trees
20531 (when (not (eq org-export-with-archived-trees t))
20532 (goto-char (point-min))
20533 (while (re-search-forward re-archive nil t)
20534 (if (not (org-on-heading-p t))
20535 (org-end-of-subtree t)
20536 (beginning-of-line 1)
20537 (setq a (if org-export-with-archived-trees
20538 (1+ (point-at-eol)) (point))
20539 b (org-end-of-subtree t))
20540 (if (> b a) (delete-region a b)))))
20542 ;; Get rid of property drawers
20543 (unless org-export-with-property-drawer
20544 (goto-char (point-min))
20545 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
20546 (replace-match "")))
20548 ;; Find targets in comments and move them out of comments,
20549 ;; but mark them as targets that should be invisible
20550 (goto-char (point-min))
20551 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
20552 (replace-match "\\1(INVISIBLE)"))
20554 ;; Protect backend specific stuff, throw away the others.
20555 (goto-char (point-min))
20556 (let ((formatters
20557 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
20558 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
20559 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
20560 fmt)
20561 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
20562 (add-text-properties (match-beginning 0) (match-end 0)
20563 '(org-protected t)))
20564 (while formatters
20565 (setq fmt (pop formatters))
20566 (when (car fmt)
20567 (goto-char (point-min))
20568 (while (re-search-forward (concat "^#\\+" (cadr fmt)
20569 ":[ \t]*\\(.*\\)") nil t)
20570 (replace-match "\\1" t)
20571 (add-text-properties
20572 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
20573 '(org-protected t))))
20574 (goto-char (point-min))
20575 (while (re-search-forward
20576 (concat "^#\\+"
20577 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
20578 (cadddr fmt) "\\>.*\n?") nil t)
20579 (if (car fmt)
20580 (add-text-properties (match-beginning 1) (1+ (match-end 1))
20581 '(org-protected t))
20582 (delete-region (match-beginning 0) (match-end 0))))))
20584 ;; Protect quoted subtreedes
20585 (goto-char (point-min))
20586 (while (re-search-forward re-quote nil t)
20587 (goto-char (match-beginning 0))
20588 (end-of-line 1)
20589 (add-text-properties (point) (org-end-of-subtree t)
20590 '(org-protected t)))
20592 ;; Remove subtrees that are commented
20593 (goto-char (point-min))
20594 (while (re-search-forward re-commented nil t)
20595 (goto-char (match-beginning 0))
20596 (delete-region (point) (org-end-of-subtree t)))
20598 ;; Remove special table lines
20599 (when org-export-table-remove-special-lines
20600 (goto-char (point-min))
20601 (while (re-search-forward "^[ \t]*|" nil t)
20602 (beginning-of-line 1)
20603 (if (or (looking-at "[ \t]*| *[!_^] *|")
20604 (and (looking-at ".*?| *<[0-9]+> *|")
20605 (not (looking-at ".*?| *[^ <|]"))))
20606 (delete-region (max (point-min) (1- (point-at-bol)))
20607 (point-at-eol))
20608 (end-of-line 1))))
20610 ;; Specific LaTeX cleaning
20611 (when latexp
20612 (require 'org-export-latex nil t)
20613 (org-export-latex-cleaned-string))
20615 ;; Remove or replace comments
20616 ;; If :comments is set, use this char for commenting out comments and
20617 ;; protect them. otherwise delete them
20618 (goto-char (point-min))
20619 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
20620 (if commentsp
20621 (progn (add-text-properties
20622 (match-beginning 0) (match-end 0) '(org-protected t))
20623 (replace-match (format commentsp (match-string 1)) t t))
20624 (replace-match "")))
20626 ;; Find matches for radio targets and turn them into internal links
20627 (goto-char (point-min))
20628 (when re-radio
20629 (while (re-search-forward re-radio nil t)
20630 (org-if-unprotected
20631 (replace-match "\\1[[\\2]]"))))
20633 ;; Find all links that contain a newline and put them into a single line
20634 (goto-char (point-min))
20635 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
20636 (org-if-unprotected
20637 (replace-match "\\1 \\3")
20638 (goto-char (match-beginning 0))))
20640 ;; Convert LaTeX fragments to images
20641 (when (plist-get parameters :LaTeX-fragments)
20642 (org-format-latex
20643 (concat "ltxpng/" (file-name-sans-extension
20644 (file-name-nondirectory
20645 org-current-export-file)))
20646 org-current-export-dir nil "Creating LaTeX image %s"))
20647 (message "Exporting...")
20649 ;; Normalize links: Convert angle and plain links into bracket links
20650 ;; Expand link abbreviations
20651 (goto-char (point-min))
20652 (while (re-search-forward re-plain-link nil t)
20653 (goto-char (1- (match-end 0)))
20654 (org-if-unprotected
20655 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20656 ":" (match-string 3) "]]")))
20657 ;; added 'org-link face to links
20658 (put-text-property 0 (length s) 'face 'org-link s)
20659 (replace-match s t t))))
20660 (goto-char (point-min))
20661 (while (re-search-forward re-angle-link nil t)
20662 (goto-char (1- (match-end 0)))
20663 (org-if-unprotected
20664 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20665 ":" (match-string 3) "]]")))
20666 (put-text-property 0 (length s) 'face 'org-link s)
20667 (replace-match s t t))))
20668 (goto-char (point-min))
20669 (while (re-search-forward org-bracket-link-regexp nil t)
20670 (org-if-unprotected
20671 (let* ((s (concat "[[" (setq xx (save-match-data
20672 (org-link-expand-abbrev (match-string 1))))
20674 (if (match-end 3)
20675 (match-string 2)
20676 (concat "[" xx "]"))
20677 "]")))
20678 (put-text-property 0 (length s) 'face 'org-link s)
20679 (replace-match s t t))))
20681 ;; Find multiline emphasis and put them into single line
20682 (when (plist-get parameters :emph-multiline)
20683 (goto-char (point-min))
20684 (while (re-search-forward org-emph-re nil t)
20685 (if (not (= (char-after (match-beginning 3))
20686 (char-after (match-beginning 4))))
20687 (org-if-unprotected
20688 (subst-char-in-region (match-beginning 0) (match-end 0)
20689 ?\n ?\ t)
20690 (goto-char (1- (match-end 0))))
20691 (goto-char (1+ (match-beginning 0))))))
20693 (setq rtn (buffer-string)))
20694 (kill-buffer " org-mode-tmp")
20695 rtn))
20697 (defun org-export-grab-title-from-buffer ()
20698 "Get a title for the current document, from looking at the buffer."
20699 (let ((inhibit-read-only t))
20700 (save-excursion
20701 (goto-char (point-min))
20702 (let ((end (save-excursion (outline-next-heading) (point))))
20703 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
20704 ;; Mark the line so that it will not be exported as normal text.
20705 (org-unmodified
20706 (add-text-properties (match-beginning 0) (match-end 0)
20707 (list :org-license-to-kill t)))
20708 ;; Return the title string
20709 (org-trim (match-string 0)))))))
20711 (defun org-solidify-link-text (s &optional alist)
20712 "Take link text and make a safe target out of it."
20713 (save-match-data
20714 (let* ((rtn
20715 (mapconcat
20716 'identity
20717 (org-split-string s "[ \t\r\n]+") "--"))
20718 (a (assoc rtn alist)))
20719 (or (cdr a) rtn))))
20721 ;; Variable holding the vector with section numbers
20722 (defvar org-section-numbers (make-vector org-level-max 0))
20724 (defun org-init-section-numbers ()
20725 "Initialize the vector for the section numbers."
20726 (let* ((level -1)
20727 (numbers (nreverse (org-split-string "" "\\.")))
20728 (depth (1- (length org-section-numbers)))
20729 (i depth) number-string)
20730 (while (>= i 0)
20731 (if (> i level)
20732 (aset org-section-numbers i 0)
20733 (setq number-string (or (car numbers) "0"))
20734 (if (string-match "\\`[A-Z]\\'" number-string)
20735 (aset org-section-numbers i
20736 (- (string-to-char number-string) ?A -1))
20737 (aset org-section-numbers i (string-to-number number-string)))
20738 (pop numbers))
20739 (setq i (1- i)))))
20741 (defun org-section-number (&optional level)
20742 "Return a string with the current section number.
20743 When LEVEL is non-nil, increase section numbers on that level."
20744 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
20745 (when level
20746 (when (> level -1)
20747 (aset org-section-numbers
20748 level (1+ (aref org-section-numbers level))))
20749 (setq idx (1+ level))
20750 (while (<= idx depth)
20751 (if (not (= idx 1))
20752 (aset org-section-numbers idx 0))
20753 (setq idx (1+ idx))))
20754 (setq idx 0)
20755 (while (<= idx depth)
20756 (setq n (aref org-section-numbers idx))
20757 (setq string (concat string (if (not (string= string "")) "." "")
20758 (int-to-string n)))
20759 (setq idx (1+ idx)))
20760 (save-match-data
20761 (if (string-match "\\`\\([@0]\\.\\)+" string)
20762 (setq string (replace-match "" t nil string)))
20763 (if (string-match "\\(\\.0\\)+\\'" string)
20764 (setq string (replace-match "" t nil string))))
20765 string))
20767 ;;; ASCII export
20769 (defvar org-last-level nil) ; dynamically scoped variable
20770 (defvar org-levels-open nil) ; dynamically scoped parameter
20771 (defvar org-ascii-current-indentation nil) ; For communication
20773 (defun org-export-as-ascii (arg)
20774 "Export the outline as a pretty ASCII file.
20775 If there is an active region, export only the region.
20776 The prefix ARG specifies how many levels of the outline should become
20777 underlined headlines. The default is 3."
20778 (interactive "P")
20779 (setq-default org-todo-line-regexp org-todo-line-regexp)
20780 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20781 (org-infile-export-plist)))
20782 (custom-times org-display-custom-times)
20783 (org-ascii-current-indentation '(0 . 0))
20784 (level 0) line txt
20785 (umax nil)
20786 (umax-toc nil)
20787 (case-fold-search nil)
20788 (filename (concat (file-name-as-directory
20789 (org-export-directory :ascii opt-plist))
20790 (file-name-sans-extension
20791 (file-name-nondirectory buffer-file-name))
20792 ".txt"))
20793 (filename (if (equal (file-truename filename)
20794 (file-truename buffer-file-name))
20795 (concat filename ".txt")
20796 filename))
20797 (buffer (find-file-noselect filename))
20798 (org-levels-open (make-vector org-level-max nil))
20799 (odd org-odd-levels-only)
20800 (date (format-time-string "%Y/%m/%d" (current-time)))
20801 (time (format-time-string "%X" (org-current-time)))
20802 (author (plist-get opt-plist :author))
20803 (title (or (plist-get opt-plist :title)
20804 (and (not
20805 (plist-get opt-plist :skip-before-1st-heading))
20806 (org-export-grab-title-from-buffer))
20807 (file-name-sans-extension
20808 (file-name-nondirectory buffer-file-name))))
20809 (email (plist-get opt-plist :email))
20810 (language (plist-get opt-plist :language))
20811 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
20812 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
20813 (todo nil)
20814 (lang-words nil)
20815 (region
20816 (buffer-substring
20817 (if (org-region-active-p) (region-beginning) (point-min))
20818 (if (org-region-active-p) (region-end) (point-max))))
20819 (lines (org-split-string
20820 (org-cleaned-string-for-export
20821 region
20822 :for-ascii t
20823 :skip-before-1st-heading
20824 (plist-get opt-plist :skip-before-1st-heading)
20825 :add-text (plist-get opt-plist :text))
20826 "[\r\n]")) ;; FIXME: why \r here???/
20827 thetoc have-headings first-heading-pos
20828 table-open table-buffer)
20830 (let ((inhibit-read-only t))
20831 (org-unmodified
20832 (remove-text-properties (point-min) (point-max)
20833 '(:org-license-to-kill t))))
20835 (setq org-last-level 1)
20836 (org-init-section-numbers)
20838 (find-file-noselect filename)
20840 (setq lang-words (or (assoc language org-export-language-setup)
20841 (assoc "en" org-export-language-setup)))
20842 (switch-to-buffer-other-window buffer)
20843 (erase-buffer)
20844 (fundamental-mode)
20845 ;; create local variables for all options, to make sure all called
20846 ;; functions get the correct information
20847 (mapcar (lambda (x)
20848 (set (make-local-variable (cdr x))
20849 (plist-get opt-plist (car x))))
20850 org-export-plist-vars)
20851 (org-set-local 'org-odd-levels-only odd)
20852 (setq umax (if arg (prefix-numeric-value arg)
20853 org-export-headline-levels))
20854 (setq umax-toc (if (integerp org-export-with-toc)
20855 (min org-export-with-toc umax)
20856 umax))
20858 ;; File header
20859 (if title (org-insert-centered title ?=))
20860 (insert "\n")
20861 (if (and (or author email)
20862 org-export-author-info)
20863 (insert (concat (nth 1 lang-words) ": " (or author "")
20864 (if email (concat " <" email ">") "")
20865 "\n")))
20866 (if (and date time org-export-time-stamp-file)
20867 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
20869 (insert "\n\n")
20871 (if org-export-with-toc
20872 (progn
20873 (push (concat (nth 3 lang-words) "\n") thetoc)
20874 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
20875 (mapcar '(lambda (line)
20876 (if (string-match org-todo-line-regexp
20877 line)
20878 ;; This is a headline
20879 (progn
20880 (setq have-headings t)
20881 (setq level (- (match-end 1) (match-beginning 1))
20882 level (org-tr-level level)
20883 txt (match-string 3 line)
20884 todo
20885 (or (and org-export-mark-todo-in-toc
20886 (match-beginning 2)
20887 (not (member (match-string 2 line)
20888 org-done-keywords)))
20889 ; TODO, not DONE
20890 (and org-export-mark-todo-in-toc
20891 (= level umax-toc)
20892 (org-search-todo-below
20893 line lines level))))
20894 (setq txt (org-html-expand-for-ascii txt))
20896 (if (and (memq org-export-with-tags '(not-in-toc nil))
20897 (string-match
20898 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
20899 txt))
20900 (setq txt (replace-match "" t t txt)))
20901 (if (string-match quote-re0 txt)
20902 (setq txt (replace-match "" t t txt)))
20904 (if org-export-with-section-numbers
20905 (setq txt (concat (org-section-number level)
20906 " " txt)))
20907 (if (<= level umax-toc)
20908 (progn
20909 (push
20910 (concat
20911 (make-string (* (1- level) 4) ?\ )
20912 (format (if todo "%s (*)\n" "%s\n") txt))
20913 thetoc)
20914 (setq org-last-level level))
20915 ))))
20916 lines)
20917 (setq thetoc (if have-headings (nreverse thetoc) nil))))
20919 (org-init-section-numbers)
20920 (while (setq line (pop lines))
20921 ;; Remove the quoted HTML tags.
20922 (setq line (org-html-expand-for-ascii line))
20923 ;; Remove targets
20924 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
20925 (setq line (replace-match "" t t line)))
20926 ;; Replace internal links
20927 (while (string-match org-bracket-link-regexp line)
20928 (setq line (replace-match
20929 (if (match-end 3) "[\\3]" "[\\1]")
20930 t nil line)))
20931 (when custom-times
20932 (setq line (org-translate-time line)))
20933 (cond
20934 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
20935 ;; a Headline
20936 (setq first-heading-pos (or first-heading-pos (point)))
20937 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
20938 txt (match-string 2 line))
20939 (org-ascii-level-start level txt umax lines))
20941 ((and org-export-with-tables
20942 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
20943 (if (not table-open)
20944 ;; New table starts
20945 (setq table-open t table-buffer nil))
20946 ;; Accumulate lines
20947 (setq table-buffer (cons line table-buffer))
20948 (when (or (not lines)
20949 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
20950 (car lines))))
20951 (setq table-open nil
20952 table-buffer (nreverse table-buffer))
20953 (insert (mapconcat
20954 (lambda (x)
20955 (org-fix-indentation x org-ascii-current-indentation))
20956 (org-format-table-ascii table-buffer)
20957 "\n") "\n")))
20959 (setq line (org-fix-indentation line org-ascii-current-indentation))
20960 (if (and org-export-with-fixed-width
20961 (string-match "^\\([ \t]*\\)\\(:\\)" line))
20962 (setq line (replace-match "\\1" nil nil line)))
20963 (insert line "\n"))))
20965 (normal-mode)
20967 ;; insert the table of contents
20968 (when thetoc
20969 (goto-char (point-min))
20970 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
20971 (progn
20972 (goto-char (match-beginning 0))
20973 (replace-match ""))
20974 (goto-char first-heading-pos))
20975 (mapc 'insert thetoc)
20976 (or (looking-at "[ \t]*\n[ \t]*\n")
20977 (insert "\n\n")))
20979 (save-buffer)
20980 ;; remove display and invisible chars
20981 (let (beg end)
20982 (goto-char (point-min))
20983 (while (setq beg (next-single-property-change (point) 'display))
20984 (setq end (next-single-property-change beg 'display))
20985 (delete-region beg end)
20986 (goto-char beg)
20987 (insert "=>"))
20988 (goto-char (point-min))
20989 (while (setq beg (next-single-property-change (point) 'org-cwidth))
20990 (setq end (next-single-property-change beg 'org-cwidth))
20991 (delete-region beg end)
20992 (goto-char beg)))
20993 (goto-char (point-min))))
20995 (defun org-search-todo-below (line lines level)
20996 "Search the subtree below LINE for any TODO entries."
20997 (let ((rest (cdr (memq line lines)))
20998 (re org-todo-line-regexp)
20999 line lv todo)
21000 (catch 'exit
21001 (while (setq line (pop rest))
21002 (if (string-match re line)
21003 (progn
21004 (setq lv (- (match-end 1) (match-beginning 1))
21005 todo (and (match-beginning 2)
21006 (not (member (match-string 2 line)
21007 org-done-keywords))))
21008 ; TODO, not DONE
21009 (if (<= lv level) (throw 'exit nil))
21010 (if todo (throw 'exit t))))))))
21012 (defun org-html-expand-for-ascii (line)
21013 "Handle quoted HTML for ASCII export."
21014 (if org-export-html-expand
21015 (while (string-match "@<[^<>\n]*>" line)
21016 ;; We just remove the tags for now.
21017 (setq line (replace-match "" nil nil line))))
21018 line)
21020 (defun org-insert-centered (s &optional underline)
21021 "Insert the string S centered and underline it with character UNDERLINE."
21022 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
21023 (insert (make-string ind ?\ ) s "\n")
21024 (if underline
21025 (insert (make-string ind ?\ )
21026 (make-string (string-width s) underline)
21027 "\n"))))
21029 (defun org-ascii-level-start (level title umax &optional lines)
21030 "Insert a new level in ASCII export."
21031 (let (char (n (- level umax 1)) (ind 0))
21032 (if (> level umax)
21033 (progn
21034 (insert (make-string (* 2 n) ?\ )
21035 (char-to-string (nth (% n (length org-export-ascii-bullets))
21036 org-export-ascii-bullets))
21037 " " title "\n")
21038 ;; find the indentation of the next non-empty line
21039 (catch 'stop
21040 (while lines
21041 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
21042 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
21043 (throw 'stop (setq ind (org-get-indentation (car lines)))))
21044 (pop lines)))
21045 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
21046 (if (or (not (equal (char-before) ?\n))
21047 (not (equal (char-before (1- (point))) ?\n)))
21048 (insert "\n"))
21049 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
21050 (unless org-export-with-tags
21051 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
21052 (setq title (replace-match "" t t title))))
21053 (if org-export-with-section-numbers
21054 (setq title (concat (org-section-number level) " " title)))
21055 (insert title "\n" (make-string (string-width title) char) "\n")
21056 (setq org-ascii-current-indentation '(0 . 0)))))
21058 (defun org-export-visible (type arg)
21059 "Create a copy of the visible part of the current buffer, and export it.
21060 The copy is created in a temporary buffer and removed after use.
21061 TYPE is the final key (as a string) that also select the export command in
21062 the `C-c C-e' export dispatcher.
21063 As a special case, if the you type SPC at the prompt, the temporary
21064 org-mode file will not be removed but presented to you so that you can
21065 continue to use it. The prefix arg ARG is passed through to the exporting
21066 command."
21067 (interactive
21068 (list (progn
21069 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
21070 (read-char-exclusive))
21071 current-prefix-arg))
21072 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
21073 (error "Invalid export key"))
21074 (let* ((binding (cdr (assoc type
21075 '((?a . org-export-as-ascii)
21076 (?\C-a . org-export-as-ascii)
21077 (?b . org-export-as-html-and-open)
21078 (?\C-b . org-export-as-html-and-open)
21079 (?h . org-export-as-html)
21080 (?H . org-export-as-html-to-buffer)
21081 (?R . org-export-region-as-html)
21082 (?x . org-export-as-xoxo)))))
21083 (keepp (equal type ?\ ))
21084 (file buffer-file-name)
21085 (buffer (get-buffer-create "*Org Export Visible*"))
21086 s e)
21087 (with-current-buffer buffer (erase-buffer))
21088 (save-excursion
21089 (setq s (goto-char (point-min)))
21090 (while (not (= (point) (point-max)))
21091 (goto-char (org-find-invisible))
21092 (append-to-buffer buffer s (point))
21093 (setq s (goto-char (org-find-visible))))
21094 (goto-char (point-min))
21095 (unless keepp
21096 ;; Copy all comment lines to the end, to make sure #+ settings are
21097 ;; still available for the second export step. Kind of a hack, but
21098 ;; does do the trick.
21099 (if (looking-at "#[^\r\n]*")
21100 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
21101 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
21102 (append-to-buffer buffer (1+ (match-beginning 0))
21103 (min (point-max) (1+ (match-end 0))))))
21104 (set-buffer buffer)
21105 (let ((buffer-file-name file)
21106 (org-inhibit-startup t))
21107 (org-mode)
21108 (show-all)
21109 (unless keepp (funcall binding arg))))
21110 (if (not keepp)
21111 (kill-buffer buffer)
21112 (switch-to-buffer-other-window buffer)
21113 (goto-char (point-min)))))
21115 (defun org-find-visible ()
21116 (let ((s (point)))
21117 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21118 (get-char-property s 'invisible)))
21120 (defun org-find-invisible ()
21121 (let ((s (point)))
21122 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21123 (not (get-char-property s 'invisible))))
21126 ;;; HTML export
21128 (defun org-get-current-options ()
21129 "Return a string with current options as keyword options.
21130 Does include HTML export options as well as TODO and CATEGORY stuff."
21131 (format
21132 "#+TITLE: %s
21133 #+AUTHOR: %s
21134 #+EMAIL: %s
21135 #+LANGUAGE: %s
21136 #+TEXT: Some descriptive text to be emitted. Several lines OK.
21137 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
21138 #+CATEGORY: %s
21139 #+SEQ_TODO: %s
21140 #+TYP_TODO: %s
21141 #+PRIORITIES: %c %c %c
21142 #+STARTUP: %s %s %s %s %s
21143 #+TAGS: %s
21144 #+ARCHIVE: %s
21145 #+LINK: %s
21147 (buffer-name) (user-full-name) user-mail-address org-export-default-language
21148 org-export-headline-levels
21149 org-export-with-section-numbers
21150 org-export-with-toc
21151 org-export-preserve-breaks
21152 org-export-html-expand
21153 org-export-with-fixed-width
21154 org-export-with-tables
21155 org-export-with-sub-superscripts
21156 org-export-with-footnotes
21157 org-export-with-emphasize
21158 org-export-with-TeX-macros
21159 org-export-with-LaTeX-fragments
21160 org-export-skip-text-before-1st-heading
21161 org-export-with-property-drawer
21162 (file-name-nondirectory buffer-file-name)
21163 "TODO FEEDBACK VERIFY DONE"
21164 "Me Jason Marie DONE"
21165 org-highest-priority org-lowest-priority org-default-priority
21166 (cdr (assoc org-startup-folded
21167 '((nil . "showall") (t . "overview") (content . "content"))))
21168 (if org-odd-levels-only "odd" "oddeven")
21169 (if org-hide-leading-stars "hidestars" "showstars")
21170 (if org-startup-align-all-tables "align" "noalign")
21171 (cond ((eq t org-log-done) "logdone")
21172 ((not org-log-done) "nologging")
21173 ((listp org-log-done)
21174 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
21175 org-log-done " ")))
21176 (or (mapconcat (lambda (x)
21177 (cond
21178 ((equal '(:startgroup) x) "{")
21179 ((equal '(:endgroup) x) "}")
21180 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
21181 (t (car x))))
21182 (or org-tag-alist (org-get-buffer-tags)) " ") "")
21183 org-archive-location
21184 "org file:~/org/%s.org"
21187 (defun org-insert-export-options-template ()
21188 "Insert into the buffer a template with information for exporting."
21189 (interactive)
21190 (if (not (bolp)) (newline))
21191 (let ((s (org-get-current-options)))
21192 (and (string-match "#\\+CATEGORY" s)
21193 (setq s (substring s 0 (match-beginning 0))))
21194 (insert s)))
21196 (defun org-toggle-fixed-width-section (arg)
21197 "Toggle the fixed-width export.
21198 If there is no active region, the QUOTE keyword at the current headline is
21199 inserted or removed. When present, it causes the text between this headline
21200 and the next to be exported as fixed-width text, and unmodified.
21201 If there is an active region, this command adds or removes a colon as the
21202 first character of this line. If the first character of a line is a colon,
21203 this line is also exported in fixed-width font."
21204 (interactive "P")
21205 (let* ((cc 0)
21206 (regionp (org-region-active-p))
21207 (beg (if regionp (region-beginning) (point)))
21208 (end (if regionp (region-end)))
21209 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21210 (re "[ \t]*\\(:\\)")
21211 off)
21212 (if regionp
21213 (save-excursion
21214 (goto-char beg)
21215 (setq cc (current-column))
21216 (beginning-of-line 1)
21217 (setq off (looking-at re))
21218 (while (> nlines 0)
21219 (setq nlines (1- nlines))
21220 (beginning-of-line 1)
21221 (cond
21222 (arg
21223 (move-to-column cc t)
21224 (insert ":\n")
21225 (forward-line -1))
21226 ((and off (looking-at re))
21227 (replace-match "" t t nil 1))
21228 ((not off) (move-to-column cc t) (insert ":")))
21229 (forward-line 1)))
21230 (save-excursion
21231 (org-back-to-heading)
21232 (if (looking-at (concat outline-regexp
21233 "\\( *\\<" org-quote-string "\\>\\)"))
21234 (replace-match "" t t nil 1)
21235 (if (looking-at outline-regexp)
21236 (progn
21237 (goto-char (match-end 0))
21238 (insert org-quote-string " "))))))))
21240 (defun org-export-as-html-and-open (arg)
21241 "Export the outline as HTML and immediately open it with a browser.
21242 If there is an active region, export only the region.
21243 The prefix ARG specifies how many levels of the outline should become
21244 headlines. The default is 3. Lower levels will become bulleted lists."
21245 (interactive "P")
21246 (org-export-as-html arg 'hidden)
21247 (org-open-file buffer-file-name))
21249 (defun org-export-as-html-batch ()
21250 "Call `org-export-as-html', may be used in batch processing as
21251 emacs --batch
21252 --load=$HOME/lib/emacs/org.el
21253 --eval \"(setq org-export-headline-levels 2)\"
21254 --visit=MyFile --funcall org-export-as-html-batch"
21255 (org-export-as-html org-export-headline-levels 'hidden))
21257 (defun org-export-as-html-to-buffer (arg)
21258 "Call `org-exort-as-html` with output to a temporary buffer.
21259 No file is created. The prefix ARG is passed through to `org-export-as-html'."
21260 (interactive "P")
21261 (org-export-as-html arg nil nil "*Org HTML Export*")
21262 (switch-to-buffer-other-window "*Org HTML Export*"))
21264 (defun org-replace-region-by-html (beg end)
21265 "Assume the current region has org-mode syntax, and convert it to HTML.
21266 This can be used in any buffer. For example, you could write an
21267 itemized list in org-mode syntax in an HTML buffer and then use this
21268 command to convert it."
21269 (interactive "r")
21270 (let (reg html buf)
21271 (save-window-excursion
21272 (if (org-mode-p)
21273 (setq html (org-export-region-as-html
21274 beg end t 'string))
21275 (setq reg (buffer-substring beg end)
21276 buf (get-buffer-create "*Org tmp*"))
21277 (with-current-buffer buf
21278 (erase-buffer)
21279 (insert reg)
21280 (org-mode)
21281 (setq html (org-export-region-as-html
21282 (point-min) (point-max) t 'string)))
21283 (kill-buffer buf)))
21284 (delete-region beg end)
21285 (insert html)))
21287 (defun org-export-region-as-html (beg end &optional body-only buffer)
21288 "Convert region from BEG to END in org-mode buffer to HTML.
21289 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
21290 contents, and only produce the region of converted text, useful for
21291 cut-and-paste operations.
21292 If BUFFER is a buffer or a string, use/create that buffer as a target
21293 of the converted HTML. If BUFFER is the symbol `string', return the
21294 produced HTML as a string and leave not buffer behind. For example,
21295 a Lisp program could call this function in the following way:
21297 (setq html (org-export-region-as-html beg end t 'string))
21299 When called interactively, the output buffer is selected, and shown
21300 in a window. A non-interactive call will only retunr the buffer."
21301 (interactive "r\nP")
21302 (when (interactive-p)
21303 (setq buffer "*Org HTML Export*"))
21304 (let ((transient-mark-mode t) (zmacs-regions t)
21305 rtn)
21306 (goto-char end)
21307 (set-mark (point)) ;; to activate the region
21308 (goto-char beg)
21309 (setq rtn (org-export-as-html
21310 nil nil nil
21311 buffer body-only))
21312 (if (fboundp 'deactivate-mark) (deactivate-mark))
21313 (if (and (interactive-p) (bufferp rtn))
21314 (switch-to-buffer-other-window rtn)
21315 rtn)))
21317 (defun org-export-as-html (arg &optional hidden ext-plist
21318 to-buffer body-only)
21319 "Export the outline as a pretty HTML file.
21320 If there is an active region, export only the region. The prefix
21321 ARG specifies how many levels of the outline should become
21322 headlines. The default is 3. Lower levels will become bulleted
21323 lists. When HIDDEN is non-nil, don't display the HTML buffer.
21324 EXT-PLIST is a property list with external parameters overriding
21325 org-mode's default settings, but still inferior to file-local
21326 settings. When TO-BUFFER is non-nil, create a buffer with that
21327 name and export to that buffer. If TO-BUFFER is the symbol `string',
21328 don't leave any buffer behind but just return the resulting HTML as
21329 a string. When BODY-ONLY is set, don't produce the file header and footer,
21330 simply return the content of <body>...</body>, without even
21331 the body tags themselves."
21332 (interactive "P")
21334 ;; Make sure we have a file name when we need it.
21335 (when (and (not (or to-buffer body-only))
21336 (not buffer-file-name))
21337 (if (buffer-base-buffer)
21338 (org-set-local 'buffer-file-name
21339 (with-current-buffer (buffer-base-buffer)
21340 buffer-file-name))
21341 (error "Need a file name to be able to export.")))
21343 (message "Exporting...")
21344 (setq-default org-todo-line-regexp org-todo-line-regexp)
21345 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
21346 (setq-default org-done-keywords org-done-keywords)
21347 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
21348 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21349 ext-plist
21350 (org-infile-export-plist)))
21352 (style (plist-get opt-plist :style))
21353 (link-validate (plist-get opt-plist :link-validation-function))
21354 valid thetoc have-headings first-heading-pos
21355 (odd org-odd-levels-only)
21356 (region-p (org-region-active-p))
21357 ;; The following two are dynamically scoped into other
21358 ;; routines below.
21359 (org-current-export-dir (org-export-directory :html opt-plist))
21360 (org-current-export-file buffer-file-name)
21361 (level 0) (line "") (origline "") txt todo
21362 (umax nil)
21363 (umax-toc nil)
21364 (filename (if to-buffer nil
21365 (concat (file-name-as-directory
21366 (org-export-directory :html opt-plist))
21367 (file-name-sans-extension
21368 (file-name-nondirectory buffer-file-name))
21369 ".html")))
21370 (current-dir (if buffer-file-name
21371 (file-name-directory buffer-file-name)
21372 default-directory))
21373 (buffer (if to-buffer
21374 (cond
21375 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
21376 (t (get-buffer-create to-buffer)))
21377 (find-file-noselect filename)))
21378 (org-levels-open (make-vector org-level-max nil))
21379 (date (format-time-string "%Y/%m/%d" (current-time)))
21380 (time (format-time-string "%X" (org-current-time)))
21381 (author (plist-get opt-plist :author))
21382 (title (or (plist-get opt-plist :title)
21383 (and (not
21384 (plist-get opt-plist :skip-before-1st-heading))
21385 (org-export-grab-title-from-buffer))
21386 (and buffer-file-name
21387 (file-name-sans-extension
21388 (file-name-nondirectory buffer-file-name)))
21389 "UNTITLED"))
21390 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21391 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
21392 (inquote nil)
21393 (infixed nil)
21394 (in-local-list nil)
21395 (local-list-num nil)
21396 (local-list-indent nil)
21397 (llt org-plain-list-ordered-item-terminator)
21398 (email (plist-get opt-plist :email))
21399 (language (plist-get opt-plist :language))
21400 (lang-words nil)
21401 (target-alist nil) tg
21402 (head-count 0) cnt
21403 (start 0)
21404 (coding-system (and (boundp 'buffer-file-coding-system)
21405 buffer-file-coding-system))
21406 (coding-system-for-write (or org-export-html-coding-system
21407 coding-system))
21408 (save-buffer-coding-system (or org-export-html-coding-system
21409 coding-system))
21410 (charset (and coding-system-for-write
21411 (fboundp 'coding-system-get)
21412 (coding-system-get coding-system-for-write
21413 'mime-charset)))
21414 (region
21415 (buffer-substring
21416 (if region-p (region-beginning) (point-min))
21417 (if region-p (region-end) (point-max))))
21418 (lines
21419 (org-split-string
21420 (org-cleaned-string-for-export
21421 region
21422 :emph-multiline t
21423 :for-html t
21424 :skip-before-1st-heading
21425 (plist-get opt-plist :skip-before-1st-heading)
21426 :add-text
21427 (plist-get opt-plist :text)
21428 :LaTeX-fragments
21429 (plist-get opt-plist :LaTeX-fragments))
21430 "[\r\n]"))
21431 table-open type
21432 table-buffer table-orig-buffer
21433 ind start-is-num starter didclose
21434 rpl path desc descp desc1 desc2 link
21437 (let ((inhibit-read-only t))
21438 (org-unmodified
21439 (remove-text-properties (point-min) (point-max)
21440 '(:org-license-to-kill t))))
21442 (message "Exporting...")
21444 (setq org-last-level 1)
21445 (org-init-section-numbers)
21447 ;; Get the language-dependent settings
21448 (setq lang-words (or (assoc language org-export-language-setup)
21449 (assoc "en" org-export-language-setup)))
21451 ;; Switch to the output buffer
21452 (set-buffer buffer)
21453 (erase-buffer)
21454 (fundamental-mode)
21456 (and (fboundp 'set-buffer-file-coding-system)
21457 (set-buffer-file-coding-system coding-system-for-write))
21459 (let ((case-fold-search nil)
21460 (org-odd-levels-only odd))
21461 ;; create local variables for all options, to make sure all called
21462 ;; functions get the correct information
21463 (mapcar (lambda (x)
21464 (set (make-local-variable (cdr x))
21465 (plist-get opt-plist (car x))))
21466 org-export-plist-vars)
21467 (setq umax (if arg (prefix-numeric-value arg)
21468 org-export-headline-levels))
21469 (setq umax-toc (if (integerp org-export-with-toc)
21470 (min org-export-with-toc umax)
21471 umax))
21472 (unless body-only
21473 ;; File header
21474 (insert (format
21475 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
21476 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
21477 <html xmlns=\"http://www.w3.org/1999/xhtml\"
21478 lang=\"%s\" xml:lang=\"%s\">
21479 <head>
21480 <title>%s</title>
21481 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
21482 <meta name=\"generator\" content=\"Org-mode\"/>
21483 <meta name=\"generated\" content=\"%s %s\"/>
21484 <meta name=\"author\" content=\"%s\"/>
21486 </head><body>
21488 language language (org-html-expand title)
21489 (or charset "iso-8859-1") date time author style))
21491 (insert (or (plist-get opt-plist :preamble) ""))
21493 (when (plist-get opt-plist :auto-preamble)
21494 (if title (insert (format org-export-html-title-format
21495 (org-html-expand title))))))
21497 (if (and org-export-with-toc (not body-only))
21498 (progn
21499 (push (format "<h%d>%s</h%d>\n"
21500 org-export-html-toplevel-hlevel
21501 (nth 3 lang-words)
21502 org-export-html-toplevel-hlevel)
21503 thetoc)
21504 (push "<ul>\n<li>" thetoc)
21505 (setq lines
21506 (mapcar '(lambda (line)
21507 (if (string-match org-todo-line-regexp line)
21508 ;; This is a headline
21509 (progn
21510 (setq have-headings t)
21511 (setq level (- (match-end 1) (match-beginning 1))
21512 level (org-tr-level level)
21513 txt (save-match-data
21514 (org-html-expand
21515 (org-export-cleanup-toc-line
21516 (match-string 3 line))))
21517 todo
21518 (or (and org-export-mark-todo-in-toc
21519 (match-beginning 2)
21520 (not (member (match-string 2 line)
21521 org-done-keywords)))
21522 ; TODO, not DONE
21523 (and org-export-mark-todo-in-toc
21524 (= level umax-toc)
21525 (org-search-todo-below
21526 line lines level))))
21527 (if (and (memq org-export-with-tags '(not-in-toc nil))
21528 (string-match
21529 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21530 txt))
21531 (setq txt (replace-match "" t t txt)))
21532 (if (string-match quote-re0 txt)
21533 (setq txt (replace-match "" t t txt)))
21534 (if org-export-with-section-numbers
21535 (setq txt (concat (org-section-number level)
21536 " " txt)))
21537 (if (<= level (max umax umax-toc))
21538 (setq head-count (+ head-count 1)))
21539 (if (<= level umax-toc)
21540 (progn
21541 (if (> level org-last-level)
21542 (progn
21543 (setq cnt (- level org-last-level))
21544 (while (>= (setq cnt (1- cnt)) 0)
21545 (push "\n<ul>\n<li>" thetoc))
21546 (push "\n" thetoc)))
21547 (if (< level org-last-level)
21548 (progn
21549 (setq cnt (- org-last-level level))
21550 (while (>= (setq cnt (1- cnt)) 0)
21551 (push "</li>\n</ul>" thetoc))
21552 (push "\n" thetoc)))
21553 ;; Check for targets
21554 (while (string-match org-target-regexp line)
21555 (setq tg (match-string 1 line)
21556 line (replace-match
21557 (concat "@<span class=\"target\">" tg "@</span> ")
21558 t t line))
21559 (push (cons (org-solidify-link-text tg)
21560 (format "sec-%d" head-count))
21561 target-alist))
21562 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
21563 (setq txt (replace-match "" t t txt)))
21564 (push
21565 (format
21566 (if todo
21567 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
21568 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
21569 head-count txt) thetoc)
21571 (setq org-last-level level))
21573 line)
21574 lines))
21575 (while (> org-last-level 0)
21576 (setq org-last-level (1- org-last-level))
21577 (push "</li>\n</ul>\n" thetoc))
21578 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21580 (setq head-count 0)
21581 (org-init-section-numbers)
21583 (while (setq line (pop lines) origline line)
21584 (catch 'nextline
21586 ;; end of quote section?
21587 (when (and inquote (string-match "^\\*+ " line))
21588 (insert "</pre>\n")
21589 (setq inquote nil))
21590 ;; inside a quote section?
21591 (when inquote
21592 (insert (org-html-protect line) "\n")
21593 (throw 'nextline nil))
21595 ;; verbatim lines
21596 (when (and org-export-with-fixed-width
21597 (string-match "^[ \t]*:\\(.*\\)" line))
21598 (when (not infixed)
21599 (setq infixed t)
21600 (insert "<pre>\n"))
21601 (insert (org-html-protect (match-string 1 line)) "\n")
21602 (when (and lines
21603 (not (string-match "^[ \t]*\\(:.*\\)"
21604 (car lines))))
21605 (setq infixed nil)
21606 (insert "</pre>\n"))
21607 (throw 'nextline nil))
21609 ;; Protected HTML
21610 (when (get-text-property 0 'org-protected line)
21611 (let (par)
21612 (when (re-search-backward
21613 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
21614 (setq par (match-string 1))
21615 (replace-match "\\2\n"))
21616 (insert line "\n")
21617 (while (and lines
21618 (get-text-property 0 'org-protected (car lines)))
21619 (insert (pop lines) "\n"))
21620 (and par (insert "<p>\n")))
21621 (throw 'nextline nil))
21623 ;; Horizontal line
21624 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
21625 (insert "\n<hr/>\n")
21626 (throw 'nextline nil))
21628 ;; make targets to anchors
21629 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
21630 (cond
21631 ((match-end 2)
21632 (setq line (replace-match
21633 (concat "@<a name=\""
21634 (org-solidify-link-text (match-string 1 line))
21635 "\">\\nbsp@</a>")
21636 t t line)))
21637 ((and org-export-with-toc (equal (string-to-char line) ?*))
21638 (setq line (replace-match
21639 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
21640 ; (concat "@<i>" (match-string 1 line) "@</i> ")
21641 t t line)))
21643 (setq line (replace-match
21644 (concat "@<a name=\""
21645 (org-solidify-link-text (match-string 1 line))
21646 "\" class=\"target\">" (match-string 1 line) "@</a> ")
21647 t t line)))))
21649 (setq line (org-html-handle-time-stamps line))
21651 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
21652 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
21653 ;; Also handle sub_superscripts and checkboxes
21654 (setq line (org-html-expand line))
21656 ;; Format the links
21657 (setq start 0)
21658 (while (string-match org-bracket-link-analytic-regexp line start)
21659 (setq start (match-beginning 0))
21660 (setq type (if (match-end 2) (match-string 2 line) "internal"))
21661 (setq path (match-string 3 line))
21662 (setq desc1 (if (match-end 5) (match-string 5 line))
21663 desc2 (if (match-end 2) (concat type ":" path) path)
21664 descp (and desc1 (not (equal desc1 desc2)))
21665 desc (or desc1 desc2))
21666 ;; Make an image out of the description if that is so wanted
21667 (when (and descp (org-file-image-p desc))
21668 (save-match-data
21669 (if (string-match "^file:" desc)
21670 (setq desc (substring desc (match-end 0)))))
21671 (setq desc (concat "<img src=\"" desc "\"/>")))
21672 ;; FIXME: do we need to unescape here somewhere?
21673 (cond
21674 ((equal type "internal")
21675 (setq rpl
21676 (concat
21677 "<a href=\"#"
21678 (org-solidify-link-text
21679 (save-match-data (org-link-unescape path)) target-alist)
21680 "\">" desc "</a>")))
21681 ((member type '("http" "https")) ; FIXME: need to test this.
21682 ;; standard URL, just check if we need to inline an image
21683 (if (and (or (eq t org-export-html-inline-images)
21684 (and org-export-html-inline-images (not descp)))
21685 (org-file-image-p path))
21686 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
21687 (setq link (concat type ":" path))
21688 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
21689 ((member type '("ftp" "mailto" "news"))
21690 ;; standard URL
21691 (setq link (concat type ":" path))
21692 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
21693 ((string= type "file")
21694 ;; FILE link
21695 (let* ((filename path)
21696 (abs-p (file-name-absolute-p filename))
21697 thefile file-is-image-p search)
21698 (save-match-data
21699 (if (string-match "::\\(.*\\)" filename)
21700 (setq search (match-string 1 filename)
21701 filename (replace-match "" t nil filename)))
21702 (setq valid
21703 (if (functionp link-validate)
21704 (funcall link-validate filename current-dir)
21706 (setq file-is-image-p (org-file-image-p filename))
21707 (setq thefile (if abs-p (expand-file-name filename) filename))
21708 (when (and org-export-html-link-org-files-as-html
21709 (string-match "\\.org$" thefile))
21710 (setq thefile (concat (substring thefile 0
21711 (match-beginning 0))
21712 ".html"))
21713 (if (and search
21714 ;; make sure this is can be used as target search
21715 (not (string-match "^[0-9]*$" search))
21716 (not (string-match "^\\*" search))
21717 (not (string-match "^/.*/$" search)))
21718 (setq thefile (concat thefile "#"
21719 (org-solidify-link-text
21720 (org-link-unescape search)))))
21721 (when (string-match "^file:" desc)
21722 (setq desc (replace-match "" t t desc))
21723 (if (string-match "\\.org$" desc)
21724 (setq desc (replace-match "" t t desc))))))
21725 (setq rpl (if (and file-is-image-p
21726 (or (eq t org-export-html-inline-images)
21727 (and org-export-html-inline-images
21728 (not descp))))
21729 (concat "<img src=\"" thefile "\"/>")
21730 (concat "<a href=\"" thefile "\">" desc "</a>")))
21731 (if (not valid) (setq rpl desc))))
21732 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
21733 (setq rpl (concat "<i>&lt;" type ":"
21734 (save-match-data (org-link-unescape path))
21735 "&gt;</i>"))))
21736 (setq line (replace-match rpl t t line)
21737 start (+ start (length rpl))))
21739 ;; TODO items
21740 (if (and (string-match org-todo-line-regexp line)
21741 (match-beginning 2))
21743 (setq line
21744 (concat (substring line 0 (match-beginning 2))
21745 "<span class=\""
21746 (if (member (match-string 2 line)
21747 org-done-keywords)
21748 "done" "todo")
21749 "\">" (match-string 2 line)
21750 "</span>" (substring line (match-end 2)))))
21752 ;; Does this contain a reference to a footnote?
21753 (when org-export-with-footnotes
21754 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
21755 (let ((n (match-string 2 line)))
21756 (setq line
21757 (replace-match
21758 (format
21759 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
21760 (match-string 1 line) n n n)
21761 t t line)))))
21763 (cond
21764 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21765 ;; This is a headline
21766 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21767 txt (match-string 2 line))
21768 (if (string-match quote-re0 txt)
21769 (setq txt (replace-match "" t t txt)))
21770 (if (<= level (max umax umax-toc))
21771 (setq head-count (+ head-count 1)))
21772 (when in-local-list
21773 ;; Close any local lists before inserting a new header line
21774 (while local-list-num
21775 (org-close-li)
21776 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21777 (pop local-list-num))
21778 (setq local-list-indent nil
21779 in-local-list nil))
21780 (setq first-heading-pos (or first-heading-pos (point)))
21781 (org-html-level-start level txt umax
21782 (and org-export-with-toc (<= level umax))
21783 head-count)
21784 ;; QUOTES
21785 (when (string-match quote-re line)
21786 (insert "<pre>")
21787 (setq inquote t)))
21789 ((and org-export-with-tables
21790 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21791 (if (not table-open)
21792 ;; New table starts
21793 (setq table-open t table-buffer nil table-orig-buffer nil))
21794 ;; Accumulate lines
21795 (setq table-buffer (cons line table-buffer)
21796 table-orig-buffer (cons origline table-orig-buffer))
21797 (when (or (not lines)
21798 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21799 (car lines))))
21800 (setq table-open nil
21801 table-buffer (nreverse table-buffer)
21802 table-orig-buffer (nreverse table-orig-buffer))
21803 (org-close-par-maybe)
21804 (insert (org-format-table-html table-buffer table-orig-buffer))))
21806 ;; Normal lines
21807 (when (string-match
21808 (cond
21809 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21810 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21811 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21812 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
21813 line)
21814 (setq ind (org-get-string-indentation line)
21815 start-is-num (match-beginning 4)
21816 starter (if (match-beginning 2)
21817 (substring (match-string 2 line) 0 -1))
21818 line (substring line (match-beginning 5)))
21819 (unless (string-match "[^ \t]" line)
21820 ;; empty line. Pretend indentation is large.
21821 (setq ind (if org-empty-line-terminates-plain-lists
21823 (1+ (or (car local-list-indent) 1)))))
21824 (setq didclose nil)
21825 (while (and in-local-list
21826 (or (and (= ind (car local-list-indent))
21827 (not starter))
21828 (< ind (car local-list-indent))))
21829 (setq didclose t)
21830 (org-close-li)
21831 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21832 (pop local-list-num) (pop local-list-indent)
21833 (setq in-local-list local-list-indent))
21834 (cond
21835 ((and starter
21836 (or (not in-local-list)
21837 (> ind (car local-list-indent))))
21838 ;; Start new (level of) list
21839 (org-close-par-maybe)
21840 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
21841 (push start-is-num local-list-num)
21842 (push ind local-list-indent)
21843 (setq in-local-list t))
21844 (starter
21845 ;; continue current list
21846 (org-close-li)
21847 (insert "<li>\n"))
21848 (didclose
21849 ;; we did close a list, normal text follows: need <p>
21850 (org-open-par)))
21851 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
21852 (setq line
21853 (replace-match
21854 (if (equal (match-string 1 line) "X")
21855 "<b>[X]</b>"
21856 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
21857 t t line))))
21859 ;; Empty lines start a new paragraph. If hand-formatted lists
21860 ;; are not fully interpreted, lines starting with "-", "+", "*"
21861 ;; also start a new paragraph.
21862 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
21864 ;; Is this the start of a footnote?
21865 (when org-export-with-footnotes
21866 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
21867 (org-close-par-maybe)
21868 (let ((n (match-string 1 line)))
21869 (setq line (replace-match
21870 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
21872 ;; Check if the line break needs to be conserved
21873 (cond
21874 ((string-match "\\\\\\\\[ \t]*$" line)
21875 (setq line (replace-match "<br/>" t t line)))
21876 (org-export-preserve-breaks
21877 (setq line (concat line "<br/>"))))
21879 (insert line "\n")))))
21881 ;; Properly close all local lists and other lists
21882 (when inquote (insert "</pre>\n"))
21883 (when in-local-list
21884 ;; Close any local lists before inserting a new header line
21885 (while local-list-num
21886 (org-close-li)
21887 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
21888 (pop local-list-num))
21889 (setq local-list-indent nil
21890 in-local-list nil))
21891 (org-html-level-start 1 nil umax
21892 (and org-export-with-toc (<= level umax))
21893 head-count)
21895 (unless body-only
21896 (when (plist-get opt-plist :auto-postamble)
21897 (when (and org-export-author-info author)
21898 (insert "<p class=\"author\"> "
21899 (nth 1 lang-words) ": " author "\n")
21900 (when email
21901 (insert "<a href=\"mailto:" email "\">&lt;"
21902 email "&gt;</a>\n"))
21903 (insert "</p>\n"))
21904 (when (and date time org-export-time-stamp-file)
21905 (insert "<p class=\"date\"> "
21906 (nth 2 lang-words) ": "
21907 date " " time "</p>\n")))
21909 (if org-export-html-with-timestamp
21910 (insert org-export-html-html-helper-timestamp))
21911 (insert (or (plist-get opt-plist :postamble) ""))
21912 (insert "</body>\n</html>\n"))
21914 (normal-mode)
21915 (if (eq major-mode default-major-mode) (html-mode))
21917 ;; insert the table of contents
21918 (goto-char (point-min))
21919 (when thetoc
21920 (if (or (re-search-forward
21921 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
21922 (re-search-forward
21923 "\\[TABLE-OF-CONTENTS\\]" nil t))
21924 (progn
21925 (goto-char (match-beginning 0))
21926 (replace-match ""))
21927 (goto-char first-heading-pos)
21928 (when (looking-at "\\s-*</p>")
21929 (goto-char (match-end 0))
21930 (insert "\n")))
21931 (mapc 'insert thetoc))
21932 ;; remove empty paragraphs and lists
21933 (goto-char (point-min))
21934 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
21935 (replace-match ""))
21936 (goto-char (point-min))
21937 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
21938 (replace-match ""))
21939 (or to-buffer (save-buffer))
21940 (goto-char (point-min))
21941 (message "Exporting... done")
21942 (if (eq to-buffer 'string)
21943 (prog1 (buffer-substring (point-min) (point-max))
21944 (kill-buffer (current-buffer)))
21945 (current-buffer)))))
21947 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
21948 (defun org-format-table-ascii (lines)
21949 "Format a table for ascii export."
21950 (if (stringp lines)
21951 (setq lines (org-split-string lines "\n")))
21952 (if (not (string-match "^[ \t]*|" (car lines)))
21953 ;; Table made by table.el - test for spanning
21954 lines
21956 ;; A normal org table
21957 ;; Get rid of hlines at beginning and end
21958 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21959 (setq lines (nreverse lines))
21960 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21961 (setq lines (nreverse lines))
21962 (when org-export-table-remove-special-lines
21963 ;; Check if the table has a marking column. If yes remove the
21964 ;; column and the special lines
21965 (setq lines (org-table-clean-before-export lines)))
21966 ;; Get rid of the vertical lines except for grouping
21967 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
21968 rtn line vl1 start)
21969 (while (setq line (pop lines))
21970 (if (string-match org-table-hline-regexp line)
21971 (and (string-match "|\\(.*\\)|" line)
21972 (setq line (replace-match " \\1" t nil line)))
21973 (setq start 0 vl1 vl)
21974 (while (string-match "|" line start)
21975 (setq start (match-end 0))
21976 (or (pop vl1) (setq line (replace-match " " t t line)))))
21977 (push line rtn))
21978 (nreverse rtn))))
21980 (defun org-colgroup-info-to-vline-list (info)
21981 (let (vl new last)
21982 (while info
21983 (setq last new new (pop info))
21984 (if (or (memq last '(:end :startend))
21985 (memq new '(:start :startend)))
21986 (push t vl)
21987 (push nil vl)))
21988 (setq vl (cons nil (nreverse vl)))))
21991 (defun org-format-table-html (lines olines)
21992 "Find out which HTML converter to use and return the HTML code."
21993 (if (stringp lines)
21994 (setq lines (org-split-string lines "\n")))
21995 (if (string-match "^[ \t]*|" (car lines))
21996 ;; A normal org table
21997 (org-format-org-table-html lines)
21998 ;; Table made by table.el - test for spanning
21999 (let* ((hlines (delq nil (mapcar
22000 (lambda (x)
22001 (if (string-match "^[ \t]*\\+-" x) x
22002 nil))
22003 lines)))
22004 (first (car hlines))
22005 (ll (and (string-match "\\S-+" first)
22006 (match-string 0 first)))
22007 (re (concat "^[ \t]*" (regexp-quote ll)))
22008 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
22009 hlines))))
22010 (if (and (not spanning)
22011 (not org-export-prefer-native-exporter-for-tables))
22012 ;; We can use my own converter with HTML conversions
22013 (org-format-table-table-html lines)
22014 ;; Need to use the code generator in table.el, with the original text.
22015 (org-format-table-table-html-using-table-generate-source olines)))))
22017 (defun org-format-org-table-html (lines &optional splice)
22018 "Format a table into HTML."
22019 ;; Get rid of hlines at beginning and end
22020 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22021 (setq lines (nreverse lines))
22022 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22023 (setq lines (nreverse lines))
22024 (when org-export-table-remove-special-lines
22025 ;; Check if the table has a marking column. If yes remove the
22026 ;; column and the special lines
22027 (setq lines (org-table-clean-before-export lines)))
22029 (let ((head (and org-export-highlight-first-table-line
22030 (delq nil (mapcar
22031 (lambda (x) (string-match "^[ \t]*|-" x))
22032 (cdr lines)))))
22033 (nlines 0) fnum i
22034 tbopen line fields html gr colgropen)
22035 (if splice (setq head nil))
22036 (unless splice (push (if head "<thead>" "<tbody>") html))
22037 (setq tbopen t)
22038 (while (setq line (pop lines))
22039 (catch 'next-line
22040 (if (string-match "^[ \t]*|-" line)
22041 (progn
22042 (unless splice
22043 (push (if head "</thead>" "</tbody>") html)
22044 (if lines (push "<tbody>" html) (setq tbopen nil)))
22045 (setq head nil) ;; head ends here, first time around
22046 ;; ignore this line
22047 (throw 'next-line t)))
22048 ;; Break the line into fields
22049 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22050 (unless fnum (setq fnum (make-vector (length fields) 0)))
22051 (setq nlines (1+ nlines) i -1)
22052 (push (concat "<tr>"
22053 (mapconcat
22054 (lambda (x)
22055 (setq i (1+ i))
22056 (if (and (< i nlines)
22057 (string-match org-table-number-regexp x))
22058 (incf (aref fnum i)))
22059 (if head
22060 (concat (car org-export-table-header-tags) x
22061 (cdr org-export-table-header-tags))
22062 (concat (car org-export-table-data-tags) x
22063 (cdr org-export-table-data-tags))))
22064 fields "")
22065 "</tr>")
22066 html)))
22067 (unless splice (if tbopen (push "</tbody>" html)))
22068 (unless splice (push "</table>\n" html))
22069 (setq html (nreverse html))
22070 (unless splice
22071 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
22072 (push (mapconcat
22073 (lambda (x)
22074 (setq gr (pop org-table-colgroup-info))
22075 (format "%s<COL align=\"%s\"></COL>%s"
22076 (if (memq gr '(:start :startend))
22077 (prog1
22078 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
22079 (setq colgropen t))
22081 (if (> (/ (float x) nlines) org-table-number-fraction)
22082 "right" "left")
22083 (if (memq gr '(:end :startend))
22084 (progn (setq colgropen nil) "</colgroup>")
22085 "")))
22086 fnum "")
22087 html)
22088 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
22089 (push org-export-html-table-tag html))
22090 (concat (mapconcat 'identity html "\n") "\n")))
22092 (defun org-table-clean-before-export (lines)
22093 "Check if the table has a marking column.
22094 If yes remove the column and the special lines."
22095 (setq org-table-colgroup-info nil)
22096 (if (memq nil
22097 (mapcar
22098 (lambda (x) (or (string-match "^[ \t]*|-" x)
22099 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
22100 lines))
22101 (progn
22102 (setq org-table-clean-did-remove-column nil)
22103 (delq nil
22104 (mapcar
22105 (lambda (x)
22106 (cond
22107 ((string-match "^[ \t]*| */ *|" x)
22108 (setq org-table-colgroup-info
22109 (mapcar (lambda (x)
22110 (cond ((member x '("<" "&lt;")) :start)
22111 ((member x '(">" "&gt;")) :end)
22112 ((member x '("<>" "&lt;&gt;")) :startend)
22113 (t nil)))
22114 (org-split-string x "[ \t]*|[ \t]*")))
22115 nil)
22116 (t x)))
22117 lines)))
22118 (setq org-table-clean-did-remove-column t)
22119 (delq nil
22120 (mapcar
22121 (lambda (x)
22122 (cond
22123 ((string-match "^[ \t]*| */ *|" x)
22124 (setq org-table-colgroup-info
22125 (mapcar (lambda (x)
22126 (cond ((member x '("<" "&lt;")) :start)
22127 ((member x '(">" "&gt;")) :end)
22128 ((member x '("<>" "&lt;&gt;")) :startend)
22129 (t nil)))
22130 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
22131 nil)
22132 ((string-match "^[ \t]*| *[!_^/] *|" x)
22133 nil) ; ignore this line
22134 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
22135 (string-match "^\\([ \t]*\\)|[^|]*|" x))
22136 ;; remove the first column
22137 (replace-match "\\1|" t nil x))
22138 (t (error "This should not happen"))))
22139 lines))))
22141 (defun org-format-table-table-html (lines)
22142 "Format a table generated by table.el into HTML.
22143 This conversion does *not* use `table-generate-source' from table.el.
22144 This has the advantage that Org-mode's HTML conversions can be used.
22145 But it has the disadvantage, that no cell- or row-spanning is allowed."
22146 (let (line field-buffer
22147 (head org-export-highlight-first-table-line)
22148 fields html empty)
22149 (setq html (concat org-export-html-table-tag "\n"))
22150 (while (setq line (pop lines))
22151 (setq empty "&nbsp;")
22152 (catch 'next-line
22153 (if (string-match "^[ \t]*\\+-" line)
22154 (progn
22155 (if field-buffer
22156 (progn
22157 (setq
22158 html
22159 (concat
22160 html
22161 "<tr>"
22162 (mapconcat
22163 (lambda (x)
22164 (if (equal x "") (setq x empty))
22165 (if head
22166 (concat (car org-export-table-header-tags) x
22167 (cdr org-export-table-header-tags))
22168 (concat (car org-export-table-data-tags) x
22169 (cdr org-export-table-data-tags))))
22170 field-buffer "\n")
22171 "</tr>\n"))
22172 (setq head nil)
22173 (setq field-buffer nil)))
22174 ;; Ignore this line
22175 (throw 'next-line t)))
22176 ;; Break the line into fields and store the fields
22177 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22178 (if field-buffer
22179 (setq field-buffer (mapcar
22180 (lambda (x)
22181 (concat x "<br/>" (pop fields)))
22182 field-buffer))
22183 (setq field-buffer fields))))
22184 (setq html (concat html "</table>\n"))
22185 html))
22187 (defun org-format-table-table-html-using-table-generate-source (lines)
22188 "Format a table into html, using `table-generate-source' from table.el.
22189 This has the advantage that cell- or row-spanning is allowed.
22190 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
22191 (require 'table)
22192 (with-current-buffer (get-buffer-create " org-tmp1 ")
22193 (erase-buffer)
22194 (insert (mapconcat 'identity lines "\n"))
22195 (goto-char (point-min))
22196 (if (not (re-search-forward "|[^+]" nil t))
22197 (error "Error processing table"))
22198 (table-recognize-table)
22199 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
22200 (table-generate-source 'html " org-tmp2 ")
22201 (set-buffer " org-tmp2 ")
22202 (buffer-substring (point-min) (point-max))))
22204 (defun org-html-handle-time-stamps (s)
22205 "Format time stamps in string S, or remove them."
22206 (catch 'exit
22207 (let (r b)
22208 (while (string-match org-maybe-keyword-time-regexp s)
22209 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
22210 ;; never export CLOCK
22211 (throw 'exit ""))
22212 (or b (setq b (substring s 0 (match-beginning 0))))
22213 (if (not org-export-with-timestamps)
22214 (setq r (concat r (substring s 0 (match-beginning 0)))
22215 s (substring s (match-end 0)))
22216 (setq r (concat
22217 r (substring s 0 (match-beginning 0))
22218 (if (match-end 1)
22219 (format "@<span class=\"timestamp-kwd\">%s @</span>"
22220 (match-string 1 s)))
22221 (format " @<span class=\"timestamp\">%s@</span>"
22222 (substring
22223 (org-translate-time (match-string 3 s)) 1 -1)))
22224 s (substring s (match-end 0)))))
22225 ;; Line break if line started and ended with time stamp stuff
22226 (if (not r)
22228 (setq r (concat r s))
22229 (unless (string-match "\\S-" (concat b s))
22230 (setq r (concat r "@<br/>")))
22231 r))))
22233 (defun org-html-protect (s)
22234 ;; convert & to &amp;, < to &lt; and > to &gt;
22235 (let ((start 0))
22236 (while (string-match "&" s start)
22237 (setq s (replace-match "&amp;" t t s)
22238 start (1+ (match-beginning 0))))
22239 (while (string-match "<" s)
22240 (setq s (replace-match "&lt;" t t s)))
22241 (while (string-match ">" s)
22242 (setq s (replace-match "&gt;" t t s))))
22245 (defun org-export-cleanup-toc-line (s)
22246 "Remove tags and time staps from lines going into the toc."
22247 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
22248 (setq s (replace-match "" t t s)))
22249 (when org-export-remove-timestamps-from-toc
22250 (while (string-match org-maybe-keyword-time-regexp s)
22251 (setq s (replace-match "" t t s))))
22252 (while (string-match org-bracket-link-regexp s)
22253 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
22254 t t s)))
22257 (defun org-html-expand (string)
22258 "Prepare STRING for HTML export. Applies all active conversions.
22259 If there are links in the string, don't modify these."
22260 (let* (m s l res)
22261 (while (setq m (string-match org-bracket-link-regexp string))
22262 (setq s (substring string 0 m)
22263 l (match-string 0 string)
22264 string (substring string (match-end 0)))
22265 (push (org-html-do-expand s) res)
22266 (push l res))
22267 (push (org-html-do-expand string) res)
22268 (apply 'concat (nreverse res))))
22270 (defun org-html-do-expand (s)
22271 "Apply all active conversions to translate special ASCII to HTML."
22272 (setq s (org-html-protect s))
22273 (if org-export-html-expand
22274 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
22275 (setq s (replace-match "<\\1>" t nil s))))
22276 (if org-export-with-emphasize
22277 (setq s (org-export-html-convert-emphasize s)))
22278 (if org-export-with-sub-superscripts
22279 (setq s (org-export-html-convert-sub-super s)))
22280 (if org-export-with-TeX-macros
22281 (let ((start 0) wd ass)
22282 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
22283 (setq wd (match-string 1 s))
22284 (if (setq ass (assoc wd org-html-entities))
22285 (setq s (replace-match (or (cdr ass)
22286 (concat "&" (car ass) ";"))
22287 t t s))
22288 (setq start (+ start (length wd)))))))
22291 (defun org-create-multibrace-regexp (left right n)
22292 "Create a regular expression which will match a balanced sexp.
22293 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
22294 as single character strings.
22295 The regexp returned will match the entire expression including the
22296 delimiters. It will also define a single group which contains the
22297 match except for the outermost delimiters. The maximum depth of
22298 stacked delimiters is N. Escaping delimiters is not possible."
22299 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
22300 (or "\\|")
22301 (re nothing)
22302 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
22303 (while (> n 1)
22304 (setq n (1- n)
22305 re (concat re or next)
22306 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
22307 (concat left "\\(" re "\\)" right)))
22309 (defvar org-match-substring-regexp
22310 (concat
22311 "\\([^\\]\\)\\([_^]\\)\\("
22312 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
22313 "\\|"
22314 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
22315 "\\|"
22316 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
22317 "The regular expression matching a sub- or superscript.")
22319 ;(let ((s "a\\_b"))
22320 ; (and (string-match org-match-substring-regexp s)
22321 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
22323 (defun org-export-html-convert-sub-super (string)
22324 "Convert sub- and superscripts in STRING to HTML."
22325 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
22326 (while (string-match org-match-substring-regexp string s)
22327 (if (and requireb (match-end 8))
22328 (setq s (match-end 2))
22329 (setq s (match-end 1)
22330 key (if (string= (match-string 2 string) "_") "sub" "sup")
22331 c (or (match-string 8 string)
22332 (match-string 6 string)
22333 (match-string 5 string))
22334 string (replace-match
22335 (concat (match-string 1 string)
22336 "<" key ">" c "</" key ">")
22337 t t string))))
22338 (while (string-match "\\\\\\([_^]\\)" string)
22339 (setq string (replace-match (match-string 1 string) t t string)))
22340 string))
22342 (defun org-export-html-convert-emphasize (string)
22343 "Apply emphasis."
22344 (let ((s 0))
22345 (while (string-match org-emph-re string s)
22346 (if (not (equal
22347 (substring string (match-beginning 3) (1+ (match-beginning 3)))
22348 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
22349 (setq string (replace-match
22350 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
22351 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
22352 "\\5") t nil string))
22353 (setq s (1+ s))))
22354 string))
22356 (defvar org-par-open nil)
22357 (defun org-open-par ()
22358 "Insert <p>, but first close previous paragraph if any."
22359 (org-close-par-maybe)
22360 (insert "\n<p>")
22361 (setq org-par-open t))
22362 (defun org-close-par-maybe ()
22363 "Close paragraph if there is one open."
22364 (when org-par-open
22365 (insert "</p>")
22366 (setq org-par-open nil)))
22367 (defun org-close-li ()
22368 "Close <li> if necessary."
22369 (org-close-par-maybe)
22370 (insert "</li>\n"))
22372 (defvar body-only) ; dynamically scoped into this.
22373 (defun org-html-level-start (level title umax with-toc head-count)
22374 "Insert a new level in HTML export.
22375 When TITLE is nil, just close all open levels."
22376 (org-close-par-maybe)
22377 (let ((l (1+ (max level umax))))
22378 (while (<= l org-level-max)
22379 (if (aref org-levels-open (1- l))
22380 (progn
22381 (org-html-level-close l)
22382 (aset org-levels-open (1- l) nil)))
22383 (setq l (1+ l)))
22384 (when title
22385 ;; If title is nil, this means this function is called to close
22386 ;; all levels, so the rest is done only if title is given
22387 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22388 (setq title (replace-match
22389 (if org-export-with-tags
22390 (save-match-data
22391 (concat
22392 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
22393 (mapconcat 'identity (org-split-string
22394 (match-string 1 title) ":")
22395 "&nbsp;")
22396 "</span>"))
22398 t t title)))
22399 (if (> level umax)
22400 (progn
22401 (if (aref org-levels-open (1- level))
22402 (progn
22403 (org-close-li)
22404 (insert "<li>" title "<br/>\n"))
22405 (aset org-levels-open (1- level) t)
22406 (org-close-par-maybe)
22407 (insert "<ul>\n<li>" title "<br/>\n")))
22408 (if (and org-export-with-section-numbers (not body-only))
22409 (setq title (concat (org-section-number level) " " title)))
22410 (setq level (+ level org-export-html-toplevel-hlevel -1))
22411 (if with-toc
22412 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
22413 level head-count title level))
22414 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
22415 (org-open-par)))))
22417 (defun org-html-level-close (&rest args)
22418 "Terminate one level in HTML export."
22419 (org-close-li)
22420 (insert "</ul>\n"))
22422 ;;; iCalendar export
22424 ;;;###autoload
22425 (defun org-export-icalendar-this-file ()
22426 "Export current file as an iCalendar file.
22427 The iCalendar file will be located in the same directory as the Org-mode
22428 file, but with extension `.ics'."
22429 (interactive)
22430 (org-export-icalendar nil buffer-file-name))
22432 ;;;###autoload
22433 (defun org-export-icalendar-all-agenda-files ()
22434 "Export all files in `org-agenda-files' to iCalendar .ics files.
22435 Each iCalendar file will be located in the same directory as the Org-mode
22436 file, but with extension `.ics'."
22437 (interactive)
22438 (apply 'org-export-icalendar nil (org-agenda-files t)))
22440 ;;;###autoload
22441 (defun org-export-icalendar-combine-agenda-files ()
22442 "Export all files in `org-agenda-files' to a single combined iCalendar file.
22443 The file is stored under the name `org-combined-agenda-icalendar-file'."
22444 (interactive)
22445 (apply 'org-export-icalendar t (org-agenda-files t)))
22447 (defun org-export-icalendar (combine &rest files)
22448 "Create iCalendar files for all elements of FILES.
22449 If COMBINE is non-nil, combine all calendar entries into a single large
22450 file and store it under the name `org-combined-agenda-icalendar-file'."
22451 (save-excursion
22452 (org-prepare-agenda-buffers files)
22453 (let* ((dir (org-export-directory
22454 :ical (list :publishing-directory
22455 org-export-publishing-directory)))
22456 file ical-file ical-buffer category started org-agenda-new-buffers)
22458 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
22459 (when combine
22460 (setq ical-file
22461 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
22462 org-combined-agenda-icalendar-file
22463 (expand-file-name org-combined-agenda-icalendar-file dir))
22464 ical-buffer (org-get-agenda-file-buffer ical-file))
22465 (set-buffer ical-buffer) (erase-buffer))
22466 (while (setq file (pop files))
22467 (catch 'nextfile
22468 (org-check-agenda-file file)
22469 (set-buffer (org-get-agenda-file-buffer file))
22470 (unless combine
22471 (setq ical-file (concat (file-name-as-directory dir)
22472 (file-name-sans-extension
22473 (file-name-nondirectory buffer-file-name))
22474 ".ics"))
22475 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
22476 (with-current-buffer ical-buffer (erase-buffer)))
22477 (setq category (or org-category
22478 (file-name-sans-extension
22479 (file-name-nondirectory buffer-file-name))))
22480 (if (symbolp category) (setq category (symbol-name category)))
22481 (let ((standard-output ical-buffer))
22482 (if combine
22483 (and (not started) (setq started t)
22484 (org-start-icalendar-file org-icalendar-combined-name))
22485 (org-start-icalendar-file category))
22486 (org-print-icalendar-entries combine)
22487 (when (or (and combine (not files)) (not combine))
22488 (org-finish-icalendar-file)
22489 (set-buffer ical-buffer)
22490 (save-buffer)
22491 (run-hooks 'org-after-save-iCalendar-file-hook)))))
22492 (org-release-buffers org-agenda-new-buffers))))
22494 (defvar org-after-save-iCalendar-file-hook nil
22495 "Hook run after an iCalendar file has been saved.
22496 The iCalendar buffer is still current when this hook is run.
22497 A good way to use this is to tell a desktop calenndar application to re-read
22498 the iCalendar file.")
22500 (defun org-print-icalendar-entries (&optional combine)
22501 "Print iCalendar entries for the current Org-mode file to `standard-output'.
22502 When COMBINE is non nil, add the category to each line."
22503 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
22504 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
22505 (org-category-table (org-get-category-table))
22506 (dts (org-ical-ts-to-string
22507 (format-time-string (cdr org-time-stamp-formats) (current-time))
22508 "DTSTART"))
22509 hd ts ts2 state status (inc t) pos b sexp rrule
22510 scheduledp deadlinep tmp pri category
22511 (sexp-buffer (get-buffer-create "*ical-tmp*")))
22512 (save-excursion
22513 (goto-char (point-min))
22514 (while (re-search-forward re1 nil t)
22515 (catch :skip
22516 (org-agenda-skip)
22517 (setq pos (match-beginning 0)
22518 ts (match-string 0)
22519 inc t
22520 hd (org-get-heading)
22521 category (org-get-category))
22522 (if (looking-at re2)
22523 (progn
22524 (goto-char (match-end 0))
22525 (setq ts2 (match-string 1) inc nil))
22526 (setq tmp (buffer-substring (max (point-min)
22527 (- pos org-ds-keyword-length))
22528 pos)
22529 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
22530 (progn
22531 (setq inc nil)
22532 (replace-match "\\1" t nil ts))
22534 deadlinep (string-match org-deadline-regexp tmp)
22535 scheduledp (string-match org-scheduled-regexp tmp)
22536 ;; donep (org-entry-is-done-p)
22538 (if (or (string-match org-tr-regexp hd)
22539 (string-match org-ts-regexp hd))
22540 (setq hd (replace-match "" t t hd)))
22541 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
22542 (setq rrule
22543 (concat "\nRRULE:FREQ="
22544 (cdr (assoc
22545 (match-string 2 ts)
22546 '(("d" . "DAILY")("w" . "WEEKLY")
22547 ("m" . "MONTHLY")("y" . "YEARLY"))))
22548 ";INTERVAL=" (match-string 1 ts)))
22549 (setq rrule ""))
22550 (if (string-match org-bracket-link-regexp hd)
22551 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22552 (match-string 1 hd))
22553 t t hd)))
22554 (if deadlinep (setq hd (concat "DL: " hd)))
22555 (if scheduledp (setq hd (concat "S: " hd)))
22556 (if (string-match "\\`<%%" ts)
22557 (with-current-buffer sexp-buffer
22558 (insert (substring ts 1 -1) " " hd "\n"))
22559 (princ (format "BEGIN:VEVENT
22561 %s%s
22562 SUMMARY:%s
22563 CATEGORIES:%s
22564 END:VEVENT\n"
22565 (org-ical-ts-to-string ts "DTSTART")
22566 (org-ical-ts-to-string ts2 "DTEND" inc)
22567 rrule hd category)))))
22569 (when (and org-icalendar-include-sexps
22570 (condition-case nil (require 'icalendar) (error nil))
22571 (fboundp 'icalendar-export-region))
22572 ;; Get all the literal sexps
22573 (goto-char (point-min))
22574 (while (re-search-forward "^&?%%(" nil t)
22575 (catch :skip
22576 (org-agenda-skip)
22577 (setq b (match-beginning 0))
22578 (goto-char (1- (match-end 0)))
22579 (forward-sexp 1)
22580 (end-of-line 1)
22581 (setq sexp (buffer-substring b (point)))
22582 (with-current-buffer sexp-buffer
22583 (insert sexp "\n"))
22584 (princ (org-diary-to-ical-string sexp-buffer)))))
22586 (when org-icalendar-include-todo
22587 (goto-char (point-min))
22588 (while (re-search-forward org-todo-line-regexp nil t)
22589 (catch :skip
22590 (org-agenda-skip)
22591 (setq state (match-string 2))
22592 (setq status (if (member state org-done-keywords)
22593 "COMPLETED" "NEEDS-ACTION"))
22594 (when (and state
22595 (or (not (member state org-done-keywords))
22596 (eq org-icalendar-include-todo 'all))
22597 (not (member org-archive-tag (org-get-tags-at)))
22599 (setq hd (match-string 3))
22600 (if (string-match org-bracket-link-regexp hd)
22601 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22602 (match-string 1 hd))
22603 t t hd)))
22604 (if (string-match org-priority-regexp hd)
22605 (setq pri (string-to-char (match-string 2 hd))
22606 hd (concat (substring hd 0 (match-beginning 1))
22607 (substring hd (match-end 1))))
22608 (setq pri org-default-priority))
22609 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
22610 (- org-lowest-priority org-highest-priority))))))
22612 (princ (format "BEGIN:VTODO
22614 SUMMARY:%s
22615 CATEGORIES:%s
22616 SEQUENCE:1
22617 PRIORITY:%d
22618 STATUS:%s
22619 END:VTODO\n"
22620 dts hd category pri status)))))))))
22622 (defun org-start-icalendar-file (name)
22623 "Start an iCalendar file by inserting the header."
22624 (let ((user user-full-name)
22625 (name (or name "unknown"))
22626 (timezone (cadr (current-time-zone))))
22627 (princ
22628 (format "BEGIN:VCALENDAR
22629 VERSION:2.0
22630 X-WR-CALNAME:%s
22631 PRODID:-//%s//Emacs with Org-mode//EN
22632 X-WR-TIMEZONE:%s
22633 CALSCALE:GREGORIAN\n" name user timezone))))
22635 (defun org-finish-icalendar-file ()
22636 "Finish an iCalendar file by inserting the END statement."
22637 (princ "END:VCALENDAR\n"))
22639 (defun org-ical-ts-to-string (s keyword &optional inc)
22640 "Take a time string S and convert it to iCalendar format.
22641 KEYWORD is added in front, to make a complete line like DTSTART....
22642 When INC is non-nil, increase the hour by two (if time string contains
22643 a time), or the day by one (if it does not contain a time)."
22644 (let ((t1 (org-parse-time-string s 'nodefault))
22645 t2 fmt have-time time)
22646 (if (and (car t1) (nth 1 t1) (nth 2 t1))
22647 (setq t2 t1 have-time t)
22648 (setq t2 (org-parse-time-string s)))
22649 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
22650 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
22651 (when inc
22652 (if have-time
22653 (if org-agenda-default-appointment-duration
22654 (setq mi (+ org-agenda-default-appointment-duration mi))
22655 (setq h (+ 2 h)))
22656 (setq d (1+ d))))
22657 (setq time (encode-time s mi h d m y)))
22658 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
22659 (concat keyword (format-time-string fmt time))))
22661 ;;; XOXO export
22663 (defun org-export-as-xoxo-insert-into (buffer &rest output)
22664 (with-current-buffer buffer
22665 (apply 'insert output)))
22666 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
22668 (defun org-export-as-xoxo (&optional buffer)
22669 "Export the org buffer as XOXO.
22670 The XOXO buffer is named *xoxo-<source buffer name>*"
22671 (interactive (list (current-buffer)))
22672 ;; A quickie abstraction
22674 ;; Output everything as XOXO
22675 (with-current-buffer (get-buffer buffer)
22676 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
22677 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22678 (org-infile-export-plist)))
22679 (filename (concat (file-name-as-directory
22680 (org-export-directory :xoxo opt-plist))
22681 (file-name-sans-extension
22682 (file-name-nondirectory buffer-file-name))
22683 ".html"))
22684 (out (find-file-noselect filename))
22685 (last-level 1)
22686 (hanging-li nil))
22687 ;; Check the output buffer is empty.
22688 (with-current-buffer out (erase-buffer))
22689 ;; Kick off the output
22690 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
22691 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
22692 (let* ((hd (match-string-no-properties 1))
22693 (level (length hd))
22694 (text (concat
22695 (match-string-no-properties 2)
22696 (save-excursion
22697 (goto-char (match-end 0))
22698 (let ((str ""))
22699 (catch 'loop
22700 (while 't
22701 (forward-line)
22702 (if (looking-at "^[ \t]\\(.*\\)")
22703 (setq str (concat str (match-string-no-properties 1)))
22704 (throw 'loop str)))))))))
22706 ;; Handle level rendering
22707 (cond
22708 ((> level last-level)
22709 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
22711 ((< level last-level)
22712 (dotimes (- (- last-level level) 1)
22713 (if hanging-li
22714 (org-export-as-xoxo-insert-into out "</li>\n"))
22715 (org-export-as-xoxo-insert-into out "</ol>\n"))
22716 (when hanging-li
22717 (org-export-as-xoxo-insert-into out "</li>\n")
22718 (setq hanging-li nil)))
22720 ((equal level last-level)
22721 (if hanging-li
22722 (org-export-as-xoxo-insert-into out "</li>\n")))
22725 (setq last-level level)
22727 ;; And output the new li
22728 (setq hanging-li 't)
22729 (if (equal ?+ (elt text 0))
22730 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
22731 (org-export-as-xoxo-insert-into out "<li>" text))))
22733 ;; Finally finish off the ol
22734 (dotimes (- last-level 1)
22735 (if hanging-li
22736 (org-export-as-xoxo-insert-into out "</li>\n"))
22737 (org-export-as-xoxo-insert-into out "</ol>\n"))
22739 ;; Finish the buffer off and clean it up.
22740 (switch-to-buffer-other-window out)
22741 (indent-region (point-min) (point-max) nil)
22742 (save-buffer)
22743 (goto-char (point-min))
22747 ;;;; Key bindings
22749 ;; Make `C-c C-x' a prefix key
22750 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
22752 ;; TAB key with modifiers
22753 (org-defkey org-mode-map "\C-i" 'org-cycle)
22754 (org-defkey org-mode-map [(tab)] 'org-cycle)
22755 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
22756 (org-defkey org-mode-map [(meta tab)] 'org-complete)
22757 (org-defkey org-mode-map "\M-\t" 'org-complete)
22758 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
22759 ;; The following line is necessary under Suse GNU/Linux
22760 (unless (featurep 'xemacs)
22761 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
22762 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
22763 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
22765 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
22766 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
22767 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
22769 ;; Cursor keys with modifiers
22770 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
22771 (org-defkey org-mode-map [(meta right)] 'org-metaright)
22772 (org-defkey org-mode-map [(meta up)] 'org-metaup)
22773 (org-defkey org-mode-map [(meta down)] 'org-metadown)
22775 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
22776 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
22777 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
22778 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
22780 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
22781 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
22782 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
22783 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
22785 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
22786 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
22788 ;;; Extra keys for tty access.
22789 ;; We only set them when really needed because otherwise the
22790 ;; menus don't show the simple keys
22792 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
22793 (not window-system))
22794 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
22795 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
22796 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
22797 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
22798 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
22799 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
22800 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
22801 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
22802 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
22803 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
22804 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
22805 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
22806 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
22807 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
22808 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
22809 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
22810 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
22811 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
22812 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
22813 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
22814 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
22815 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
22817 ;; All the other keys
22819 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
22820 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
22821 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
22822 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
22823 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
22824 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
22825 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
22826 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
22827 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
22828 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
22829 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
22830 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
22831 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
22832 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
22833 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
22834 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
22835 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
22836 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
22837 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
22838 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
22839 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
22840 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
22841 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
22842 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
22843 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
22844 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
22845 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
22846 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
22847 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
22848 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
22849 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
22850 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
22851 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
22852 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
22853 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
22854 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
22855 (org-defkey org-mode-map "\C-c^" 'org-sort)
22856 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
22857 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
22858 (org-defkey org-mode-map "\C-m" 'org-return)
22859 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
22860 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
22861 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
22862 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
22863 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
22864 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
22865 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
22866 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
22867 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
22868 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
22869 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
22870 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
22871 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
22872 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
22873 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
22874 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
22876 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
22877 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
22878 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
22879 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
22881 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
22882 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
22883 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
22884 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
22885 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
22886 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
22887 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
22888 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
22889 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
22891 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
22893 (when (featurep 'xemacs)
22894 (org-defkey org-mode-map 'button3 'popup-mode-menu))
22896 (defsubst org-table-p () (org-at-table-p))
22898 (defun org-self-insert-command (N)
22899 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
22900 If the cursor is in a table looking at whitespace, the whitespace is
22901 overwritten, and the table is not marked as requiring realignment."
22902 (interactive "p")
22903 (if (and (org-table-p)
22904 (progn
22905 ;; check if we blank the field, and if that triggers align
22906 (and org-table-auto-blank-field
22907 (member last-command
22908 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
22909 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
22910 ;; got extra space, this field does not determine column width
22911 (let (org-table-may-need-update) (org-table-blank-field))
22912 ;; no extra space, this field may determine column width
22913 (org-table-blank-field)))
22915 (eq N 1)
22916 (looking-at "[^|\n]* |"))
22917 (let (org-table-may-need-update)
22918 (goto-char (1- (match-end 0)))
22919 (delete-backward-char 1)
22920 (goto-char (match-beginning 0))
22921 (self-insert-command N))
22922 (setq org-table-may-need-update t)
22923 (self-insert-command N)
22924 (org-fix-tags-on-the-fly)))
22926 (defun org-fix-tags-on-the-fly ()
22927 (when (and (equal (char-after (point-at-bol)) ?*)
22928 (org-on-heading-p))
22929 (org-align-tags-here org-tags-column)))
22931 (defun org-delete-backward-char (N)
22932 "Like `delete-backward-char', insert whitespace at field end in tables.
22933 When deleting backwards, in tables this function will insert whitespace in
22934 front of the next \"|\" separator, to keep the table aligned. The table will
22935 still be marked for re-alignment if the field did fill the entire column,
22936 because, in this case the deletion might narrow the column."
22937 (interactive "p")
22938 (if (and (org-table-p)
22939 (eq N 1)
22940 (string-match "|" (buffer-substring (point-at-bol) (point)))
22941 (looking-at ".*?|"))
22942 (let ((pos (point))
22943 (noalign (looking-at "[^|\n\r]* |"))
22944 (c org-table-may-need-update))
22945 (backward-delete-char N)
22946 (skip-chars-forward "^|")
22947 (insert " ")
22948 (goto-char (1- pos))
22949 ;; noalign: if there were two spaces at the end, this field
22950 ;; does not determine the width of the column.
22951 (if noalign (setq org-table-may-need-update c)))
22952 (backward-delete-char N)
22953 (org-fix-tags-on-the-fly)))
22955 (defun org-delete-char (N)
22956 "Like `delete-char', but insert whitespace at field end in tables.
22957 When deleting characters, in tables this function will insert whitespace in
22958 front of the next \"|\" separator, to keep the table aligned. The table will
22959 still be marked for re-alignment if the field did fill the entire column,
22960 because, in this case the deletion might narrow the column."
22961 (interactive "p")
22962 (if (and (org-table-p)
22963 (not (bolp))
22964 (not (= (char-after) ?|))
22965 (eq N 1))
22966 (if (looking-at ".*?|")
22967 (let ((pos (point))
22968 (noalign (looking-at "[^|\n\r]* |"))
22969 (c org-table-may-need-update))
22970 (replace-match (concat
22971 (substring (match-string 0) 1 -1)
22972 " |"))
22973 (goto-char pos)
22974 ;; noalign: if there were two spaces at the end, this field
22975 ;; does not determine the width of the column.
22976 (if noalign (setq org-table-may-need-update c)))
22977 (delete-char N))
22978 (delete-char N)
22979 (org-fix-tags-on-the-fly)))
22981 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
22982 (put 'org-self-insert-command 'delete-selection t)
22983 (put 'orgtbl-self-insert-command 'delete-selection t)
22984 (put 'org-delete-char 'delete-selection 'supersede)
22985 (put 'org-delete-backward-char 'delete-selection 'supersede)
22987 ;; Make `flyspell-mode' delay after some commands
22988 (put 'org-self-insert-command 'flyspell-delayed t)
22989 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
22990 (put 'org-delete-char 'flyspell-delayed t)
22991 (put 'org-delete-backward-char 'flyspell-delayed t)
22993 ;; How to do this: Measure non-white length of current string
22994 ;; If equal to column width, we should realign.
22996 (defun org-remap (map &rest commands)
22997 "In MAP, remap the functions given in COMMANDS.
22998 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
22999 (let (new old)
23000 (while commands
23001 (setq old (pop commands) new (pop commands))
23002 (if (fboundp 'command-remapping)
23003 (org-defkey map (vector 'remap old) new)
23004 (substitute-key-definition old new map global-map)))))
23006 (when (eq org-enable-table-editor 'optimized)
23007 ;; If the user wants maximum table support, we need to hijack
23008 ;; some standard editing functions
23009 (org-remap org-mode-map
23010 'self-insert-command 'org-self-insert-command
23011 'delete-char 'org-delete-char
23012 'delete-backward-char 'org-delete-backward-char)
23013 (org-defkey org-mode-map "|" 'org-force-self-insert))
23015 (defun org-shiftcursor-error ()
23016 "Throw an error because Shift-Cursor command was applied in wrong context."
23017 (error "This command is active in special context like tables, headlines or timestamps"))
23019 (defun org-shifttab (&optional arg)
23020 "Global visibility cycling or move to previous table field.
23021 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
23022 on context.
23023 See the individual commands for more information."
23024 (interactive "P")
23025 (cond
23026 ((org-at-table-p) (call-interactively 'org-table-previous-field))
23027 (arg (message "Content view to level: ")
23028 (org-content (prefix-numeric-value arg))
23029 (setq org-cycle-global-status 'overview))
23030 (t (call-interactively 'org-global-cycle))))
23032 (defun org-shiftmetaleft ()
23033 "Promote subtree or delete table column.
23034 Calls `org-promote-subtree', `org-outdent-item',
23035 or `org-table-delete-column', depending on context.
23036 See the individual commands for more information."
23037 (interactive)
23038 (cond
23039 ((org-at-table-p) (call-interactively 'org-table-delete-column))
23040 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
23041 ((org-at-item-p) (call-interactively 'org-outdent-item))
23042 (t (org-shiftcursor-error))))
23044 (defun org-shiftmetaright ()
23045 "Demote subtree or insert table column.
23046 Calls `org-demote-subtree', `org-indent-item',
23047 or `org-table-insert-column', depending on context.
23048 See the individual commands for more information."
23049 (interactive)
23050 (cond
23051 ((org-at-table-p) (call-interactively 'org-table-insert-column))
23052 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
23053 ((org-at-item-p) (call-interactively 'org-indent-item))
23054 (t (org-shiftcursor-error))))
23056 (defun org-shiftmetaup (&optional arg)
23057 "Move subtree up or kill table row.
23058 Calls `org-move-subtree-up' or `org-table-kill-row' or
23059 `org-move-item-up' depending on context. See the individual commands
23060 for more information."
23061 (interactive "P")
23062 (cond
23063 ((org-at-table-p) (call-interactively 'org-table-kill-row))
23064 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23065 ((org-at-item-p) (call-interactively 'org-move-item-up))
23066 (t (org-shiftcursor-error))))
23067 (defun org-shiftmetadown (&optional arg)
23068 "Move subtree down or insert table row.
23069 Calls `org-move-subtree-down' or `org-table-insert-row' or
23070 `org-move-item-down', depending on context. See the individual
23071 commands for more information."
23072 (interactive "P")
23073 (cond
23074 ((org-at-table-p) (call-interactively 'org-table-insert-row))
23075 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23076 ((org-at-item-p) (call-interactively 'org-move-item-down))
23077 (t (org-shiftcursor-error))))
23079 (defun org-metaleft (&optional arg)
23080 "Promote heading or move table column to left.
23081 Calls `org-do-promote' or `org-table-move-column', depending on context.
23082 With no specific context, calls the Emacs default `backward-word'.
23083 See the individual commands for more information."
23084 (interactive "P")
23085 (cond
23086 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
23087 ((or (org-on-heading-p) (org-region-active-p))
23088 (call-interactively 'org-do-promote))
23089 ((org-at-item-p) (call-interactively 'org-outdent-item))
23090 (t (call-interactively 'backward-word))))
23092 (defun org-metaright (&optional arg)
23093 "Demote subtree or move table column to right.
23094 Calls `org-do-demote' or `org-table-move-column', depending on context.
23095 With no specific context, calls the Emacs default `forward-word'.
23096 See the individual commands for more information."
23097 (interactive "P")
23098 (cond
23099 ((org-at-table-p) (call-interactively 'org-table-move-column))
23100 ((or (org-on-heading-p) (org-region-active-p))
23101 (call-interactively 'org-do-demote))
23102 ((org-at-item-p) (call-interactively 'org-indent-item))
23103 (t (call-interactively 'forward-word))))
23105 (defun org-metaup (&optional arg)
23106 "Move subtree up or move table row up.
23107 Calls `org-move-subtree-up' or `org-table-move-row' or
23108 `org-move-item-up', depending on context. See the individual commands
23109 for more information."
23110 (interactive "P")
23111 (cond
23112 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
23113 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23114 ((org-at-item-p) (call-interactively 'org-move-item-up))
23115 (t (org-shiftcursor-error))))
23117 (defun org-metadown (&optional arg)
23118 "Move subtree down or move table row down.
23119 Calls `org-move-subtree-down' or `org-table-move-row' or
23120 `org-move-item-down', depending on context. See the individual
23121 commands for more information."
23122 (interactive "P")
23123 (cond
23124 ((org-at-table-p) (call-interactively 'org-table-move-row))
23125 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23126 ((org-at-item-p) (call-interactively 'org-move-item-down))
23127 (t (org-shiftcursor-error))))
23129 (defun org-shiftup (&optional arg)
23130 "Increase item in timestamp or increase priority of current headline.
23131 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
23132 depending on context. See the individual commands for more information."
23133 (interactive "P")
23134 (cond
23135 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
23136 ((org-on-heading-p) (call-interactively 'org-priority-up))
23137 ((org-at-item-p) (call-interactively 'org-previous-item))
23138 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
23140 (defun org-shiftdown (&optional arg)
23141 "Decrease item in timestamp or decrease priority of current headline.
23142 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
23143 depending on context. See the individual commands for more information."
23144 (interactive "P")
23145 (cond
23146 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
23147 ((org-on-heading-p) (call-interactively 'org-priority-down))
23148 (t (call-interactively 'org-next-item))))
23150 (defun org-shiftright ()
23151 "Next TODO keyword or timestamp one day later, depending on context."
23152 (interactive)
23153 (cond
23154 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
23155 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
23156 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
23157 (t (org-shiftcursor-error))))
23159 (defun org-shiftleft ()
23160 "Previous TODO keyword or timestamp one day earlier, depending on context."
23161 (interactive)
23162 (cond
23163 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
23164 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
23165 ((org-at-property-p)
23166 (call-interactively 'org-property-previous-allowed-value))
23167 (t (org-shiftcursor-error))))
23169 (defun org-shiftcontrolright ()
23170 "Switch to next TODO set."
23171 (interactive)
23172 (cond
23173 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
23174 (t (org-shiftcursor-error))))
23176 (defun org-shiftcontrolleft ()
23177 "Switch to previous TODO set."
23178 (interactive)
23179 (cond
23180 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
23181 (t (org-shiftcursor-error))))
23183 (defun org-ctrl-c-ret ()
23184 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
23185 (interactive)
23186 (cond
23187 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
23188 (t (call-interactively 'org-insert-heading))))
23190 (defun org-copy-special ()
23191 "Copy region in table or copy current subtree.
23192 Calls `org-table-copy' or `org-copy-subtree', depending on context.
23193 See the individual commands for more information."
23194 (interactive)
23195 (call-interactively
23196 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
23198 (defun org-cut-special ()
23199 "Cut region in table or cut current subtree.
23200 Calls `org-table-copy' or `org-cut-subtree', depending on context.
23201 See the individual commands for more information."
23202 (interactive)
23203 (call-interactively
23204 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
23206 (defun org-paste-special (arg)
23207 "Paste rectangular region into table, or past subtree relative to level.
23208 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
23209 See the individual commands for more information."
23210 (interactive "P")
23211 (if (org-at-table-p)
23212 (org-table-paste-rectangle)
23213 (org-paste-subtree arg)))
23215 (defun org-ctrl-c-ctrl-c (&optional arg)
23216 "Set tags in headline, or update according to changed information at point.
23218 This command does many different things, depending on context:
23220 - If the cursor is in a headline, prompt for tags and insert them
23221 into the current line, aligned to `org-tags-column'. When called
23222 with prefix arg, realign all tags in the current buffer.
23224 - If the cursor is in one of the special #+KEYWORD lines, this
23225 triggers scanning the buffer for these lines and updating the
23226 information.
23228 - If the cursor is inside a table, realign the table. This command
23229 works even if the automatic table editor has been turned off.
23231 - If the cursor is on a #+TBLFM line, re-apply the formulas to
23232 the entire table.
23234 - If the cursor is inside a table created by the table.el package,
23235 activate that table.
23237 - If the current buffer is a remember buffer, close note and file it.
23238 with a prefix argument, file it without further interaction to the default
23239 location.
23241 - If the cursor is on a <<<target>>>, update radio targets and corresponding
23242 links in this buffer.
23244 - If the cursor is on a numbered item in a plain list, renumber the
23245 ordered list."
23246 (interactive "P")
23247 (let ((org-enable-table-editor t))
23248 (cond
23249 ((or org-clock-overlays
23250 org-occur-highlights
23251 org-latex-fragment-image-overlays)
23252 (org-remove-clock-overlays)
23253 (org-remove-occur-highlights)
23254 (org-remove-latex-fragment-image-overlays)
23255 (message "Temporary highlights/overlays removed from current buffer"))
23256 ((and (local-variable-p 'org-finish-function (current-buffer))
23257 (fboundp org-finish-function))
23258 (funcall org-finish-function))
23259 ((org-at-property-p)
23260 (call-interactively 'org-property-action))
23261 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
23262 ((org-on-heading-p) (call-interactively 'org-set-tags))
23263 ((org-at-table.el-p)
23264 (require 'table)
23265 (beginning-of-line 1)
23266 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
23267 (call-interactively 'table-recognize-table))
23268 ((org-at-table-p)
23269 (org-table-maybe-eval-formula)
23270 (if arg
23271 (call-interactively 'org-table-recalculate)
23272 (org-table-maybe-recalculate-line))
23273 (call-interactively 'org-table-align))
23274 ((org-at-item-checkbox-p)
23275 (call-interactively 'org-toggle-checkbox))
23276 ((org-at-item-p)
23277 (call-interactively 'org-maybe-renumber-ordered-list))
23278 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
23279 (cond
23280 ((equal (match-string 1) "TBLFM")
23281 ;; Recalculate the table before this line
23282 (save-excursion
23283 (beginning-of-line 1)
23284 (skip-chars-backward " \r\n\t")
23285 (if (org-at-table-p)
23286 (org-call-with-arg 'org-table-recalculate t))))
23288 (call-interactively 'org-mode-restart))))
23289 (t (error "C-c C-c can do nothing useful at this location.")))))
23291 (defun org-mode-restart ()
23292 "Restart Org-mode, to scan again for special lines.
23293 Also updates the keyword regular expressions."
23294 (interactive)
23295 (let ((org-inhibit-startup t)) (org-mode))
23296 (message "Org-mode restarted to refresh keyword and special line setup"))
23298 (defun org-return ()
23299 "Goto next table row or insert a newline.
23300 Calls `org-table-next-row' or `newline', depending on context.
23301 See the individual commands for more information."
23302 (interactive)
23303 (cond
23304 ((bobp) (newline))
23305 ((org-at-table-p)
23306 (org-table-justify-field-maybe)
23307 (call-interactively 'org-table-next-row))
23308 (t (newline))))
23310 (defun org-ctrl-c-minus ()
23311 "Insert separator line in table or modify bullet type in list.
23312 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
23313 depending on context."
23314 (interactive)
23315 (cond
23316 ((org-at-table-p)
23317 (call-interactively 'org-table-insert-hline))
23318 ((org-in-item-p)
23319 (call-interactively 'org-cycle-list-bullet))
23320 (t (error "`C-c -' does have no function here."))))
23322 (defun org-meta-return (&optional arg)
23323 "Insert a new heading or wrap a region in a table.
23324 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
23325 See the individual commands for more information."
23326 (interactive "P")
23327 (cond
23328 ((org-at-table-p)
23329 (call-interactively 'org-table-wrap-region))
23330 (t (call-interactively 'org-insert-heading))))
23332 ;;; Menu entries
23334 ;; Define the Org-mode menus
23335 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
23336 '("Tbl"
23337 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
23338 ["Next Field" org-cycle (org-at-table-p)]
23339 ["Previous Field" org-shifttab (org-at-table-p)]
23340 ["Next Row" org-return (org-at-table-p)]
23341 "--"
23342 ["Blank Field" org-table-blank-field (org-at-table-p)]
23343 ["Edit Field" org-table-edit-field (org-at-table-p)]
23344 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
23345 "--"
23346 ("Column"
23347 ["Move Column Left" org-metaleft (org-at-table-p)]
23348 ["Move Column Right" org-metaright (org-at-table-p)]
23349 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
23350 ["Insert Column" org-shiftmetaright (org-at-table-p)])
23351 ("Row"
23352 ["Move Row Up" org-metaup (org-at-table-p)]
23353 ["Move Row Down" org-metadown (org-at-table-p)]
23354 ["Delete Row" org-shiftmetaup (org-at-table-p)]
23355 ["Insert Row" org-shiftmetadown (org-at-table-p)]
23356 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
23357 "--"
23358 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
23359 ("Rectangle"
23360 ["Copy Rectangle" org-copy-special (org-at-table-p)]
23361 ["Cut Rectangle" org-cut-special (org-at-table-p)]
23362 ["Paste Rectangle" org-paste-special (org-at-table-p)]
23363 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
23364 "--"
23365 ("Calculate"
23366 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
23367 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
23368 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
23369 "--"
23370 ["Recalculate line" org-table-recalculate (org-at-table-p)]
23371 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
23372 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
23373 "--"
23374 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
23375 "--"
23376 ["Sum Column/Rectangle" org-table-sum
23377 (or (org-at-table-p) (org-region-active-p))]
23378 ["Which Column?" org-table-current-column (org-at-table-p)])
23379 ["Debug Formulas"
23380 org-table-toggle-formula-debugger
23381 :style toggle :selected org-table-formula-debug]
23382 ["Show Col/Row Numbers"
23383 org-table-toggle-coordinate-overlays
23384 :style toggle :selected org-table-overlay-coordinates]
23385 "--"
23386 ["Create" org-table-create (and (not (org-at-table-p))
23387 org-enable-table-editor)]
23388 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
23389 ["Import from File" org-table-import (not (org-at-table-p))]
23390 ["Export to File" org-table-export (org-at-table-p)]
23391 "--"
23392 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
23394 (easy-menu-define org-org-menu org-mode-map "Org menu"
23395 '("Org"
23396 ("Show/Hide"
23397 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
23398 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
23399 ["Sparse Tree" org-occur t]
23400 ["Reveal Context" org-reveal t]
23401 ["Show All" show-all t]
23402 "--"
23403 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
23404 "--"
23405 ["New Heading" org-insert-heading t]
23406 ("Navigate Headings"
23407 ["Up" outline-up-heading t]
23408 ["Next" outline-next-visible-heading t]
23409 ["Previous" outline-previous-visible-heading t]
23410 ["Next Same Level" outline-forward-same-level t]
23411 ["Previous Same Level" outline-backward-same-level t]
23412 "--"
23413 ["Jump" org-goto t]
23414 "--"
23415 ["C-a/e find headline/item start/end"
23416 (setq org-special-ctrl-a/e (not org-special-ctrl-a/e))
23417 :style toggle :selected org-special-ctrl-a/e])
23418 ("Edit Structure"
23419 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
23420 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
23421 "--"
23422 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
23423 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
23424 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
23425 "--"
23426 ["Promote Heading" org-metaleft (not (org-at-table-p))]
23427 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
23428 ["Demote Heading" org-metaright (not (org-at-table-p))]
23429 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
23430 "--"
23431 ["Sort Region/Children" org-sort (not (org-at-table-p))]
23432 "--"
23433 ["Convert to odd levels" org-convert-to-odd-levels t]
23434 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
23435 ("Editing"
23436 ["Emphasis..." org-emphasize t])
23437 ("Archive"
23438 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
23439 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
23440 ; :active t :keys "C-u C-c C-x C-a"]
23441 ["Sparse trees open ARCHIVE trees"
23442 (setq org-sparse-tree-open-archived-trees
23443 (not org-sparse-tree-open-archived-trees))
23444 :style toggle :selected org-sparse-tree-open-archived-trees]
23445 ["Cycling opens ARCHIVE trees"
23446 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
23447 :style toggle :selected org-cycle-open-archived-trees]
23448 ["Agenda includes ARCHIVE trees"
23449 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
23450 :style toggle :selected (not org-agenda-skip-archived-trees)]
23451 "--"
23452 ["Move Subtree to Archive" org-advertized-archive-subtree t]
23453 ; ["Check and Move Children" (org-archive-subtree '(4))
23454 ; :active t :keys "C-u C-c C-x C-s"]
23456 "--"
23457 ("TODO Lists"
23458 ["TODO/DONE/-" org-todo t]
23459 ("Select keyword"
23460 ["Next keyword" org-shiftright (org-on-heading-p)]
23461 ["Previous keyword" org-shiftleft (org-on-heading-p)]
23462 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
23463 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
23464 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
23465 ["Show TODO Tree" org-show-todo-tree t]
23466 ["Global TODO list" org-todo-list t]
23467 "--"
23468 ["Set Priority" org-priority t]
23469 ["Priority Up" org-shiftup t]
23470 ["Priority Down" org-shiftdown t])
23471 ("TAGS and Properties"
23472 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
23473 ["Column view of properties" org-columns t])
23474 ("Dates and Scheduling"
23475 ["Timestamp" org-time-stamp t]
23476 ["Timestamp (inactive)" org-time-stamp-inactive t]
23477 ("Change Date"
23478 ["1 Day Later" org-shiftright t]
23479 ["1 Day Earlier" org-shiftleft t]
23480 ["1 ... Later" org-shiftup t]
23481 ["1 ... Earlier" org-shiftdown t])
23482 ["Compute Time Range" org-evaluate-time-range t]
23483 ["Schedule Item" org-schedule t]
23484 ["Deadline" org-deadline t]
23485 "--"
23486 ["Custom time format" org-toggle-time-stamp-overlays
23487 :style radio :selected org-display-custom-times]
23488 "--"
23489 ["Goto Calendar" org-goto-calendar t]
23490 ["Date from Calendar" org-date-from-calendar t])
23491 ("Logging work"
23492 ["Clock in" org-clock-in t]
23493 ["Clock out" org-clock-out t]
23494 ["Clock cancel" org-clock-cancel t]
23495 ["Display times" org-clock-display t]
23496 ["Create clock table" org-clock-report t]
23497 "--"
23498 ["Record DONE time"
23499 (progn (setq org-log-done (not org-log-done))
23500 (message "Switching to %s will %s record a timestamp"
23501 (car org-done-keywords)
23502 (if org-log-done "automatically" "not")))
23503 :style toggle :selected org-log-done])
23504 "--"
23505 ["Agenda Command..." org-agenda t]
23506 ("File List for Agenda")
23507 ("Special views current file"
23508 ["TODO Tree" org-show-todo-tree t]
23509 ["Check Deadlines" org-check-deadlines t]
23510 ["Timeline" org-timeline t]
23511 ["Tags Tree" org-tags-sparse-tree t])
23512 "--"
23513 ("Hyperlinks"
23514 ["Store Link (Global)" org-store-link t]
23515 ["Insert Link" org-insert-link t]
23516 ["Follow Link" org-open-at-point t]
23517 "--"
23518 ["Next link" org-next-link t]
23519 ["Previous link" org-previous-link t]
23520 "--"
23521 ["Descriptive Links"
23522 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
23523 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
23524 ["Literal Links"
23525 (progn
23526 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
23527 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
23528 "--"
23529 ["Export/Publish..." org-export t]
23530 ("LaTeX"
23531 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
23532 :selected org-cdlatex-mode]
23533 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
23534 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
23535 ["Modify math symbol" org-cdlatex-math-modify
23536 (org-inside-LaTeX-fragment-p)]
23537 ["Export LaTeX fragments as images"
23538 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
23539 :style toggle :selected org-export-with-LaTeX-fragments])
23540 "--"
23541 ("Documentation"
23542 ["Show Version" org-version t]
23543 ["Info Documentation" org-info t])
23544 ("Customize"
23545 ["Browse Org Group" org-customize t]
23546 "--"
23547 ["Expand This Menu" org-create-customize-menu
23548 (fboundp 'customize-menu-create)])
23549 "--"
23550 ["Refresh setup" org-mode-restart t]
23553 (defun org-info (&optional node)
23554 "Read documentation for Org-mode in the info system.
23555 With optional NODE, go directly to that node."
23556 (interactive)
23557 (require 'info)
23558 (Info-goto-node (format "(org)%s" (or node ""))))
23560 (defun org-install-agenda-files-menu ()
23561 (let ((bl (buffer-list)))
23562 (save-excursion
23563 (while bl
23564 (set-buffer (pop bl))
23565 (if (org-mode-p) (setq bl nil)))
23566 (when (org-mode-p)
23567 (easy-menu-change
23568 '("Org") "File List for Agenda"
23569 (append
23570 (list
23571 ["Edit File List" (org-edit-agenda-file-list) t]
23572 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
23573 ["Remove Current File from List" org-remove-file t]
23574 ["Cycle through agenda files" org-cycle-agenda-files t]
23575 "--")
23576 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
23578 ;;;; Documentation
23580 (defun org-customize ()
23581 "Call the customize function with org as argument."
23582 (interactive)
23583 (customize-browse 'org))
23585 (defun org-create-customize-menu ()
23586 "Create a full customization menu for Org-mode, insert it into the menu."
23587 (interactive)
23588 (if (fboundp 'customize-menu-create)
23589 (progn
23590 (easy-menu-change
23591 '("Org") "Customize"
23592 `(["Browse Org group" org-customize t]
23593 "--"
23594 ,(customize-menu-create 'org)
23595 ["Set" Custom-set t]
23596 ["Save" Custom-save t]
23597 ["Reset to Current" Custom-reset-current t]
23598 ["Reset to Saved" Custom-reset-saved t]
23599 ["Reset to Standard Settings" Custom-reset-standard t]))
23600 (message "\"Org\"-menu now contains full customization menu"))
23601 (error "Cannot expand menu (outdated version of cus-edit.el)")))
23603 ;;;; Miscellaneous stuff
23606 ;;; Generally useful functions
23608 (defun org-context ()
23609 "Return a list of contexts of the current cursor position.
23610 If several contexts apply, all are returned.
23611 Each context entry is a list with a symbol naming the context, and
23612 two positions indicating start and end of the context. Possible
23613 contexts are:
23615 :headline anywhere in a headline
23616 :headline-stars on the leading stars in a headline
23617 :todo-keyword on a TODO keyword (including DONE) in a headline
23618 :tags on the TAGS in a headline
23619 :priority on the priority cookie in a headline
23620 :item on the first line of a plain list item
23621 :item-bullet on the bullet/number of a plain list item
23622 :checkbox on the checkbox in a plain list item
23623 :table in an org-mode table
23624 :table-special on a special filed in a table
23625 :table-table in a table.el table
23626 :link on a hyperlink
23627 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
23628 :target on a <<target>>
23629 :radio-target on a <<<radio-target>>>
23630 :latex-fragment on a LaTeX fragment
23631 :latex-preview on a LaTeX fragment with overlayed preview image
23633 This function expects the position to be visible because it uses font-lock
23634 faces as a help to recognize the following contexts: :table-special, :link,
23635 and :keyword."
23636 (let* ((f (get-text-property (point) 'face))
23637 (faces (if (listp f) f (list f)))
23638 (p (point)) clist o)
23639 ;; First the large context
23640 (cond
23641 ((org-on-heading-p t)
23642 (push (list :headline (point-at-bol) (point-at-eol)) clist)
23643 (when (progn
23644 (beginning-of-line 1)
23645 (looking-at org-todo-line-tags-regexp))
23646 (push (org-point-in-group p 1 :headline-stars) clist)
23647 (push (org-point-in-group p 2 :todo-keyword) clist)
23648 (push (org-point-in-group p 4 :tags) clist))
23649 (goto-char p)
23650 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
23651 (if (looking-at "\\[#[A-Z0-9]\\]")
23652 (push (org-point-in-group p 0 :priority) clist)))
23654 ((org-at-item-p)
23655 (push (org-point-in-group p 2 :item-bullet) clist)
23656 (push (list :item (point-at-bol)
23657 (save-excursion (org-end-of-item) (point)))
23658 clist)
23659 (and (org-at-item-checkbox-p)
23660 (push (org-point-in-group p 0 :checkbox) clist)))
23662 ((org-at-table-p)
23663 (push (list :table (org-table-begin) (org-table-end)) clist)
23664 (if (memq 'org-formula faces)
23665 (push (list :table-special
23666 (previous-single-property-change p 'face)
23667 (next-single-property-change p 'face)) clist)))
23668 ((org-at-table-p 'any)
23669 (push (list :table-table) clist)))
23670 (goto-char p)
23672 ;; Now the small context
23673 (cond
23674 ((org-at-timestamp-p)
23675 (push (org-point-in-group p 0 :timestamp) clist))
23676 ((memq 'org-link faces)
23677 (push (list :link
23678 (previous-single-property-change p 'face)
23679 (next-single-property-change p 'face)) clist))
23680 ((memq 'org-special-keyword faces)
23681 (push (list :keyword
23682 (previous-single-property-change p 'face)
23683 (next-single-property-change p 'face)) clist))
23684 ((org-on-target-p)
23685 (push (org-point-in-group p 0 :target) clist)
23686 (goto-char (1- (match-beginning 0)))
23687 (if (looking-at org-radio-target-regexp)
23688 (push (org-point-in-group p 0 :radio-target) clist))
23689 (goto-char p))
23690 ((setq o (car (delq nil
23691 (mapcar
23692 (lambda (x)
23693 (if (memq x org-latex-fragment-image-overlays) x))
23694 (org-overlays-at (point))))))
23695 (push (list :latex-fragment
23696 (org-overlay-start o) (org-overlay-end o)) clist)
23697 (push (list :latex-preview
23698 (org-overlay-start o) (org-overlay-end o)) clist))
23699 ((org-inside-LaTeX-fragment-p)
23700 ;; FIXME: positions wrong.
23701 (push (list :latex-fragment (point) (point)) clist)))
23703 (setq clist (nreverse (delq nil clist)))
23704 clist))
23706 ;; FIXME Compare with at-regexp-p
23707 (defun org-in-regexp (re &optional nlines visually)
23708 "Check if point is inside a match of regexp.
23709 Normally only the current line is checked, but you can include NLINES extra
23710 lines both before and after point into the search.
23711 If VISUALLY is set, require that the cursor is not after the match but
23712 really on, so that the block visually is on the match."
23713 (catch 'exit
23714 (let ((pos (point))
23715 (eol (point-at-eol (+ 1 (or nlines 0))))
23716 (inc (if visually 1 0)))
23717 (save-excursion
23718 (beginning-of-line (- 1 (or nlines 0)))
23719 (while (re-search-forward re eol t)
23720 (if (and (<= (match-beginning 0) pos)
23721 (>= (+ inc (match-end 0)) pos))
23722 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
23724 (defun org-at-regexp-p (regexp)
23725 "Is point inside a match of REGEXP in the current line?"
23726 (catch 'exit
23727 (save-excursion
23728 (let ((pos (point)) (end (point-at-eol)))
23729 (beginning-of-line 1)
23730 (while (re-search-forward regexp end t)
23731 (if (and (<= (match-beginning 0) pos)
23732 (>= (match-end 0) pos))
23733 (throw 'exit t)))
23734 nil))))
23736 (defun org-uniquify (list)
23737 "Remove duplicate elements from LIST."
23738 (let (res)
23739 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
23740 res))
23742 (defun org-delete-all (elts list)
23743 "Remove all elements in ELTS from LIST."
23744 (while elts
23745 (setq list (delete (pop elts) list)))
23746 list)
23748 (defun org-point-in-group (point group &optional context)
23749 "Check if POINT is in match-group GROUP.
23750 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
23751 match. If the match group does ot exist or point is not inside it,
23752 return nil."
23753 (and (match-beginning group)
23754 (>= point (match-beginning group))
23755 (<= point (match-end group))
23756 (if context
23757 (list context (match-beginning group) (match-end group))
23758 t)))
23760 (defun org-combine-plists (&rest plists)
23761 "Create a single property list from all plists in PLISTS.
23762 The process starts by copying the first list, and then setting properties
23763 from the other lists. Settings in the last list are the most significant
23764 ones and overrule settings in the other lists."
23765 (let ((rtn (copy-sequence (pop plists)))
23766 p v ls)
23767 (while plists
23768 (setq ls (pop plists))
23769 (while ls
23770 (setq p (pop ls) v (pop ls))
23771 (setq rtn (plist-put rtn p v))))
23772 rtn))
23774 (defun org-move-line-down (arg)
23775 "Move the current line down. With prefix argument, move it past ARG lines."
23776 (interactive "p")
23777 (let ((col (current-column))
23778 beg end pos)
23779 (beginning-of-line 1) (setq beg (point))
23780 (beginning-of-line 2) (setq end (point))
23781 (beginning-of-line (+ 1 arg))
23782 (setq pos (move-marker (make-marker) (point)))
23783 (insert (delete-and-extract-region beg end))
23784 (goto-char pos)
23785 (move-to-column col)))
23787 (defun org-move-line-up (arg)
23788 "Move the current line up. With prefix argument, move it past ARG lines."
23789 (interactive "p")
23790 (let ((col (current-column))
23791 beg end pos)
23792 (beginning-of-line 1) (setq beg (point))
23793 (beginning-of-line 2) (setq end (point))
23794 (beginning-of-line (- arg))
23795 (setq pos (move-marker (make-marker) (point)))
23796 (insert (delete-and-extract-region beg end))
23797 (goto-char pos)
23798 (move-to-column col)))
23800 (defun org-replace-escapes (string table)
23801 "Replace %-escapes in STRING with values in TABLE.
23802 TABLE is an association list with keys line \"%a\" and string values.
23803 The sequences in STRING may contain normal field width and padding information,
23804 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
23805 so values can contain further %-escapes if they are define later in TABLE."
23806 (let ((case-fold-search nil)
23807 e re rpl)
23808 (while (setq e (pop table))
23809 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
23810 (while (string-match re string)
23811 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
23812 (cdr e)))
23813 (setq string (replace-match rpl t t string))))
23814 string))
23817 (defun org-sublist (list start end)
23818 "Return a section of LIST, from START to END.
23819 Counting starts at 1."
23820 (let (rtn (c start))
23821 (setq list (nthcdr (1- start) list))
23822 (while (and list (<= c end))
23823 (push (pop list) rtn)
23824 (setq c (1+ c)))
23825 (nreverse rtn)))
23827 (defun org-find-base-buffer-visiting (file)
23828 "Like `find-buffer-visiting' but alway return the base buffer and
23829 not an indirect buffer"
23830 (let ((buf (find-buffer-visiting file)))
23831 (or (buffer-base-buffer buf) buf)))
23833 (defun org-image-file-name-regexp ()
23834 "Return regexp matching the file names of images."
23835 (if (fboundp 'image-file-name-regexp)
23836 (image-file-name-regexp)
23837 (let ((image-file-name-extensions
23838 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
23839 "xbm" "xpm" "pbm" "pgm" "ppm")))
23840 (concat "\\."
23841 (regexp-opt (nconc (mapcar 'upcase
23842 image-file-name-extensions)
23843 image-file-name-extensions)
23845 "\\'"))))
23847 (defun org-file-image-p (file)
23848 "Return non-nil if FILE is an image."
23849 (save-match-data
23850 (string-match (org-image-file-name-regexp) file)))
23852 ;;; Paragraph filling stuff.
23853 ;; We want this to be just right, so use the full arsenal.
23855 (defun org-indent-line-function ()
23856 "Indent line like previous, but further if previous was headline or item."
23857 (interactive)
23858 (let* ((pos (point))
23859 (itemp (org-at-item-p))
23860 column bpos bcol tpos tcol bullet btype bullet-type)
23861 ;; Find the previous relevant line
23862 (beginning-of-line 1)
23863 (cond
23864 ((looking-at "#") (setq column 0))
23865 ((looking-at "\\*+ ") (setq column 0))
23867 (beginning-of-line 0)
23868 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
23869 (beginning-of-line 0))
23870 (cond
23871 ((looking-at "\\*+[ \t]+")
23872 (goto-char (match-end 0))
23873 (setq column (current-column)))
23874 ((org-in-item-p)
23875 (org-beginning-of-item)
23876 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
23877 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
23878 (setq bpos (match-beginning 1) tpos (match-end 0)
23879 bcol (progn (goto-char bpos) (current-column))
23880 tcol (progn (goto-char tpos) (current-column))
23881 bullet (match-string 1)
23882 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
23883 (if (not itemp)
23884 (setq column tcol)
23885 (goto-char pos)
23886 (beginning-of-line 1)
23887 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
23888 (setq bullet (match-string 1)
23889 btype (if (string-match "[0-9]" bullet) "n" bullet))
23890 (setq column (if (equal btype bullet-type) bcol tcol))))
23891 (t (setq column (org-get-indentation))))))
23892 (goto-char pos)
23893 (if (<= (current-column) (current-indentation))
23894 (indent-line-to column)
23895 (save-excursion (indent-line-to column)))
23896 (setq column (current-column))
23897 (beginning-of-line 1)
23898 (if (looking-at
23899 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
23900 (replace-match (concat "\\1" (format org-property-format
23901 (match-string 2) (match-string 3)))
23902 t nil))
23903 (move-to-column column)))
23905 (defun org-set-autofill-regexps ()
23906 (interactive)
23907 ;; In the paragraph separator we include headlines, because filling
23908 ;; text in a line directly attached to a headline would otherwise
23909 ;; fill the headline as well.
23910 (org-set-local 'comment-start-skip "^#+[ \t]*")
23911 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
23912 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
23913 ;; The paragraph starter includes hand-formatted lists.
23914 (org-set-local 'paragraph-start
23915 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
23916 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
23917 ;; But only if the user has not turned off tables or fixed-width regions
23918 (org-set-local
23919 'auto-fill-inhibit-regexp
23920 (concat "\\*+ \\|#\\+"
23921 "\\|[ \t]*" org-keyword-time-regexp
23922 (if (or org-enable-table-editor org-enable-fixed-width-editor)
23923 (concat
23924 "\\|[ \t]*["
23925 (if org-enable-table-editor "|" "")
23926 (if org-enable-fixed-width-editor ":" "")
23927 "]"))))
23928 ;; We use our own fill-paragraph function, to make sure that tables
23929 ;; and fixed-width regions are not wrapped. That function will pass
23930 ;; through to `fill-paragraph' when appropriate.
23931 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
23932 ; Adaptive filling: To get full control, first make sure that
23933 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
23934 (org-set-local 'adaptive-fill-regexp "\000")
23935 (org-set-local 'adaptive-fill-function
23936 'org-adaptive-fill-function))
23938 (defun org-fill-paragraph (&optional justify)
23939 "Re-align a table, pass through to fill-paragraph if no table."
23940 (let ((table-p (org-at-table-p))
23941 (table.el-p (org-at-table.el-p)))
23942 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
23943 (table.el-p t) ; skip table.el tables
23944 (table-p (org-table-align) t) ; align org-mode tables
23945 (t nil)))) ; call paragraph-fill
23947 ;; For reference, this is the default value of adaptive-fill-regexp
23948 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
23950 (defun org-adaptive-fill-function ()
23951 "Return a fill prefix for org-mode files.
23952 In particular, this makes sure hanging paragraphs for hand-formatted lists
23953 work correctly."
23954 (cond ((looking-at "#[ \t]+")
23955 (match-string 0))
23956 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
23957 (save-excursion
23958 (goto-char (match-end 0))
23959 (make-string (current-column) ?\ )))
23960 (t nil)))
23962 ;;;; Functions extending outline functionality
23964 (defun org-beginning-of-line (&optional arg)
23965 "Go to the beginning of the current line. If that is invisible, continue
23966 to a visible line beginning. This makes the function of C-a more intuitive.
23967 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23968 first attempt, and only move to after the tags when the cursor is already
23969 beyond the end of the headline."
23970 (interactive "P")
23971 (let ((pos (point)))
23972 (beginning-of-line 1)
23973 (if (bobp)
23975 (backward-char 1)
23976 (if (org-invisible-p)
23977 (while (and (not (bobp)) (org-invisible-p))
23978 (backward-char 1)
23979 (beginning-of-line 1))
23980 (forward-char 1)))
23981 (when org-special-ctrl-a/e
23982 (cond
23983 ((and (looking-at org-todo-line-regexp)
23984 (= (char-after (match-end 1)) ?\ ))
23985 (goto-char
23986 (cond ((> pos (match-beginning 3)) (match-beginning 3))
23987 ((= pos (point)) (match-beginning 3))
23988 (t (point)))))
23989 ((org-at-item-p)
23990 (goto-char
23991 (cond ((> pos (match-end 4)) (match-end 4))
23992 ((= pos (point)) (match-end 4))
23993 (t (point)))))))))
23995 (defun org-end-of-line (&optional arg)
23996 "Go to the end of the line.
23997 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23998 first attempt, and only move to after the tags when the cursor is already
23999 beyond the end of the headline."
24000 (interactive "P")
24001 (if (or (not org-special-ctrl-a/e)
24002 (not (org-on-heading-p)))
24003 (end-of-line arg)
24004 (let ((pos (point)))
24005 (beginning-of-line 1)
24006 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
24007 (if (or (< pos (match-beginning 1))
24008 (= pos (match-end 0)))
24009 (goto-char (match-beginning 1))
24010 (goto-char (match-end 0)))
24011 (end-of-line arg)))))
24013 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24014 (define-key org-mode-map "\C-e" 'org-end-of-line)
24016 (defun org-invisible-p ()
24017 "Check if point is at a character currently not visible."
24018 ;; Early versions of noutline don't have `outline-invisible-p'.
24019 (if (fboundp 'outline-invisible-p)
24020 (outline-invisible-p)
24021 (get-char-property (point) 'invisible)))
24023 (defun org-invisible-p2 ()
24024 "Check if point is at a character currently not visible."
24025 (save-excursion
24026 (if (and (eolp) (not (bobp))) (backward-char 1))
24027 ;; Early versions of noutline don't have `outline-invisible-p'.
24028 (if (fboundp 'outline-invisible-p)
24029 (outline-invisible-p)
24030 (get-char-property (point) 'invisible))))
24032 (defalias 'org-back-to-heading 'outline-back-to-heading)
24033 (defalias 'org-on-heading-p 'outline-on-heading-p)
24034 (defalias 'org-at-heading-p 'outline-on-heading-p)
24035 (defun org-at-heading-or-item-p ()
24036 (or (org-on-heading-p) (org-at-item-p)))
24038 (defun org-on-target-p ()
24039 (or (org-in-regexp org-radio-target-regexp)
24040 (org-in-regexp org-target-regexp)))
24042 (defun org-up-heading-all (arg)
24043 "Move to the heading line of which the present line is a subheading.
24044 This function considers both visible and invisible heading lines.
24045 With argument, move up ARG levels."
24046 (if (fboundp 'outline-up-heading-all)
24047 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24048 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24050 (defun org-goto-sibling (&optional previous)
24051 "Goto the next sibling, even if it is invisible.
24052 When PREVIOUS is set, go to the previous sibling instead. Returns t
24053 when a sibling was found. When none is found, return nil and don't
24054 move point."
24055 (let ((fun (if previous 're-search-backward 're-search-forward))
24056 (pos (point))
24057 (re (concat "^" outline-regexp))
24058 level l)
24059 (when (condition-case nil (org-back-to-heading t) (error nil))
24060 (setq level (funcall outline-level))
24061 (catch 'exit
24062 (or previous (forward-char 1))
24063 (while (funcall fun re nil t)
24064 (setq l (funcall outline-level))
24065 (when (< l level) (goto-char pos) (throw 'exit nil))
24066 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24067 (goto-char pos)
24068 nil))))
24070 (defun org-show-siblings ()
24071 "Show all siblings of the current headline."
24072 (save-excursion
24073 (while (org-goto-sibling) (org-flag-heading nil)))
24074 (save-excursion
24075 (while (org-goto-sibling 'previous)
24076 (org-flag-heading nil))))
24078 (defun org-show-hidden-entry ()
24079 "Show an entry where even the heading is hidden."
24080 (save-excursion
24081 (org-show-entry)))
24083 (defun org-flag-heading (flag &optional entry)
24084 "Flag the current heading. FLAG non-nil means make invisible.
24085 When ENTRY is non-nil, show the entire entry."
24086 (save-excursion
24087 (org-back-to-heading t)
24088 ;; Check if we should show the entire entry
24089 (if entry
24090 (progn
24091 (org-show-entry)
24092 (save-excursion
24093 (and (outline-next-heading)
24094 (org-flag-heading nil))))
24095 (outline-flag-region (max (point-min) (1- (point)))
24096 (save-excursion (outline-end-of-heading) (point))
24097 flag))))
24099 (defun org-end-of-subtree (&optional invisible-OK to-heading)
24100 ;; This is an exact copy of the original function, but it uses
24101 ;; `org-back-to-heading', to make it work also in invisible
24102 ;; trees. And is uses an invisible-OK argument.
24103 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24104 (org-back-to-heading invisible-OK)
24105 (let ((first t)
24106 (level (funcall outline-level)))
24107 (while (and (not (eobp))
24108 (or first (> (funcall outline-level) level)))
24109 (setq first nil)
24110 (outline-next-heading))
24111 (unless to-heading
24112 (if (memq (preceding-char) '(?\n ?\^M))
24113 (progn
24114 ;; Go to end of line before heading
24115 (forward-char -1)
24116 (if (memq (preceding-char) '(?\n ?\^M))
24117 ;; leave blank line before heading
24118 (forward-char -1))))))
24119 (point))
24121 (defun org-show-subtree ()
24122 "Show everything after this heading at deeper levels."
24123 (outline-flag-region
24124 (point)
24125 (save-excursion
24126 (outline-end-of-subtree) (outline-next-heading) (point))
24127 nil))
24129 (defun org-show-entry ()
24130 "Show the body directly following this heading.
24131 Show the heading too, if it is currently invisible."
24132 (interactive)
24133 (save-excursion
24134 (org-back-to-heading t)
24135 (outline-flag-region
24136 (max (point-min) (1- (point)))
24137 (save-excursion
24138 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
24139 (or (match-beginning 1) (point-max)))
24140 nil)))
24142 (defun org-make-options-regexp (kwds)
24143 "Make a regular expression for keyword lines."
24144 (concat
24146 "#?[ \t]*\\+\\("
24147 (mapconcat 'regexp-quote kwds "\\|")
24148 "\\):[ \t]*"
24149 "\\(.+\\)"))
24151 ;; Make isearch reveal the necessary context
24152 (defun org-isearch-end ()
24153 "Reveal context after isearch exits."
24154 (when isearch-success ; only if search was successful
24155 (if (featurep 'xemacs)
24156 ;; Under XEmacs, the hook is run in the correct place,
24157 ;; we directly show the context.
24158 (org-show-context 'isearch)
24159 ;; In Emacs the hook runs *before* restoring the overlays.
24160 ;; So we have to use a one-time post-command-hook to do this.
24161 ;; (Emacs 22 has a special variable, see function `org-mode')
24162 (unless (and (boundp 'isearch-mode-end-hook-quit)
24163 isearch-mode-end-hook-quit)
24164 ;; Only when the isearch was not quitted.
24165 (org-add-hook 'post-command-hook 'org-isearch-post-command
24166 'append 'local)))))
24168 (defun org-isearch-post-command ()
24169 "Remove self from hook, and show context."
24170 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24171 (org-show-context 'isearch))
24174 ;;;; Address problems with some other packages
24176 ;; Make flyspell not check words in links, to not mess up our keymap
24177 (defun org-mode-flyspell-verify ()
24178 "Don't let flyspell put overlays at active buttons."
24179 (not (get-text-property (point) 'keymap)))
24181 ;; Make `bookmark-jump' show the jump location if it was hidden.
24182 (eval-after-load "bookmark"
24183 '(if (boundp 'bookmark-after-jump-hook)
24184 ;; We can use the hook
24185 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24186 ;; Hook not available, use advice
24187 (defadvice bookmark-jump (after org-make-visible activate)
24188 "Make the position visible."
24189 (org-bookmark-jump-unhide))))
24191 (defun org-bookmark-jump-unhide ()
24192 "Unhide the current position, to show the bookmark location."
24193 (and (org-mode-p)
24194 (or (org-invisible-p)
24195 (save-excursion (goto-char (max (point-min) (1- (point))))
24196 (org-invisible-p)))
24197 (org-show-context 'bookmark-jump)))
24199 ;; Make session.el ignore our circular variable
24200 (eval-after-load "session"
24201 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24203 ;;;; Experimental code
24205 ;; Make appt aware of appointments from the agenda
24206 (defun org-agenda-to-appt ()
24207 "Activate appointments found in `org-agenda-files'."
24208 (interactive)
24209 (require 'org)
24210 (let* ((today (org-date-to-gregorian
24211 (time-to-days (current-time))))
24212 (files org-agenda-files) entries file)
24213 (while (setq file (pop files))
24214 (setq entries (append entries (org-agenda-get-day-entries
24215 file today :timestamp))))
24216 (setq entries (delq nil entries))
24217 (mapc (lambda(x)
24218 (let* ((event (org-trim (get-text-property 1 'txt x)))
24219 (time-of-day (get-text-property 1 'time-of-day x)) tod)
24220 (when time-of-day
24221 (setq tod (number-to-string time-of-day)
24222 tod (when (string-match
24223 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
24224 (concat (match-string 1 tod) ":"
24225 (match-string 2 tod))))
24226 (if tod (appt-add tod event))))) entries)))
24228 (defun org-closed-in-range ()
24229 "Sparse tree of items closed in a certain time range.
24230 Still experimental, may disappear in the furture."
24231 (interactive)
24232 ;; Get the time interval from the user.
24233 (let* ((time1 (time-to-seconds
24234 (org-read-date nil 'to-time nil "Starting date: ")))
24235 (time2 (time-to-seconds
24236 (org-read-date nil 'to-time nil "End date:")))
24237 ;; callback function
24238 (callback (lambda ()
24239 (let ((time
24240 (time-to-seconds
24241 (apply 'encode-time
24242 (org-parse-time-string
24243 (match-string 1))))))
24244 ;; check if time in interval
24245 (and (>= time time1) (<= time time2))))))
24246 ;; make tree, check each match with the callback
24247 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
24249 (defun org-fill-paragraph-experimental (&optional justify)
24250 "Re-align a table, pass through to fill-paragraph if no table."
24251 (let ((table-p (org-at-table-p))
24252 (table.el-p (org-at-table.el-p)))
24253 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24254 (table.el-p t) ; skip table.el tables
24255 (table-p (org-table-align) t) ; align org-mode tables
24256 ((save-excursion
24257 (let ((pos (1+ (point-at-eol))))
24258 (backward-paragraph 1)
24259 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
24260 (save-excursion
24261 (save-restriction
24262 (narrow-to-region (1+ (match-end 0)) (point-max))
24263 (fill-paragraph nil)
24264 t)))
24265 (t nil)))) ; call paragraph-fill
24269 ;;;; Finish up
24271 (provide 'org)
24273 (run-hooks 'org-load-hook)
24275 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
24276 ;;; org.el ends here