Release 5.07a
[org-mode/org-mode-NeilSmithlineMods.git] / org.el
blobc0c84b2df9c6470b3238a89a112f98e476633076
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.07a
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://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.07a"
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 When a face, use the standart 3 dots, but with the specified face.
240 The change affects only Org-mode (which will then use its own display table).
241 Changing this requires executing `M-x org-mode' in a buffer to become
242 effective."
243 :group 'org-startup
244 :type '(choice (const :tag "Default" nil)
245 (face :tag "Face" :value org-warning)
246 (string :tag "String" :value "...#")))
248 (defvar org-display-table nil
249 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
251 (defgroup org-keywords nil
252 "Keywords in Org-mode."
253 :tag "Org Keywords"
254 :group 'org)
256 (defcustom org-deadline-string "DEADLINE:"
257 "String to mark deadline entries.
258 A deadline is this string, followed by a time stamp. Should be a word,
259 terminated by a colon. You can insert a schedule keyword and
260 a timestamp with \\[org-deadline].
261 Changes become only effective after restarting Emacs."
262 :group 'org-keywords
263 :type 'string)
265 (defcustom org-scheduled-string "SCHEDULED:"
266 "String to mark scheduled TODO entries.
267 A schedule is this string, followed by a time stamp. Should be a word,
268 terminated by a colon. You can insert a schedule keyword and
269 a timestamp with \\[org-schedule].
270 Changes become only effective after restarting Emacs."
271 :group 'org-keywords
272 :type 'string)
274 (defcustom org-closed-string "CLOSED:"
275 "String used as the prefix for timestamps logging closing a TODO entry."
276 :group 'org-keywords
277 :type 'string)
279 (defcustom org-clock-string "CLOCK:"
280 "String used as prefix for timestamps clocking work hours on an item."
281 :group 'org-keywords
282 :type 'string)
284 (defcustom org-comment-string "COMMENT"
285 "Entries starting with this keyword will never be exported.
286 An entry can be toggled between COMMENT and normal with
287 \\[org-toggle-comment].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
292 (defcustom org-quote-string "QUOTE"
293 "Entries starting with this keyword will be exported in fixed-width font.
294 Quoting applies only to the text in the entry following the headline, and does
295 not extend beyond the next headline, even if that is lower level.
296 An entry can be toggled between QUOTE and normal with
297 \\[org-toggle-fixed-width-section]."
298 :group 'org-keywords
299 :type 'string)
301 (defconst org-repeat-re
302 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
303 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
304 "Regular expression for specifying repeated events.
305 After a match, group 1 contains the repeat expression.")
307 (defgroup org-structure nil
308 "Options concerning the general structure of Org-mode files."
309 :tag "Org Structure"
310 :group 'org)
312 (defgroup org-reveal-location nil
313 "Options about how to make context of a location visible."
314 :tag "Org Reveal Location"
315 :group 'org-structure)
317 (defcustom org-show-hierarchy-above '((default . t))
318 "Non-nil means, show full hierarchy when revealing a location.
319 Org-mode often shows locations in an org-mode file which might have
320 been invisible before. When this is set, the hierarchy of headings
321 above the exposed location is shown.
322 Turning this off for example for sparse trees makes them very compact.
323 Instead of t, this can also be an alist specifying this option for different
324 contexts. Valid contexts are
325 agenda when exposing an entry from the agenda
326 org-goto when using the command `org-goto' on key C-c C-j
327 occur-tree when using the command `org-occur' on key C-c /
328 tags-tree when constructing a sparse tree based on tags matches
329 link-search when exposing search matches associated with a link
330 mark-goto when exposing the jump goal of a mark
331 bookmark-jump when exposing a bookmark location
332 isearch when exiting from an incremental search
333 default default for all contexts not set explicitly"
334 :group 'org-reveal-location
335 :type '(choice
336 (const :tag "Always" t)
337 (const :tag "Never" nil)
338 (repeat :greedy t :tag "Individual contexts"
339 (cons
340 (choice :tag "Context"
341 (const agenda)
342 (const org-goto)
343 (const occur-tree)
344 (const tags-tree)
345 (const link-search)
346 (const mark-goto)
347 (const bookmark-jump)
348 (const isearch)
349 (const default))
350 (boolean)))))
352 (defcustom org-show-following-heading '((default . nil))
353 "Non-nil means, show following heading when revealing a location.
354 Org-mode often shows locations in an org-mode file which might have
355 been invisible before. When this is set, the heading following the
356 match is shown.
357 Turning this off for example for sparse trees makes them very compact,
358 but makes it harder to edit the location of the match. In such a case,
359 use the command \\[org-reveal] to show more context.
360 Instead of t, this can also be an alist specifying this option for different
361 contexts. See `org-show-hierarchy-above' for valid contexts."
362 :group 'org-reveal-location
363 :type '(choice
364 (const :tag "Always" t)
365 (const :tag "Never" nil)
366 (repeat :greedy t :tag "Individual contexts"
367 (cons
368 (choice :tag "Context"
369 (const agenda)
370 (const org-goto)
371 (const occur-tree)
372 (const tags-tree)
373 (const link-search)
374 (const mark-goto)
375 (const bookmark-jump)
376 (const isearch)
377 (const default))
378 (boolean)))))
380 (defcustom org-show-siblings '((default . nil) (isearch t))
381 "Non-nil means, show all sibling heading when revealing a location.
382 Org-mode often shows locations in an org-mode file which might have
383 been invisible before. When this is set, the sibling of the current entry
384 heading are all made visible. If `org-show-hierarchy-above' is t,
385 the same happens on each level of the hierarchy above the current entry.
387 By default this is on for the isearch context, off for all other contexts.
388 Turning this off for example for sparse trees makes them very compact,
389 but makes it harder to edit the location of the match. In such a case,
390 use the command \\[org-reveal] to show more context.
391 Instead of t, this can also be an alist specifying this option for different
392 contexts. See `org-show-hierarchy-above' for valid contexts."
393 :group 'org-reveal-location
394 :type '(choice
395 (const :tag "Always" t)
396 (const :tag "Never" nil)
397 (repeat :greedy t :tag "Individual contexts"
398 (cons
399 (choice :tag "Context"
400 (const agenda)
401 (const org-goto)
402 (const occur-tree)
403 (const tags-tree)
404 (const link-search)
405 (const mark-goto)
406 (const bookmark-jump)
407 (const isearch)
408 (const default))
409 (boolean)))))
411 (defgroup org-cycle nil
412 "Options concerning visibility cycling in Org-mode."
413 :tag "Org Cycle"
414 :group 'org-structure)
416 (defcustom org-drawers '("PROPERTIES")
417 "Names of drawers. Drawers are not opened by cycling on the headline above.
418 Drawers only open with a TAB on the drawer line itself. A drawer looks like
419 this:
420 :DRAWERNAME:
421 .....
422 :END:
423 The drawer \"PROPERTIES\" is special for capturing properties through
424 the property API."
425 :group 'org-structure
426 :type '(repeat (string :tag "Drawer Name")))
428 (defcustom org-cycle-global-at-bob nil
429 "Cycle globally if cursor is at beginning of buffer and not at a headline.
430 This makes it possible to do global cycling without having to use S-TAB or
431 C-u TAB. For this special case to work, the first line of the buffer
432 must not be a headline - it may be empty ot some other text. When used in
433 this way, `org-cycle-hook' is disables temporarily, to make sure the
434 cursor stays at the beginning of the buffer.
435 When this option is nil, don't do anything special at the beginning
436 of the buffer."
437 :group 'org-cycle
438 :type 'boolean)
440 (defcustom org-cycle-emulate-tab t
441 "Where should `org-cycle' emulate TAB.
442 nil Never
443 white Only in completely white lines
444 whitestart Only at the beginning of lines, before the first non-white char.
445 t Everywhere except in headlines
446 exc-hl-bol Everywhere except at the start of a headline
447 If TAB is used in a place where it does not emulate TAB, the current subtree
448 visibility is cycled."
449 :group 'org-cycle
450 :type '(choice (const :tag "Never" nil)
451 (const :tag "Only in completely white lines" white)
452 (const :tag "Before first char in a line" whitestart)
453 (const :tag "Everywhere except in headlines" t)
454 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
457 (defcustom org-cycle-separator-lines 2
458 "Number of empty lines needed to keep an empty line between collapsed trees.
459 If you leave an empty line between the end of a subtree and the following
460 headline, this empty line is hidden when the subtree is folded.
461 Org-mode will leave (exactly) one empty line visible if the number of
462 empty lines is equal or larger to the number given in this variable.
463 So the default 2 means, at least 2 empty lines after the end of a subtree
464 are needed to produce free space between a collapsed subtree and the
465 following headline.
467 Special case: when 0, never leave empty lines in collapsed view."
468 :group 'org-cycle
469 :type 'integer)
471 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
472 org-cycle-hide-drawers
473 org-cycle-show-empty-lines
474 org-optimize-window-after-visibility-change)
475 "Hook that is run after `org-cycle' has changed the buffer visibility.
476 The function(s) in this hook must accept a single argument which indicates
477 the new state that was set by the most recent `org-cycle' command. The
478 argument is a symbol. After a global state change, it can have the values
479 `overview', `content', or `all'. After a local state change, it can have
480 the values `folded', `children', or `subtree'."
481 :group 'org-cycle
482 :type 'hook)
484 (defgroup org-edit-structure nil
485 "Options concerning structure editing in Org-mode."
486 :tag "Org Edit Structure"
487 :group 'org-structure)
489 (defcustom org-special-ctrl-a/e nil
490 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
491 When t, `C-a' will bring back the cursor to the beginning of the
492 headline text, i.e. after the stars and after a possible TODO keyword.
493 In an item, this will be the position after the bullet.
494 When the cursor is already at that position, another `C-a' will bring
495 it to the beginning of the line.
496 `C-e' will jump to the end of the headline, ignoring the presence of tags
497 in the headline. A second `C-e' will then jump to the true end of the
498 line, after any tags.
499 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
500 and only a directly following, identical keypress will bring the cursor
501 to the special positions."
502 :group 'org-edit-structure
503 :type '(choice
504 (const :tag "off" nil)
505 (const :tag "after bullet first" t)
506 (const :tag "border first" reversed)))
508 (if (fboundp 'defvaralias)
509 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
511 (defcustom org-odd-levels-only nil
512 "Non-nil means, skip even levels and only use odd levels for the outline.
513 This has the effect that two stars are being added/taken away in
514 promotion/demotion commands. It also influences how levels are
515 handled by the exporters.
516 Changing it requires restart of `font-lock-mode' to become effective
517 for fontification also in regions already fontified.
518 You may also set this on a per-file basis by adding one of the following
519 lines to the buffer:
521 #+STARTUP: odd
522 #+STARTUP: oddeven"
523 :group 'org-edit-structure
524 :group 'org-font-lock
525 :type 'boolean)
527 (defcustom org-adapt-indentation t
528 "Non-nil means, adapt indentation when promoting and demoting.
529 When this is set and the *entire* text in an entry is indented, the
530 indentation is increased by one space in a demotion command, and
531 decreased by one in a promotion command. If any line in the entry
532 body starts at column 0, indentation is not changed at all."
533 :group 'org-edit-structure
534 :type 'boolean)
536 (defcustom org-blank-before-new-entry '((heading . nil)
537 (plain-list-item . nil))
538 "Should `org-insert-heading' leave a blank line before new heading/item?
539 The value is an alist, with `heading' and `plain-list-item' as car,
540 and a boolean flag as cdr."
541 :group 'org-edit-structure
542 :type '(list
543 (cons (const heading) (boolean))
544 (cons (const plain-list-item) (boolean))))
546 (defcustom org-insert-heading-hook nil
547 "Hook being run after inserting a new heading."
548 :group 'org-edit-structure
549 :type 'boolean)
551 (defcustom org-enable-fixed-width-editor t
552 "Non-nil means, lines starting with \":\" are treated as fixed-width.
553 This currently only means, they are never auto-wrapped.
554 When nil, such lines will be treated like ordinary lines.
555 See also the QUOTE keyword."
556 :group 'org-edit-structure
557 :type 'boolean)
559 (defgroup org-sparse-trees nil
560 "Options concerning sparse trees in Org-mode."
561 :tag "Org Sparse Trees"
562 :group 'org-structure)
564 (defcustom org-highlight-sparse-tree-matches t
565 "Non-nil means, highlight all matches that define a sparse tree.
566 The highlights will automatically disappear the next time the buffer is
567 changed by an edit command."
568 :group 'org-sparse-trees
569 :type 'boolean)
571 (defcustom org-remove-highlights-with-change t
572 "Non-nil means, any change to the buffer will remove temporary highlights.
573 Such highlights are created by `org-occur' and `org-clock-display'.
574 When nil, `C-c C-c needs to be used to get rid of the highlights.
575 The highlights created by `org-preview-latex-fragment' always need
576 `C-c C-c' to be removed."
577 :group 'org-sparse-trees
578 :group 'org-time
579 :type 'boolean)
582 (defcustom org-occur-hook '(org-first-headline-recenter)
583 "Hook that is run after `org-occur' has constructed a sparse tree.
584 This can be used to recenter the window to show as much of the structure
585 as possible."
586 :group 'org-sparse-trees
587 :type 'hook)
589 (defgroup org-plain-lists nil
590 "Options concerning plain lists in Org-mode."
591 :tag "Org Plain lists"
592 :group 'org-structure)
594 (defcustom org-cycle-include-plain-lists nil
595 "Non-nil means, include plain lists into visibility cycling.
596 This means that during cycling, plain list items will *temporarily* be
597 interpreted as outline headlines with a level given by 1000+i where i is the
598 indentation of the bullet. In all other operations, plain list items are
599 not seen as headlines. For example, you cannot assign a TODO keyword to
600 such an item."
601 :group 'org-plain-lists
602 :type 'boolean)
604 (defcustom org-plain-list-ordered-item-terminator t
605 "The character that makes a line with leading number an ordered list item.
606 Valid values are ?. and ?\). To get both terminators, use t. While
607 ?. may look nicer, it creates the danger that a line with leading
608 number may be incorrectly interpreted as an item. ?\) therefore is
609 the safe choice."
610 :group 'org-plain-lists
611 :type '(choice (const :tag "dot like in \"2.\"" ?.)
612 (const :tag "paren like in \"2)\"" ?\))
613 (const :tab "both" t)))
615 (defcustom org-auto-renumber-ordered-lists t
616 "Non-nil means, automatically renumber ordered plain lists.
617 Renumbering happens when the sequence have been changed with
618 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
619 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
620 :group 'org-plain-lists
621 :type 'boolean)
623 (defcustom org-provide-checkbox-statistics t
624 "Non-nil means, update checkbox statistics after insert and toggle.
625 When this is set, checkbox statistics is updated each time you either insert
626 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
627 with \\[org-ctrl-c-ctrl-c\\]."
628 :group 'org-plain-lists
629 :type 'boolean)
631 (defgroup org-archive nil
632 "Options concerning archiving in Org-mode."
633 :tag "Org Archive"
634 :group 'org-structure)
636 (defcustom org-archive-tag "ARCHIVE"
637 "The tag that marks a subtree as archived.
638 An archived subtree does not open during visibility cycling, and does
639 not contribute to the agenda listings."
640 :group 'org-archive
641 :group 'org-keywords
642 :type 'string)
644 (defcustom org-agenda-skip-archived-trees t
645 "Non-nil means, the agenda will skip any items located in archived trees.
646 An archived tree is a tree marked with the tag ARCHIVE."
647 :group 'org-archive
648 :group 'org-agenda-skip
649 :type 'boolean)
651 (defcustom org-cycle-open-archived-trees nil
652 "Non-nil means, `org-cycle' will open archived trees.
653 An archived tree is a tree marked with the tag ARCHIVE.
654 When nil, archived trees will stay folded. You can still open them with
655 normal outline commands like `show-all', but not with the cycling commands."
656 :group 'org-archive
657 :group 'org-cycle
658 :type 'boolean)
660 (defcustom org-sparse-tree-open-archived-trees nil
661 "Non-nil means sparse tree construction shows matches in archived trees.
662 When nil, matches in these trees are highlighted, but the trees are kept in
663 collapsed state."
664 :group 'org-archive
665 :group 'org-sparse-trees
666 :type 'boolean)
668 (defcustom org-archive-location "%s_archive::"
669 "The location where subtrees should be archived.
670 This string consists of two parts, separated by a double-colon.
672 The first part is a file name - when omitted, archiving happens in the same
673 file. %s will be replaced by the current file name (without directory part).
674 Archiving to a different file is useful to keep archived entries from
675 contributing to the Org-mode Agenda.
677 The part after the double colon is a headline. The archived entries will be
678 filed under that headline. When omitted, the subtrees are simply filed away
679 at the end of the file, as top-level entries.
681 Here are a few examples:
682 \"%s_archive::\"
683 If the current file is Projects.org, archive in file
684 Projects.org_archive, as top-level trees. This is the default.
686 \"::* Archived Tasks\"
687 Archive in the current file, under the top-level headline
688 \"* Archived Tasks\".
690 \"~/org/archive.org::\"
691 Archive in file ~/org/archive.org (absolute path), as top-level trees.
693 \"basement::** Finished Tasks\"
694 Archive in file ./basement (relative path), as level 3 trees
695 below the level 2 heading \"** Finished Tasks\".
697 You may set this option on a per-file basis by adding to the buffer a
698 line like
700 #+ARCHIVE: basement::** Finished Tasks"
701 :group 'org-archive
702 :type 'string)
704 (defcustom org-archive-mark-done t
705 "Non-nil means, mark entries as DONE when they are moved to the archive file.
706 This can be a string to set the keyword to use. When t, Org-mode will
707 use the first keyword in its list that means done."
708 :group 'org-archive
709 :type '(choice
710 (const :tag "No" nil)
711 (const :tag "Yes" t)
712 (string :tag "Use this keyword")))
714 (defcustom org-archive-stamp-time t
715 "Non-nil means, add a time stamp to entries moved to an archive file."
716 :group 'org-archive
717 :type 'boolean)
719 (defcustom org-archive-save-context-info '(time file category todo itags)
720 "Parts of context info that should be stored as properties when archiving.
721 When a subtree is moved to an archive file, it looses information given by
722 context, like inherited tags, the category, and possibly also the TODO
723 state (depending on the variable `org-archive-mark-done').
724 This variable can be a list of any of the following symbols:
726 time The time of archiving.
727 file The file where the entry originates.
728 itags The local tags, in the headline of the subtree.
729 ltags The tags the subtree inherits from further up the hierarchy.
730 todo The pre-archive TODO state.
731 category The category, taken from file name or #+CATEGORY lines.
733 For each symbol present in the list, a property will be created in
734 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
735 information."
736 :group 'org-archive
737 :type '(set
738 (const :tag "File" file)
739 (const :tag "Category" category)
740 (const :tag "TODO state" todo)
741 (const :tag "TODO state" priority)
742 (const :tag "Inherited tags" itags)
743 (const :tag "Local tags" ltags)))
745 (defgroup org-table nil
746 "Options concerning tables in Org-mode."
747 :tag "Org Table"
748 :group 'org)
750 (defcustom org-enable-table-editor 'optimized
751 "Non-nil means, lines starting with \"|\" are handled by the table editor.
752 When nil, such lines will be treated like ordinary lines.
754 When equal to the symbol `optimized', the table editor will be optimized to
755 do the following:
756 - Automatic overwrite mode in front of whitespace in table fields.
757 This makes the structure of the table stay in tact as long as the edited
758 field does not exceed the column width.
759 - Minimize the number of realigns. Normally, the table is aligned each time
760 TAB or RET are pressed to move to another field. With optimization this
761 happens only if changes to a field might have changed the column width.
762 Optimization requires replacing the functions `self-insert-command',
763 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
764 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
765 very good at guessing when a re-align will be necessary, but you can always
766 force one with \\[org-ctrl-c-ctrl-c].
768 If you would like to use the optimized version in Org-mode, but the
769 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
771 This variable can be used to turn on and off the table editor during a session,
772 but in order to toggle optimization, a restart is required.
774 See also the variable `org-table-auto-blank-field'."
775 :group 'org-table
776 :type '(choice
777 (const :tag "off" nil)
778 (const :tag "on" t)
779 (const :tag "on, optimized" optimized)))
781 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
782 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
783 In the optimized version, the table editor takes over all simple keys that
784 normally just insert a character. In tables, the characters are inserted
785 in a way to minimize disturbing the table structure (i.e. in overwrite mode
786 for empty fields). Outside tables, the correct binding of the keys is
787 restored.
789 The default for this option is t if the optimized version is also used in
790 Org-mode. See the variable `org-enable-table-editor' for details. Changing
791 this variable requires a restart of Emacs to become effective."
792 :group 'org-table
793 :type 'boolean)
795 (defcustom orgtbl-radio-table-templates
796 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
797 % END RECEIVE ORGTBL %n
798 \\begin{comment}
799 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
800 | | |
801 \\end{comment}\n")
802 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
803 @c END RECEIVE ORGTBL %n
804 @ignore
805 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
806 | | |
807 @end ignore\n")
808 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
809 <!-- END RECEIVE ORGTBL %n -->
810 <!--
811 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
812 | | |
813 -->\n"))
814 "Templates for radio tables in different major modes.
815 All occurrences of %n in a template will be replaced with the name of the
816 table, obtained by prompting the user."
817 :group 'org-table
818 :type '(repeat
819 (list (symbol :tag "Major mode")
820 (string :tag "Format"))))
822 (defgroup org-table-settings nil
823 "Settings for tables in Org-mode."
824 :tag "Org Table Settings"
825 :group 'org-table)
827 (defcustom org-table-default-size "5x2"
828 "The default size for newly created tables, Columns x Rows."
829 :group 'org-table-settings
830 :type 'string)
832 (defcustom org-table-number-regexp
833 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
834 "Regular expression for recognizing numbers in table columns.
835 If a table column contains mostly numbers, it will be aligned to the
836 right. If not, it will be aligned to the left.
838 The default value of this option is a regular expression which allows
839 anything which looks remotely like a number as used in scientific
840 context. For example, all of the following will be considered a
841 number:
842 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
844 Other options offered by the customize interface are more restrictive."
845 :group 'org-table-settings
846 :type '(choice
847 (const :tag "Positive Integers"
848 "^[0-9]+$")
849 (const :tag "Integers"
850 "^[-+]?[0-9]+$")
851 (const :tag "Floating Point Numbers"
852 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
853 (const :tag "Floating Point Number or Integer"
854 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
855 (const :tag "Exponential, Floating point, Integer"
856 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
857 (const :tag "Very General Number-Like, including hex"
858 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
859 (string :tag "Regexp:")))
861 (defcustom org-table-number-fraction 0.5
862 "Fraction of numbers in a column required to make the column align right.
863 In a column all non-white fields are considered. If at least this
864 fraction of fields is matched by `org-table-number-fraction',
865 alignment to the right border applies."
866 :group 'org-table-settings
867 :type 'number)
869 (defgroup org-table-editing nil
870 "Bahavior of tables during editing in Org-mode."
871 :tag "Org Table Editing"
872 :group 'org-table)
874 (defcustom org-table-automatic-realign t
875 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
876 When nil, aligning is only done with \\[org-table-align], or after column
877 removal/insertion."
878 :group 'org-table-editing
879 :type 'boolean)
881 (defcustom org-table-auto-blank-field t
882 "Non-nil means, automatically blank table field when starting to type into it.
883 This only happens when typing immediately after a field motion
884 command (TAB, S-TAB or RET).
885 Only relevant when `org-enable-table-editor' is equal to `optimized'."
886 :group 'org-table-editing
887 :type 'boolean)
889 (defcustom org-table-tab-jumps-over-hlines t
890 "Non-nil means, tab in the last column of a table with jump over a hline.
891 If a horizontal separator line is following the current line,
892 `org-table-next-field' can either create a new row before that line, or jump
893 over the line. When this option is nil, a new line will be created before
894 this line."
895 :group 'org-table-editing
896 :type 'boolean)
898 (defcustom org-table-tab-recognizes-table.el t
899 "Non-nil means, TAB will automatically notice a table.el table.
900 When it sees such a table, it moves point into it and - if necessary -
901 calls `table-recognize-table'."
902 :group 'org-table-editing
903 :type 'boolean)
905 (defgroup org-table-calculation nil
906 "Options concerning tables in Org-mode."
907 :tag "Org Table Calculation"
908 :group 'org-table)
910 (defcustom org-table-use-standard-references t
911 "Should org-mode work with table refrences like B3 instead of @3$2?
912 Possible values are:
913 nil never use them
914 from accept as input, do not present for editing
915 t: accept as input and present for editing"
916 :group 'org-table-calculation
917 :type '(choice
918 (const :tag "Never, don't even check unser input for them" nil)
919 (const :tag "Always, both as user input, and when editing" t)
920 (const :tag "Convert user input, don't offer during editing" 'from)))
922 (defcustom org-table-copy-increment t
923 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
924 :group 'org-table-calculation
925 :type 'boolean)
927 (defcustom org-calc-default-modes
928 '(calc-internal-prec 12
929 calc-float-format (float 5)
930 calc-angle-mode deg
931 calc-prefer-frac nil
932 calc-symbolic-mode nil
933 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
934 calc-display-working-message t
936 "List with Calc mode settings for use in calc-eval for table formulas.
937 The list must contain alternating symbols (Calc modes variables and values).
938 Don't remove any of the default settings, just change the values. Org-mode
939 relies on the variables to be present in the list."
940 :group 'org-table-calculation
941 :type 'plist)
943 (defcustom org-table-formula-evaluate-inline t
944 "Non-nil means, TAB and RET evaluate a formula in current table field.
945 If the current field starts with an equal sign, it is assumed to be a formula
946 which should be evaluated as described in the manual and in the documentation
947 string of the command `org-table-eval-formula'. This feature requires the
948 Emacs calc package.
949 When this variable is nil, formula calculation is only available through
950 the command \\[org-table-eval-formula]."
951 :group 'org-table-calculation
952 :type 'boolean)
954 (defcustom org-table-formula-use-constants t
955 "Non-nil means, interpret constants in formulas in tables.
956 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
957 by the value given in `org-table-formula-constants', or by a value obtained
958 from the `constants.el' package."
959 :group 'org-table-calculation
960 :type 'boolean)
962 (defcustom org-table-formula-constants nil
963 "Alist with constant names and values, for use in table formulas.
964 The car of each element is a name of a constant, without the `$' before it.
965 The cdr is the value as a string. For example, if you'd like to use the
966 speed of light in a formula, you would configure
968 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
970 and then use it in an equation like `$1*$c'.
972 Constants can also be defined on a per-file basis using a line like
974 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
975 :group 'org-table-calculation
976 :type '(repeat
977 (cons (string :tag "name")
978 (string :tag "value"))))
980 (defvar org-table-formula-constants-local nil
981 "Local version of `org-table-formula-constants'.")
982 (make-variable-buffer-local 'org-table-formula-constants-local)
984 (defcustom org-table-allow-automatic-line-recalculation t
985 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
986 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
987 :group 'org-table-calculation
988 :type 'boolean)
990 (defgroup org-link nil
991 "Options concerning links in Org-mode."
992 :tag "Org Link"
993 :group 'org)
995 (defvar org-link-abbrev-alist-local nil
996 "Buffer-local version of `org-link-abbrev-alist', which see.
997 The value of this is taken from the #+LINK lines.")
998 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1000 (defcustom org-link-abbrev-alist nil
1001 "Alist of link abbreviations.
1002 The car of each element is a string, to be replaced at the start of a link.
1003 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1004 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1006 [[linkkey:tag][description]]
1008 If REPLACE is a string, the tag will simply be appended to create the link.
1009 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1010 also be a function that will be called with the tag as the only argument to
1011 create the link. See the manual for examples."
1012 :group 'org-link
1013 :type 'alist)
1015 (defcustom org-descriptive-links t
1016 "Non-nil means, hide link part and only show description of bracket links.
1017 Bracket links are like [[link][descritpion]]. This variable sets the initial
1018 state in new org-mode buffers. The setting can then be toggled on a
1019 per-buffer basis from the Org->Hyperlinks menu."
1020 :group 'org-link
1021 :type 'boolean)
1023 (defcustom org-link-file-path-type 'adaptive
1024 "How the path name in file links should be stored.
1025 Valid values are:
1027 relative relative to the current directory, i.e. the directory of the file
1028 into which the link is being inserted.
1029 absolute absolute path, if possible with ~ for home directory.
1030 noabbrev absolute path, no abbreviation of home directory.
1031 adaptive Use relative path for files in the current directory and sub-
1032 directories of it. For other files, use an absolute path."
1033 :group 'org-link
1034 :type '(choice
1035 (const relative)
1036 (const absolute)
1037 (const noabbrev)
1038 (const adaptive)))
1040 (defcustom org-activate-links '(bracket angle plain radio tag date)
1041 "Types of links that should be activated in Org-mode files.
1042 This is a list of symbols, each leading to the activation of a certain link
1043 type. In principle, it does not hurt to turn on most link types - there may
1044 be a small gain when turning off unused link types. The types are:
1046 bracket The recommended [[link][description]] or [[link]] links with hiding.
1047 angular Links in angular brackes that may contain whitespace like
1048 <bbdb:Carsten Dominik>.
1049 plain Plain links in normal text, no whitespace, like http://google.com.
1050 radio Text that is matched by a radio target, see manual for details.
1051 tag Tag settings in a headline (link to tag search).
1052 date Time stamps (link to calendar).
1054 Changing this variable requires a restart of Emacs to become effective."
1055 :group 'org-link
1056 :type '(set (const :tag "Double bracket links (new style)" bracket)
1057 (const :tag "Angular bracket links (old style)" angular)
1058 (const :tag "plain text links" plain)
1059 (const :tag "Radio target matches" radio)
1060 (const :tag "Tags" tag)
1061 (const :tag "Tags" target)
1062 (const :tag "Timestamps" date)))
1064 (defgroup org-link-store nil
1065 "Options concerning storing links in Org-mode"
1066 :tag "Org Store Link"
1067 :group 'org-link)
1069 (defcustom org-email-link-description-format "Email %c: %.30s"
1070 "Format of the description part of a link to an email or usenet message.
1071 The following %-excapes will be replaced by corresponding information:
1073 %F full \"From\" field
1074 %f name, taken from \"From\" field, address if no name
1075 %T full \"To\" field
1076 %t first name in \"To\" field, address if no name
1077 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1078 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1079 %s subject
1080 %m message-id.
1082 You may use normal field width specification between the % and the letter.
1083 This is for example useful to limit the length of the subject.
1085 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1086 :group 'org-link-store
1087 :type 'string)
1089 (defcustom org-from-is-user-regexp
1090 (let (r1 r2)
1091 (when (and user-mail-address (not (string= user-mail-address "")))
1092 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1093 (when (and user-full-name (not (string= user-full-name "")))
1094 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1095 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1096 "Regexp mached against the \"From:\" header of an email or usenet message.
1097 It should match if the message is from the user him/herself."
1098 :group 'org-link-store
1099 :type 'regexp)
1101 (defcustom org-context-in-file-links t
1102 "Non-nil means, file links from `org-store-link' contain context.
1103 A search string will be added to the file name with :: as separator and
1104 used to find the context when the link is activated by the command
1105 `org-open-at-point'.
1106 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1107 negates this setting for the duration of the command."
1108 :group 'org-link-store
1109 :type 'boolean)
1111 (defcustom org-keep-stored-link-after-insertion nil
1112 "Non-nil means, keep link in list for entire session.
1114 The command `org-store-link' adds a link pointing to the current
1115 location to an internal list. These links accumulate during a session.
1116 The command `org-insert-link' can be used to insert links into any
1117 Org-mode file (offering completion for all stored links). When this
1118 option is nil, every link which has been inserted once using \\[org-insert-link]
1119 will be removed from the list, to make completing the unused links
1120 more efficient."
1121 :group 'org-link-store
1122 :type 'boolean)
1124 (defcustom org-usenet-links-prefer-google nil
1125 "Non-nil means, `org-store-link' will create web links to Google groups.
1126 When nil, Gnus will be used for such links.
1127 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1128 negates this setting for the duration of the command."
1129 :group 'org-link-store
1130 :type 'boolean)
1132 (defgroup org-link-follow nil
1133 "Options concerning following links in Org-mode"
1134 :tag "Org Follow Link"
1135 :group 'org-link)
1137 (defcustom org-tab-follows-link nil
1138 "Non-nil means, on links TAB will follow the link.
1139 Needs to be set before org.el is loaded."
1140 :group 'org-link-follow
1141 :type 'boolean)
1143 (defcustom org-return-follows-link nil
1144 "Non-nil means, on links RET will follow the link.
1145 Needs to be set before org.el is loaded."
1146 :group 'org-link-follow
1147 :type 'boolean)
1149 (defcustom org-mouse-1-follows-link t
1150 "Non-nil means, mouse-1 on a link will follow the link.
1151 A longer mouse click will still set point. Does not wortk on XEmacs.
1152 Needs to be set before org.el is loaded."
1153 :group 'org-link-follow
1154 :type 'boolean)
1156 (defcustom org-mark-ring-length 4
1157 "Number of different positions to be recorded in the ring
1158 Changing this requires a restart of Emacs to work correctly."
1159 :group 'org-link-follow
1160 :type 'interger)
1162 (defcustom org-link-frame-setup
1163 '((vm . vm-visit-folder-other-frame)
1164 (gnus . gnus-other-frame)
1165 (file . find-file-other-window))
1166 "Setup the frame configuration for following links.
1167 When following a link with Emacs, it may often be useful to display
1168 this link in another window or frame. This variable can be used to
1169 set this up for the different types of links.
1170 For VM, use any of
1171 `vm-visit-folder'
1172 `vm-visit-folder-other-frame'
1173 For Gnus, use any of
1174 `gnus'
1175 `gnus-other-frame'
1176 For FILE, use any of
1177 `find-file'
1178 `find-file-other-window'
1179 `find-file-other-frame'
1180 For the calendar, use the variable `calendar-setup'.
1181 For BBDB, it is currently only possible to display the matches in
1182 another window."
1183 :group 'org-link-follow
1184 :type '(list
1185 (cons (const vm)
1186 (choice
1187 (const vm-visit-folder)
1188 (const vm-visit-folder-other-window)
1189 (const vm-visit-folder-other-frame)))
1190 (cons (const gnus)
1191 (choice
1192 (const gnus)
1193 (const gnus-other-frame)))
1194 (cons (const file)
1195 (choice
1196 (const find-file)
1197 (const find-file-other-window)
1198 (const find-file-other-frame)))))
1200 (defcustom org-display-internal-link-with-indirect-buffer nil
1201 "Non-nil means, use indirect buffer to display infile links.
1202 Activating internal links (from one location in a file to another location
1203 in the same file) normally just jumps to the location. When the link is
1204 activated with a C-u prefix (or with mouse-3), the link is displayed in
1205 another window. When this option is set, the other window actually displays
1206 an indirect buffer clone of the current buffer, to avoid any visibility
1207 changes to the current buffer."
1208 :group 'org-link-follow
1209 :type 'boolean)
1211 (defcustom org-open-non-existing-files nil
1212 "Non-nil means, `org-open-file' will open non-existing files.
1213 When nil, an error will be generated."
1214 :group 'org-link-follow
1215 :type 'boolean)
1217 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1218 "Function and arguments to call for following mailto links.
1219 This is a list with the first element being a lisp function, and the
1220 remaining elements being arguments to the function. In string arguments,
1221 %a will be replaced by the address, and %s will be replaced by the subject
1222 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1223 :group 'org-link-follow
1224 :type '(choice
1225 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1226 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1227 (const :tag "message-mail" (message-mail "%a" "%s"))
1228 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1230 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing shell links.
1232 Shell links can be dangerous, just thing about a link
1234 [[shell:rm -rf ~/*][Google Search]]
1236 This link would show up in your Org-mode document as \"Google Search\"
1237 but really it would remove your entire home directory.
1238 Therefore I *definitely* advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a single key press
1240 rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1247 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1248 "Non-nil means, ask for confirmation before executing elisp links.
1249 Elisp links can be dangerous, just think about a link
1251 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1253 This link would show up in your Org-mode document as \"Google Search\"
1254 but really it would remove your entire home directory.
1255 Therefore I *definitely* advise against setting this variable to nil.
1256 Just change it to `y-or-n-p' of you want to confirm with a single key press
1257 rather than having to type \"yes\"."
1258 :group 'org-link-follow
1259 :type '(choice
1260 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1261 (const :tag "with y-or-n (faster)" y-or-n-p)
1262 (const :tag "no confirmation (dangerous)" nil)))
1264 (defconst org-file-apps-defaults-gnu
1265 '((remote . emacs)
1266 (t . mailcap))
1267 "Default file applications on a UNIX or GNU/Linux system.
1268 See `org-file-apps'.")
1270 (defconst org-file-apps-defaults-macosx
1271 '((remote . emacs)
1272 (t . "open %s")
1273 ("ps" . "gv %s")
1274 ("ps.gz" . "gv %s")
1275 ("eps" . "gv %s")
1276 ("eps.gz" . "gv %s")
1277 ("dvi" . "xdvi %s")
1278 ("fig" . "xfig %s"))
1279 "Default file applications on a MacOS X system.
1280 The system \"open\" is known as a default, but we use X11 applications
1281 for some files for which the OS does not have a good default.
1282 See `org-file-apps'.")
1284 (defconst org-file-apps-defaults-windowsnt
1285 (list
1286 '(remote . emacs)
1287 (cons t
1288 (list (if (featurep 'xemacs)
1289 'mswindows-shell-execute
1290 'w32-shell-execute)
1291 "open" 'file)))
1292 "Default file applications on a Windows NT system.
1293 The system \"open\" is used for most files.
1294 See `org-file-apps'.")
1296 (defcustom org-file-apps
1298 ("txt" . emacs)
1299 ("tex" . emacs)
1300 ("ltx" . emacs)
1301 ("org" . emacs)
1302 ("el" . emacs)
1303 ("bib" . emacs)
1305 "External applications for opening `file:path' items in a document.
1306 Org-mode uses system defaults for different file types, but
1307 you can use this variable to set the application for a given file
1308 extension. The entries in this list are cons cells where the car identifies
1309 files and the cdr the corresponding command. Possible values for the
1310 file identifier are
1311 \"ext\" A string identifying an extension
1312 `directory' Matches a directory
1313 `remote' Matches a remote file, accessible through tramp or efs.
1314 Remote files most likely should be visited through Emacs
1315 because external applications cannot handle such paths.
1316 t Default for all remaining files
1318 Possible values for the command are:
1319 `emacs' The file will be visited by the current Emacs process.
1320 `default' Use the default application for this file type.
1321 string A command to be executed by a shell; %s will be replaced
1322 by the path to the file.
1323 sexp A Lisp form which will be evaluated. The file path will
1324 be available in the Lisp variable `file'.
1325 For more examples, see the system specific constants
1326 `org-file-apps-defaults-macosx'
1327 `org-file-apps-defaults-windowsnt'
1328 `org-file-apps-defaults-gnu'."
1329 :group 'org-link-follow
1330 :type '(repeat
1331 (cons (choice :value ""
1332 (string :tag "Extension")
1333 (const :tag "Default for unrecognized files" t)
1334 (const :tag "Remote file" remote)
1335 (const :tag "Links to a directory" directory))
1336 (choice :value ""
1337 (const :tag "Visit with Emacs" emacs)
1338 (const :tag "Use system default" default)
1339 (string :tag "Command")
1340 (sexp :tag "Lisp form")))))
1342 (defcustom org-mhe-search-all-folders nil
1343 "Non-nil means, that the search for the mh-message will be extended to
1344 all folders if the message cannot be found in the folder given in the link.
1345 Searching all folders is very efficient with one of the search engines
1346 supported by MH-E, but will be slow with pick."
1347 :group 'org-link-follow
1348 :type 'boolean)
1350 (defgroup org-remember nil
1351 "Options concerning interaction with remember.el."
1352 :tag "Org Remember"
1353 :group 'org)
1355 (defcustom org-directory "~/org"
1356 "Directory with org files.
1357 This directory will be used as default to prompt for org files.
1358 Used by the hooks for remember.el."
1359 :group 'org-remember
1360 :type 'directory)
1362 (defcustom org-default-notes-file "~/.notes"
1363 "Default target for storing notes.
1364 Used by the hooks for remember.el. This can be a string, or nil to mean
1365 the value of `remember-data-file'.
1366 You can set this on a per-template basis with the variable
1367 `org-remember-templates'."
1368 :group 'org-remember
1369 :type '(choice
1370 (const :tag "Default from remember-data-file" nil)
1371 file))
1373 (defcustom org-remember-store-without-prompt nil
1374 "Non-nil means, `C-c C-c' stores remember note without further promts.
1375 In this case, you need `C-u C-c C-c' to get the prompts for
1376 note file and headline.
1377 When this variable is nil, `C-c C-c' give you the prompts, and
1378 `C-u C-c C-c' trigger the fasttrack."
1379 :group 'org-remember
1380 :type 'boolean)
1382 (defcustom org-remember-default-headline ""
1383 "The headline that should be the default location in the notes file.
1384 When filing remember notes, the cursor will start at that position.
1385 You can set this on a per-template basis with the variable
1386 `org-remember-templates'."
1387 :group 'org-remember
1388 :type 'string)
1390 (defcustom org-remember-templates nil
1391 "Templates for the creation of remember buffers.
1392 When nil, just let remember make the buffer.
1393 When not nil, this is a list of 4-element lists. In each entry, the first
1394 element is a character, a unique key to select this template.
1395 The second element is the template. The third element is optional and can
1396 specify a destination file for remember items created with this template.
1397 The default file is given by `org-default-notes-file'. An optional forth
1398 element can specify the headline in that file that should be offered
1399 first when the user is asked to file the entry. The default headline is
1400 given in the variable `org-remember-default-headline'.
1402 The template specifies the structure of the remember buffer. It should have
1403 a first line starting with a star, to act as the org-mode headline.
1404 Furthermore, the following %-escapes will be replaced with content:
1406 %^{prompt} prompt the user for a string and replace this sequence with it.
1407 %t time stamp, date only
1408 %T time stamp with date and time
1409 %u, %U like the above, but inactive time stamps
1410 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1411 You may define a prompt like %^{Please specify birthday}t
1412 %n user name (taken from `user-full-name')
1413 %a annotation, normally the link created with org-store-link
1414 %i initial content, the region when remember is called with C-u.
1415 If %i is indented, the entire inserted text will be indented
1416 as well.
1418 %? After completing the template, position cursor here.
1420 Apart from these general escapes, you can access information specific to the
1421 link type that is created. For example, calling `remember' in emails or gnus
1422 will record the author and the subject of the message, which you can access
1423 with %:author and %:subject, respectively. Here is a complete list of what
1424 is recorded for each link type.
1426 Link type | Available information
1427 -------------------+------------------------------------------------------
1428 bbdb | %:type %:name %:company
1429 vm, wl, mh, rmail | %:type %:subject %:message-id
1430 | %:from %:fromname %:fromaddress
1431 | %:to %:toname %:toaddress
1432 | %:fromto (either \"to NAME\" or \"from NAME\")
1433 gnus | %:group, for messages also all email fields
1434 w3, w3m | %:type %:url
1435 info | %:type %:file %:node
1436 calendar | %:type %:date"
1437 :group 'org-remember
1438 :get (lambda (var) ; Make sure all entries have 4 elements
1439 (mapcar (lambda (x)
1440 (cond ((= (length x) 3) (append x '("")))
1441 ((= (length x) 2) (append x '("" "")))
1442 (t x)))
1443 (default-value var)))
1444 :type '(repeat
1445 :tag "enabled"
1446 (list :value (?a "\n" nil nil)
1447 (character :tag "Selection Key")
1448 (string :tag "Template")
1449 (file :tag "Destination file (optional)")
1450 (string :tag "Destination headline (optional)"))))
1452 (defcustom org-reverse-note-order nil
1453 "Non-nil means, store new notes at the beginning of a file or entry.
1454 When nil, new notes will be filed to the end of a file or entry."
1455 :group 'org-remember
1456 :type '(choice
1457 (const :tag "Reverse always" t)
1458 (const :tag "Reverse never" nil)
1459 (repeat :tag "By file name regexp"
1460 (cons regexp boolean))))
1462 (defgroup org-todo nil
1463 "Options concerning TODO items in Org-mode."
1464 :tag "Org TODO"
1465 :group 'org)
1467 (defgroup org-progress nil
1468 "Options concerning Progress logging in Org-mode."
1469 :tag "Org Progress"
1470 :group 'org-time)
1472 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1473 "List of TODO entry keyword sequences and their interpretation.
1474 \\<org-mode-map>This is a list of sequences.
1476 Each sequence starts with a symbol, either `sequence' or `type',
1477 indicating if the keywords should be interpreted as a sequence of
1478 action steps, or as different types of TODO items. The first
1479 keywords are states requiring action - these states will select a headline
1480 for inclusion into the global TODO list Org-mode produces. If one of
1481 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1482 signify that no further action is necessary. If \"|\" is not found,
1483 the last keyword is treated as the only DONE state of the sequence.
1485 The command \\[org-todo] cycles an entry through these states, and one
1486 additional state where no keyword is present. For details about this
1487 cycling, see the manual.
1489 TODO keywords and interpretation can also be set on a per-file basis with
1490 the special #+SEQ_TODO and #+TYP_TODO lines.
1492 For backward compatibility, this variable may also be just a list
1493 of keywords - in this case the interptetation (sequence or type) will be
1494 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1495 :group 'org-todo
1496 :group 'org-keywords
1497 :type '(choice
1498 (repeat :tag "Old syntax, just keywords"
1499 (string :tag "Keyword"))
1500 (repeat :tag "New syntax"
1501 (cons
1502 (choice
1503 :tag "Interpretation"
1504 (const :tag "Sequence (cycling hits every state)" sequence)
1505 (const :tag "Type (cycling directly to DONE)" type))
1506 (repeat
1507 (string :tag "Keyword"))))))
1509 (defvar org-todo-keywords-1 nil)
1510 (make-variable-buffer-local 'org-todo-keywords-1)
1511 (defvar org-todo-tag-alist nil)
1512 (make-variable-buffer-local 'org-todo-tag-alist)
1513 (defvar org-todo-keywords-for-agenda nil)
1514 (defvar org-done-keywords-for-agenda nil)
1515 (defvar org-not-done-keywords nil)
1516 (make-variable-buffer-local 'org-not-done-keywords)
1517 (defvar org-done-keywords nil)
1518 (make-variable-buffer-local 'org-done-keywords)
1519 (defvar org-todo-heads nil)
1520 (make-variable-buffer-local 'org-todo-heads)
1521 (defvar org-todo-sets nil)
1522 (make-variable-buffer-local 'org-todo-sets)
1523 (defvar org-todo-kwd-alist nil)
1524 (make-variable-buffer-local 'org-todo-kwd-alist)
1526 (defcustom org-todo-interpretation 'sequence
1527 "Controls how TODO keywords are interpreted.
1528 This variable is in principle obsolete and is only used for
1529 backward compatibility, if the interpretation of todo keywords is
1530 not given already in `org-todo-keywords'. See that variable for
1531 more information."
1532 :group 'org-todo
1533 :group 'org-keywords
1534 :type '(choice (const sequence)
1535 (const type)))
1537 (defcustom org-after-todo-state-change-hook nil
1538 "Hook which is run after the state of a TODO item was changed.
1539 The new state (a string with a TODO keyword, or nil) is available in the
1540 Lisp variable `state'."
1541 :group 'org-todo
1542 :type 'hook)
1544 (defcustom org-log-done nil
1545 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1546 When the state of an entry is changed from nothing to TODO, remove a previous
1547 closing date.
1549 This can also be a list of symbols indicating under which conditions
1550 the time stamp recording the action should be annotated with a short note.
1551 Valid members of this list are
1553 done Offer to record a note when marking entries done
1554 state Offer to record a note whenever changing the TODO state
1555 of an item. This is only relevant if TODO keywords are
1556 interpreted as sequence, see variable `org-todo-interpretation'.
1557 When `state' is set, this includes tracking `done'.
1558 clock-out Offer to record a note when clocking out of an item.
1560 A separate window will then pop up and allow you to type a note.
1561 After finishing with C-c C-c, the note will be added directly after the
1562 timestamp, as a plain list item. See also the variable
1563 `org-log-note-headings'.
1565 Logging can also be configured on a per-file basis by adding one of
1566 the following lines anywhere in the buffer:
1568 #+STARTUP: logdone
1569 #+STARTUP: nologging
1570 #+STARTUP: lognotedone
1571 #+STARTUP: lognotestate
1572 #+STARTUP: lognoteclock-out"
1573 :group 'org-todo
1574 :group 'org-progress
1575 :type '(choice
1576 (const :tag "off" nil)
1577 (const :tag "on" t)
1578 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1579 (const :tag "when item is marked DONE" done)
1580 (const :tag "when TODO state changes" state)
1581 (const :tag "when clocking out" clock-out))))
1583 (defcustom org-log-done-with-time t
1584 "Non-nil means, the CLOSED time stamp will contain date and time.
1585 When nil, only the date will be recorded."
1586 :group 'org-progress
1587 :type 'boolean)
1589 (defcustom org-log-note-headings
1590 '((done . "CLOSING NOTE %t")
1591 (state . "State %-12s %t")
1592 (clock-out . ""))
1593 "Headings for notes added when clocking out or closing TODO items.
1594 The value is an alist, with the car being a symbol indicating the note
1595 context, and the cdr is the heading to be used. The heading may also be the
1596 empty string.
1597 %t in the heading will be replaced by a time stamp.
1598 %s will be replaced by the new TODO state, in double quotes.
1599 %u will be replaced by the user name.
1600 %U will be replaced by the full user name."
1601 :group 'org-todo
1602 :group 'org-progress
1603 :type '(list :greedy t
1604 (cons (const :tag "Heading when closing an item" done) string)
1605 (cons (const :tag
1606 "Heading when changing todo state (todo sequence only)"
1607 state) string)
1608 (cons (const :tag "Heading when clocking out" clock-out) string)))
1610 (defcustom org-log-states-order-reversed t
1611 "Non-nil means, the latest state change note will be directly after heading.
1612 When nil, the notes will be orderer according to time."
1613 :group 'org-todo
1614 :group 'org-progress
1615 :type 'boolean)
1617 (defcustom org-log-repeat t
1618 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1619 When nil, no note will be taken."
1620 :group 'org-todo
1621 :group 'org-progress
1622 :type 'boolean)
1624 (defcustom org-clock-out-when-done t
1625 "When t, the clock will be stopped when the relevant entry is marked DONE.
1626 Nil means, clock will keep running until stopped explicitly with
1627 `C-c C-x C-o', or until the clock is started in a different item."
1628 :group 'org-progress
1629 :type 'boolean)
1631 (defgroup org-priorities nil
1632 "Priorities in Org-mode."
1633 :tag "Org Priorities"
1634 :group 'org-todo)
1636 (defcustom org-highest-priority ?A
1637 "The highest priority of TODO items. A character like ?A, ?B etc.
1638 Must have a smaller ASCII number than `org-lowest-priority'."
1639 :group 'org-priorities
1640 :type 'character)
1642 (defcustom org-lowest-priority ?C
1643 "The lowest priority of TODO items. A character like ?A, ?B etc.
1644 Must have a larger ASCII number than `org-highest-priority'."
1645 :group 'org-priorities
1646 :type 'character)
1648 (defcustom org-default-priority ?B
1649 "The default priority of TODO items.
1650 This is the priority an item get if no explicit priority is given."
1651 :group 'org-priorities
1652 :type 'character)
1654 (defgroup org-time nil
1655 "Options concerning time stamps and deadlines in Org-mode."
1656 :tag "Org Time"
1657 :group 'org)
1659 (defcustom org-insert-labeled-timestamps-at-point nil
1660 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1661 When nil, these labeled time stamps are forces into the second line of an
1662 entry, just after the headline. When scheduling from the global TODO list,
1663 the time stamp will always be forced into the second line."
1664 :group 'org-time
1665 :type 'boolean)
1667 (defcustom org-insert-labeled-timestamps-before-properties-drawer t
1668 "Non-nil means, always insert planning info before property drawer.
1669 When this is nil and there is a property drawer *directly* after
1670 the headline, move the planning info into the drawer. If the property
1671 drawer separated from the headline by at least one line, this variable
1672 has no effect."
1673 :group 'org-time
1674 :type 'boolean)
1676 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1677 "Formats for `format-time-string' which are used for time stamps.
1678 It is not recommended to change this constant.")
1680 (defcustom org-time-stamp-rounding-minutes 0
1681 "Number of minutes to round time stamps to upon insertion.
1682 When zero, insert the time unmodified. Useful rounding numbers
1683 should be factors of 60, so for example 5, 10, 15.
1684 When this is not zero, you can still force an exact time-stamp by using
1685 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1686 :group 'org-time
1687 :type 'integer)
1689 (defcustom org-display-custom-times nil
1690 "Non-nil means, overlay custom formats over all time stamps.
1691 The formats are defined through the variable `org-time-stamp-custom-formats'.
1692 To turn this on on a per-file basis, insert anywhere in the file:
1693 #+STARTUP: customtime"
1694 :group 'org-time
1695 :set 'set-default
1696 :type 'sexp)
1697 (make-variable-buffer-local 'org-display-custom-times)
1699 (defcustom org-time-stamp-custom-formats
1700 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1701 "Custom formats for time stamps. See `format-time-string' for the syntax.
1702 These are overlayed over the default ISO format if the variable
1703 `org-display-custom-times' is set. Time like %H:%M should be at the
1704 end of the second format."
1705 :group 'org-time
1706 :type 'sexp)
1708 (defun org-time-stamp-format (&optional long inactive)
1709 "Get the right format for a time string."
1710 (let ((f (if long (cdr org-time-stamp-formats)
1711 (car org-time-stamp-formats))))
1712 (if inactive
1713 (concat "[" (substring f 1 -1) "]")
1714 f)))
1716 (defcustom org-deadline-warning-days 30
1717 "No. of days before expiration during which a deadline becomes active.
1718 This variable governs the display in sparse trees and in the agenda."
1719 :group 'org-time
1720 :type 'number)
1722 (defcustom org-popup-calendar-for-date-prompt t
1723 "Non-nil means, pop up a calendar when prompting for a date.
1724 In the calendar, the date can be selected with mouse-1. However, the
1725 minibuffer will also be active, and you can simply enter the date as well.
1726 When nil, only the minibuffer will be available."
1727 :group 'org-time
1728 :type 'boolean)
1730 (defcustom org-calendar-follow-timestamp-change t
1731 "Non-nil means, make the calendar window follow timestamp changes.
1732 When a timestamp is modified and the calendar window is visible, it will be
1733 moved to the new date."
1734 :group 'org-time
1735 :type 'boolean)
1737 (defgroup org-tags nil
1738 "Options concerning tags in Org-mode."
1739 :tag "Org Tags"
1740 :group 'org)
1742 (defcustom org-tag-alist nil
1743 "List of tags allowed in Org-mode files.
1744 When this list is nil, Org-mode will base TAG input on what is already in the
1745 buffer.
1746 The value of this variable is an alist, the car may be (and should) be a
1747 character that is used to select that tag through the fast-tag-selection
1748 interface. See the manual for details."
1749 :group 'org-tags
1750 :type '(repeat
1751 (choice
1752 (cons (string :tag "Tag name")
1753 (character :tag "Access char"))
1754 (const :tag "Start radio group" (:startgroup))
1755 (const :tag "End radio group" (:endgroup)))))
1757 (defcustom org-use-fast-tag-selection 'auto
1758 "Non-nil means, use fast tag selection scheme.
1759 This is a special interface to select and deselect tags with single keys.
1760 When nil, fast selection is never used.
1761 When the symbol `auto', fast selection is used if and only if selection
1762 characters for tags have been configured, either through the variable
1763 `org-tag-alist' or through a #+TAGS line in the buffer.
1764 When t, fast selection is always used and selection keys are assigned
1765 automatically if necessary."
1766 :group 'org-tags
1767 :type '(choice
1768 (const :tag "Always" t)
1769 (const :tag "Never" nil)
1770 (const :tag "When selection characters are configured" 'auto)))
1772 (defcustom org-fast-tag-selection-single-key nil
1773 "Non-nil means, fast tag selection exits after first change.
1774 When nil, you have to press RET to exit it.
1775 During fast tag selection, you can toggle this flag with `C-c'.
1776 This variable can also have the value `expert'. In this case, the window
1777 displaying the tags menu is not even shown, until you press C-c again."
1778 :group 'org-tags
1779 :type '(choice
1780 (const :tag "No" nil)
1781 (const :tag "Yes" t)
1782 (const :tag "Expert" expert)))
1784 (defcustom org-tags-column 48
1785 "The column to which tags should be indented in a headline.
1786 If this number is positive, it specifies the column. If it is negative,
1787 it means that the tags should be flushright to that column. For example,
1788 -79 works well for a normal 80 character screen."
1789 :group 'org-tags
1790 :type 'integer)
1792 (defcustom org-auto-align-tags t
1793 "Non-nil means, realign tags after pro/demotion of TODO state change.
1794 These operations change the length of a headline and therefore shift
1795 the tags around. With this options turned on, after each such operation
1796 the tags are again aligned to `org-tags-column'."
1797 :group 'org-tags
1798 :type 'boolean)
1800 (defcustom org-use-tag-inheritance t
1801 "Non-nil means, tags in levels apply also for sublevels.
1802 When nil, only the tags directly given in a specific line apply there.
1803 If you turn off this option, you very likely want to turn on the
1804 companion option `org-tags-match-list-sublevels'."
1805 :group 'org-tags
1806 :type 'boolean)
1808 (defcustom org-tags-match-list-sublevels nil
1809 "Non-nil means list also sublevels of headlines matching tag search.
1810 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1811 the sublevels of a headline matching a tag search often also match
1812 the same search. Listing all of them can create very long lists.
1813 Setting this variable to nil causes subtrees of a match to be skipped.
1814 This option is off by default, because inheritance in on. If you turn
1815 inheritance off, you very likely want to turn this option on.
1817 As a special case, if the tag search is restricted to TODO items, the
1818 value of this variable is ignored and sublevels are always checked, to
1819 make sure all corresponding TODO items find their way into the list."
1820 :group 'org-tags
1821 :type 'boolean)
1823 (defvar org-tags-history nil
1824 "History of minibuffer reads for tags.")
1825 (defvar org-last-tags-completion-table nil
1826 "The last used completion table for tags.")
1828 (defgroup org-properties nil
1829 "Options concerning properties in Org-mode."
1830 :tag "Org Properties"
1831 :group 'org)
1833 (defcustom org-property-format "%-10s %s"
1834 "How property key/value pairs should be formatted by `indent-line'.
1835 When `indent-line' hits a property definition, it will format the line
1836 according to this format, mainly to make sure that the values are
1837 lined-up with respect to each other."
1838 :group 'org-properties
1839 :type 'string)
1841 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1842 "The default column format, if no other format has been defined.
1843 This variable can be set on the per-file basis by inserting a line
1845 #+COLUMNS: %25ITEM ....."
1846 :group 'org-properties
1847 :type 'string)
1849 (defcustom org-global-properties nil
1850 "List of property/value pairs that can be inherited by any entry.
1851 You can set buffer-local values for this by adding lines like
1853 #+PROPERTY: NAME VALUE"
1854 :group 'org-properties
1855 :type '(repeat
1856 (cons (string :tag "Property")
1857 (string :tag "Value"))))
1859 (defvar org-local-properties nil
1860 "List of property/value pairs that can be inherited by any entry.
1861 Valid for the current buffer.
1862 This variable is populated from #+PROPERTY lines.")
1864 (defgroup org-agenda nil
1865 "Options concerning agenda views in Org-mode."
1866 :tag "Org Agenda"
1867 :group 'org)
1869 (defvar org-category nil
1870 "Variable used by org files to set a category for agenda display.
1871 Such files should use a file variable to set it, for example
1873 # -*- mode: org; org-category: \"ELisp\"
1875 or contain a special line
1877 #+CATEGORY: ELisp
1879 If the file does not specify a category, then file's base name
1880 is used instead.")
1881 (make-variable-buffer-local 'org-category)
1883 (defcustom org-agenda-files nil
1884 "The files to be used for agenda display.
1885 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1886 \\[org-remove-file]. You can also use customize to edit the list.
1888 If the value of the variable is not a list but a single file name, then
1889 the list of agenda files is actually stored and maintained in that file, one
1890 agenda file per line."
1891 :group 'org-agenda
1892 :type '(choice
1893 (repeat :tag "List of files" file)
1894 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1896 (defcustom org-agenda-skip-unavailable-files nil
1897 "t means to just skip non-reachable files in `org-agenda-files'.
1898 Nil means to remove them, after a query, from the list."
1899 :group 'org-agenda
1900 :type 'boolean)
1902 (defcustom org-agenda-confirm-kill 1
1903 "When set, remote killing from the agenda buffer needs confirmation.
1904 When t, a confirmation is always needed. When a number N, confirmation is
1905 only needed when the text to be killed contains more than N non-white lines."
1906 :group 'org-agenda
1907 :type '(choice
1908 (const :tag "Never" nil)
1909 (const :tag "Always" t)
1910 (number :tag "When more than N lines")))
1912 (defcustom org-calendar-to-agenda-key [?c]
1913 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1914 The command `org-calendar-goto-agenda' will be bound to this key. The
1915 default is the character `c' because then `c' can be used to switch back and
1916 forth between agenda and calendar."
1917 :group 'org-agenda
1918 :type 'sexp)
1920 (defgroup org-agenda-export nil
1921 "Options concerning exporting agenda views in Org-mode."
1922 :tag "Org Agenda Export"
1923 :group 'org-agenda)
1925 (defcustom org-agenda-with-colors t
1926 "Non-nil means, use colors in agenda views."
1927 :group 'org-agenda-export
1928 :type 'boolean)
1930 (defcustom org-agenda-exporter-settings nil
1931 "Alist of variable/value pairs that should be active during agenda export.
1932 This is a good place to set uptions for ps-print and for htmlize."
1933 :group 'org-agenda-export
1934 :type '(repeat
1935 (list
1936 (variable)
1937 (sexp :tag "Value"))))
1939 (defcustom org-agenda-export-html-style ""
1940 "The style specification for exported HTML Agenda files.
1941 If this variable contains a string, it will replace the default <style>
1942 section as produced by `htmlize'.
1943 Since there are different ways of setting style information, this variable
1944 needs to contain the full HTML structure to provide a style, including the
1945 surrounding HTML tags. The style specifications should include definitions
1946 the fonts used by the agenda, here is an example:
1948 <style type=\"text/css\">
1949 p { font-weight: normal; color: gray; }
1950 .org-agenda-structure {
1951 font-size: 110%;
1952 color: #003399;
1953 font-weight: 600;
1955 .org-todo {
1956 color: #cc6666;Week-agenda:
1957 font-weight: bold;
1959 .org-done {
1960 color: #339933;
1962 .title { text-align: center; }
1963 .todo, .deadline { color: red; }
1964 .done { color: green; }
1965 </style>
1967 or, if you want to keep the style in a file,
1969 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1971 As the value of this option simply gets inserted into the HTML <head> header,
1972 you can \"misuse\" it to also add other text to the header. However,
1973 <style>...</style> is required, if not present the variable will be ignored."
1974 :group 'org-agenda-export
1975 :group 'org-export-html
1976 :type 'string)
1978 (defgroup org-agenda-custom-commands nil
1979 "Options concerning agenda views in Org-mode."
1980 :tag "Org Agenda Custom Commands"
1981 :group 'org-agenda)
1983 (defcustom org-agenda-custom-commands nil
1984 "Custom commands for the agenda.
1985 These commands will be offered on the splash screen displayed by the
1986 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1988 (key type match options files)
1990 key The key (a single char as a string) to be associated with the command.
1991 type The command type, any of the following symbols:
1992 todo Entries with a specific TODO keyword, in all agenda files.
1993 tags Tags match in all agenda files.
1994 tags-todo Tags match in all agenda files, TODO entries only.
1995 todo-tree Sparse tree of specific TODO keyword in *current* file.
1996 tags-tree Sparse tree with all tags matches in *current* file.
1997 occur-tree Occur sparse tree for *current* file.
1998 match What to search for:
1999 - a single keyword for TODO keyword searches
2000 - a tags match expression for tags searches
2001 - a regular expression for occur searches
2002 options A list of option settings, similar to that in a let form, so like
2003 this: ((opt1 val1) (opt2 val2) ...)
2004 files A list of files file to write the produced agenda buffer to
2005 with the command `org-store-agenda-views'.
2006 If a file name ends in \".html\", an HTML version of the buffer
2007 is written out. If it ends in \".ps\", a postscript version is
2008 produced. Otherwide, only the plain text is written to the file.
2010 You can also define a set of commands, to create a composite agenda buffer.
2011 In this case, an entry looks like this:
2013 (key desc (cmd1 cmd2 ...) general-options file)
2015 where
2017 desc A description string to be displayed in the dispatcher menu.
2018 cmd An agenda command, similar to the above. However, tree commands
2019 are no allowed, but instead you can get agenda and global todo list.
2020 So valid commands for a set are:
2021 (agenda)
2022 (alltodo)
2023 (stuck)
2024 (todo \"match\" options files)
2025 (tags \"match\" options files)
2026 (tags-todo \"match\" options files)
2028 Each command can carry a list of options, and another set of options can be
2029 given for the whole set of commands. Individual command options take
2030 precedence over the general options."
2031 :group 'org-agenda-custom-commands
2032 :type '(repeat
2033 (choice :value ("a" tags "" nil)
2034 (list :tag "Single command"
2035 (string :tag "Key")
2036 (choice
2037 (const :tag "Agenda" agenda)
2038 (const :tag "TODO list" alltodo)
2039 (const :tag "Stuck projects" stuck)
2040 (const :tag "Tags search (all agenda files)" tags)
2041 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2042 (const :tag "TODO keyword search (all agenda files)" todo)
2043 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2044 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2045 (const :tag "Occur tree (current buffer)" occur-tree)
2046 (symbol :tag "Other, user-defined function"))
2047 (string :tag "Match")
2048 (repeat :tag "Local options"
2049 (list (variable :tag "Option") (sexp :tag "Value")))
2050 (option (repeat :tag "Export" (file :tag "Export to"))))
2051 (list :tag "Command series, all agenda files"
2052 (string :tag "Key")
2053 (string :tag "Description")
2054 (repeat
2055 (choice
2056 (const :tag "Agenda" (agenda))
2057 (const :tag "TODO list" (alltodo))
2058 (const :tag "Stuck projects" (stuck))
2059 (list :tag "Tags search"
2060 (const :format "" tags)
2061 (string :tag "Match")
2062 (repeat :tag "Local options"
2063 (list (variable :tag "Option")
2064 (sexp :tag "Value"))))
2066 (list :tag "Tags search, TODO entries only"
2067 (const :format "" tags-todo)
2068 (string :tag "Match")
2069 (repeat :tag "Local options"
2070 (list (variable :tag "Option")
2071 (sexp :tag "Value"))))
2073 (list :tag "TODO keyword search"
2074 (const :format "" todo)
2075 (string :tag "Match")
2076 (repeat :tag "Local options"
2077 (list (variable :tag "Option")
2078 (sexp :tag "Value"))))
2080 (list :tag "Other, user-defined function"
2081 (symbol :tag "function")
2082 (string :tag "Match")
2083 (repeat :tag "Local options"
2084 (list (variable :tag "Option")
2085 (sexp :tag "Value"))))))
2087 (repeat :tag "General options"
2088 (list (variable :tag "Option")
2089 (sexp :tag "Value")))
2090 (option (repeat :tag "Export" (file :tag "Export to")))))))
2092 (defcustom org-stuck-projects
2093 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2094 "How to identify stuck projects.
2095 This is a list of four items:
2096 1. A tags/todo matcher string that is used to identify a project.
2097 The entire tree below a headline matched by this is considered one project.
2098 2. A list of TODO keywords identifying non-stuck projects.
2099 If the project subtree contains any headline with one of these todo
2100 keywords, the project is considered to be not stuck. If you specify
2101 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2102 3. A list of tags identifying non-stuck projects.
2103 If the project subtree contains any headline with one of these tags,
2104 the project is considered to be not stuck. If you specify \"*\" as
2105 a tag, any tag will mark the project unstuck.
2106 4. An arbitrary regular expression matching non-stuck projects.
2108 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2109 or `C-c a #' to produce the list."
2110 :group 'org-agenda-custom-commands
2111 :type '(list
2112 (string :tag "Tags/TODO match to identify a project")
2113 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2114 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2115 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2118 (defgroup org-agenda-skip nil
2119 "Options concerning skipping parts of agenda files."
2120 :tag "Org Agenda Skip"
2121 :group 'org-agenda)
2123 (defcustom org-agenda-todo-list-sublevels t
2124 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2125 When nil, the sublevels of a TODO entry are not checked, resulting in
2126 potentially much shorter TODO lists."
2127 :group 'org-agenda-skip
2128 :group 'org-todo
2129 :type 'boolean)
2131 (defcustom org-agenda-todo-ignore-scheduled nil
2132 "Non-nil means, don't show scheduled entries in the global todo list.
2133 The idea behind this is that by scheduling it, you have already taken care
2134 of this item."
2135 :group 'org-agenda-skip
2136 :group 'org-todo
2137 :type 'boolean)
2139 (defcustom org-agenda-todo-ignore-deadlines nil
2140 "Non-nil means, don't show near deadline entries in the global todo list.
2141 Near means closer than `org-deadline-warning-days' days.
2142 The idea behind this is that such items will appear in the agenda anyway."
2143 :group 'org-agenda-skip
2144 :group 'org-todo
2145 :type 'boolean)
2147 (defcustom org-agenda-skip-scheduled-if-done nil
2148 "Non-nil means don't show scheduled items in agenda when they are done.
2149 This is relevant for the daily/weekly agenda, not for the TODO list. And
2150 it applied only to the actualy date of the scheduling. Warnings about
2151 an item with a past scheduling dates are always turned off when the item
2152 is DONE."
2153 :group 'org-agenda-skip
2154 :type 'boolean)
2156 (defcustom org-agenda-skip-deadline-if-done nil
2157 "Non-nil means don't show deadines when the corresponding item is done.
2158 When nil, the deadline is still shown and should give you a happy feeling.
2159 This is relevant for the daily/weekly agenda. And it applied only to the
2160 actualy date of the deadline. Warnings about approching and past-due
2161 deadlines are always turned off when the item is DONE."
2162 :group 'org-agenda-skip
2163 :type 'boolean)
2165 (defcustom org-timeline-show-empty-dates 3
2166 "Non-nil means, `org-timeline' also shows dates without an entry.
2167 When nil, only the days which actually have entries are shown.
2168 When t, all days between the first and the last date are shown.
2169 When an integer, show also empty dates, but if there is a gap of more than
2170 N days, just insert a special line indicating the size of the gap."
2171 :group 'org-agenda-skip
2172 :type '(choice
2173 (const :tag "None" nil)
2174 (const :tag "All" t)
2175 (number :tag "at most")))
2178 (defgroup org-agenda-startup nil
2179 "Options concerning initial settings in the Agenda in Org Mode."
2180 :tag "Org Agenda Startup"
2181 :group 'org-agenda)
2183 (defcustom org-finalize-agenda-hook nil
2184 "Hook run just before displaying an agenda buffer."
2185 :group 'org-agenda-startup
2186 :type 'hook)
2188 (defcustom org-agenda-mouse-1-follows-link nil
2189 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2190 A longer mouse click will still set point. Does not wortk on XEmacs.
2191 Needs to be set before org.el is loaded."
2192 :group 'org-agenda-startup
2193 :type 'boolean)
2195 (defcustom org-agenda-start-with-follow-mode nil
2196 "The initial value of follow-mode in a newly created agenda window."
2197 :group 'org-agenda-startup
2198 :type 'boolean)
2200 (defgroup org-agenda-windows nil
2201 "Options concerning the windows used by the Agenda in Org Mode."
2202 :tag "Org Agenda Windows"
2203 :group 'org-agenda)
2205 (defcustom org-agenda-window-setup 'reorganize-frame
2206 "How the agenda buffer should be displayed.
2207 Possible values for this option are:
2209 current-window Show agenda in the current window, keeping all other windows.
2210 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2211 other-window Use `switch-to-buffer-other-window' to display agenda.
2212 reorganize-frame Show only two windows on the current frame, the current
2213 window and the agenda.
2214 See also the variable `org-agenda-restore-windows-after-quit'."
2215 :group 'org-agenda-windows
2216 :type '(choice
2217 (const current-window)
2218 (const other-frame)
2219 (const other-window)
2220 (const reorganize-frame)))
2222 (defcustom org-agenda-restore-windows-after-quit nil
2223 "Non-nil means, restore window configuration open exiting agenda.
2224 Before the window configuration is changed for displaying the agenda,
2225 the current status is recorded. When the agenda is exited with
2226 `q' or `x' and this option is set, the old state is restored. If
2227 `org-agenda-window-setup' is `other-frame', the value of this
2228 option will be ignored.."
2229 :group 'org-agenda-windows
2230 :type 'boolean)
2232 (defcustom org-indirect-buffer-display 'other-window
2233 "How should indirect tree buffers be displayed?
2234 This applies to indirect buffers created with the commands
2235 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2236 Valid values are:
2237 current-window Display in the current window
2238 other-window Just display in another window.
2239 dedicated-frame Create one new frame, and re-use it each time.
2240 new-frame Make a new frame each time."
2241 :group 'org-structure
2242 :group 'org-agenda-windows
2243 :type '(choice
2244 (const :tag "In current window" current-window)
2245 (const :tag "In current frame, other window" other-window)
2246 (const :tag "Each time a new frame" new-frame)
2247 (const :tag "One dedicated frame" dedicated-frame)))
2249 (defgroup org-agenda-daily/weekly nil
2250 "Options concerning the daily/weekly agenda."
2251 :tag "Org Agenda Daily/Weekly"
2252 :group 'org-agenda)
2254 (defcustom org-agenda-ndays 7
2255 "Number of days to include in overview display.
2256 Should be 1 or 7."
2257 :group 'org-agenda-daily/weekly
2258 :type 'number)
2260 (defcustom org-agenda-start-on-weekday 1
2261 "Non-nil means, start the overview always on the specified weekday.
2262 0 denotes Sunday, 1 denotes Monday etc.
2263 When nil, always start on the current day."
2264 :group 'org-agenda-daily/weekly
2265 :type '(choice (const :tag "Today" nil)
2266 (number :tag "Weekday No.")))
2268 (defcustom org-agenda-show-all-dates t
2269 "Non-nil means, `org-agenda' shows every day in the selected range.
2270 When nil, only the days which actually have entries are shown."
2271 :group 'org-agenda-daily/weekly
2272 :type 'boolean)
2274 (defcustom org-agenda-date-format "%A %d %B %Y"
2275 "Format string for displaying dates in the agenda.
2276 Used by the daily/weekly agenda and by the timeline. This should be
2277 a format string understood by `format-time-string'.
2278 FIXME: Not used currently, because of timezone problem."
2279 :group 'org-agenda-daily/weekly
2280 :type 'string)
2282 (defcustom org-agenda-include-diary nil
2283 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2284 :group 'org-agenda-daily/weekly
2285 :type 'boolean)
2287 (defcustom org-agenda-include-all-todo nil
2288 "Set means weekly/daily agenda will always contain all TODO entries.
2289 The TODO entries will be listed at the top of the agenda, before
2290 the entries for specific days."
2291 :group 'org-agenda-daily/weekly
2292 :type 'boolean)
2294 (defcustom org-agenda-repeating-timestamp-show-all t
2295 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2296 When nil, only one occurence is shown, either today or the
2297 nearest into the future."
2298 :group 'org-agenda-daily/weekly
2299 :type 'boolean)
2301 (defgroup org-agenda-time-grid nil
2302 "Options concerning the time grid in the Org-mode Agenda."
2303 :tag "Org Agenda Time Grid"
2304 :group 'org-agenda)
2306 (defcustom org-agenda-use-time-grid t
2307 "Non-nil means, show a time grid in the agenda schedule.
2308 A time grid is a set of lines for specific times (like every two hours between
2309 8:00 and 20:00). The items scheduled for a day at specific times are
2310 sorted in between these lines.
2311 For details about when the grid will be shown, and what it will look like, see
2312 the variable `org-agenda-time-grid'."
2313 :group 'org-agenda-time-grid
2314 :type 'boolean)
2316 (defcustom org-agenda-time-grid
2317 '((daily today require-timed)
2318 "----------------"
2319 (800 1000 1200 1400 1600 1800 2000))
2321 "The settings for time grid for agenda display.
2322 This is a list of three items. The first item is again a list. It contains
2323 symbols specifying conditions when the grid should be displayed:
2325 daily if the agenda shows a single day
2326 weekly if the agenda shows an entire week
2327 today show grid on current date, independent of daily/weekly display
2328 require-timed show grid only if at least one item has a time specification
2330 The second item is a string which will be places behing the grid time.
2332 The third item is a list of integers, indicating the times that should have
2333 a grid line."
2334 :group 'org-agenda-time-grid
2335 :type
2336 '(list
2337 (set :greedy t :tag "Grid Display Options"
2338 (const :tag "Show grid in single day agenda display" daily)
2339 (const :tag "Show grid in weekly agenda display" weekly)
2340 (const :tag "Always show grid for today" today)
2341 (const :tag "Show grid only if any timed entries are present"
2342 require-timed)
2343 (const :tag "Skip grid times already present in an entry"
2344 remove-match))
2345 (string :tag "Grid String")
2346 (repeat :tag "Grid Times" (integer :tag "Time"))))
2348 (defgroup org-agenda-sorting nil
2349 "Options concerning sorting in the Org-mode Agenda."
2350 :tag "Org Agenda Sorting"
2351 :group 'org-agenda)
2353 (let ((sorting-choice
2354 '(choice
2355 (const time-up) (const time-down)
2356 (const category-keep) (const category-up) (const category-down)
2357 (const tag-down) (const tag-up)
2358 (const priority-up) (const priority-down))))
2360 (defcustom org-agenda-sorting-strategy
2361 '((agenda time-up category-keep priority-down)
2362 (todo category-keep priority-down)
2363 (tags category-keep priority-down))
2364 "Sorting structure for the agenda items of a single day.
2365 This is a list of symbols which will be used in sequence to determine
2366 if an entry should be listed before another entry. The following
2367 symbols are recognized:
2369 time-up Put entries with time-of-day indications first, early first
2370 time-down Put entries with time-of-day indications first, late first
2371 category-keep Keep the default order of categories, corresponding to the
2372 sequence in `org-agenda-files'.
2373 category-up Sort alphabetically by category, A-Z.
2374 category-down Sort alphabetically by category, Z-A.
2375 tag-up Sort alphabetically by last tag, A-Z.
2376 tag-down Sort alphabetically by last tag, Z-A.
2377 priority-up Sort numerically by priority, high priority last.
2378 priority-down Sort numerically by priority, high priority first.
2380 The different possibilities will be tried in sequence, and testing stops
2381 if one comparison returns a \"not-equal\". For example, the default
2382 '(time-up category-keep priority-down)
2383 means: Pull out all entries having a specified time of day and sort them,
2384 in order to make a time schedule for the current day the first thing in the
2385 agenda listing for the day. Of the entries without a time indication, keep
2386 the grouped in categories, don't sort the categories, but keep them in
2387 the sequence given in `org-agenda-files'. Within each category sort by
2388 priority.
2390 Leaving out `category-keep' would mean that items will be sorted across
2391 categories by priority."
2392 :group 'org-agenda-sorting
2393 :type `(choice
2394 (repeat :tag "General" ,sorting-choice)
2395 (list :tag "Individually"
2396 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2397 (repeat ,sorting-choice))
2398 (cons (const :tag "Strategy for TODO lists" todo)
2399 (repeat ,sorting-choice))
2400 (cons (const :tag "Strategy for Tags matches" tags)
2401 (repeat ,sorting-choice))))))
2403 (defcustom org-sort-agenda-notime-is-late t
2404 "Non-nil means, items without time are considered late.
2405 This is only relevant for sorting. When t, items which have no explicit
2406 time like 15:30 will be considered as 99:01, i.e. later than any items which
2407 do have a time. When nil, the default time is before 0:00. You can use this
2408 option to decide if the schedule for today should come before or after timeless
2409 agenda entries."
2410 :group 'org-agenda-sorting
2411 :type 'boolean)
2413 (defgroup org-agenda-prefix nil
2414 "Options concerning the entry prefix in the Org-mode agenda display."
2415 :tag "Org Agenda Prefix"
2416 :group 'org-agenda)
2418 (defcustom org-agenda-prefix-format
2419 '((agenda . " %-12:c%?-12t% s")
2420 (timeline . " % s")
2421 (todo . " %-12:c")
2422 (tags . " %-12:c"))
2423 "Format specifications for the prefix of items in the agenda views.
2424 An alist with four entries, for the different agenda types. The keys to the
2425 sublists are `agenda', `timeline', `todo', and `tags'. The values
2426 are format strings.
2427 This format works similar to a printf format, with the following meaning:
2429 %c the category of the item, \"Diary\" for entries from the diary, or
2430 as given by the CATEGORY keyword or derived from the file name.
2431 %T the *last* tag of the item. Last because inherited tags come
2432 first in the list.
2433 %t the time-of-day specification if one applies to the entry, in the
2434 format HH:MM
2435 %s Scheduling/Deadline information, a short string
2437 All specifiers work basically like the standard `%s' of printf, but may
2438 contain two additional characters: A question mark just after the `%' and
2439 a whitespace/punctuation character just before the final letter.
2441 If the first character after `%' is a question mark, the entire field
2442 will only be included if the corresponding value applies to the
2443 current entry. This is useful for fields which should have fixed
2444 width when present, but zero width when absent. For example,
2445 \"%?-12t\" will result in a 12 character time field if a time of the
2446 day is specified, but will completely disappear in entries which do
2447 not contain a time.
2449 If there is punctuation or whitespace character just before the final
2450 format letter, this character will be appended to the field value if
2451 the value is not empty. For example, the format \"%-12:c\" leads to
2452 \"Diary: \" if the category is \"Diary\". If the category were be
2453 empty, no additional colon would be interted.
2455 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2456 - Indent the line with two space characters
2457 - Give the category in a 12 chars wide field, padded with whitespace on
2458 the right (because of `-'). Append a colon if there is a category
2459 (because of `:').
2460 - If there is a time-of-day, put it into a 12 chars wide field. If no
2461 time, don't put in an empty field, just skip it (because of '?').
2462 - Finally, put the scheduling information and append a whitespace.
2464 As another example, if you don't want the time-of-day of entries in
2465 the prefix, you could use:
2467 (setq org-agenda-prefix-format \" %-11:c% s\")
2469 See also the variables `org-agenda-remove-times-when-in-prefix' and
2470 `org-agenda-remove-tags'."
2471 :type '(choice
2472 (string :tag "General format")
2473 (list :greedy t :tag "View dependent"
2474 (cons (const agenda) (string :tag "Format"))
2475 (cons (const timeline) (string :tag "Format"))
2476 (cons (const todo) (string :tag "Format"))
2477 (cons (const tags) (string :tag "Format"))))
2478 :group 'org-agenda-prefix)
2480 (defvar org-prefix-format-compiled nil
2481 "The compiled version of the most recently used prefix format.
2482 See the variable `org-agenda-prefix-format'.")
2484 (defcustom org-agenda-remove-times-when-in-prefix t
2485 "Non-nil means, remove duplicate time specifications in agenda items.
2486 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2487 time-of-day specification in a headline or diary entry is extracted and
2488 placed into the prefix. If this option is non-nil, the original specification
2489 \(a timestamp or -range, or just a plain time(range) specification like
2490 11:30-4pm) will be removed for agenda display. This makes the agenda less
2491 cluttered.
2492 The option can be t or nil. It may also be the symbol `beg', indicating
2493 that the time should only be removed what it is located at the beginning of
2494 the headline/diary entry."
2495 :group 'org-agenda-prefix
2496 :type '(choice
2497 (const :tag "Always" t)
2498 (const :tag "Never" nil)
2499 (const :tag "When at beginning of entry" beg)))
2502 (defcustom org-agenda-default-appointment-duration nil
2503 "Default duration for appointments that only have a starting time.
2504 When nil, no duration is specified in such cases.
2505 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2506 :group 'org-agenda-prefix
2507 :type '(choice
2508 (integer :tag "Minutes")
2509 (const :tag "No default duration")))
2512 (defcustom org-agenda-remove-tags nil
2513 "Non-nil means, remove the tags from the headline copy in the agenda.
2514 When this is the symbol `prefix', only remove tags when
2515 `org-agenda-prefix-format' contains a `%T' specifier."
2516 :group 'org-agenda-prefix
2517 :type '(choice
2518 (const :tag "Always" t)
2519 (const :tag "Never" nil)
2520 (const :tag "When prefix format contains %T" prefix)))
2522 (if (fboundp 'defvaralias)
2523 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2524 'org-agenda-remove-tags))
2526 (defcustom org-agenda-align-tags-to-column 65
2527 "Shift tags in agenda items to this column."
2528 :group 'org-agenda-prefix
2529 :type 'integer)
2531 (defgroup org-latex nil
2532 "Options for embedding LaTeX code into Org-mode"
2533 :tag "Org LaTeX"
2534 :group 'org)
2536 (defcustom org-format-latex-options
2537 '(:foreground default :background default :scale 1.0
2538 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2539 :matchers ("begin" "$" "$$" "\\(" "\\["))
2540 "Options for creating images from LaTeX fragments.
2541 This is a property list with the following properties:
2542 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2543 `default' means use the forground of the default face.
2544 :background the background color, or \"Transparent\".
2545 `default' means use the background of the default face.
2546 :scale a scaling factor for the size of the images
2547 :html-foreground, :html-background, :html-scale
2548 The same numbers for HTML export.
2549 :matchers a list indicating which matchers should be used to
2550 find LaTeX fragments. Valid members of this list are:
2551 \"begin\" find environments
2552 \"$\" find math expressions surrounded by $...$
2553 \"$$\" find math expressions surrounded by $$....$$
2554 \"\\(\" find math expressions surrounded by \\(...\\)
2555 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2556 :group 'org-export-latex
2557 :type 'plist)
2559 (defcustom org-format-latex-header "\\documentclass{article}
2560 \\usepackage{fullpage} % do not remove
2561 \\usepackage{amssymb}
2562 \\usepackage[usenames]{color}
2563 \\usepackage{amsmath}
2564 \\usepackage{latexsym}
2565 \\usepackage[mathscr]{eucal}
2566 \\pagestyle{empty} % do not remove"
2567 "The document header used for processing LaTeX fragments."
2568 :group 'org-export-latex
2569 :type 'string)
2571 (defgroup org-export nil
2572 "Options for exporting org-listings."
2573 :tag "Org Export"
2574 :group 'org)
2576 (defgroup org-export-general nil
2577 "General options for exporting Org-mode files."
2578 :tag "Org Export General"
2579 :group 'org-export)
2581 (defcustom org-export-publishing-directory "."
2582 "Path to the location where exported files should be located.
2583 This path may be relative to the directory where the Org-mode file lives.
2584 The default is to put them into the same directory as the Org-mode file.
2585 The variable may also be an alist with export types `:html', `:ascii',
2586 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2587 If a directory path is relative, it is interpreted relative to the
2588 directory where the exported Org-mode files lives."
2589 :group 'org-export-general
2590 :type '(choice
2591 (directory)
2592 (repeat
2593 (cons
2594 (choice :tag "Type"
2595 (const :html) (const :LaTeX)
2596 (const :ascii) (const :ical) (const :xoxo))
2597 (directory)))))
2599 (defcustom org-export-language-setup
2600 '(("en" "Author" "Date" "Table of Contents")
2601 ("cs" "Autor" "Datum" "Obsah")
2602 ("da" "Ophavsmand" "Dato" "Indhold")
2603 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2604 ("es" "Autor" "Fecha" "\xccndice")
2605 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2606 ("it" "Autore" "Data" "Indice")
2607 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2608 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2609 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2610 "Terms used in export text, translated to different languages.
2611 Use the variable `org-export-default-language' to set the language,
2612 or use the +OPTION lines for a per-file setting."
2613 :group 'org-export-general
2614 :type '(repeat
2615 (list
2616 (string :tag "HTML language tag")
2617 (string :tag "Author")
2618 (string :tag "Date")
2619 (string :tag "Table of Contents"))))
2621 (defcustom org-export-default-language "en"
2622 "The default language of HTML export, as a string.
2623 This should have an association in `org-export-language-setup'."
2624 :group 'org-export-general
2625 :type 'string)
2627 (defcustom org-export-skip-text-before-1st-heading t
2628 "Non-nil means, skip all text before the first headline when exporting.
2629 When nil, that text is exported as well."
2630 :group 'org-export-general
2631 :type 'boolean)
2633 (defcustom org-export-headline-levels 3
2634 "The last level which is still exported as a headline.
2635 Inferior levels will produce itemize lists when exported.
2636 Note that a numeric prefix argument to an exporter function overrides
2637 this setting.
2639 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2640 :group 'org-export-general
2641 :type 'number)
2643 (defcustom org-export-with-section-numbers t
2644 "Non-nil means, add section numbers to headlines when exporting.
2646 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2647 :group 'org-export-general
2648 :type 'boolean)
2650 (defcustom org-export-with-toc t
2651 "Non-nil means, create a table of contents in exported files.
2652 The TOC contains headlines with levels up to`org-export-headline-levels'.
2653 When an integer, include levels up to N in the toc, this may then be
2654 different from `org-export-headline-levels', but it will not be allowed
2655 to be larger than the number of headline levels.
2656 When nil, no table of contents is made.
2658 Headlines which contain any TODO items will be marked with \"(*)\" in
2659 ASCII export, and with red color in HTML output, if the option
2660 `org-export-mark-todo-in-toc' is set.
2662 In HTML output, the TOC will be clickable.
2664 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2665 or \"toc:3\"."
2666 :group 'org-export-general
2667 :type '(choice
2668 (const :tag "No Table of Contents" nil)
2669 (const :tag "Full Table of Contents" t)
2670 (integer :tag "TOC to level")))
2672 (defcustom org-export-mark-todo-in-toc nil
2673 "Non-nil means, mark TOC lines that contain any open TODO items."
2674 :group 'org-export-general
2675 :type 'boolean)
2677 (defcustom org-export-preserve-breaks nil
2678 "Non-nil means, preserve all line breaks when exporting.
2679 Normally, in HTML output paragraphs will be reformatted. In ASCII
2680 export, line breaks will always be preserved, regardless of this variable.
2682 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2683 :group 'org-export-general
2684 :type 'boolean)
2686 (defcustom org-export-with-archived-trees 'headline
2687 "Whether subtrees with the ARCHIVE tag should be exported.
2688 This can have three different values
2689 nil Do not export, pretend this tree is not present
2690 t Do export the entire tree
2691 headline Only export the headline, but skip the tree below it."
2692 :group 'org-export-general
2693 :group 'org-archive
2694 :type '(choice
2695 (const :tag "not at all" nil)
2696 (const :tag "headline only" 'headline)
2697 (const :tag "entirely" t)))
2699 (defcustom org-export-author-info t
2700 "Non-nil means, insert author name and email into the exported file.
2702 This option can also be set with the +OPTIONS line,
2703 e.g. \"author-info:nil\"."
2704 :group 'org-export-general
2705 :type 'boolean)
2707 (defcustom org-export-time-stamp-file t
2708 "Non-nil means, insert a time stamp into the exported file.
2709 The time stamp shows when the file was created.
2711 This option can also be set with the +OPTIONS line,
2712 e.g. \"timestamp:nil\"."
2713 :group 'org-export-general
2714 :type 'boolean)
2716 (defcustom org-export-with-timestamps t
2717 "If nil, do not export time stamps and associated keywords."
2718 :group 'org-export-general
2719 :type 'boolean)
2721 (defcustom org-export-remove-timestamps-from-toc t
2722 "If nil, remove timestamps from the table of contents entries."
2723 :group 'org-export-general
2724 :type 'boolean)
2726 (defcustom org-export-with-tags 'not-in-toc
2727 "If nil, do not export tags, just remove them from headlines.
2728 If this is the symbol `not-in-toc', tags will be removed from table of
2729 contents entries, but still be shown in the headlines of the document."
2730 :group 'org-export-general
2731 :type '(choice
2732 (const :tag "Off" nil)
2733 (const :tag "Not in TOC" not-in-toc)
2734 (const :tag "On" t)))
2736 (defcustom org-export-with-property-drawer nil
2737 "Non-nil means, export property drawers.
2738 When nil, these drawers are removed before export.
2740 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2741 :group 'org-export-general
2742 :type 'boolean)
2744 (defgroup org-export-translation nil
2745 "Options for translating special ascii sequences for the export backends."
2746 :tag "Org Export Translation"
2747 :group 'org-export)
2749 (defcustom org-export-with-emphasize t
2750 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2751 If the export target supports emphasizing text, the word will be
2752 typeset in bold, italic, or underlined, respectively. Works only for
2753 single words, but you can say: I *really* *mean* *this*.
2754 Not all export backends support this.
2756 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2757 :group 'org-export-translation
2758 :type 'boolean)
2760 (defcustom org-export-with-footnotes t
2761 "If nil, export [1] as a footnote marker.
2762 Lines starting with [1] will be formatted as footnotes.
2764 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2765 :group 'org-export-translation
2766 :type 'boolean)
2768 (defcustom org-export-with-sub-superscripts t
2769 "Non-nil means, interpret \"_\" and \"^\" for export.
2770 When this option is turned on, you can use TeX-like syntax for sub- and
2771 superscripts. Several characters after \"_\" or \"^\" will be
2772 considered as a single item - so grouping with {} is normally not
2773 needed. For example, the following things will be parsed as single
2774 sub- or superscripts.
2776 10^24 or 10^tau several digits will be considered 1 item.
2777 10^-12 or 10^-tau a leading sign with digits or a word
2778 x^2-y^3 will be read as x^2 - y^3, because items are
2779 terminated by almost any nonword/nondigit char.
2780 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2782 Still, ambiguity is possible - so when in doubt use {} to enclose the
2783 sub/superscript. If you set this variable to the symbol `{}',
2784 the braces are *required* in order to trigger interpretations as
2785 sub/superscript. This can be helpful in documents that need \"_\"
2786 frequently in plain text.
2788 Not all export backends support this, but HTML does.
2790 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2791 :group 'org-export-translation
2792 :type '(choice
2793 (const :tag "Always interpret" t)
2794 (const :tag "Only with braces" {})
2795 (const :tag "Never interpret" nil)))
2797 (defcustom org-export-with-TeX-macros t
2798 "Non-nil means, interpret simple TeX-like macros when exporting.
2799 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2800 No only real TeX macros will work here, but the standard HTML entities
2801 for math can be used as macro names as well. For a list of supported
2802 names in HTML export, see the constant `org-html-entities'.
2803 Not all export backends support this.
2805 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2806 :group 'org-export-translation
2807 :group 'org-export-latex
2808 :type 'boolean)
2810 (defcustom org-export-with-LaTeX-fragments nil
2811 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2812 When set, the exporter will find LaTeX environments if the \\begin line is
2813 the first non-white thing on a line. It will also find the math delimiters
2814 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2815 display math.
2817 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2818 :group 'org-export-translation
2819 :group 'org-export-latex
2820 :type 'boolean)
2822 (defcustom org-export-with-fixed-width t
2823 "Non-nil means, lines starting with \":\" will be in fixed width font.
2824 This can be used to have pre-formatted text, fragments of code etc. For
2825 example:
2826 : ;; Some Lisp examples
2827 : (while (defc cnt)
2828 : (ding))
2829 will be looking just like this in also HTML. See also the QUOTE keyword.
2830 Not all export backends support this.
2832 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2833 :group 'org-export-translation
2834 :type 'boolean)
2836 (defcustom org-match-sexp-depth 3
2837 "Number of stacked braces for sub/superscript matching.
2838 This has to be set before loading org.el to be effective."
2839 :group 'org-export-translation
2840 :type 'integer)
2842 (defgroup org-export-tables nil
2843 "Options for exporting tables in Org-mode."
2844 :tag "Org Export Tables"
2845 :group 'org-export)
2847 (defcustom org-export-with-tables t
2848 "If non-nil, lines starting with \"|\" define a table.
2849 For example:
2851 | Name | Address | Birthday |
2852 |-------------+----------+-----------|
2853 | Arthur Dent | England | 29.2.2100 |
2855 Not all export backends support this.
2857 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2858 :group 'org-export-tables
2859 :type 'boolean)
2861 (defcustom org-export-highlight-first-table-line t
2862 "Non-nil means, highlight the first table line.
2863 In HTML export, this means use <th> instead of <td>.
2864 In tables created with table.el, this applies to the first table line.
2865 In Org-mode tables, all lines before the first horizontal separator
2866 line will be formatted with <th> tags."
2867 :group 'org-export-tables
2868 :type 'boolean)
2870 (defcustom org-export-table-remove-special-lines t
2871 "Remove special lines and marking characters in calculating tables.
2872 This removes the special marking character column from tables that are set
2873 up for spreadsheet calculations. It also removes the entire lines
2874 marked with `!', `_', or `^'. The lines with `$' are kept, because
2875 the values of constants may be useful to have."
2876 :group 'org-export-tables
2877 :type 'boolean)
2879 (defcustom org-export-prefer-native-exporter-for-tables nil
2880 "Non-nil means, always export tables created with table.el natively.
2881 Natively means, use the HTML code generator in table.el.
2882 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2883 the table does not use row- or column-spanning). This has the
2884 advantage, that the automatic HTML conversions for math symbols and
2885 sub/superscripts can be applied. Org-mode's HTML generator is also
2886 much faster."
2887 :group 'org-export-tables
2888 :type 'boolean)
2890 (defgroup org-export-ascii nil
2891 "Options specific for ASCII export of Org-mode files."
2892 :tag "Org Export ASCII"
2893 :group 'org-export)
2895 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2896 "Characters for underlining headings in ASCII export.
2897 In the given sequence, these characters will be used for level 1, 2, ..."
2898 :group 'org-export-ascii
2899 :type '(repeat character))
2901 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2902 "Bullet characters for headlines converted to lists in ASCII export.
2903 The first character is is used for the first lest level generated in this
2904 way, and so on. If there are more levels than characters given here,
2905 the list will be repeated.
2906 Note that plain lists will keep the same bullets as the have in the
2907 Org-mode file."
2908 :group 'org-export-ascii
2909 :type '(repeat character))
2911 (defgroup org-export-xml nil
2912 "Options specific for XML export of Org-mode files."
2913 :tag "Org Export XML"
2914 :group 'org-export)
2916 (defgroup org-export-html nil
2917 "Options specific for HTML export of Org-mode files."
2918 :tag "Org Export HTML"
2919 :group 'org-export)
2921 (defcustom org-export-html-coding-system nil
2923 :group 'org-export-html
2924 :type 'coding-system)
2926 (defcustom org-export-html-style
2927 "<style type=\"text/css\">
2928 html {
2929 font-family: Times, serif;
2930 font-size: 12pt;
2932 .title { text-align: center; }
2933 .todo { color: red; }
2934 .done { color: green; }
2935 .timestamp { color: grey }
2936 .timestamp-kwd { color: CadetBlue }
2937 .tag { background-color:lightblue; font-weight:normal }
2938 .target { background-color: lavender; }
2939 pre {
2940 border: 1pt solid #AEBDCC;
2941 background-color: #F3F5F7;
2942 padding: 5pt;
2943 font-family: courier, monospace;
2945 table { border-collapse: collapse; }
2946 td, th {
2947 vertical-align: top;
2948 <!--border: 1pt solid #ADB9CC;-->
2950 </style>"
2951 "The default style specification for exported HTML files.
2952 Since there are different ways of setting style information, this variable
2953 needs to contain the full HTML structure to provide a style, including the
2954 surrounding HTML tags. The style specifications should include definitions
2955 for new classes todo, done, title, and deadline. For example, legal values
2956 would be:
2958 <style type=\"text/css\">
2959 p { font-weight: normal; color: gray; }
2960 h1 { color: black; }
2961 .title { text-align: center; }
2962 .todo, .deadline { color: red; }
2963 .done { color: green; }
2964 </style>
2966 or, if you want to keep the style in a file,
2968 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2970 As the value of this option simply gets inserted into the HTML <head> header,
2971 you can \"misuse\" it to add arbitrary text to the header."
2972 :group 'org-export-html
2973 :type 'string)
2976 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2977 "Format for typesetting the document title in HTML export."
2978 :group 'org-export-html
2979 :type 'string)
2981 (defcustom org-export-html-toplevel-hlevel 2
2982 "The <H> level for level 1 headings in HTML export."
2983 :group 'org-export-html
2984 :type 'string)
2986 (defcustom org-export-html-link-org-files-as-html t
2987 "Non-nil means, make file links to `file.org' point to `file.html'.
2988 When org-mode is exporting an org-mode file to HTML, links to
2989 non-html files are directly put into a href tag in HTML.
2990 However, links to other Org-mode files (recognized by the
2991 extension `.org.) should become links to the corresponding html
2992 file, assuming that the linked org-mode file will also be
2993 converted to HTML.
2994 When nil, the links still point to the plain `.org' file."
2995 :group 'org-export-html
2996 :type 'boolean)
2998 (defcustom org-export-html-inline-images 'maybe
2999 "Non-nil means, inline images into exported HTML pages.
3000 This is done using an <img> tag. When nil, an anchor with href is used to
3001 link to the image. If this option is `maybe', then images in links with
3002 an empty description will be inlined, while images with a description will
3003 be linked only."
3004 :group 'org-export-html
3005 :type '(choice (const :tag "Never" nil)
3006 (const :tag "Always" t)
3007 (const :tag "When there is no description" maybe)))
3009 ;; FIXME: rename
3010 (defcustom org-export-html-expand t
3011 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3012 When nil, these tags will be exported as plain text and therefore
3013 not be interpreted by a browser.
3015 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3016 :group 'org-export-html
3017 :type 'boolean)
3019 (defcustom org-export-html-table-tag
3020 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3021 "The HTML tag that is used to start a table.
3022 This must be a <table> tag, but you may change the options like
3023 borders and spacing."
3024 :group 'org-export-html
3025 :type 'string)
3027 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3028 "The opening tag for table header fields.
3029 This is customizable so that alignment options can be specified."
3030 :group 'org-export-tables
3031 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3033 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3034 "The opening tag for table data fields.
3035 This is customizable so that alignment options can be specified."
3036 :group 'org-export-tables
3037 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3039 (defcustom org-export-html-with-timestamp nil
3040 "If non-nil, write `org-export-html-html-helper-timestamp'
3041 into the exported HTML text. Otherwise, the buffer will just be saved
3042 to a file."
3043 :group 'org-export-html
3044 :type 'boolean)
3046 (defcustom org-export-html-html-helper-timestamp
3047 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3048 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3049 :group 'org-export-html
3050 :type 'string)
3052 (defgroup org-export-icalendar nil
3053 "Options specific for iCalendar export of Org-mode files."
3054 :tag "Org Export iCalendar"
3055 :group 'org-export)
3057 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3058 "The file name for the iCalendar file covering all agenda files.
3059 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3060 The file name should be absolute."
3061 :group 'org-export-icalendar
3062 :type 'file)
3064 (defcustom org-icalendar-include-todo nil
3065 "Non-nil means, export to iCalendar files should also cover TODO items."
3066 :group 'org-export-icalendar
3067 :type '(choice
3068 (const :tag "None" nil)
3069 (const :tag "Unfinished" t)
3070 (const :tag "All" all)))
3072 (defcustom org-icalendar-include-sexps t
3073 "Non-nil means, export to iCalendar files should also cover sexp entries.
3074 These are entries like in the diary, but directly in an Org-mode file."
3075 :group 'org-export-icalendar
3076 :type 'boolean)
3078 (defcustom org-icalendar-combined-name "OrgMode"
3079 "Calendar name for the combined iCalendar representing all agenda files."
3080 :group 'org-export-icalendar
3081 :type 'string)
3083 (defgroup org-font-lock nil
3084 "Font-lock settings for highlighting in Org-mode."
3085 :tag "Org Font Lock"
3086 :group 'org)
3088 (defcustom org-level-color-stars-only nil
3089 "Non-nil means fontify only the stars in each headline.
3090 When nil, the entire headline is fontified.
3091 Changing it requires restart of `font-lock-mode' to become effective
3092 also in regions already fontified."
3093 :group 'org-font-lock
3094 :type 'boolean)
3096 (defcustom org-hide-leading-stars nil
3097 "Non-nil means, hide the first N-1 stars in a headline.
3098 This works by using the face `org-hide' for these stars. This
3099 face is white for a light background, and black for a dark
3100 background. You may have to customize the face `org-hide' to
3101 make this work.
3102 Changing it requires restart of `font-lock-mode' to become effective
3103 also in regions already fontified.
3104 You may also set this on a per-file basis by adding one of the following
3105 lines to the buffer:
3107 #+STARTUP: hidestars
3108 #+STARTUP: showstars"
3109 :group 'org-font-lock
3110 :type 'boolean)
3112 (defcustom org-fontify-done-headline nil
3113 "Non-nil means, change the face of a headline if it is marked DONE.
3114 Normally, only the TODO/DONE keyword indicates the state of a headline.
3115 When this is non-nil, the headline after the keyword is set to the
3116 `org-headline-done' as an additional indication."
3117 :group 'org-font-lock
3118 :type 'boolean)
3120 (defcustom org-fontify-emphasized-text t
3121 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3122 Changing this variable requires a restart of Emacs to take effect."
3123 :group 'org-font-lock
3124 :type 'boolean)
3126 (defvar org-emph-re nil
3127 "Regular expression for matching emphasis.")
3128 (defvar org-emphasis-regexp-components) ; defined just below
3129 (defvar org-emphasis-alist) ; defined just below
3130 (defun org-set-emph-re (var val)
3131 "Set variable and compute the emphasis regular expression."
3132 (set var val)
3133 (when (and (boundp 'org-emphasis-alist)
3134 (boundp 'org-emphasis-regexp-components)
3135 org-emphasis-alist org-emphasis-regexp-components)
3136 (let* ((e org-emphasis-regexp-components)
3137 (pre (car e))
3138 (post (nth 1 e))
3139 (border (nth 2 e))
3140 (body (nth 3 e))
3141 (nl (nth 4 e))
3142 (stacked (nth 5 e))
3143 (body1 (concat body "*?"))
3144 (markers (mapconcat 'car org-emphasis-alist "")))
3145 ;; make sure special characters appear at the right position in the class
3146 (if (string-match "\\^" markers)
3147 (setq markers (concat (replace-match "" t t markers) "^")))
3148 (if (string-match "-" markers)
3149 (setq markers (concat (replace-match "" t t markers) "-")))
3150 (if (> nl 0)
3151 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3152 (int-to-string nl) "\\}")))
3153 ;; Make the regexp
3154 (setq org-emph-re
3155 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3156 "\\("
3157 "\\([" markers "]\\)"
3158 "\\("
3159 "[^" border (if (and nil stacked) markers) "]"
3160 body1
3161 "[^" border (if (and nil stacked) markers) "]"
3162 "\\)"
3163 "\\3\\)"
3164 "\\([" post (if stacked markers) "]\\|$\\)")))))
3166 (defcustom org-emphasis-regexp-components
3167 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3168 "Components used to build the reqular expression for emphasis.
3169 This is a list with 6 entries. Terminology: In an emphasis string
3170 like \" *strong word* \", we call the initial space PREMATCH, the final
3171 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3172 and \"trong wor\" is the body. The different components in this variable
3173 specify what is allowed/forbidden in each part:
3175 pre Chars allowed as prematch. Beginning of line will be allowed too.
3176 post Chars allowed as postmatch. End of line will be allowed too.
3177 border The chars *forbidden* as border characters.
3178 body-regexp A regexp like \".\" to match a body character. Don't use
3179 non-shy groups here, and don't allow newline here.
3180 newline The maximum number of newlines allowed in an emphasis exp.
3181 stacked Non-nil means, allow stacked styles. This works only in HTML
3182 export. When this is set, all marker characters (as given in
3183 `org-emphasis-alist') will be allowed as pre/post, aiding
3184 inside-out matching.
3185 Use customize to modify this, or restart Emacs after changing it."
3186 :group 'org-font-lock
3187 :set 'org-set-emph-re
3188 :type '(list
3189 (sexp :tag "Allowed chars in pre ")
3190 (sexp :tag "Allowed chars in post ")
3191 (sexp :tag "Forbidden chars in border ")
3192 (sexp :tag "Regexp for body ")
3193 (integer :tag "number of newlines allowed")
3194 (boolean :tag "Stacking allowed ")))
3196 (defcustom org-emphasis-alist
3197 '(("*" bold "<b>" "</b>")
3198 ("/" italic "<i>" "</i>")
3199 ("_" underline "<u>" "</u>")
3200 ("=" org-code "<code>" "</code>")
3201 ("+" (:strike-through t) "<del>" "</del>")
3203 "Special syntax for emphasized text.
3204 Text starting and ending with a special character will be emphasized, for
3205 example *bold*, _underlined_ and /italic/. This variable sets the marker
3206 characters, the face to be used by font-lock for highlighting in Org-mode
3207 Emacs buffers, and the HTML tags to be used for this.
3208 Use customize to modify this, or restart Emacs after changing it."
3209 :group 'org-font-lock
3210 :set 'org-set-emph-re
3211 :type '(repeat
3212 (list
3213 (string :tag "Marker character")
3214 (choice
3215 (face :tag "Font-lock-face")
3216 (plist :tag "Face property list"))
3217 (string :tag "HTML start tag")
3218 (string :tag "HTML end tag"))))
3220 ;;; The faces
3222 (defgroup org-faces nil
3223 "Faces in Org-mode."
3224 :tag "Org Faces"
3225 :group 'org-font-lock)
3227 ;; FIXME: convert that into a macro? Not critical, because this
3228 ;; is only executed a few times at load time.
3229 (defun org-compatible-face (specs)
3230 "Make a compatible face specification.
3231 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3232 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3233 to the top of the list. The `min-colors' attribute will be removed from
3234 any other entries, and any resulting duplicates will be removed entirely."
3235 (if (or (featurep 'xemacs) (< emacs-major-version 22))
3236 (let (r e a)
3237 (while (setq e (pop specs))
3238 (cond
3239 ((memq (car e) '(t default)) (push e r))
3240 ((setq a (member '(min-colors 8) (car e)))
3241 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3242 (cdr e)))))
3243 ((setq a (assq 'min-colors (car e)))
3244 (setq e (cons (delq a (car e)) (cdr e)))
3245 (or (assoc (car e) r) (push e r)))
3246 (t (or (assoc (car e) r) (push e r)))))
3247 (nreverse r))
3248 specs))
3250 (defface org-hide
3251 '((((background light)) (:foreground "white"))
3252 (((background dark)) (:foreground "black")))
3253 "Face used to hide leading stars in headlines.
3254 The forground color of this face should be equal to the background
3255 color of the frame."
3256 :group 'org-faces)
3258 (defface org-level-1 ;; font-lock-function-name-face
3259 (org-compatible-face
3260 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3261 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3262 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3263 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3264 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3265 (t (:bold t))))
3266 "Face used for level 1 headlines."
3267 :group 'org-faces)
3269 (defface org-level-2 ;; font-lock-variable-name-face
3270 (org-compatible-face
3271 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3272 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3273 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3274 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3275 (t (:bold t))))
3276 "Face used for level 2 headlines."
3277 :group 'org-faces)
3279 (defface org-level-3 ;; font-lock-keyword-face
3280 (org-compatible-face
3281 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3282 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3283 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3284 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3285 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3286 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3287 (t (:bold t))))
3288 "Face used for level 3 headlines."
3289 :group 'org-faces)
3291 (defface org-level-4 ;; font-lock-comment-face
3292 (org-compatible-face
3293 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3294 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3295 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3296 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3297 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3298 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3299 (t (:bold t))))
3300 "Face used for level 4 headlines."
3301 :group 'org-faces)
3303 (defface org-level-5 ;; font-lock-type-face
3304 (org-compatible-face
3305 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3306 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3307 (((class color) (min-colors 8)) (:foreground "green"))))
3308 "Face used for level 5 headlines."
3309 :group 'org-faces)
3311 (defface org-level-6 ;; font-lock-constant-face
3312 (org-compatible-face
3313 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3314 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3315 (((class color) (min-colors 8)) (:foreground "magenta"))))
3316 "Face used for level 6 headlines."
3317 :group 'org-faces)
3319 (defface org-level-7 ;; font-lock-builtin-face
3320 (org-compatible-face
3321 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3322 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3323 (((class color) (min-colors 8)) (:foreground "blue"))))
3324 "Face used for level 7 headlines."
3325 :group 'org-faces)
3327 (defface org-level-8 ;; font-lock-string-face
3328 (org-compatible-face
3329 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3330 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3331 (((class color) (min-colors 8)) (:foreground "green"))))
3332 "Face used for level 8 headlines."
3333 :group 'org-faces)
3335 (defface org-special-keyword ;; font-lock-string-face
3336 (org-compatible-face
3337 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3338 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3339 (t (:italic t))))
3340 "Face used for special keywords."
3341 :group 'org-faces)
3343 (defface org-drawer ;; font-lock-function-name-face
3344 (org-compatible-face
3345 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3346 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3347 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3348 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3349 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3350 (t (:bold t))))
3351 "Face used for drawers."
3352 :group 'org-faces)
3354 (defface org-property-value nil
3355 "Face used for the value of a property."
3356 :group 'org-faces)
3358 (defface org-column
3359 (org-compatible-face
3360 '((((class color) (min-colors 16) (background light))
3361 (:background "grey90"))
3362 (((class color) (min-colors 16) (background dark))
3363 (:background "grey30"))
3364 (((class color) (min-colors 8))
3365 (:background "cyan" :foreground "black"))
3366 (t (:inverse-video t))))
3367 "Face for column display of entry properties."
3368 :group 'org-faces)
3370 (when (fboundp 'set-face-attribute)
3371 ;; Make sure that a fixed-width face is used when we have a column table.
3372 (set-face-attribute 'org-column nil
3373 :height (face-attribute 'default :height)
3374 :family (face-attribute 'default :family)))
3376 (defface org-warning ;; font-lock-warning-face
3377 (org-compatible-face
3378 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3379 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3380 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3381 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3382 (t (:bold t))))
3383 "Face for deadlines and TODO keywords."
3384 :group 'org-faces)
3386 (defface org-archived ; similar to shadow
3387 (org-compatible-face
3388 '((((class color grayscale) (min-colors 88) (background light))
3389 (:foreground "grey50"))
3390 (((class color grayscale) (min-colors 88) (background dark))
3391 (:foreground "grey70"))
3392 (((class color) (min-colors 8) (background light))
3393 (:foreground "green"))
3394 (((class color) (min-colors 8) (background dark))
3395 (:foreground "yellow"))))
3396 "Face for headline with the ARCHIVE tag."
3397 :group 'org-faces)
3399 (defface org-link
3400 '((((class color) (background light)) (:foreground "Purple" :underline t))
3401 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3402 (t (:underline t)))
3403 "Face for links."
3404 :group 'org-faces)
3406 (defface org-target
3407 '((((class color) (background light)) (:underline t))
3408 (((class color) (background dark)) (:underline t))
3409 (t (:underline t)))
3410 "Face for links."
3411 :group 'org-faces)
3413 (defface org-date
3414 '((((class color) (background light)) (:foreground "Purple" :underline t))
3415 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3416 (t (:underline t)))
3417 "Face for links."
3418 :group 'org-faces)
3420 (defface org-sexp-date
3421 '((((class color) (background light)) (:foreground "Purple"))
3422 (((class color) (background dark)) (:foreground "Cyan"))
3423 (t (:underline t)))
3424 "Face for links."
3425 :group 'org-faces)
3427 (defface org-tag
3428 '((t (:bold t)))
3429 "Face for tags."
3430 :group 'org-faces)
3432 (defface org-todo ;; font-lock-warning-face
3433 (org-compatible-face
3434 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3435 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3436 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3437 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3438 (t (:inverse-video t :bold t))))
3439 "Face for TODO keywords."
3440 :group 'org-faces)
3442 (defface org-done ;; font-lock-type-face
3443 (org-compatible-face
3444 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3445 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3446 (((class color) (min-colors 8)) (:foreground "green"))
3447 (t (:bold t))))
3448 "Face used for todo keywords that indicate DONE items."
3449 :group 'org-faces)
3451 (defface org-headline-done ;; font-lock-string-face
3452 (org-compatible-face
3453 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3454 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3455 (((class color) (min-colors 8) (background light)) (:bold nil))))
3456 "Face used to indicate that a headline is DONE.
3457 This face is only used if `org-fontify-done-headline' is set. If applies
3458 to the part of the headline after the DONE keyword."
3459 :group 'org-faces)
3461 (defcustom org-todo-keyword-faces nil
3462 "Faces for specific TODO keywords.
3463 This is a list of cons cells, with TODO keywords in the car
3464 and faces in the cdr. The face can be a symbol, or a property
3465 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3466 :group 'org-faces
3467 :group 'org-todo
3468 :type '(repeat
3469 (cons
3470 (string :tag "keyword")
3471 (sexp :tag "face"))))
3473 (defface org-table ;; font-lock-function-name-face
3474 (org-compatible-face
3475 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3476 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3477 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3478 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3479 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3480 (((class color) (min-colors 8) (background dark)))))
3481 "Face used for tables."
3482 :group 'org-faces)
3484 (defface org-formula
3485 (org-compatible-face
3486 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3487 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3488 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3489 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3490 (t (:bold t :italic t))))
3491 "Face for formulas."
3492 :group 'org-faces)
3494 (defface org-code
3495 (org-compatible-face
3496 '((((class color grayscale) (min-colors 88) (background light))
3497 (:foreground "grey50"))
3498 (((class color grayscale) (min-colors 88) (background dark))
3499 (:foreground "grey70"))
3500 (((class color) (min-colors 8) (background light))
3501 (:foreground "green"))
3502 (((class color) (min-colors 8) (background dark))
3503 (:foreground "yellow"))))
3504 "Face for fixed-with text like code snippets."
3505 :group 'org-faces
3506 :version "22.1")
3508 (defface org-agenda-structure ;; font-lock-function-name-face
3509 (org-compatible-face
3510 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3511 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3512 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3513 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3514 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3515 (t (:bold t))))
3516 "Face used in agenda for captions and dates."
3517 :group 'org-faces)
3519 (defface org-scheduled-today
3520 (org-compatible-face
3521 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3522 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3523 (((class color) (min-colors 8)) (:foreground "green"))
3524 (t (:bold t :italic t))))
3525 "Face for items scheduled for a certain day."
3526 :group 'org-faces)
3528 (defface org-scheduled-previously
3529 (org-compatible-face
3530 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3531 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3532 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3533 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3534 (t (:bold t))))
3535 "Face for items scheduled previously, and not yet done."
3536 :group 'org-faces)
3538 (defface org-upcoming-deadline
3539 (org-compatible-face
3540 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3541 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3542 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3543 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3544 (t (:bold t))))
3545 "Face for items scheduled previously, and not yet done."
3546 :group 'org-faces)
3548 (defcustom org-agenda-deadline-faces
3549 '((1.0 . org-warning)
3550 (0.5 . org-upcoming-deadline)
3551 (0.0 . default))
3552 "Faces for showing deadlines in the agenda.
3553 This is a list of cons cells. The cdr of each cess is a face to be used,
3554 and it can also just be a like like '(:foreground \"yellow\").
3555 Each car is a fraction of the head-warning time that must have passed for
3556 this the face in the cdr to be used for display. The numbers must be
3557 given in descending order. The head-warning time is normally taken
3558 from `org-deadline-warning-days', but can also be specified in the deadline
3559 timestamp itself, like this:
3561 DEADLINE: <2007-08-13 Mon -8d>
3563 You may use d for days, w for weeks, m for months and y for years. Months
3564 and years will only be treated in an approximate fashion (30.4 days for a
3565 month and 365.24 days for a year)."
3566 :group 'org-faces
3567 :group 'org-agenda-daily/weekly
3568 :type '(repeat
3569 (cons
3570 (number :tag "Fraction of head-warning time passed")
3571 (sexp :tag "Face"))))
3573 (defface org-time-grid ;; font-lock-variable-name-face
3574 (org-compatible-face
3575 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3576 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3577 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3578 "Face used for time grids."
3579 :group 'org-faces)
3581 (defconst org-level-faces
3582 '(org-level-1 org-level-2 org-level-3 org-level-4
3583 org-level-5 org-level-6 org-level-7 org-level-8
3586 (defcustom org-n-level-faces (length org-level-faces)
3587 "The number different faces to be used for headlines.
3588 Org-mode defines 8 different headline faces, so this can be at most 8.
3589 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3590 :type 'number
3591 :group 'org-faces)
3593 ;;; Variables for pre-computed regular expressions, all buffer local
3595 (defvar org-drawer-regexp nil
3596 "Matches first line of a hidden block.")
3597 (make-variable-buffer-local 'org-drawer-regexp)
3598 (defvar org-todo-regexp nil
3599 "Matches any of the TODO state keywords.")
3600 (make-variable-buffer-local 'org-todo-regexp)
3601 (defvar org-not-done-regexp nil
3602 "Matches any of the TODO state keywords except the last one.")
3603 (make-variable-buffer-local 'org-not-done-regexp)
3604 (defvar org-todo-line-regexp nil
3605 "Matches a headline and puts TODO state into group 2 if present.")
3606 (make-variable-buffer-local 'org-todo-line-regexp)
3607 (defvar org-todo-line-tags-regexp nil
3608 "Matches a headline and puts TODO state into group 2 if present.
3609 Also put tags into group 4 if tags are present.")
3610 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3611 (defvar org-nl-done-regexp nil
3612 "Matches newline followed by a headline with the DONE keyword.")
3613 (make-variable-buffer-local 'org-nl-done-regexp)
3614 (defvar org-looking-at-done-regexp nil
3615 "Matches the DONE keyword a point.")
3616 (make-variable-buffer-local 'org-looking-at-done-regexp)
3617 (defvar org-ds-keyword-length 12
3618 "Maximum length of the Deadline and SCHEDULED keywords.")
3619 (make-variable-buffer-local 'org-ds-keyword-length)
3620 (defvar org-deadline-regexp nil
3621 "Matches the DEADLINE keyword.")
3622 (make-variable-buffer-local 'org-deadline-regexp)
3623 (defvar org-deadline-time-regexp nil
3624 "Matches the DEADLINE keyword together with a time stamp.")
3625 (make-variable-buffer-local 'org-deadline-time-regexp)
3626 (defvar org-deadline-line-regexp nil
3627 "Matches the DEADLINE keyword and the rest of the line.")
3628 (make-variable-buffer-local 'org-deadline-line-regexp)
3629 (defvar org-scheduled-regexp nil
3630 "Matches the SCHEDULED keyword.")
3631 (make-variable-buffer-local 'org-scheduled-regexp)
3632 (defvar org-scheduled-time-regexp nil
3633 "Matches the SCHEDULED keyword together with a time stamp.")
3634 (make-variable-buffer-local 'org-scheduled-time-regexp)
3635 (defvar org-closed-time-regexp nil
3636 "Matches the CLOSED keyword together with a time stamp.")
3637 (make-variable-buffer-local 'org-closed-time-regexp)
3639 (defvar org-keyword-time-regexp nil
3640 "Matches any of the 4 keywords, together with the time stamp.")
3641 (make-variable-buffer-local 'org-keyword-time-regexp)
3642 (defvar org-keyword-time-not-clock-regexp nil
3643 "Matches any of the 3 keywords, together with the time stamp.")
3644 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3645 (defvar org-maybe-keyword-time-regexp nil
3646 "Matches a timestamp, possibly preceeded by a keyword.")
3647 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3648 (defvar org-planning-or-clock-line-re nil
3649 "Matches a line with planning or clock info.")
3650 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3652 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3653 rear-nonsticky t mouse-map t fontified t)
3654 "Properties to remove when a string without properties is wanted.")
3656 (defsubst org-match-string-no-properties (num &optional string)
3657 (if (featurep 'xemacs)
3658 (let ((s (match-string num string)))
3659 (remove-text-properties 0 (length s) org-rm-props s)
3661 (match-string-no-properties num string)))
3663 (defsubst org-no-properties (s)
3664 (if (fboundp 'set-text-properties)
3665 (set-text-properties 0 (length s) nil s)
3666 (remove-text-properties 0 (length s) org-rm-props s))
3669 (defsubst org-get-alist-option (option key)
3670 (cond ((eq key t) t)
3671 ((eq option t) t)
3672 ((assoc key option) (cdr (assoc key option)))
3673 (t (cdr (assq 'default option)))))
3675 (defsubst org-inhibit-invisibility ()
3676 "Modified `buffer-invisibility-spec' for Emacs 21.
3677 Some ops with invisible text do not work correctly on Emacs 21. For these
3678 we turn off invisibility temporarily. Use this in a `let' form."
3679 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3681 (defsubst org-set-local (var value)
3682 "Make VAR local in current buffer and set it to VALUE."
3683 (set (make-variable-buffer-local var) value))
3685 (defsubst org-mode-p ()
3686 "Check if the current buffer is in Org-mode."
3687 (eq major-mode 'org-mode))
3689 (defsubst org-last (list)
3690 "Return the last element of LIST."
3691 (car (last list)))
3693 (defun org-let (list &rest body)
3694 (eval (cons 'let (cons list body))))
3695 (put 'org-let 'lisp-indent-function 1)
3697 (defun org-let2 (list1 list2 &rest body)
3698 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3699 (put 'org-let2 'lisp-indent-function 2)
3700 (defconst org-startup-options
3701 '(("fold" org-startup-folded t)
3702 ("overview" org-startup-folded t)
3703 ("nofold" org-startup-folded nil)
3704 ("showall" org-startup-folded nil)
3705 ("content" org-startup-folded content)
3706 ("hidestars" org-hide-leading-stars t)
3707 ("showstars" org-hide-leading-stars nil)
3708 ("odd" org-odd-levels-only t)
3709 ("oddeven" org-odd-levels-only nil)
3710 ("align" org-startup-align-all-tables t)
3711 ("noalign" org-startup-align-all-tables nil)
3712 ("customtime" org-display-custom-times t)
3713 ("logging" org-log-done t)
3714 ("logdone" org-log-done t)
3715 ("nologging" org-log-done nil)
3716 ("lognotedone" org-log-done done push)
3717 ("lognotestate" org-log-done state push)
3718 ("lognoteclock-out" org-log-done clock-out push)
3719 ("logrepeat" org-log-repeat t)
3720 ("nologrepeat" org-log-repeat nil)
3721 ("constcgs" constants-unit-system cgs)
3722 ("constSI" constants-unit-system SI))
3723 "Variable associated with STARTUP options for org-mode.
3724 Each element is a list of three items: The startup options as written
3725 in the #+STARTUP line, the corresponding variable, and the value to
3726 set this variable to if the option is found. An optional forth element PUSH
3727 means to push this value onto the list in the variable.")
3729 (defun org-set-regexps-and-options ()
3730 "Precompute regular expressions for current buffer."
3731 (when (org-mode-p)
3732 (org-set-local 'org-todo-kwd-alist nil)
3733 (org-set-local 'org-todo-keywords-1 nil)
3734 (org-set-local 'org-todo-tag-alist nil)
3735 (org-set-local 'org-done-keywords nil)
3736 (org-set-local 'org-todo-heads nil)
3737 (org-set-local 'org-todo-sets nil)
3738 (let ((re (org-make-options-regexp
3739 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "COLUMNS"
3740 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3741 "CONSTANTS" "PROPERTY")))
3742 (splitre "[ \t]+")
3743 kwds kws0 kwsa key value cat arch tags const links hw dws
3744 tail sep kws1 prio props)
3745 (save-excursion
3746 (save-restriction
3747 (widen)
3748 (goto-char (point-min))
3749 (while (re-search-forward re nil t)
3750 (setq key (match-string 1) value (org-match-string-no-properties 2))
3751 (cond
3752 ((equal key "CATEGORY")
3753 (if (string-match "[ \t]+$" value)
3754 (setq value (replace-match "" t t value)))
3755 (setq cat (intern value)))
3756 ((equal key "SEQ_TODO")
3757 (push (cons 'sequence (org-split-string value splitre)) kwds))
3758 ((equal key "TYP_TODO")
3759 (push (cons 'type (org-split-string value splitre)) kwds))
3760 ((equal key "TAGS")
3761 (setq tags (append tags (org-split-string value splitre))))
3762 ((equal key "COLUMNS")
3763 (org-set-local 'org-columns-default-format value))
3764 ((equal key "LINK")
3765 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3766 (push (cons (match-string 1 value)
3767 (org-trim (match-string 2 value)))
3768 links)))
3769 ((equal key "PRIORITIES")
3770 (setq prio (org-split-string value " +")))
3771 ((equal key "PROPERTY")
3772 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3773 (push (cons (match-string 1 value) (match-string 2 value))
3774 props)))
3775 ((equal key "CONSTANTS")
3776 (setq const (append const (org-split-string value splitre))))
3777 ((equal key "STARTUP")
3778 (let ((opts (org-split-string value splitre))
3779 l var val)
3780 (while (setq l (pop opts))
3781 (when (setq l (assoc l org-startup-options))
3782 (setq var (nth 1 l) val (nth 2 l))
3783 (if (not (nth 3 l))
3784 (set (make-local-variable var) val)
3785 (if (not (listp (symbol-value var)))
3786 (set (make-local-variable var) nil))
3787 (set (make-local-variable var) (symbol-value var))
3788 (add-to-list var val))))))
3789 ((equal key "ARCHIVE")
3790 (string-match " *$" value)
3791 (setq arch (replace-match "" t t value))
3792 (remove-text-properties 0 (length arch)
3793 '(face t fontified t) arch)))
3795 (and cat (org-set-local 'org-category cat))
3796 (when prio
3797 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3798 (setq prio (mapcar 'string-to-char prio))
3799 (org-set-local 'org-highest-priority (nth 0 prio))
3800 (org-set-local 'org-lowest-priority (nth 1 prio))
3801 (org-set-local 'org-default-priority (nth 2 prio)))
3802 (and props (org-set-local 'org-local-properties (nreverse props)))
3803 (and arch (org-set-local 'org-archive-location arch))
3804 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3805 ;; Process the TODO keywords
3806 (unless kwds
3807 ;; Use the global values as if they had been given locally.
3808 (setq kwds (default-value 'org-todo-keywords))
3809 (if (stringp (car kwds))
3810 (setq kwds (list (cons org-todo-interpretation
3811 (default-value 'org-todo-keywords)))))
3812 (setq kwds (reverse kwds)))
3813 (setq kwds (nreverse kwds))
3814 (let (inter kws)
3815 (while (setq kws (pop kwds))
3816 (setq inter (pop kws) sep (member "|" kws)
3817 kws0 (delete "|" (copy-sequence kws))
3818 kwsa nil
3819 kws1 (mapcar (lambda (x)
3820 (if (string-match "\\(.*\\)(\\(.\\))" x)
3821 (progn
3822 (push (cons (match-string 1 x)
3823 (string-to-char
3824 (match-string 2 x))) kwsa)
3825 (match-string 1 x))
3827 kws0)
3828 kwsa (if kwsa (append '((:startgroup)) kwsa '((:endgroup))))
3829 hw (car kws1)
3830 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3831 tail (list inter hw (car dws) (org-last dws)))
3832 (add-to-list 'org-todo-heads hw 'append)
3833 (push kws1 org-todo-sets)
3834 (setq org-done-keywords (append org-done-keywords dws nil))
3835 (setq org-todo-tag-alist (append org-todo-tag-alist kwsa))
3836 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3837 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3838 (setq org-todo-sets (nreverse org-todo-sets)
3839 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3840 ;; Process the constants
3841 (when const
3842 (let (e cst)
3843 (while (setq e (pop const))
3844 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3845 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3846 (setq org-table-formula-constants-local cst)))
3848 ;; Process the tags.
3849 (when tags
3850 (let (e tgs)
3851 (while (setq e (pop tags))
3852 (cond
3853 ((equal e "{") (push '(:startgroup) tgs))
3854 ((equal e "}") (push '(:endgroup) tgs))
3855 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3856 (push (cons (match-string 1 e)
3857 (string-to-char (match-string 2 e)))
3858 tgs))
3859 (t (push (list e) tgs))))
3860 (org-set-local 'org-tag-alist nil)
3861 (while (setq e (pop tgs))
3862 (or (and (stringp (car e))
3863 (assoc (car e) org-tag-alist))
3864 (push e org-tag-alist))))))
3866 ;; Compute the regular expressions and other local variables
3867 (if (not org-done-keywords)
3868 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3869 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3870 (length org-scheduled-string)))
3871 org-drawer-regexp
3872 (concat "^[ \t]*:\\("
3873 (mapconcat 'regexp-quote org-drawers "\\|")
3874 "\\):[ \t]*$")
3875 org-not-done-keywords
3876 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3877 org-todo-regexp
3878 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3879 "\\|") "\\)\\>")
3880 org-not-done-regexp
3881 (concat "\\<\\("
3882 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3883 "\\)\\>")
3884 org-todo-line-regexp
3885 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3886 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3887 "\\)\\>\\)?[ \t]*\\(.*\\)")
3888 org-nl-done-regexp
3889 (concat "\n\\*+[ \t]+"
3890 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3891 "\\)" "\\>")
3892 org-todo-line-tags-regexp
3893 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3894 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3895 (org-re
3896 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3897 org-looking-at-done-regexp
3898 (concat "^" "\\(?:"
3899 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3900 "\\>")
3901 org-deadline-regexp (concat "\\<" org-deadline-string)
3902 org-deadline-time-regexp
3903 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3904 org-deadline-line-regexp
3905 (concat "\\<\\(" org-deadline-string "\\).*")
3906 org-scheduled-regexp
3907 (concat "\\<" org-scheduled-string)
3908 org-scheduled-time-regexp
3909 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3910 org-closed-time-regexp
3911 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3912 org-keyword-time-regexp
3913 (concat "\\<\\(" org-scheduled-string
3914 "\\|" org-deadline-string
3915 "\\|" org-closed-string
3916 "\\|" org-clock-string "\\)"
3917 " *[[<]\\([^]>]+\\)[]>]")
3918 org-keyword-time-not-clock-regexp
3919 (concat "\\<\\(" org-scheduled-string
3920 "\\|" org-deadline-string
3921 "\\|" org-closed-string
3922 "\\)"
3923 " *[[<]\\([^]>]+\\)[]>]")
3924 org-maybe-keyword-time-regexp
3925 (concat "\\(\\<\\(" org-scheduled-string
3926 "\\|" org-deadline-string
3927 "\\|" org-closed-string
3928 "\\|" org-clock-string "\\)\\)?"
3929 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3930 org-planning-or-clock-line-re
3931 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3932 "\\|" org-deadline-string
3933 "\\|" org-closed-string "\\|" org-clock-string
3934 "\\)\\>\\)")
3937 (org-set-font-lock-defaults)))
3939 (defun org-remove-keyword-keys (list)
3940 (mapcar (lambda (x)
3941 (if (string-match "(.)$" x)
3942 (substring x 0 (match-beginning 0))
3944 list))
3946 ;;; Some variables ujsed in various places
3948 (defvar org-window-configuration nil
3949 "Used in various places to store a window configuration.")
3950 (defvar org-finish-function nil
3951 "Function to be called when `C-c C-c' is used.
3952 This is for getting out of special buffers like remember.")
3954 ;;; Foreign variables, to inform the compiler
3956 ;; XEmacs only
3957 (defvar outline-mode-menu-heading)
3958 (defvar outline-mode-menu-show)
3959 (defvar outline-mode-menu-hide)
3960 (defvar zmacs-regions) ; XEmacs regions
3961 ;; Emacs only
3962 (defvar mark-active)
3964 ;; Packages that org-mode interacts with
3965 (defvar calc-embedded-close-formula)
3966 (defvar calc-embedded-open-formula)
3967 (defvar font-lock-unfontify-region-function)
3968 (defvar org-goto-start-pos)
3969 (defvar vm-message-pointer)
3970 (defvar vm-folder-directory)
3971 (defvar wl-summary-buffer-elmo-folder)
3972 (defvar wl-summary-buffer-folder-name)
3973 (defvar gnus-other-frame-object)
3974 (defvar gnus-group-name)
3975 (defvar gnus-article-current)
3976 (defvar w3m-current-url)
3977 (defvar w3m-current-title)
3978 (defvar mh-progs)
3979 (defvar mh-current-folder)
3980 (defvar mh-show-folder-buffer)
3981 (defvar mh-index-folder)
3982 (defvar mh-searcher)
3983 (defvar calendar-mode-map)
3984 (defvar Info-current-file)
3985 (defvar Info-current-node)
3986 (defvar texmathp-why)
3987 (defvar remember-save-after-remembering)
3988 (defvar remember-data-file)
3989 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3990 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3991 (defvar org-latex-regexps)
3992 (defvar constants-unit-system)
3994 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3996 ;; FIXME: Occasionally check by commenting these, to make sure
3997 ;; no other functions uses these, forgetting to let-bind them.
3998 (defvar entry)
3999 (defvar state)
4000 (defvar last-state)
4001 (defvar date)
4002 (defvar description)
4005 ;; Defined somewhere in this file, but used before definition.
4006 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4007 (defvar org-agenda-buffer-name)
4008 (defvar org-agenda-undo-list)
4009 (defvar org-agenda-pending-undo-list)
4010 (defvar org-agenda-overriding-header)
4011 (defvar orgtbl-mode)
4012 (defvar org-html-entities)
4013 (defvar org-struct-menu)
4014 (defvar org-org-menu)
4015 (defvar org-tbl-menu)
4016 (defvar org-agenda-keymap)
4017 (defvar org-category-table)
4019 ;;;; Emacs/XEmacs compatibility
4021 ;; Overlay compatibility functions
4022 (defun org-make-overlay (beg end &optional buffer)
4023 (if (featurep 'xemacs)
4024 (make-extent beg end buffer)
4025 (make-overlay beg end buffer)))
4026 (defun org-delete-overlay (ovl)
4027 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4028 (defun org-detach-overlay (ovl)
4029 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4030 (defun org-move-overlay (ovl beg end &optional buffer)
4031 (if (featurep 'xemacs)
4032 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4033 (move-overlay ovl beg end buffer)))
4034 (defun org-overlay-put (ovl prop value)
4035 (if (featurep 'xemacs)
4036 (set-extent-property ovl prop value)
4037 (overlay-put ovl prop value)))
4038 (defun org-overlay-display (ovl text &optional face evap)
4039 "Make overlay OVL display TEXT with face FACE."
4040 (if (featurep 'xemacs)
4041 (let ((gl (make-glyph text)))
4042 (and face (set-glyph-face gl face))
4043 (set-extent-property ovl 'invisible t)
4044 (set-extent-property ovl 'end-glyph gl))
4045 (overlay-put ovl 'display text)
4046 (if face (overlay-put ovl 'face face))
4047 (if evap (overlay-put ovl 'evaporate t))))
4048 (defun org-overlay-before-string (ovl text &optional face evap)
4049 "Make overlay OVL display TEXT with face FACE."
4050 (if (featurep 'xemacs)
4051 (let ((gl (make-glyph text)))
4052 (and face (set-glyph-face gl face))
4053 (set-extent-property ovl 'begin-glyph gl))
4054 (if face (org-add-props text nil 'face face))
4055 (overlay-put ovl 'before-string text)
4056 (if evap (overlay-put ovl 'evaporate t))))
4057 (defun org-overlay-get (ovl prop)
4058 (if (featurep 'xemacs)
4059 (extent-property ovl prop)
4060 (overlay-get ovl prop)))
4061 (defun org-overlays-at (pos)
4062 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4063 ;; FIXME: this is currently not used
4064 (defun org-overlays-in (&optional start end)
4065 (if (featurep 'xemacs)
4066 (extent-list nil start end)
4067 (overlays-in start end)))
4068 (defun org-overlay-start (o)
4069 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4070 (defun org-overlay-end (o)
4071 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4072 ;; FIXME: this is currently not used
4073 (defun org-find-overlays (prop &optional pos delete)
4074 "Find all overlays specifying PROP at POS or point.
4075 If DELETE is non-nil, delete all those overlays."
4076 (let ((overlays (org-overlays-at (or pos (point))))
4077 ov found)
4078 (while (setq ov (pop overlays))
4079 (if (org-overlay-get ov prop)
4080 (if delete (org-delete-overlay ov) (push ov found))))
4081 found))
4083 ;; Region compatibility
4085 (defun org-add-hook (hook function &optional append local)
4086 "Add-hook, compatible with both Emacsen."
4087 (if (and local (featurep 'xemacs))
4088 (add-local-hook hook function append)
4089 (add-hook hook function append local)))
4091 (defvar org-ignore-region nil
4092 "To temporarily disable the active region.")
4094 (defun org-region-active-p ()
4095 "Is `transient-mark-mode' on and the region active?
4096 Works on both Emacs and XEmacs."
4097 (if org-ignore-region
4099 (if (featurep 'xemacs)
4100 (and zmacs-regions (region-active-p))
4101 (and transient-mark-mode mark-active))))
4103 ;; Invisibility compatibility
4105 (defun org-add-to-invisibility-spec (arg)
4106 "Add elements to `buffer-invisibility-spec'.
4107 See documentation for `buffer-invisibility-spec' for the kind of elements
4108 that can be added."
4109 (cond
4110 ((fboundp 'add-to-invisibility-spec)
4111 (add-to-invisibility-spec arg))
4112 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4113 (setq buffer-invisibility-spec (list arg)))
4115 (setq buffer-invisibility-spec
4116 (cons arg buffer-invisibility-spec)))))
4118 (defun org-remove-from-invisibility-spec (arg)
4119 "Remove elements from `buffer-invisibility-spec'."
4120 (if (fboundp 'remove-from-invisibility-spec)
4121 (remove-from-invisibility-spec arg)
4122 (if (consp buffer-invisibility-spec)
4123 (setq buffer-invisibility-spec
4124 (delete arg buffer-invisibility-spec)))))
4126 ;; FIXME: this is currently not used
4127 (defun org-in-invisibility-spec-p (arg)
4128 "Is ARG a member of `buffer-invisibility-spec'?"
4129 (if (consp buffer-invisibility-spec)
4130 (member arg buffer-invisibility-spec)
4131 nil))
4133 ;;;; Define the Org-mode
4135 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4136 (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."))
4139 ;; We use a before-change function to check if a table might need
4140 ;; an update.
4141 (defvar org-table-may-need-update t
4142 "Indicates that a table might need an update.
4143 This variable is set by `org-before-change-function'.
4144 `org-table-align' sets it back to nil.")
4145 (defvar org-mode-map)
4146 (defvar org-mode-hook nil)
4147 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4148 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4149 (defvar org-table-buffer-is-an nil)
4152 ;;;###autoload
4153 (define-derived-mode org-mode outline-mode "Org"
4154 "Outline-based notes management and organizer, alias
4155 \"Carsten's outline-mode for keeping track of everything.\"
4157 Org-mode develops organizational tasks around a NOTES file which
4158 contains information about projects as plain text. Org-mode is
4159 implemented on top of outline-mode, which is ideal to keep the content
4160 of large files well structured. It supports ToDo items, deadlines and
4161 time stamps, which magically appear in the diary listing of the Emacs
4162 calendar. Tables are easily created with a built-in table editor.
4163 Plain text URL-like links connect to websites, emails (VM), Usenet
4164 messages (Gnus), BBDB entries, and any files related to the project.
4165 For printing and sharing of notes, an Org-mode file (or a part of it)
4166 can be exported as a structured ASCII or HTML file.
4168 The following commands are available:
4170 \\{org-mode-map}"
4172 ;; Get rid of Outline menus, they are not needed
4173 ;; Need to do this here because define-derived-mode sets up
4174 ;; the keymap so late. Still, it is a waste to call this each time
4175 ;; we switch another buffer into org-mode.
4176 (if (featurep 'xemacs)
4177 (when (boundp 'outline-mode-menu-heading)
4178 ;; Assume this is Greg's port, it used easymenu
4179 (easy-menu-remove outline-mode-menu-heading)
4180 (easy-menu-remove outline-mode-menu-show)
4181 (easy-menu-remove outline-mode-menu-hide))
4182 (define-key org-mode-map [menu-bar headings] 'undefined)
4183 (define-key org-mode-map [menu-bar hide] 'undefined)
4184 (define-key org-mode-map [menu-bar show] 'undefined))
4186 (easy-menu-add org-org-menu)
4187 (easy-menu-add org-tbl-menu)
4188 (org-install-agenda-files-menu)
4189 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4190 (org-add-to-invisibility-spec '(org-cwidth))
4191 (when (featurep 'xemacs)
4192 (org-set-local 'line-move-ignore-invisible t))
4193 (org-set-local 'outline-regexp "\\*+ ")
4194 (setq outline-level 'org-outline-level)
4195 (when (and org-ellipsis
4196 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4197 (fboundp 'make-glyph-code))
4198 (unless org-display-table
4199 (setq org-display-table (make-display-table)))
4200 (set-display-table-slot
4201 org-display-table 4
4202 (vconcat (mapcar
4203 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4204 org-ellipsis)))
4205 (if (stringp org-ellipsis) org-ellipsis "..."))))
4206 (setq buffer-display-table org-display-table))
4207 (org-set-regexps-and-options)
4208 ;; Calc embedded
4209 (org-set-local 'calc-embedded-open-mode "# ")
4210 (modify-syntax-entry ?# "<")
4211 (modify-syntax-entry ?@ "w")
4212 (if org-startup-truncated (setq truncate-lines t))
4213 (org-set-local 'font-lock-unfontify-region-function
4214 'org-unfontify-region)
4215 ;; Activate before-change-function
4216 (org-set-local 'org-table-may-need-update t)
4217 (org-add-hook 'before-change-functions 'org-before-change-function nil
4218 'local)
4219 ;; Check for running clock before killing a buffer
4220 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4221 ;; Paragraphs and auto-filling
4222 (org-set-autofill-regexps)
4223 (setq indent-line-function 'org-indent-line-function)
4224 (org-update-radio-target-regexp)
4226 ;; Comment characters
4227 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4228 (org-set-local 'comment-padding " ")
4230 ;; Make isearch reveal context
4231 (if (or (featurep 'xemacs)
4232 (not (boundp 'outline-isearch-open-invisible-function)))
4233 ;; Emacs 21 and XEmacs make use of the hook
4234 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4235 ;; Emacs 22 deals with this through a special variable
4236 (org-set-local 'outline-isearch-open-invisible-function
4237 (lambda (&rest ignore) (org-show-context 'isearch))))
4239 ;; If empty file that did not turn on org-mode automatically, make it to.
4240 (if (and org-insert-mode-line-in-empty-file
4241 (interactive-p)
4242 (= (point-min) (point-max)))
4243 (insert "# -*- mode: org -*-\n\n"))
4245 (unless org-inhibit-startup
4246 (when org-startup-align-all-tables
4247 (let ((bmp (buffer-modified-p)))
4248 (org-table-map-tables 'org-table-align)
4249 (set-buffer-modified-p bmp)))
4250 (org-cycle-hide-drawers 'all)
4251 (cond
4252 ((eq org-startup-folded t)
4253 (org-cycle '(4)))
4254 ((eq org-startup-folded 'content)
4255 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4256 (org-cycle '(4)) (org-cycle '(4)))))))
4258 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4260 (defsubst org-call-with-arg (command arg)
4261 "Call COMMAND interactively, but pretend prefix are was ARG."
4262 (let ((current-prefix-arg arg)) (call-interactively command)))
4264 (defsubst org-current-line (&optional pos)
4265 (save-excursion
4266 (and pos (goto-char pos))
4267 ;; works also in narrowed buffer, because we start at 1, not point-min
4268 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4270 (defun org-current-time ()
4271 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4272 (if (> org-time-stamp-rounding-minutes 0)
4273 (let ((r org-time-stamp-rounding-minutes)
4274 (time (decode-time)))
4275 (apply 'encode-time
4276 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4277 (nthcdr 2 time))))
4278 (current-time)))
4280 (defun org-add-props (string plist &rest props)
4281 "Add text properties to entire string, from beginning to end.
4282 PLIST may be a list of properties, PROPS are individual properties and values
4283 that will be added to PLIST. Returns the string that was modified."
4284 (add-text-properties
4285 0 (length string) (if props (append plist props) plist) string)
4286 string)
4287 (put 'org-add-props 'lisp-indent-function 2)
4290 ;;;; Font-Lock stuff, including the activators
4292 (defvar org-mouse-map (make-sparse-keymap))
4293 (org-defkey org-mouse-map
4294 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4295 (org-defkey org-mouse-map
4296 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4297 (when org-mouse-1-follows-link
4298 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4299 (when org-tab-follows-link
4300 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4301 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4302 (when org-return-follows-link
4303 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4304 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4306 (require 'font-lock)
4308 (defconst org-non-link-chars "]\t\n\r<>")
4309 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4310 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4311 (defvar org-link-re-with-space nil
4312 "Matches a link with spaces, optional angular brackets around it.")
4313 (defvar org-link-re-with-space2 nil
4314 "Matches a link with spaces, optional angular brackets around it.")
4315 (defvar org-angle-link-re nil
4316 "Matches link with angular brackets, spaces are allowed.")
4317 (defvar org-plain-link-re nil
4318 "Matches plain link, without spaces.")
4319 (defvar org-bracket-link-regexp nil
4320 "Matches a link in double brackets.")
4321 (defvar org-bracket-link-analytic-regexp nil
4322 "Regular expression used to analyze links.
4323 Here is what the match groups contain after a match:
4324 1: http:
4325 2: http
4326 3: path
4327 4: [desc]
4328 5: desc")
4329 (defvar org-any-link-re nil
4330 "Regular expression matching any link.")
4332 (defun org-make-link-regexps ()
4333 "Update the link regular expressions.
4334 This should be called after the variable `org-link-types' has changed."
4335 (setq org-link-re-with-space
4336 (concat
4337 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4338 "\\([^" org-non-link-chars " ]"
4339 "[^" org-non-link-chars "]*"
4340 "[^" org-non-link-chars " ]\\)>?")
4341 org-link-re-with-space2
4342 (concat
4343 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4344 "\\([^" org-non-link-chars " ]"
4345 "[^]\t\n\r]*"
4346 "[^" org-non-link-chars " ]\\)>?")
4347 org-angle-link-re
4348 (concat
4349 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4350 "\\([^" org-non-link-chars " ]"
4351 "[^" org-non-link-chars "]*"
4352 "\\)>")
4353 org-plain-link-re
4354 (concat
4355 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4356 "\\([^]\t\n\r<>,;() ]+\\)")
4357 org-bracket-link-regexp
4358 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4359 org-bracket-link-analytic-regexp
4360 (concat
4361 "\\[\\["
4362 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4363 "\\([^]]+\\)"
4364 "\\]"
4365 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4366 "\\]")
4367 org-any-link-re
4368 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4369 org-angle-link-re "\\)\\|\\("
4370 org-plain-link-re "\\)")))
4372 (org-make-link-regexps)
4374 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4375 "Regular expression for fast time stamp matching.")
4376 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4377 "Regular expression for fast time stamp matching.")
4378 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4379 "Regular expression matching time strings for analysis.
4380 This one does not require the space after the date.")
4381 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4382 "Regular expression matching time strings for analysis.")
4383 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4384 "Regular expression matching time stamps, with groups.")
4385 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4386 "Regular expression matching time stamps (also [..]), with groups.")
4387 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4388 "Regular expression matching a time stamp range.")
4389 (defconst org-tr-regexp-both
4390 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4391 "Regular expression matching a time stamp range.")
4392 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4393 org-ts-regexp "\\)?")
4394 "Regular expression matching a time stamp or time stamp range.")
4395 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4396 org-ts-regexp-both "\\)?")
4397 "Regular expression matching a time stamp or time stamp range.
4398 The time stamps may be either active or inactive.")
4400 (defvar org-emph-face nil)
4402 (defun org-do-emphasis-faces (limit)
4403 "Run through the buffer and add overlays to links."
4404 (let (rtn)
4405 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4406 (if (not (= (char-after (match-beginning 3))
4407 (char-after (match-beginning 4))))
4408 (progn
4409 (setq rtn t)
4410 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4411 'face
4412 (nth 1 (assoc (match-string 3)
4413 org-emphasis-alist)))
4414 (add-text-properties (match-beginning 2) (match-end 2)
4415 '(font-lock-multiline t))
4416 (backward-char 1))))
4417 rtn))
4419 (defun org-emphasize (&optional char)
4420 "Insert or change an emphasis, i.e. a font like bold or italic.
4421 If there is an active region, change that region to a new emphasis.
4422 If there is no region, just insert the marker characters and position
4423 the cursor between them.
4424 CHAR should be either the marker character, or the first character of the
4425 HTML tag associated with that emphasis. If CHAR is a space, the means
4426 to remove the emphasis of the selected region.
4427 If char is not given (for example in an interactive call) it
4428 will be prompted for."
4429 (interactive)
4430 (let ((eal org-emphasis-alist) e det
4431 (erc org-emphasis-regexp-components)
4432 (prompt "")
4433 (string "") beg end move tag c s)
4434 (if (org-region-active-p)
4435 (setq beg (region-beginning) end (region-end)
4436 string (buffer-substring beg end))
4437 (setq move t))
4439 (while (setq e (pop eal))
4440 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4441 c (aref tag 0))
4442 (push (cons c (string-to-char (car e))) det)
4443 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4444 (substring tag 1)))))
4445 (unless char
4446 (message "%s" (concat "Emphasis marker or tag:" prompt))
4447 (setq char (read-char-exclusive)))
4448 (setq char (or (cdr (assoc char det)) char))
4449 (if (equal char ?\ )
4450 (setq s "" move nil)
4451 (unless (assoc (char-to-string char) org-emphasis-alist)
4452 (error "No such emphasis marker: \"%c\"" char))
4453 (setq s (char-to-string char)))
4454 (while (and (> (length string) 1)
4455 (equal (substring string 0 1) (substring string -1))
4456 (assoc (substring string 0 1) org-emphasis-alist))
4457 (setq string (substring string 1 -1)))
4458 (setq string (concat s string s))
4459 (if beg (delete-region beg end))
4460 (unless (or (bolp)
4461 (string-match (concat "[" (nth 0 erc) "\n]")
4462 (char-to-string (char-before (point)))))
4463 (insert " "))
4464 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4465 (char-to-string (char-after (point))))
4466 (insert " ") (backward-char 1))
4467 (insert string)
4468 (and move (backward-char 1))))
4470 (defun org-activate-plain-links (limit)
4471 "Run through the buffer and add overlays to links."
4472 (catch 'exit
4473 (let (f)
4474 (while (re-search-forward org-plain-link-re limit t)
4475 (setq f (get-text-property (match-beginning 0) 'face))
4476 (if (or (eq f 'org-tag)
4477 (and (listp f) (memq 'org-tag f)))
4479 (add-text-properties (match-beginning 0) (match-end 0)
4480 (list 'mouse-face 'highlight
4481 'rear-nonsticky t
4482 'keymap org-mouse-map
4484 (throw 'exit t))))))
4486 (defun org-activate-angle-links (limit)
4487 "Run through the buffer and add overlays to links."
4488 (if (re-search-forward org-angle-link-re limit t)
4489 (progn
4490 (add-text-properties (match-beginning 0) (match-end 0)
4491 (list 'mouse-face 'highlight
4492 'rear-nonsticky t
4493 'keymap org-mouse-map
4495 t)))
4497 (defmacro org-maybe-intangible (props)
4498 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4499 In emacs 21, invisible text is not avoided by the command loop, so the
4500 intangible property is needed to make sure point skips this text.
4501 In Emacs 22, this is not necessary. The intangible text property has
4502 led to problems with flyspell. These problems are fixed in flyspell.el,
4503 but we still avoid setting the property in Emacs 22 and later.
4504 We use a macro so that the test can happen at compilation time."
4505 (if (< emacs-major-version 22)
4506 `(append '(intangible t) ,props)
4507 props))
4509 (defun org-activate-bracket-links (limit)
4510 "Run through the buffer and add overlays to bracketed links."
4511 (if (re-search-forward org-bracket-link-regexp limit t)
4512 (let* ((help (concat "LINK: "
4513 (org-match-string-no-properties 1)))
4514 ;; FIXME: above we should remove the escapes.
4515 ;; but that requires another match, protecting match data,
4516 ;; a lot of overhead for font-lock.
4517 (ip (org-maybe-intangible
4518 (list 'invisible 'org-link 'rear-nonsticky t
4519 'keymap org-mouse-map 'mouse-face 'highlight
4520 'help-echo help)))
4521 (vp (list 'rear-nonsticky t
4522 'keymap org-mouse-map 'mouse-face 'highlight
4523 'help-echo help)))
4524 ;; We need to remove the invisible property here. Table narrowing
4525 ;; may have made some of this invisible.
4526 (remove-text-properties (match-beginning 0) (match-end 0)
4527 '(invisible nil))
4528 (if (match-end 3)
4529 (progn
4530 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4531 (add-text-properties (match-beginning 3) (match-end 3) vp)
4532 (add-text-properties (match-end 3) (match-end 0) ip))
4533 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4534 (add-text-properties (match-beginning 1) (match-end 1) vp)
4535 (add-text-properties (match-end 1) (match-end 0) ip))
4536 t)))
4538 (defun org-activate-dates (limit)
4539 "Run through the buffer and add overlays to dates."
4540 (if (re-search-forward org-tsr-regexp-both limit t)
4541 (progn
4542 (add-text-properties (match-beginning 0) (match-end 0)
4543 (list 'mouse-face 'highlight
4544 'rear-nonsticky t
4545 'keymap org-mouse-map))
4546 (when org-display-custom-times
4547 (if (match-end 3)
4548 (org-display-custom-time (match-beginning 3) (match-end 3)))
4549 (org-display-custom-time (match-beginning 1) (match-end 1)))
4550 t)))
4552 (defvar org-target-link-regexp nil
4553 "Regular expression matching radio targets in plain text.")
4554 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4555 "Regular expression matching a link target.")
4556 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4557 "Regular expression matching a radio target.")
4558 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4559 "Regular expression matching any target.")
4561 (defun org-activate-target-links (limit)
4562 "Run through the buffer and add overlays to target matches."
4563 (when org-target-link-regexp
4564 (let ((case-fold-search t))
4565 (if (re-search-forward org-target-link-regexp limit t)
4566 (progn
4567 (add-text-properties (match-beginning 0) (match-end 0)
4568 (list 'mouse-face 'highlight
4569 'rear-nonsticky t
4570 'keymap org-mouse-map
4571 'help-echo "Radio target link"
4572 'org-linked-text t))
4573 t)))))
4575 (defun org-update-radio-target-regexp ()
4576 "Find all radio targets in this file and update the regular expression."
4577 (interactive)
4578 (when (memq 'radio org-activate-links)
4579 (setq org-target-link-regexp
4580 (org-make-target-link-regexp (org-all-targets 'radio)))
4581 (org-restart-font-lock)))
4583 (defun org-hide-wide-columns (limit)
4584 (let (s e)
4585 (setq s (text-property-any (point) (or limit (point-max))
4586 'org-cwidth t))
4587 (when s
4588 (setq e (next-single-property-change s 'org-cwidth))
4589 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4590 (goto-char e)
4591 t)))
4593 (defun org-restart-font-lock ()
4594 "Restart font-lock-mode, to force refontification."
4595 (when (and (boundp 'font-lock-mode) font-lock-mode)
4596 ;; FIXME: Could font-lock-fontify-buffer be enough???
4597 (font-lock-mode -1)
4598 (font-lock-mode 1)))
4600 (defun org-all-targets (&optional radio)
4601 "Return a list of all targets in this file.
4602 With optional argument RADIO, only find radio targets."
4603 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4604 rtn)
4605 (save-excursion
4606 (goto-char (point-min))
4607 (while (re-search-forward re nil t)
4608 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4609 rtn)))
4611 (defun org-make-target-link-regexp (targets)
4612 "Make regular expression matching all strings in TARGETS.
4613 The regular expression finds the targets also if there is a line break
4614 between words."
4615 (and targets
4616 (concat
4617 "\\<\\("
4618 (mapconcat
4619 (lambda (x)
4620 (while (string-match " +" x)
4621 (setq x (replace-match "\\s-+" t t x)))
4623 targets
4624 "\\|")
4625 "\\)\\>")))
4627 (defun org-activate-tags (limit)
4628 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4629 (progn
4630 (add-text-properties (match-beginning 1) (match-end 1)
4631 (list 'mouse-face 'highlight
4632 'rear-nonsticky t
4633 'keymap org-mouse-map))
4634 t)))
4636 (defun org-outline-level ()
4637 (save-excursion
4638 (looking-at outline-regexp)
4639 (if (match-beginning 1)
4640 (+ (org-get-string-indentation (match-string 1)) 1000)
4641 (1- (- (match-end 0) (match-beginning 0))))))
4643 (defvar org-font-lock-keywords nil)
4645 (defconst org-property-re "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(\\S-.*\\)"
4646 "Regular expression matching a property line.")
4648 (defun org-set-font-lock-defaults ()
4649 (let* ((em org-fontify-emphasized-text)
4650 (lk org-activate-links)
4651 (org-font-lock-extra-keywords
4652 (list
4653 ;; Headlines
4654 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4655 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4656 ;; Table lines
4657 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4658 (1 'org-table))
4659 ;; Links
4660 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4661 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4662 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4663 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4664 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4665 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4666 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4667 '(org-hide-wide-columns (0 nil append))
4668 ;; TODO lines
4669 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4670 '(1 (org-get-todo-face 1) t))
4671 ;; DONE
4672 (if org-fontify-done-headline
4673 (list (concat "^[*]+ +\\<\\("
4674 (mapconcat 'regexp-quote org-done-keywords "\\|")
4675 "\\)\\(.*\\)")
4676 '(2 'org-headline-done t))
4677 nil)
4678 ;; Priorities
4679 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4680 ;; Special keywords
4681 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4682 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4683 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4684 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4685 ;; Emphasis
4686 (if em
4687 (if (featurep 'xemacs)
4688 '(org-do-emphasis-faces (0 nil append))
4689 '(org-do-emphasis-faces)))
4690 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4691 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4692 2 'bold prepend)
4693 (if org-provide-checkbox-statistics
4694 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4695 (0 (org-get-checkbox-statistics-face) t)))
4696 ;; COMMENT
4697 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4698 "\\|" org-quote-string "\\)\\>")
4699 '(1 'org-special-keyword t))
4700 '("^#.*" (0 'font-lock-comment-face t))
4701 ;; Code
4702 '("^[ \t]*\\(:.*\\)" (1 'org-code t))
4703 ;; Table internals
4704 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4705 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4706 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4707 ;; Drawers
4708 (list org-drawer-regexp '(0 'org-special-keyword t))
4709 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4710 ;; Properties
4711 (list org-property-re
4712 '(1 'org-special-keyword t)
4713 '(3 'org-property-value t))
4714 (if org-format-transports-properties-p
4715 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4716 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4718 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4719 ;; Now set the full font-lock-keywords
4720 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4721 (org-set-local 'font-lock-defaults
4722 '(org-font-lock-keywords t nil nil backward-paragraph))
4723 (kill-local-variable 'font-lock-keywords) nil))
4725 (defvar org-m nil)
4726 (defvar org-l nil)
4727 (defvar org-f nil)
4728 (defun org-get-level-face (n)
4729 "Get the right face for match N in font-lock matching of healdines."
4730 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4731 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4732 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4733 (cond
4734 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4735 ((eq n 2) org-f)
4736 (t (if org-level-color-stars-only nil org-f))))
4739 (defun org-get-todo-face (kwd)
4740 "Get the right face for a TODO keyword KWD.
4741 If KWD is a number, get the corresponding match group."
4742 (if (numberp kwd) (setq kwd (match-string kwd)))
4743 (or (cdr (assoc kwd org-todo-keyword-faces))
4744 (and (member kwd org-done-keywords) 'org-done)
4745 'org-todo))
4747 (defun org-unfontify-region (beg end &optional maybe_loudly)
4748 "Remove fontification and activation overlays from links."
4749 (font-lock-default-unfontify-region beg end)
4750 (let* ((buffer-undo-list t)
4751 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4752 (inhibit-modification-hooks t)
4753 deactivate-mark buffer-file-name buffer-file-truename)
4754 (remove-text-properties beg end
4755 '(mouse-face t keymap t org-linked-text t
4756 rear-nonsticky t
4757 invisible t intangible t))))
4759 ;;;; Visibility cycling, including org-goto and indirect buffer
4761 ;;; Cycling
4763 (defvar org-cycle-global-status nil)
4764 (make-variable-buffer-local 'org-cycle-global-status)
4765 (defvar org-cycle-subtree-status nil)
4766 (make-variable-buffer-local 'org-cycle-subtree-status)
4768 ;;;###autoload
4769 (defun org-cycle (&optional arg)
4770 "Visibility cycling for Org-mode.
4772 - When this function is called with a prefix argument, rotate the entire
4773 buffer through 3 states (global cycling)
4774 1. OVERVIEW: Show only top-level headlines.
4775 2. CONTENTS: Show all headlines of all levels, but no body text.
4776 3. SHOW ALL: Show everything.
4778 - When point is at the beginning of a headline, rotate the subtree started
4779 by this line through 3 different states (local cycling)
4780 1. FOLDED: Only the main headline is shown.
4781 2. CHILDREN: The main headline and the direct children are shown.
4782 From this state, you can move to one of the children
4783 and zoom in further.
4784 3. SUBTREE: Show the entire subtree, including body text.
4786 - When there is a numeric prefix, go up to a heading with level ARG, do
4787 a `show-subtree' and return to the previous cursor position. If ARG
4788 is negative, go up that many levels.
4790 - When point is not at the beginning of a headline, execute
4791 `indent-relative', like TAB normally does. See the option
4792 `org-cycle-emulate-tab' for details.
4794 - Special case: if point is at the beginning of the buffer and there is
4795 no headline in line 1, this function will act as if called with prefix arg.
4796 But only if also the variable `org-cycle-global-at-bob' is t."
4797 (interactive "P")
4798 (let* ((outline-regexp
4799 (if (and (org-mode-p) org-cycle-include-plain-lists)
4800 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4801 outline-regexp))
4802 (bob-special (and org-cycle-global-at-bob (bobp)
4803 (not (looking-at outline-regexp))))
4804 (org-cycle-hook
4805 (if bob-special
4806 (delq 'org-optimize-window-after-visibility-change
4807 (copy-sequence org-cycle-hook))
4808 org-cycle-hook))
4809 (pos (point)))
4811 (if (or bob-special (equal arg '(4)))
4812 ;; special case: use global cycling
4813 (setq arg t))
4815 (cond
4817 ((org-at-table-p 'any)
4818 ;; Enter the table or move to the next field in the table
4819 (or (org-table-recognize-table.el)
4820 (progn
4821 (if arg (org-table-edit-field t)
4822 (org-table-justify-field-maybe)
4823 (call-interactively 'org-table-next-field)))))
4825 ((eq arg t) ;; Global cycling
4827 (cond
4828 ((and (eq last-command this-command)
4829 (eq org-cycle-global-status 'overview))
4830 ;; We just created the overview - now do table of contents
4831 ;; This can be slow in very large buffers, so indicate action
4832 (message "CONTENTS...")
4833 (org-content)
4834 (message "CONTENTS...done")
4835 (setq org-cycle-global-status 'contents)
4836 (run-hook-with-args 'org-cycle-hook 'contents))
4838 ((and (eq last-command this-command)
4839 (eq org-cycle-global-status 'contents))
4840 ;; We just showed the table of contents - now show everything
4841 (show-all)
4842 (message "SHOW ALL")
4843 (setq org-cycle-global-status 'all)
4844 (run-hook-with-args 'org-cycle-hook 'all))
4847 ;; Default action: go to overview
4848 (org-overview)
4849 (message "OVERVIEW")
4850 (setq org-cycle-global-status 'overview)
4851 (run-hook-with-args 'org-cycle-hook 'overview))))
4853 ((and org-drawers org-drawer-regexp
4854 (save-excursion
4855 (beginning-of-line 1)
4856 (looking-at org-drawer-regexp)))
4857 ;; Toggle block visibility
4858 (org-flag-drawer
4859 (not (get-char-property (match-end 0) 'invisible))))
4861 ((integerp arg)
4862 ;; Show-subtree, ARG levels up from here.
4863 (save-excursion
4864 (org-back-to-heading)
4865 (outline-up-heading (if (< arg 0) (- arg)
4866 (- (funcall outline-level) arg)))
4867 (org-show-subtree)))
4869 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4870 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4871 ;; At a heading: rotate between three different views
4872 (org-back-to-heading)
4873 (let ((goal-column 0) eoh eol eos)
4874 ;; First, some boundaries
4875 (save-excursion
4876 (org-back-to-heading)
4877 (save-excursion
4878 (beginning-of-line 2)
4879 (while (and (not (eobp)) ;; this is like `next-line'
4880 (get-char-property (1- (point)) 'invisible))
4881 (beginning-of-line 2)) (setq eol (point)))
4882 (outline-end-of-heading) (setq eoh (point))
4883 (org-end-of-subtree t)
4884 (unless (eobp)
4885 (skip-chars-forward " \t\n")
4886 (beginning-of-line 1) ; in case this is an item
4888 (setq eos (1- (point))))
4889 ;; Find out what to do next and set `this-command'
4890 (cond
4891 ((= eos eoh)
4892 ;; Nothing is hidden behind this heading
4893 (message "EMPTY ENTRY")
4894 (setq org-cycle-subtree-status nil)
4895 (save-excursion
4896 (goto-char eos)
4897 (outline-next-heading)
4898 (if (org-invisible-p) (org-flag-heading nil))))
4899 ((or (>= eol eos)
4900 (not (string-match "\\S-" (buffer-substring eol eos))))
4901 ;; Entire subtree is hidden in one line: open it
4902 (org-show-entry)
4903 (show-children)
4904 (message "CHILDREN")
4905 (save-excursion
4906 (goto-char eos)
4907 (outline-next-heading)
4908 (if (org-invisible-p) (org-flag-heading nil)))
4909 (setq org-cycle-subtree-status 'children)
4910 (run-hook-with-args 'org-cycle-hook 'children))
4911 ((and (eq last-command this-command)
4912 (eq org-cycle-subtree-status 'children))
4913 ;; We just showed the children, now show everything.
4914 (org-show-subtree)
4915 (message "SUBTREE")
4916 (setq org-cycle-subtree-status 'subtree)
4917 (run-hook-with-args 'org-cycle-hook 'subtree))
4919 ;; Default action: hide the subtree.
4920 (hide-subtree)
4921 (message "FOLDED")
4922 (setq org-cycle-subtree-status 'folded)
4923 (run-hook-with-args 'org-cycle-hook 'folded)))))
4925 ;; TAB emulation
4926 (buffer-read-only (org-back-to-heading))
4928 ((org-try-cdlatex-tab))
4930 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4931 (or (not (bolp))
4932 (not (looking-at outline-regexp))))
4933 (call-interactively (global-key-binding "\t")))
4935 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4936 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4937 (or (and (eq org-cycle-emulate-tab 'white)
4938 (= (match-end 0) (point-at-eol)))
4939 (and (eq org-cycle-emulate-tab 'whitestart)
4940 (>= (match-end 0) pos))))
4942 (eq org-cycle-emulate-tab t))
4943 (if (and (looking-at "[ \n\r\t]")
4944 (string-match "^[ \t]*$" (buffer-substring
4945 (point-at-bol) (point))))
4946 (progn
4947 (beginning-of-line 1)
4948 (and (looking-at "[ \t]+") (replace-match ""))))
4949 (call-interactively (global-key-binding "\t")))
4951 (t (save-excursion
4952 (org-back-to-heading)
4953 (org-cycle))))))
4955 ;;;###autoload
4956 (defun org-global-cycle (&optional arg)
4957 "Cycle the global visibility. For details see `org-cycle'."
4958 (interactive "P")
4959 (let ((org-cycle-include-plain-lists
4960 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4961 (if (integerp arg)
4962 (progn
4963 (show-all)
4964 (hide-sublevels arg)
4965 (setq org-cycle-global-status 'contents))
4966 (org-cycle '(4)))))
4968 (defun org-overview ()
4969 "Switch to overview mode, shoing only top-level headlines.
4970 Really, this shows all headlines with level equal or greater than the level
4971 of the first headline in the buffer. This is important, because if the
4972 first headline is not level one, then (hide-sublevels 1) gives confusing
4973 results."
4974 (interactive)
4975 (let ((level (save-excursion
4976 (goto-char (point-min))
4977 (if (re-search-forward (concat "^" outline-regexp) nil t)
4978 (progn
4979 (goto-char (match-beginning 0))
4980 (funcall outline-level))))))
4981 (and level (hide-sublevels level))))
4983 (defun org-content (&optional arg)
4984 "Show all headlines in the buffer, like a table of contents.
4985 With numerical argument N, show content up to level N."
4986 (interactive "P")
4987 (save-excursion
4988 ;; Visit all headings and show their offspring
4989 (and (integerp arg) (org-overview))
4990 (goto-char (point-max))
4991 (catch 'exit
4992 (while (and (progn (condition-case nil
4993 (outline-previous-visible-heading 1)
4994 (error (goto-char (point-min))))
4996 (looking-at outline-regexp))
4997 (if (integerp arg)
4998 (show-children (1- arg))
4999 (show-branches))
5000 (if (bobp) (throw 'exit nil))))))
5003 (defun org-optimize-window-after-visibility-change (state)
5004 "Adjust the window after a change in outline visibility.
5005 This function is the default value of the hook `org-cycle-hook'."
5006 (when (get-buffer-window (current-buffer))
5007 (cond
5008 ; ((eq state 'overview) (org-first-headline-recenter 1))
5009 ; ((eq state 'overview) (org-beginning-of-line))
5010 ((eq state 'content) nil)
5011 ((eq state 'all) nil)
5012 ((eq state 'folded) nil)
5013 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5014 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5017 (defun org-cycle-show-empty-lines (state)
5018 "Show empty lines above all visible headlines.
5019 The region to be covered depends on STATE when called through
5020 `org-cycle-hook'. Lisp program can use t for STATE to get the
5021 entire buffer covered. Note that an empty line is only shown if there
5022 are at least `org-cycle-separator-lines' empty lines before the headeline."
5023 (when (> org-cycle-separator-lines 0)
5024 (save-excursion
5025 (let* ((n org-cycle-separator-lines)
5026 (re (cond
5027 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5028 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5029 (t (let ((ns (number-to-string (- n 2))))
5030 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5031 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5032 beg end)
5033 (cond
5034 ((memq state '(overview contents t))
5035 (setq beg (point-min) end (point-max)))
5036 ((memq state '(children folded))
5037 (setq beg (point) end (progn (org-end-of-subtree t t)
5038 (beginning-of-line 2)
5039 (point)))))
5040 (when beg
5041 (goto-char beg)
5042 (while (re-search-forward re end t)
5043 (if (not (get-char-property (match-end 1) 'invisible))
5044 (outline-flag-region
5045 (match-beginning 1) (match-end 1) nil)))))))
5046 ;; Never hide empty lines at the end of the file.
5047 (save-excursion
5048 (goto-char (point-max))
5049 (outline-previous-heading)
5050 (outline-end-of-heading)
5051 (if (and (looking-at "[ \t\n]+")
5052 (= (match-end 0) (point-max)))
5053 (outline-flag-region (point) (match-end 0) nil))))
5055 (defun org-subtree-end-visible-p ()
5056 "Is the end of the current subtree visible?"
5057 (pos-visible-in-window-p
5058 (save-excursion (org-end-of-subtree t) (point))))
5060 (defun org-first-headline-recenter (&optional N)
5061 "Move cursor to the first headline and recenter the headline.
5062 Optional argument N means, put the headline into the Nth line of the window."
5063 (goto-char (point-min))
5064 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5065 (beginning-of-line)
5066 (recenter (prefix-numeric-value N))))
5068 ;;; Org-goto
5070 (defvar org-goto-window-configuration nil)
5071 (defvar org-goto-marker nil)
5072 (defvar org-goto-map
5073 (let ((map (make-sparse-keymap)))
5074 (let ((cmds '(isearch-forward isearch-backward)) cmd)
5075 (while (setq cmd (pop cmds))
5076 (substitute-key-definition cmd cmd map global-map)))
5077 (org-defkey map "\C-m" 'org-goto-ret)
5078 (org-defkey map [(left)] 'org-goto-left)
5079 (org-defkey map [(right)] 'org-goto-right)
5080 (org-defkey map [(?q)] 'org-goto-quit)
5081 (org-defkey map [(control ?g)] 'org-goto-quit)
5082 (org-defkey map "\C-i" 'org-cycle)
5083 (org-defkey map [(tab)] 'org-cycle)
5084 (org-defkey map [(down)] 'outline-next-visible-heading)
5085 (org-defkey map [(up)] 'outline-previous-visible-heading)
5086 (org-defkey map "n" 'outline-next-visible-heading)
5087 (org-defkey map "p" 'outline-previous-visible-heading)
5088 (org-defkey map "f" 'outline-forward-same-level)
5089 (org-defkey map "b" 'outline-backward-same-level)
5090 (org-defkey map "u" 'outline-up-heading)
5091 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5092 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5093 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5094 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5095 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5096 ;; FIXME: Could we use suppress-keymap?
5097 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5098 (while l (org-defkey map (int-to-string (pop l)) 'digit-argument)))
5099 map))
5101 (defconst org-goto-help
5102 "Select a location to jump to, press RET
5103 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
5105 (defun org-goto ()
5106 "Go to a different location of the document, keeping current visibility.
5108 When you want to go to a different location in a document, the fastest way
5109 is often to fold the entire buffer and then dive into the tree. This
5110 method has the disadvantage, that the previous location will be folded,
5111 which may not be what you want.
5113 This command works around this by showing a copy of the current buffer in
5114 overview mode. You can dive into the tree in that copy, to find the
5115 location you want to reach. When pressing RET, the command returns to the
5116 original buffer in which the visibility is still unchanged. It then jumps
5117 to the new location, making it and the headline hierarchy above it visible."
5118 (interactive)
5119 (let* ((org-goto-start-pos (point))
5120 (selected-point
5121 (org-get-location (current-buffer) org-goto-help)))
5122 (if selected-point
5123 (progn
5124 (org-mark-ring-push org-goto-start-pos)
5125 (goto-char selected-point)
5126 (if (or (org-invisible-p) (org-invisible-p2))
5127 (org-show-context 'org-goto)))
5128 (error "Quit"))))
5130 (defvar org-selected-point nil) ; dynamically scoped parameter
5132 (defun org-get-location (buf help)
5133 "Let the user select a location in the Org-mode buffer BUF.
5134 This function uses a recursive edit. It returns the selected position
5135 or nil."
5136 (let (org-selected-point)
5137 (save-excursion
5138 (save-window-excursion
5139 (delete-other-windows)
5140 (switch-to-buffer (get-buffer-create "*org-goto*"))
5141 (with-output-to-temp-buffer "*Help*"
5142 (princ help))
5143 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5144 (setq buffer-read-only nil)
5145 (erase-buffer)
5146 (insert-buffer-substring buf)
5147 (let ((org-startup-truncated t)
5148 (org-startup-folded t)
5149 (org-startup-align-all-tables nil))
5150 (org-mode))
5151 (setq buffer-read-only t)
5152 (if (and (boundp 'org-goto-start-pos)
5153 (integer-or-marker-p org-goto-start-pos))
5154 (let ((org-show-hierarchy-above t)
5155 (org-show-siblings t)
5156 (org-show-following-heading t))
5157 (goto-char org-goto-start-pos)
5158 (and (org-invisible-p) (org-show-context)))
5159 (goto-char (point-min)))
5160 (org-beginning-of-line)
5161 (message "Select location and press RET")
5162 ;; now we make sure that during selection, ony very few keys work
5163 ;; and that it is impossible to switch to another window.
5164 (let ((gm (current-global-map))
5165 (overriding-local-map org-goto-map))
5166 (unwind-protect
5167 (progn
5168 (use-global-map org-goto-map)
5169 (recursive-edit))
5170 (use-global-map gm)))))
5171 (kill-buffer "*org-goto*")
5172 org-selected-point))
5174 (defun org-goto-ret (&optional arg)
5175 "Finish `org-goto' by going to the new location."
5176 (interactive "P")
5177 (setq org-selected-point (point)
5178 current-prefix-arg arg)
5179 (throw 'exit nil))
5181 (defun org-goto-left ()
5182 "Finish `org-goto' by going to the new location."
5183 (interactive)
5184 (if (org-on-heading-p)
5185 (progn
5186 (beginning-of-line 1)
5187 (setq org-selected-point (point)
5188 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5189 (throw 'exit nil))
5190 (error "Not on a heading")))
5192 (defun org-goto-right ()
5193 "Finish `org-goto' by going to the new location."
5194 (interactive)
5195 (if (org-on-heading-p)
5196 (progn
5197 (outline-end-of-subtree)
5198 (or (eobp) (forward-char 1))
5199 (setq org-selected-point (point)
5200 current-prefix-arg (- (match-end 0) (match-beginning 0)))
5201 (throw 'exit nil))
5202 (error "Not on a heading")))
5204 (defun org-goto-quit ()
5205 "Finish `org-goto' without cursor motion."
5206 (interactive)
5207 (setq org-selected-point nil)
5208 (throw 'exit nil))
5210 ;;; Indirect buffer display of subtrees
5212 (defvar org-indirect-dedicated-frame nil
5213 "This is the frame being used for indirect tree display.")
5214 (defvar org-last-indirect-buffer nil)
5216 (defun org-tree-to-indirect-buffer (&optional arg)
5217 "Create indirect buffer and narrow it to current subtree.
5218 With numerical prefix ARG, go up to this level and then take that tree.
5219 If ARG is negative, go up that many levels.
5220 Normally this command removes the indirect buffer previously made
5221 with this command. However, when called with a C-u prefix, the last buffer
5222 is kept so that you can work with several indirect buffers at the same time.
5223 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5224 requests that a new frame be made for the new buffer, so that the dedicated
5225 frame is not changed."
5226 (interactive "P")
5227 (let ((cbuf (current-buffer))
5228 (cwin (selected-window))
5229 (pos (point))
5230 beg end level heading ibuf)
5231 (save-excursion
5232 (org-back-to-heading t)
5233 (when (numberp arg)
5234 (setq level (org-outline-level))
5235 (if (< arg 0) (setq arg (+ level arg)))
5236 (while (> (setq level (org-outline-level)) arg)
5237 (outline-up-heading 1 t)))
5238 (setq beg (point)
5239 heading (org-get-heading))
5240 (org-end-of-subtree t) (setq end (point)))
5241 (if (and (not arg)
5242 (buffer-live-p org-last-indirect-buffer))
5243 (kill-buffer org-last-indirect-buffer))
5244 (setq ibuf (org-get-indirect-buffer cbuf)
5245 org-last-indirect-buffer ibuf)
5246 (cond
5247 ((or (eq org-indirect-buffer-display 'new-frame)
5248 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5249 (select-frame (make-frame))
5250 (delete-other-windows)
5251 (switch-to-buffer ibuf)
5252 (org-set-frame-title heading))
5253 ((eq org-indirect-buffer-display 'dedicated-frame)
5254 (raise-frame
5255 (select-frame (or (and org-indirect-dedicated-frame
5256 (frame-live-p org-indirect-dedicated-frame)
5257 org-indirect-dedicated-frame)
5258 (setq org-indirect-dedicated-frame (make-frame)))))
5259 (delete-other-windows)
5260 (switch-to-buffer ibuf)
5261 (org-set-frame-title (concat "Indirect: " heading)))
5262 ((eq org-indirect-buffer-display 'current-window)
5263 (switch-to-buffer ibuf))
5264 ((eq org-indirect-buffer-display 'other-window)
5265 (pop-to-buffer ibuf))
5266 (t (error "Invalid value.")))
5267 (if (featurep 'xemacs)
5268 (save-excursion (org-mode) (turn-on-font-lock)))
5269 (narrow-to-region beg end)
5270 (show-all)
5271 (goto-char pos)
5272 (and (window-live-p cwin) (select-window cwin))))
5274 (defun org-get-indirect-buffer (&optional buffer)
5275 (setq buffer (or buffer (current-buffer)))
5276 (let ((n 1) (base (buffer-name buffer)) bname)
5277 (while (buffer-live-p
5278 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5279 (setq n (1+ n)))
5280 (condition-case nil
5281 (make-indirect-buffer buffer bname 'clone)
5282 (error (make-indirect-buffer buffer bname)))))
5284 (defun org-set-frame-title (title)
5285 "Set the title of the current frame to the string TITLE."
5286 ;; FIXME: how to name a single frame in XEmacs???
5287 (unless (featurep 'xemacs)
5288 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5290 ;;;; Structure editing
5292 ;;; Inserting headlines
5294 (defun org-insert-heading (&optional force-heading)
5295 "Insert a new heading or item with same depth at point.
5296 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5297 If point is at the beginning of a headline, insert a sibling before the
5298 current headline. If point is in the middle of a headline, split the headline
5299 at that position and make the rest of the headline part of the sibling below
5300 the current headline."
5301 (interactive "P")
5302 (if (= (buffer-size) 0)
5303 (insert "\n* ")
5304 (when (or force-heading (not (org-insert-item)))
5305 (let* ((head (save-excursion
5306 (condition-case nil
5307 (progn
5308 (org-back-to-heading)
5309 (match-string 0))
5310 (error "*"))))
5311 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5312 pos)
5313 (cond
5314 ((and (org-on-heading-p) (bolp)
5315 (or (bobp)
5316 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5317 (open-line (if blank 2 1)))
5318 ((and (bolp)
5319 (or (bobp)
5320 (save-excursion
5321 (backward-char 1) (not (org-invisible-p)))))
5322 nil)
5323 (t (newline (if blank 2 1))))
5324 (insert head) (just-one-space)
5325 (setq pos (point))
5326 (end-of-line 1)
5327 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5328 (run-hooks 'org-insert-heading-hook)))))
5330 (defun org-insert-todo-heading (arg)
5331 "Insert a new heading with the same level and TODO state as current heading.
5332 If the heading has no TODO state, or if the state is DONE, use the first
5333 state (TODO by default). Also with prefix arg, force first state."
5334 (interactive "P")
5335 (when (not (org-insert-item 'checkbox))
5336 (org-insert-heading)
5337 (save-excursion
5338 (org-back-to-heading)
5339 (outline-previous-heading)
5340 (looking-at org-todo-line-regexp))
5341 (if (or arg
5342 (not (match-beginning 2))
5343 (member (match-string 2) org-done-keywords))
5344 (insert (car org-todo-keywords-1) " ")
5345 (insert (match-string 2) " "))))
5347 (defun org-insert-subheading (arg)
5348 "Insert a new subheading and demote it.
5349 Works for outline headings and for plain lists alike."
5350 (interactive "P")
5351 (org-insert-heading arg)
5352 (cond
5353 ((org-on-heading-p) (org-do-demote))
5354 ((org-at-item-p) (org-indent-item 1))))
5356 (defun org-insert-todo-subheading (arg)
5357 "Insert a new subheading with TODO keyword or checkbox and demote it.
5358 Works for outline headings and for plain lists alike."
5359 (interactive "P")
5360 (org-insert-todo-heading arg)
5361 (cond
5362 ((org-on-heading-p) (org-do-demote))
5363 ((org-at-item-p) (org-indent-item 1))))
5365 ;;; Promotion and Demotion
5367 (defun org-promote-subtree ()
5368 "Promote the entire subtree.
5369 See also `org-promote'."
5370 (interactive)
5371 (save-excursion
5372 (org-map-tree 'org-promote))
5373 (org-fix-position-after-promote))
5375 (defun org-demote-subtree ()
5376 "Demote the entire subtree. See `org-demote'.
5377 See also `org-promote'."
5378 (interactive)
5379 (save-excursion
5380 (org-map-tree 'org-demote))
5381 (org-fix-position-after-promote))
5384 (defun org-do-promote ()
5385 "Promote the current heading higher up the tree.
5386 If the region is active in `transient-mark-mode', promote all headings
5387 in the region."
5388 (interactive)
5389 (save-excursion
5390 (if (org-region-active-p)
5391 (org-map-region 'org-promote (region-beginning) (region-end))
5392 (org-promote)))
5393 (org-fix-position-after-promote))
5395 (defun org-do-demote ()
5396 "Demote the current heading lower down the tree.
5397 If the region is active in `transient-mark-mode', demote all headings
5398 in the region."
5399 (interactive)
5400 (save-excursion
5401 (if (org-region-active-p)
5402 (org-map-region 'org-demote (region-beginning) (region-end))
5403 (org-demote)))
5404 (org-fix-position-after-promote))
5406 (defun org-fix-position-after-promote ()
5407 "Make sure that after pro/demotion cursor position is right."
5408 (let ((pos (point)))
5409 (when (save-excursion
5410 (beginning-of-line 1)
5411 (looking-at org-todo-line-regexp)
5412 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5413 (cond ((eobp) (insert " "))
5414 ((eolp) (insert " "))
5415 ((equal (char-after) ?\ ) (forward-char 1))))))
5417 (defun org-reduced-level (l)
5418 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5420 (defun org-get-legal-level (level &optional change)
5421 "Rectify a level change under the influence of `org-odd-levels-only'
5422 LEVEL is a current level, CHANGE is by how much the level should be
5423 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5424 even level numbers will become the next higher odd number."
5425 (if org-odd-levels-only
5426 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5427 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5428 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5429 (max 1 (+ level change))))
5431 (defun org-promote ()
5432 "Promote the current heading higher up the tree.
5433 If the region is active in `transient-mark-mode', promote all headings
5434 in the region."
5435 (org-back-to-heading t)
5436 (let* ((level (save-match-data (funcall outline-level)))
5437 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5438 (diff (abs (- level (length up-head) -1))))
5439 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5440 (replace-match up-head nil t)
5441 ;; Fixup tag positioning
5442 (and org-auto-align-tags (org-set-tags nil t))
5443 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5445 (defun org-demote ()
5446 "Demote the current heading lower down the tree.
5447 If the region is active in `transient-mark-mode', demote all headings
5448 in the region."
5449 (org-back-to-heading t)
5450 (let* ((level (save-match-data (funcall outline-level)))
5451 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5452 (diff (abs (- level (length down-head) -1))))
5453 (replace-match down-head nil t)
5454 ;; Fixup tag positioning
5455 (and org-auto-align-tags (org-set-tags nil t))
5456 (if org-adapt-indentation (org-fixup-indentation diff))))
5458 (defun org-map-tree (fun)
5459 "Call FUN for every heading underneath the current one."
5460 (org-back-to-heading)
5461 (let ((level (funcall outline-level)))
5462 (save-excursion
5463 (funcall fun)
5464 (while (and (progn
5465 (outline-next-heading)
5466 (> (funcall outline-level) level))
5467 (not (eobp)))
5468 (funcall fun)))))
5470 (defun org-map-region (fun beg end)
5471 "Call FUN for every heading between BEG and END."
5472 (let ((org-ignore-region t))
5473 (save-excursion
5474 (setq end (copy-marker end))
5475 (goto-char beg)
5476 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5477 (< (point) end))
5478 (funcall fun))
5479 (while (and (progn
5480 (outline-next-heading)
5481 (< (point) end))
5482 (not (eobp)))
5483 (funcall fun)))))
5485 (defun org-fixup-indentation (diff)
5486 "Change the indentation in the current entry by DIFF
5487 However, if any line in the current entry has no indentation, or if it
5488 would end up with no indentation after the change, nothing at all is done."
5489 (save-excursion
5490 (let ((end (save-excursion (outline-next-heading)
5491 (point-marker)))
5492 (prohibit (if (> diff 0)
5493 "^\\S-"
5494 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5495 col)
5496 (unless (save-excursion (end-of-line 1)
5497 (re-search-forward prohibit end t))
5498 (while (re-search-forward "^[ \t]+" end t)
5499 (goto-char (match-end 0))
5500 (setq col (current-column))
5501 (if (< diff 0) (replace-match ""))
5502 (indent-to (+ diff col))))
5503 (move-marker end nil))))
5505 (defun org-convert-to-odd-levels ()
5506 "Convert an org-mode file with all levels allowed to one with odd levels.
5507 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5508 level 5 etc."
5509 (interactive)
5510 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5511 (let ((org-odd-levels-only nil) n)
5512 (save-excursion
5513 (goto-char (point-min))
5514 (while (re-search-forward "^\\*\\*+ " nil t)
5515 (setq n (- (length (match-string 0)) 2))
5516 (while (>= (setq n (1- n)) 0)
5517 (org-demote))
5518 (end-of-line 1))))))
5521 (defun org-convert-to-oddeven-levels ()
5522 "Convert an org-mode file with only odd levels to one with odd and even levels.
5523 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5524 section with an even level, conversion would destroy the structure of the file. An error
5525 is signaled in this case."
5526 (interactive)
5527 (goto-char (point-min))
5528 ;; First check if there are no even levels
5529 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5530 (org-show-context t)
5531 (error "Not all levels are odd in this file. Conversion not possible."))
5532 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5533 (let ((org-odd-levels-only nil) n)
5534 (save-excursion
5535 (goto-char (point-min))
5536 (while (re-search-forward "^\\*\\*+ " nil t)
5537 (setq n (/ (length (1- (match-string 0))) 2))
5538 (while (>= (setq n (1- n)) 0)
5539 (org-promote))
5540 (end-of-line 1))))))
5542 (defun org-tr-level (n)
5543 "Make N odd if required."
5544 (if org-odd-levels-only (1+ (/ n 2)) n))
5546 ;;; Vertical tree motion, cutting and pasting of subtrees
5548 (defun org-move-subtree-up (&optional arg)
5549 "Move the current subtree up past ARG headlines of the same level."
5550 (interactive "p")
5551 (org-move-subtree-down (- (prefix-numeric-value arg))))
5553 (defun org-move-subtree-down (&optional arg)
5554 "Move the current subtree down past ARG headlines of the same level."
5555 (interactive "p")
5556 (setq arg (prefix-numeric-value arg))
5557 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5558 'outline-get-last-sibling))
5559 (ins-point (make-marker))
5560 (cnt (abs arg))
5561 beg end txt folded)
5562 ;; Select the tree
5563 (org-back-to-heading)
5564 (setq beg (point))
5565 (save-match-data
5566 (save-excursion (outline-end-of-heading)
5567 (setq folded (org-invisible-p)))
5568 (outline-end-of-subtree))
5569 (outline-next-heading)
5570 (setq end (point))
5571 ;; Find insertion point, with error handling
5572 (goto-char beg)
5573 (while (> cnt 0)
5574 (or (and (funcall movfunc) (looking-at outline-regexp))
5575 (progn (goto-char beg)
5576 (error "Cannot move past superior level or buffer limit")))
5577 (setq cnt (1- cnt)))
5578 (if (> arg 0)
5579 ;; Moving forward - still need to move over subtree
5580 (progn (outline-end-of-subtree)
5581 (outline-next-heading)
5582 (if (not (or (looking-at (concat "^" outline-regexp))
5583 (bolp)))
5584 (newline))))
5585 (move-marker ins-point (point))
5586 (setq txt (buffer-substring beg end))
5587 (delete-region beg end)
5588 (insert txt)
5589 (or (bolp) (insert "\n"))
5590 (goto-char ins-point)
5591 (if folded (hide-subtree))
5592 (move-marker ins-point nil)))
5594 (defvar org-subtree-clip ""
5595 "Clipboard for cut and paste of subtrees.
5596 This is actually only a copy of the kill, because we use the normal kill
5597 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5599 (defvar org-subtree-clip-folded nil
5600 "Was the last copied subtree folded?
5601 This is used to fold the tree back after pasting.")
5603 (defun org-cut-subtree ()
5604 "Cut the current subtree into the clipboard.
5605 This is a short-hand for marking the subtree and then cutting it."
5606 (interactive)
5607 (org-copy-subtree 'cut))
5609 (defun org-copy-subtree (&optional cut)
5610 "Cut the current subtree into the clipboard.
5611 This is a short-hand for marking the subtree and then copying it.
5612 If CUT is non-nil, actually cut the subtree."
5613 (interactive)
5614 (let (beg end folded)
5615 (if (interactive-p)
5616 (org-back-to-heading nil) ; take what looks like a subtree
5617 (org-back-to-heading t)) ; take what is really there
5618 (setq beg (point))
5619 (save-match-data
5620 (save-excursion (outline-end-of-heading)
5621 (setq folded (org-invisible-p)))
5622 (outline-end-of-subtree))
5623 (if (equal (char-after) ?\n) (forward-char 1))
5624 (setq end (point))
5625 (goto-char beg)
5626 (when (> end beg)
5627 (setq org-subtree-clip-folded folded)
5628 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5629 (setq org-subtree-clip (current-kill 0))
5630 (message "%s: Subtree with %d characters"
5631 (if cut "Cut" "Copied")
5632 (length org-subtree-clip)))))
5634 (defun org-paste-subtree (&optional level tree)
5635 "Paste the clipboard as a subtree, with modification of headline level.
5636 The entire subtree is promoted or demoted in order to match a new headline
5637 level. By default, the new level is derived from the visible headings
5638 before and after the insertion point, and taken to be the inferior headline
5639 level of the two. So if the previous visible heading is level 3 and the
5640 next is level 4 (or vice versa), level 4 will be used for insertion.
5641 This makes sure that the subtree remains an independent subtree and does
5642 not swallow low level entries.
5644 You can also force a different level, either by using a numeric prefix
5645 argument, or by inserting the heading marker by hand. For example, if the
5646 cursor is after \"*****\", then the tree will be shifted to level 5.
5648 If you want to insert the tree as is, just use \\[yank].
5650 If optional TREE is given, use this text instead of the kill ring."
5651 (interactive "P")
5652 (unless (org-kill-is-subtree-p tree)
5653 (error
5654 (substitute-command-keys
5655 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5656 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5657 (^re (concat "^\\(" outline-regexp "\\)"))
5658 (re (concat "\\(" outline-regexp "\\)"))
5659 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5661 (old-level (if (string-match ^re txt)
5662 (- (match-end 0) (match-beginning 0) 1)
5663 -1))
5664 (force-level (cond (level (prefix-numeric-value level))
5665 ((string-match
5666 ^re_ (buffer-substring (point-at-bol) (point)))
5667 (- (match-end 0) (match-beginning 0)))
5668 (t nil)))
5669 (previous-level (save-excursion
5670 (condition-case nil
5671 (progn
5672 (outline-previous-visible-heading 1)
5673 (if (looking-at re)
5674 (- (match-end 0) (match-beginning 0))
5676 (error 1))))
5677 (next-level (save-excursion
5678 (condition-case nil
5679 (progn
5680 (outline-next-visible-heading 1)
5681 (if (looking-at re)
5682 (- (match-end 0) (match-beginning 0))
5684 (error 1))))
5685 (new-level (or force-level (max previous-level next-level)))
5686 (shift (if (or (= old-level -1)
5687 (= new-level -1)
5688 (= old-level new-level))
5690 (- new-level old-level)))
5691 (shift1 shift)
5692 (delta (if (> shift 0) -1 1))
5693 (func (if (> shift 0) 'org-demote 'org-promote))
5694 (org-odd-levels-only nil)
5695 beg end)
5696 ;; Remove the forces level indicator
5697 (if force-level
5698 (delete-region (point-at-bol) (point)))
5699 ;; Make sure we start at the beginning of an empty line
5700 (if (not (bolp)) (insert "\n"))
5701 (if (not (looking-at "[ \t]*$"))
5702 (progn (insert "\n") (backward-char 1)))
5703 ;; Paste
5704 (setq beg (point))
5705 (if (string-match "[ \t\r\n]+\\'" txt)
5706 (setq txt (replace-match "\n" t t txt)))
5707 (insert txt)
5708 (setq end (point))
5709 (if (looking-at "[ \t\r\n]+")
5710 (replace-match "\n"))
5711 (goto-char beg)
5712 ;; Shift if necessary
5713 (if (= shift 0)
5714 (message "Pasted at level %d, without shift" new-level)
5715 (save-restriction
5716 (narrow-to-region beg end)
5717 (while (not (= shift 0))
5718 (org-map-region func (point-min) (point-max))
5719 (setq shift (+ delta shift)))
5720 (goto-char (point-min))
5721 (message "Pasted at level %d, with shift by %d levels"
5722 new-level shift1)))
5723 (if (and kill-ring
5724 (eq org-subtree-clip (current-kill 0))
5725 org-subtree-clip-folded)
5726 ;; The tree was folded before it was killed/copied
5727 (hide-subtree))))
5729 (defun org-kill-is-subtree-p (&optional txt)
5730 "Check if the current kill is an outline subtree, or a set of trees.
5731 Returns nil if kill does not start with a headline, or if the first
5732 headline level is not the largest headline level in the tree.
5733 So this will actually accept several entries of equal levels as well,
5734 which is OK for `org-paste-subtree'.
5735 If optional TXT is given, check this string instead of the current kill."
5736 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5737 (start-level (and kill
5738 (string-match (concat "\\`" outline-regexp) kill)
5739 (- (match-end 0) (match-beginning 0))))
5740 (re (concat "^" outline-regexp))
5741 (start 1))
5742 (if (not start-level)
5743 nil ;; does not even start with a heading
5744 (catch 'exit
5745 (while (setq start (string-match re kill (1+ start)))
5746 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5747 (throw 'exit nil)))
5748 t))))
5750 (defun org-narrow-to-subtree ()
5751 "Narrow buffer to the current subtree."
5752 (interactive)
5753 (save-excursion
5754 (narrow-to-region
5755 (progn (org-back-to-heading) (point))
5756 (progn (org-end-of-subtree t t) (point)))))
5759 ;;; Outline Sorting
5761 (defun org-sort (with-case)
5762 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5763 (interactive "P")
5764 (if (org-at-table-p)
5765 (org-call-with-arg 'org-table-sort-lines with-case)
5766 (org-call-with-arg 'org-sort-entries with-case)))
5768 (defun org-sort-entries (&optional with-case sorting-type)
5769 "Sort entries on a certain level of an outline tree.
5770 If there is an active region, the entries in the region are sorted.
5771 Else, if the cursor is before the first entry, sort the top-level items.
5772 Else, the children of the entry at point are sorted.
5774 Sorting can be alphabetically, numerically, and by date/time as given by
5775 the first time stamp in the entry. The command prompts for the sorting
5776 type unless it has been given to the function through the SORTING-TYPE
5777 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5779 Comparing entries ignores case by default. However, with an optional argument
5780 WITH-CASE, the sorting considers case as well. With two prefix arguments
5781 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5782 (interactive "P")
5783 (let ((unique (equal with-case '(16)))
5784 start beg end entries stars re re2 p nentries (nremoved 0)
5785 last txt what)
5786 ;; Find beginning and end of region to sort
5787 (cond
5788 ((org-region-active-p)
5789 ;; we will sort the region
5790 (setq end (region-end)
5791 what "region")
5792 (goto-char (region-beginning))
5793 (if (not (org-on-heading-p)) (outline-next-heading))
5794 (setq start (point)))
5795 ((or (org-on-heading-p)
5796 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5797 ;; we will sort the children of the current headline
5798 (org-back-to-heading)
5799 (setq start (point) end (org-end-of-subtree) what "children")
5800 (goto-char start)
5801 (show-subtree)
5802 (outline-next-heading))
5804 ;; we will sort the top-level entries in this file
5805 (goto-char (point-min))
5806 (or (org-on-heading-p) (outline-next-heading))
5807 (setq start (point) end (point-max) what "top-level")
5808 (goto-char start)
5809 (show-all)))
5810 (setq beg (point))
5811 (if (>= (point) end) (error "Nothing to sort"))
5812 (looking-at "\\(\\*+\\)")
5813 (setq stars (match-string 1)
5814 re (concat "^" (regexp-quote stars) " +")
5815 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5816 txt (buffer-substring beg end))
5817 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5818 (if (and (not (equal stars "*")) (string-match re2 txt))
5819 (error "Region to sort contains a level above the first entry"))
5820 ;; Make a list that can be sorted.
5821 ;; The car is the string for comparison, the cdr is the subtree
5822 (message "Sorting entries...")
5823 (setq entries
5824 (mapcar
5825 (lambda (x)
5826 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5827 (cons (match-string 0 x) x))
5828 (org-split-string txt re)))
5830 ;; Sort the list
5831 (save-excursion
5832 (goto-char start)
5833 (setq entries (org-do-sort entries what with-case sorting-type)))
5835 ;; Delete the old stuff
5836 (goto-char beg)
5837 (kill-region beg end)
5838 (setq nentries (length entries))
5839 ;; Insert the sorted entries, and remove duplicates if this is required
5840 (while (setq p (pop entries))
5841 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5842 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5843 (insert stars " " (cdr p))))
5844 (goto-char start)
5845 (message "Sorting entries...done (%d entries%s)"
5846 nentries
5847 (if unique (format ", %d duplicates removed" nremoved) ""))))
5849 (defvar org-priority-regexp) ; defined later in the file
5851 (defun org-do-sort (table what &optional with-case sorting-type)
5852 "Sort TABLE of WHAT according to SORTING-TYPE.
5853 The user will be prompted for the SORTING-TYPE if the call to this
5854 function does not specify it. WHAT is only for the prompt, to indicate
5855 what is being sorted. The sorting key will be extracted from
5856 the car of the elements of the table.
5857 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5858 (unless sorting-type
5859 (message
5860 "Sort %s: [a]lphabetic. [n]umeric. [t]ime [p]riority. A/N/T/P means reversed:"
5861 what)
5862 (setq sorting-type (read-char-exclusive)))
5863 (let ((dcst (downcase sorting-type))
5864 extractfun comparefun)
5865 ;; Define the appropriate functions
5866 (cond
5867 ((= dcst ?n)
5868 (setq extractfun 'string-to-number
5869 comparefun (if (= dcst sorting-type) '< '>)))
5870 ((= dcst ?a)
5871 (setq extractfun (if with-case 'identity 'downcase)
5872 comparefun (if (= dcst sorting-type)
5873 'string<
5874 (lambda (a b) (and (not (string< a b))
5875 (not (string= a b)))))))
5876 ((= dcst ?t)
5877 (setq extractfun
5878 (lambda (x)
5879 (if (string-match org-ts-regexp x)
5880 (time-to-seconds
5881 (org-time-string-to-time (match-string 0 x)))
5883 comparefun (if (= dcst sorting-type) '< '>)))
5884 ((= dcst ?p)
5885 (setq extractfun
5886 (lambda (x)
5887 (if (string-match org-priority-regexp x)
5888 (string-to-char (match-string 2 x))
5889 org-default-priority))
5890 comparefun (if (= dcst sorting-type) '< '>)))
5891 (t (error "Invalid sorting type `%c'" sorting-type)))
5893 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5894 table)
5895 (lambda (a b) (funcall comparefun (car a) (car b))))))
5897 ;;;; Plain list items, including checkboxes
5899 ;;; Plain list items
5901 (defun org-at-item-p ()
5902 "Is point in a line starting a hand-formatted item?"
5903 (let ((llt org-plain-list-ordered-item-terminator))
5904 (save-excursion
5905 (goto-char (point-at-bol))
5906 (looking-at
5907 (cond
5908 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5909 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5910 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5911 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5913 (defun org-in-item-p ()
5914 "It the cursor inside a plain list item.
5915 Does not have to be the first line."
5916 (save-excursion
5917 (condition-case nil
5918 (progn
5919 (org-beginning-of-item)
5920 (org-at-item-p)
5922 (error nil))))
5924 (defun org-insert-item (&optional checkbox)
5925 "Insert a new item at the current level.
5926 Return t when things worked, nil when we are not in an item."
5927 (when (save-excursion
5928 (condition-case nil
5929 (progn
5930 (org-beginning-of-item)
5931 (org-at-item-p)
5932 (if (org-invisible-p) (error "Invisible item"))
5934 (error nil)))
5935 (let* ((bul (match-string 0))
5936 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5937 (match-end 0)))
5938 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5939 pos)
5940 (cond
5941 ((and (org-at-item-p) (<= (point) eow))
5942 ;; before the bullet
5943 (beginning-of-line 1)
5944 (open-line (if blank 2 1)))
5945 ((<= (point) eow)
5946 (beginning-of-line 1))
5947 (t (newline (if blank 2 1))))
5948 (insert bul (if checkbox "[ ]" ""))
5949 (just-one-space)
5950 (setq pos (point))
5951 (end-of-line 1)
5952 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5953 (org-maybe-renumber-ordered-list)
5954 (and checkbox (org-update-checkbox-count-maybe))
5957 ;;; Checkboxes
5959 (defun org-at-item-checkbox-p ()
5960 "Is point at a line starting a plain-list item with a checklet?"
5961 (and (org-at-item-p)
5962 (save-excursion
5963 (goto-char (match-end 0))
5964 (skip-chars-forward " \t")
5965 (looking-at "\\[[- X]\\]"))))
5967 (defun org-toggle-checkbox (&optional arg)
5968 "Toggle the checkbox in the current line."
5969 (interactive "P")
5970 (catch 'exit
5971 (let (beg end status (firstnew 'unknown))
5972 (cond
5973 ((org-region-active-p)
5974 (setq beg (region-beginning) end (region-end)))
5975 ((org-on-heading-p)
5976 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5977 ((org-at-item-checkbox-p)
5978 (save-excursion
5979 (replace-match
5980 (cond (arg "[-]")
5981 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5982 (t "[ ]"))
5983 t t))
5984 (throw 'exit t))
5985 (t (error "Not at a checkbox or heading, and no active region")))
5986 (save-excursion
5987 (goto-char beg)
5988 (while (< (point) end)
5989 (when (org-at-item-checkbox-p)
5990 (setq status (equal (match-string 0) "[X]"))
5991 (when (eq firstnew 'unknown)
5992 (setq firstnew (not status)))
5993 (replace-match
5994 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5995 (beginning-of-line 2)))))
5996 (org-update-checkbox-count-maybe))
5998 (defun org-update-checkbox-count-maybe ()
5999 "Update checkbox statistics unless turned off by user."
6000 (when org-provide-checkbox-statistics
6001 (org-update-checkbox-count)))
6003 (defun org-update-checkbox-count (&optional all)
6004 "Update the checkbox statistics in the current section.
6005 This will find all statistic cookies like [57%] and [6/12] and update them
6006 with the current numbers. With optional prefix argument ALL, do this for
6007 the whole buffer."
6008 (interactive "P")
6009 (save-excursion
6010 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6011 (beg (condition-case nil
6012 (progn (outline-back-to-heading) (point))
6013 (error (point-min))))
6014 (end (move-marker (make-marker)
6015 (progn (outline-next-heading) (point))))
6016 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6017 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6018 b1 e1 f1 c-on c-off lim (cstat 0))
6019 (when all
6020 (goto-char (point-min))
6021 (outline-next-heading)
6022 (setq beg (point) end (point-max)))
6023 (goto-char beg)
6024 (while (re-search-forward re end t)
6025 (setq cstat (1+ cstat)
6026 b1 (match-beginning 0)
6027 e1 (match-end 0)
6028 f1 (match-beginning 1)
6029 lim (cond
6030 ((org-on-heading-p) (outline-next-heading) (point))
6031 ((org-at-item-p) (org-end-of-item) (point))
6032 (t nil))
6033 c-on 0 c-off 0)
6034 (goto-char e1)
6035 (when lim
6036 (while (re-search-forward re-box lim t)
6037 (if (member (match-string 2) '("[ ]" "[-]"))
6038 (setq c-off (1+ c-off))
6039 (setq c-on (1+ c-on))))
6040 ; (delete-region b1 e1)
6041 (goto-char b1)
6042 (insert (if f1
6043 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6044 (format "[%d/%d]" c-on (+ c-on c-off))))
6045 (and (looking-at "\\[.*?\\]")
6046 (replace-match ""))))
6047 (when (interactive-p)
6048 (message "Checkbox satistics updated %s (%d places)"
6049 (if all "in entire file" "in current outline entry") cstat)))))
6051 (defun org-get-checkbox-statistics-face ()
6052 "Select the face for checkbox statistics.
6053 The face will be `org-done' when all relevant boxes are checked. Otherwise
6054 it will be `org-todo'."
6055 (if (match-end 1)
6056 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6057 (if (and (> (match-end 2) (match-beginning 2))
6058 (equal (match-string 2) (match-string 3)))
6059 'org-done
6060 'org-todo)))
6062 (defun org-get-indentation (&optional line)
6063 "Get the indentation of the current line, interpreting tabs.
6064 When LINE is given, assume it represents a line and compute its indentation."
6065 (if line
6066 (if (string-match "^ *" (org-remove-tabs line))
6067 (match-end 0))
6068 (save-excursion
6069 (beginning-of-line 1)
6070 (skip-chars-forward " \t")
6071 (current-column))))
6073 (defun org-remove-tabs (s &optional width)
6074 "Replace tabulators in S with spaces.
6075 Assumes that s is a single line, starting in column 0."
6076 (setq width (or width tab-width))
6077 (while (string-match "\t" s)
6078 (setq s (replace-match
6079 (make-string
6080 (- (* width (/ (+ (match-beginning 0) width) width))
6081 (match-beginning 0)) ?\ )
6082 t t s)))
6085 (defun org-fix-indentation (line ind)
6086 "Fix indentation in LINE.
6087 IND is a cons cell with target and minimum indentation.
6088 If the current indenation in LINE is smaller than the minimum,
6089 leave it alone. If it is larger than ind, set it to the target."
6090 (let* ((l (org-remove-tabs line))
6091 (i (org-get-indentation l))
6092 (i1 (car ind)) (i2 (cdr ind)))
6093 (if (>= i i2) (setq l (substring line i2)))
6094 (if (> i1 0)
6095 (concat (make-string i1 ?\ ) l)
6096 l)))
6098 (defcustom org-empty-line-terminates-plain-lists nil
6099 "Non-nil means, an empty line ends all plain list levels.
6100 When nil, empty lines are part of the preceeding item."
6101 :group 'org-plain-lists
6102 :type 'boolean)
6104 (defun org-beginning-of-item ()
6105 "Go to the beginning of the current hand-formatted item.
6106 If the cursor is not in an item, throw an error."
6107 (interactive)
6108 (let ((pos (point))
6109 (limit (save-excursion
6110 (condition-case nil
6111 (progn
6112 (org-back-to-heading)
6113 (beginning-of-line 2) (point))
6114 (error (point-min)))))
6115 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6116 ind ind1)
6117 (if (org-at-item-p)
6118 (beginning-of-line 1)
6119 (beginning-of-line 1)
6120 (skip-chars-forward " \t")
6121 (setq ind (current-column))
6122 (if (catch 'exit
6123 (while t
6124 (beginning-of-line 0)
6125 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6127 (if (looking-at "[ \t]*$")
6128 (setq ind1 ind-empty)
6129 (skip-chars-forward " \t")
6130 (setq ind1 (current-column)))
6131 (if (< ind1 ind)
6132 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6134 (goto-char pos)
6135 (error "Not in an item")))))
6137 (defun org-end-of-item ()
6138 "Go to the end of the current hand-formatted item.
6139 If the cursor is not in an item, throw an error."
6140 (interactive)
6141 (let* ((pos (point))
6142 ind1
6143 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6144 (limit (save-excursion (outline-next-heading) (point)))
6145 (ind (save-excursion
6146 (org-beginning-of-item)
6147 (skip-chars-forward " \t")
6148 (current-column)))
6149 (end (catch 'exit
6150 (while t
6151 (beginning-of-line 2)
6152 (if (eobp) (throw 'exit (point)))
6153 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6154 (if (looking-at "[ \t]*$")
6155 (setq ind1 ind-empty)
6156 (skip-chars-forward " \t")
6157 (setq ind1 (current-column)))
6158 (if (<= ind1 ind)
6159 (throw 'exit (point-at-bol)))))))
6160 (if end
6161 (goto-char end)
6162 (goto-char pos)
6163 (error "Not in an item"))))
6165 (defun org-next-item ()
6166 "Move to the beginning of the next item in the current plain list.
6167 Error if not at a plain list, or if this is the last item in the list."
6168 (interactive)
6169 (let (ind ind1 (pos (point)))
6170 (org-beginning-of-item)
6171 (setq ind (org-get-indentation))
6172 (org-end-of-item)
6173 (setq ind1 (org-get-indentation))
6174 (unless (and (org-at-item-p) (= ind ind1))
6175 (goto-char pos)
6176 (error "On last item"))))
6178 (defun org-previous-item ()
6179 "Move to the beginning of the previous item in the current plain list.
6180 Error if not at a plain list, or if this is the first item in the list."
6181 (interactive)
6182 (let (beg ind ind1 (pos (point)))
6183 (org-beginning-of-item)
6184 (setq beg (point))
6185 (setq ind (org-get-indentation))
6186 (goto-char beg)
6187 (catch 'exit
6188 (while t
6189 (beginning-of-line 0)
6190 (if (looking-at "[ \t]*$")
6192 (if (<= (setq ind1 (org-get-indentation)) ind)
6193 (throw 'exit t)))))
6194 (condition-case nil
6195 (if (or (not (org-at-item-p))
6196 (< ind1 (1- ind)))
6197 (error "")
6198 (org-beginning-of-item))
6199 (error (goto-char pos)
6200 (error "On first item")))))
6202 (defun org-move-item-down ()
6203 "Move the plain list item at point down, i.e. swap with following item.
6204 Subitems (items with larger indentation) are considered part of the item,
6205 so this really moves item trees."
6206 (interactive)
6207 (let (beg end ind ind1 (pos (point)) txt)
6208 (org-beginning-of-item)
6209 (setq beg (point))
6210 (setq ind (org-get-indentation))
6211 (org-end-of-item)
6212 (setq end (point))
6213 (setq ind1 (org-get-indentation))
6214 (if (and (org-at-item-p) (= ind ind1))
6215 (progn
6216 (org-end-of-item)
6217 (setq txt (buffer-substring beg end))
6218 (save-excursion
6219 (delete-region beg end))
6220 (setq pos (point))
6221 (insert txt)
6222 (goto-char pos)
6223 (org-maybe-renumber-ordered-list))
6224 (goto-char pos)
6225 (error "Cannot move this item further down"))))
6227 (defun org-move-item-up (arg)
6228 "Move the plain list item at point up, i.e. swap with previous item.
6229 Subitems (items with larger indentation) are considered part of the item,
6230 so this really moves item trees."
6231 (interactive "p")
6232 (let (beg end ind ind1 (pos (point)) txt)
6233 (org-beginning-of-item)
6234 (setq beg (point))
6235 (setq ind (org-get-indentation))
6236 (org-end-of-item)
6237 (setq end (point))
6238 (goto-char beg)
6239 (catch 'exit
6240 (while t
6241 (beginning-of-line 0)
6242 (if (looking-at "[ \t]*$")
6243 (if org-empty-line-terminates-plain-lists
6244 (progn
6245 (goto-char pos)
6246 (error "Cannot move this item further up"))
6247 nil)
6248 (if (<= (setq ind1 (org-get-indentation)) ind)
6249 (throw 'exit t)))))
6250 (condition-case nil
6251 (org-beginning-of-item)
6252 (error (goto-char beg)
6253 (error "Cannot move this item further up")))
6254 (setq ind1 (org-get-indentation))
6255 (if (and (org-at-item-p) (= ind ind1))
6256 (progn
6257 (setq txt (buffer-substring beg end))
6258 (save-excursion
6259 (delete-region beg end))
6260 (setq pos (point))
6261 (insert txt)
6262 (goto-char pos)
6263 (org-maybe-renumber-ordered-list))
6264 (goto-char pos)
6265 (error "Cannot move this item further up"))))
6267 (defun org-maybe-renumber-ordered-list ()
6268 "Renumber the ordered list at point if setup allows it.
6269 This tests the user option `org-auto-renumber-ordered-lists' before
6270 doing the renumbering."
6271 (interactive)
6272 (when (and org-auto-renumber-ordered-lists
6273 (org-at-item-p))
6274 (if (match-beginning 3)
6275 (org-renumber-ordered-list 1)
6276 (org-fix-bullet-type 1))))
6278 (defun org-maybe-renumber-ordered-list-safe ()
6279 (condition-case nil
6280 (save-excursion
6281 (org-maybe-renumber-ordered-list))
6282 (error nil)))
6284 (defun org-cycle-list-bullet (&optional which)
6285 "Cycle through the different itemize/enumerate bullets.
6286 This cycle the entire list level through the sequence:
6288 `-' -> `+' -> `*' -> `1.' -> `1)'
6290 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6291 0 meand `-', 1 means `+' etc."
6292 (interactive "P")
6293 (org-preserve-lc
6294 (org-beginning-of-item-list)
6295 (org-at-item-p)
6296 (beginning-of-line 1)
6297 (let ((current (match-string 0)) new)
6298 (setq new (cond
6299 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6300 ((string-match "-" current) "+")
6301 ((string-match "\\+" current)
6302 (if (looking-at "\\S-") "1." "*"))
6303 ((string-match "\\*" current) "1.")
6304 ((string-match "\\." current) "1)")
6305 ((string-match ")" current) "-")
6306 (t (error "This should not happen"))))
6307 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6308 (org-fix-bullet-type 1)
6309 (org-maybe-renumber-ordered-list))))
6311 (defun org-get-string-indentation (s)
6312 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6313 (let ((n -1) (i 0) (w tab-width) c)
6314 (catch 'exit
6315 (while (< (setq n (1+ n)) (length s))
6316 (setq c (aref s n))
6317 (cond ((= c ?\ ) (setq i (1+ i)))
6318 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6319 (t (throw 'exit t)))))
6322 (defun org-renumber-ordered-list (arg)
6323 "Renumber an ordered plain list.
6324 Cursor needs to be in the first line of an item, the line that starts
6325 with something like \"1.\" or \"2)\"."
6326 (interactive "p")
6327 (unless (and (org-at-item-p)
6328 (match-beginning 3))
6329 (error "This is not an ordered list"))
6330 (let ((line (org-current-line))
6331 (col (current-column))
6332 (ind (org-get-string-indentation
6333 (buffer-substring (point-at-bol) (match-beginning 3))))
6334 ;; (term (substring (match-string 3) -1))
6335 ind1 (n (1- arg))
6336 fmt)
6337 ;; find where this list begins
6338 (org-beginning-of-item-list)
6339 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6340 (setq fmt (concat "%d" (match-string 1)))
6341 (beginning-of-line 0)
6342 ;; walk forward and replace these numbers
6343 (catch 'exit
6344 (while t
6345 (catch 'next
6346 (beginning-of-line 2)
6347 (if (eobp) (throw 'exit nil))
6348 (if (looking-at "[ \t]*$") (throw 'next nil))
6349 (skip-chars-forward " \t") (setq ind1 (current-column))
6350 (if (> ind1 ind) (throw 'next t))
6351 (if (< ind1 ind) (throw 'exit t))
6352 (if (not (org-at-item-p)) (throw 'exit nil))
6353 (delete-region (match-beginning 2) (match-end 2))
6354 (goto-char (match-beginning 2))
6355 (insert (format fmt (setq n (1+ n)))))))
6356 (goto-line line)
6357 (move-to-column col)))
6359 (defun org-fix-bullet-type (arg)
6360 "Make sure all items in this list have the same bullet."
6361 (interactive "p")
6362 (unless (org-at-item-p) (error "This is not a list"))
6363 (let ((line (org-current-line))
6364 (col (current-column))
6365 (ind (current-indentation))
6366 ind1 bullet)
6367 ;; find where this list begins
6368 (org-beginning-of-item-list)
6369 (beginning-of-line 1)
6370 ;; find out what the bullet type is
6371 (looking-at "[ \t]*\\(\\S-+\\)")
6372 (setq bullet (match-string 1))
6373 ;; walk forward and replace these numbers
6374 (beginning-of-line 0)
6375 (catch 'exit
6376 (while t
6377 (catch 'next
6378 (beginning-of-line 2)
6379 (if (eobp) (throw 'exit nil))
6380 (if (looking-at "[ \t]*$") (throw 'next nil))
6381 (skip-chars-forward " \t") (setq ind1 (current-column))
6382 (if (> ind1 ind) (throw 'next t))
6383 (if (< ind1 ind) (throw 'exit t))
6384 (if (not (org-at-item-p)) (throw 'exit nil))
6385 (skip-chars-forward " \t")
6386 (looking-at "\\S-+")
6387 (replace-match bullet))))
6388 (goto-line line)
6389 (move-to-column col)
6390 (if (string-match "[0-9]" bullet)
6391 (org-renumber-ordered-list 1))))
6393 (defun org-beginning-of-item-list ()
6394 "Go to the beginning of the current item list.
6395 I.e. to the first item in this list."
6396 (interactive)
6397 (org-beginning-of-item)
6398 (let ((pos (point-at-bol))
6399 (ind (org-get-indentation))
6400 ind1)
6401 ;; find where this list begins
6402 (catch 'exit
6403 (while t
6404 (catch 'next
6405 (beginning-of-line 0)
6406 (if (looking-at "[ \t]*$")
6407 (throw (if (bobp) 'exit 'next) t))
6408 (skip-chars-forward " \t") (setq ind1 (current-column))
6409 (if (or (< ind1 ind)
6410 (and (= ind1 ind)
6411 (not (org-at-item-p)))
6412 (bobp))
6413 (throw 'exit t)
6414 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6415 (goto-char pos)))
6417 (defvar org-last-indent-begin-marker (make-marker))
6418 (defvar org-last-indent-end-marker (make-marker))
6420 (defun org-outdent-item (arg)
6421 "Outdent a local list item."
6422 (interactive "p")
6423 (org-indent-item (- arg)))
6425 (defun org-indent-item (arg)
6426 "Indent a local list item."
6427 (interactive "p")
6428 (unless (org-at-item-p)
6429 (error "Not on an item"))
6430 (save-excursion
6431 (let (beg end ind ind1 tmp delta ind-down ind-up)
6432 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6433 (setq beg org-last-indent-begin-marker
6434 end org-last-indent-end-marker)
6435 (org-beginning-of-item)
6436 (setq beg (move-marker org-last-indent-begin-marker (point)))
6437 (org-end-of-item)
6438 (setq end (move-marker org-last-indent-end-marker (point))))
6439 (goto-char beg)
6440 (setq tmp (org-item-indent-positions)
6441 ind (car tmp)
6442 ind-down (nth 2 tmp)
6443 ind-up (nth 1 tmp)
6444 delta (if (> arg 0)
6445 (if ind-down (- ind-down ind) 2)
6446 (if ind-up (- ind-up ind) -2)))
6447 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6448 (while (< (point) end)
6449 (beginning-of-line 1)
6450 (skip-chars-forward " \t") (setq ind1 (current-column))
6451 (delete-region (point-at-bol) (point))
6452 (or (eolp) (indent-to-column (+ ind1 delta)))
6453 (beginning-of-line 2))))
6454 (org-maybe-renumber-ordered-list-safe)
6455 (save-excursion
6456 (beginning-of-line 0)
6457 (condition-case nil (org-beginning-of-item) (error nil))
6458 (org-maybe-renumber-ordered-list-safe)))
6461 (defun org-item-indent-positions ()
6462 "Assumes cursor in item line. FIXME"
6463 (let* ((bolpos (point-at-bol))
6464 (ind (org-get-indentation))
6465 ind-down ind-up pos)
6466 (save-excursion
6467 (org-beginning-of-item-list)
6468 (skip-chars-backward "\n\r \t")
6469 (when (org-in-item-p)
6470 (org-beginning-of-item)
6471 (setq ind-up (org-get-indentation))))
6472 (setq pos (point))
6473 (save-excursion
6474 (cond
6475 ((and (condition-case nil (progn (org-previous-item) t)
6476 (error nil))
6477 (or (forward-char 1) t)
6478 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6479 (setq ind-down (org-get-indentation)))
6480 ((and (goto-char pos)
6481 (org-at-item-p))
6482 (goto-char (match-end 0))
6483 (skip-chars-forward " \t")
6484 (setq ind-down (current-column)))))
6485 (list ind ind-up ind-down)))
6487 ;;; The orgstruct minor mode
6489 ;; Define a minor mode which can be used in other modes in order to
6490 ;; integrate the org-mode structure editing commands.
6492 ;; This is really a hack, because the org-mode structure commands use
6493 ;; keys which normally belong to the major mode. Here is how it
6494 ;; works: The minor mode defines all the keys necessary to operate the
6495 ;; structure commands, but wraps the commands into a function which
6496 ;; tests if the cursor is currently at a headline or a plain list
6497 ;; item. If that is the case, the structure command is used,
6498 ;; temporarily setting many Org-mode variables like regular
6499 ;; expressions for filling etc. However, when any of those keys is
6500 ;; used at a different location, function uses `key-binding' to look
6501 ;; up if the key has an associated command in another currently active
6502 ;; keymap (minor modes, major mode, global), and executes that
6503 ;; command. There might be problems if any of the keys is otherwise
6504 ;; used as a prefix key.
6506 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6507 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6508 ;; addresses this by checking explicitly for both bindings.
6510 (defvar orgstruct-mode-map (make-sparse-keymap)
6511 "Keymap for the minor `orgstruct-mode'.")
6513 ;;;###autoload
6514 (define-minor-mode orgstruct-mode
6515 "Toggle the minor more `orgstruct-mode'.
6516 This mode is for using Org-mode structure commands in other modes.
6517 The following key behave as if Org-mode was active, if the cursor
6518 is on a headline, or on a plain list item (both in the definition
6519 of Org-mode).
6521 M-up Move entry/item up
6522 M-down Move entry/item down
6523 M-left Promote
6524 M-right Demote
6525 M-S-up Move entry/item up
6526 M-S-down Move entry/item down
6527 M-S-left Promote subtree
6528 M-S-right Demote subtree
6529 M-q Fill paragraph and items like in Org-mode
6530 C-c ^ Sort entries
6531 C-c - Cycle list bullet
6532 TAB Cycle item visibility
6533 M-RET Insert new heading/item
6534 S-M-RET Insert new TODO heading / Chekbox item
6535 C-c C-c Set tags / toggle checkbox"
6536 nil " OrgStruct" nil
6537 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6539 ;;;###autoload
6540 (defun turn-on-orgstruct ()
6541 "Unconditionally turn on `orgstruct-mode'."
6542 (orgstruct-mode 1))
6544 (defun orgstruct-error ()
6545 "Error when there is no default binding for a structure key."
6546 (interactive)
6547 (error "This key is has no function outside structure elements"))
6549 (defvar org-local-vars nil
6550 "List of local variables, for use by `orgstruct-mode'")
6552 (defun orgstruct-setup ()
6553 "Setup orgstruct keymaps."
6554 (let ((nfunc 0)
6555 (bindings
6556 (list
6557 '([(meta up)] org-metaup)
6558 '([(meta down)] org-metadown)
6559 '([(meta left)] org-metaleft)
6560 '([(meta right)] org-metaright)
6561 '([(meta shift up)] org-shiftmetaup)
6562 '([(meta shift down)] org-shiftmetadown)
6563 '([(meta shift left)] org-shiftmetaleft)
6564 '([(meta shift right)] org-shiftmetaright)
6565 '([(shift up)] org-shiftup)
6566 '([(shift down)] org-shiftdown)
6567 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6568 '("\M-q" fill-paragraph)
6569 '("\C-c^" org-sort)
6570 '("\C-c-" org-cycle-list-bullet)))
6571 elt key fun cmd)
6572 (while (setq elt (pop bindings))
6573 (setq nfunc (1+ nfunc))
6574 (setq key (org-key (car elt))
6575 fun (nth 1 elt)
6576 cmd (orgstruct-make-binding fun nfunc key))
6577 (org-defkey orgstruct-mode-map key cmd))
6579 ;; Special treatment needed for TAB and RET
6580 (org-defkey orgstruct-mode-map [(tab)]
6581 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6582 (org-defkey orgstruct-mode-map "\C-i"
6583 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6585 (org-defkey orgstruct-mode-map "\M-\C-m"
6586 (orgstruct-make-binding 'org-insert-heading 105
6587 "\M-\C-m" [(meta return)]))
6588 (org-defkey orgstruct-mode-map [(meta return)]
6589 (orgstruct-make-binding 'org-insert-heading 106
6590 [(meta return)] "\M-\C-m"))
6592 (org-defkey orgstruct-mode-map [(shift meta return)]
6593 (orgstruct-make-binding 'org-insert-todo-heading 107
6594 [(meta return)] "\M-\C-m"))
6596 (unless org-local-vars
6597 (setq org-local-vars (org-get-local-variables)))
6601 (defun orgstruct-make-binding (fun n &rest keys)
6602 "Create a function for binding in the structure minor mode.
6603 FUN is the command to call inside a table. N is used to create a unique
6604 command name. KEYS are keys that should be checked in for a command
6605 to execute outside of tables."
6606 (eval
6607 (list 'defun
6608 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6609 '(arg)
6610 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6611 "Outside of structure, run the binding of `"
6612 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6613 "'.")
6614 '(interactive "p")
6615 (list 'if
6616 '(org-context-p 'headline 'item)
6617 (list 'org-run-like-in-org-mode (list 'quote fun))
6618 (list 'let '(orgstruct-mode)
6619 (list 'call-interactively
6620 (append '(or)
6621 (mapcar (lambda (k)
6622 (list 'key-binding k))
6623 keys)
6624 '('orgstruct-error))))))))
6626 (defun org-context-p (&rest contexts)
6627 "FIXME:"
6628 (let ((pos (point)))
6629 (goto-char (point-at-bol))
6630 (prog1 (or (and (memq 'table contexts)
6631 (looking-at "[ \t]*|"))
6632 (and (memq 'headline contexts)
6633 (looking-at "\\*+"))
6634 (and (memq 'item contexts)
6635 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6636 (goto-char pos))))
6638 (defun org-get-local-variables ()
6639 "Return a list of all local variables in an org-mode buffer."
6640 (let (varlist)
6641 (with-current-buffer (get-buffer-create "*Org tmp*")
6642 (erase-buffer)
6643 (org-mode)
6644 (setq varlist (buffer-local-variables)))
6645 (kill-buffer "*Org tmp*")
6646 (delq nil
6647 (mapcar
6648 (lambda (x)
6649 (setq x
6650 (if (symbolp x)
6651 (list x)
6652 (list (car x) (list 'quote (cdr x)))))
6653 (if (string-match
6654 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6655 (symbol-name (car x)))
6656 x nil))
6657 varlist))))
6659 ;;;###autoload
6660 (defun org-run-like-in-org-mode (cmd)
6661 (unless org-local-vars
6662 (setq org-local-vars (org-get-local-variables)))
6663 (eval (list 'let org-local-vars
6664 (list 'call-interactively (list 'quote cmd)))))
6666 ;;;; Archiving
6668 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6670 (defun org-archive-subtree (&optional find-done)
6671 "Move the current subtree to the archive.
6672 The archive can be a certain top-level heading in the current file, or in
6673 a different file. The tree will be moved to that location, the subtree
6674 heading be marked DONE, and the current time will be added.
6676 When called with prefix argument FIND-DONE, find whole trees without any
6677 open TODO items and archive them (after getting confirmation from the user).
6678 If the cursor is not at a headline when this comand is called, try all level
6679 1 trees. If the cursor is on a headline, only try the direct children of
6680 this heading."
6681 (interactive "P")
6682 (if find-done
6683 (org-archive-all-done)
6684 ;; Save all relevant TODO keyword-relatex variables
6686 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6687 (tr-org-todo-keywords-1 org-todo-keywords-1)
6688 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6689 (tr-org-done-keywords org-done-keywords)
6690 (tr-org-todo-regexp org-todo-regexp)
6691 (tr-org-todo-line-regexp org-todo-line-regexp)
6692 (tr-org-odd-levels-only org-odd-levels-only)
6693 (this-buffer (current-buffer))
6694 (org-archive-location org-archive-location)
6695 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6696 (file (abbreviate-file-name (buffer-file-name)))
6697 (time (format-time-string
6698 (substring (cdr org-time-stamp-formats) 1 -1)
6699 (current-time)))
6700 afile heading buffer level newfile-p
6701 category todo priority ltags itags)
6703 ;; Try to find a local archive location
6704 (save-excursion
6705 (save-restriction
6706 (widen)
6707 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6708 (setq org-archive-location (match-string 1)))))
6710 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6711 (progn
6712 (setq afile (format (match-string 1 org-archive-location)
6713 (file-name-nondirectory buffer-file-name))
6714 heading (match-string 2 org-archive-location)))
6715 (error "Invalid `org-archive-location'"))
6716 (if (> (length afile) 0)
6717 (setq newfile-p (not (file-exists-p afile))
6718 buffer (find-file-noselect afile))
6719 (setq buffer (current-buffer)))
6720 (unless buffer
6721 (error "Cannot access file \"%s\"" afile))
6722 (if (and (> (length heading) 0)
6723 (string-match "^\\*+" heading))
6724 (setq level (match-end 0))
6725 (setq heading nil level 0))
6726 (save-excursion
6727 (org-back-to-heading t)
6728 ;; Get context information that will be lost by moving the tree
6729 (setq category (org-get-category)
6730 todo (and (looking-at org-todo-line-regexp)
6731 (match-string 2))
6732 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
6733 ltags (org-split-string (org-get-tags) ":")
6734 itags (org-delete-all ltags (org-get-tags-at)))
6735 (setq ltags (mapconcat 'identity ltags " ")
6736 itags (mapconcat 'identity itags " "))
6737 ;; We first only copy, in case something goes wrong
6738 ;; we need to protect this-command, to avoid kill-region sets it,
6739 ;; which would lead to duplication of subtrees
6740 (let (this-command) (org-copy-subtree))
6741 (set-buffer buffer)
6742 ;; Enforce org-mode for the archive buffer
6743 (if (not (org-mode-p))
6744 ;; Force the mode for future visits.
6745 (let ((org-insert-mode-line-in-empty-file t)
6746 (org-inhibit-startup t))
6747 (call-interactively 'org-mode)))
6748 (when newfile-p
6749 (goto-char (point-max))
6750 (insert (format "\nArchived entries from file %s\n\n"
6751 (buffer-file-name this-buffer))))
6752 ;; Force the TODO keywords of the original buffer
6753 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6754 (org-todo-keywords-1 tr-org-todo-keywords-1)
6755 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6756 (org-done-keywords tr-org-done-keywords)
6757 (org-todo-regexp tr-org-todo-regexp)
6758 (org-todo-line-regexp tr-org-todo-line-regexp)
6759 (org-odd-levels-only
6760 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6761 org-odd-levels-only
6762 tr-org-odd-levels-only)))
6763 (goto-char (point-min))
6764 (if heading
6765 (progn
6766 (if (re-search-forward
6767 (concat "^" (regexp-quote heading)
6768 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6769 nil t)
6770 (goto-char (match-end 0))
6771 ;; Heading not found, just insert it at the end
6772 (goto-char (point-max))
6773 (or (bolp) (insert "\n"))
6774 (insert "\n" heading "\n")
6775 (end-of-line 0))
6776 ;; Make the subtree visible
6777 (show-subtree)
6778 (org-end-of-subtree t)
6779 (skip-chars-backward " \t\r\n")
6780 (and (looking-at "[ \t\r\n]*")
6781 (replace-match "\n\n")))
6782 ;; No specific heading, just go to end of file.
6783 (goto-char (point-max)) (insert "\n"))
6784 ;; Paste
6785 (org-paste-subtree (org-get-legal-level level 1))
6787 ;; Mark the entry as done
6788 (when (and org-archive-mark-done
6789 (looking-at org-todo-line-regexp)
6790 (or (not (match-end 2))
6791 (not (member (match-string 2) org-done-keywords))))
6792 (let (org-log-done)
6793 (org-todo
6794 (car (or (member org-archive-mark-done org-done-keywords)
6795 org-done-keywords)))))
6797 ;; Add the context info
6798 (when org-archive-save-context-info
6799 (let ((l org-archive-save-context-info) e n v)
6800 (while (setq e (pop l))
6801 (when (and (setq v (symbol-value e))
6802 (stringp v) (string-match "\\S-" v))
6803 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
6804 (org-entry-put (point) n v)))))
6806 ;; Save the buffer, if it is not the same buffer.
6807 (if (not (eq this-buffer buffer)) (save-buffer))))
6808 ;; Here we are back in the original buffer. Everything seems to have
6809 ;; worked. So now cut the tree and finish up.
6810 (let (this-command) (org-cut-subtree))
6811 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6812 (message "Subtree archived %s"
6813 (if (eq this-buffer buffer)
6814 (concat "under heading: " heading)
6815 (concat "in file: " (abbreviate-file-name afile)))))))
6817 (defun org-archive-all-done (&optional tag)
6818 "Archive sublevels of the current tree without open TODO items.
6819 If the cursor is not on a headline, try all level 1 trees. If
6820 it is on a headline, try all direct children.
6821 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6822 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6823 (rea (concat ".*:" org-archive-tag ":"))
6824 (begm (make-marker))
6825 (endm (make-marker))
6826 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6827 "Move subtree to archive (no open TODO items)? "))
6828 beg end (cntarch 0))
6829 (if (org-on-heading-p)
6830 (progn
6831 (setq re1 (concat "^" (regexp-quote
6832 (make-string
6833 (1+ (- (match-end 0) (match-beginning 0)))
6834 ?*))
6835 " "))
6836 (move-marker begm (point))
6837 (move-marker endm (org-end-of-subtree t)))
6838 (setq re1 "^* ")
6839 (move-marker begm (point-min))
6840 (move-marker endm (point-max)))
6841 (save-excursion
6842 (goto-char begm)
6843 (while (re-search-forward re1 endm t)
6844 (setq beg (match-beginning 0)
6845 end (save-excursion (org-end-of-subtree t) (point)))
6846 (goto-char beg)
6847 (if (re-search-forward re end t)
6848 (goto-char end)
6849 (goto-char beg)
6850 (if (and (or (not tag) (not (looking-at rea)))
6851 (y-or-n-p question))
6852 (progn
6853 (if tag
6854 (org-toggle-tag org-archive-tag 'on)
6855 (org-archive-subtree))
6856 (setq cntarch (1+ cntarch)))
6857 (goto-char end)))))
6858 (message "%d trees archived" cntarch)))
6860 (defun org-cycle-hide-drawers (state)
6861 "Re-hide all drawers after a visibility state change."
6862 (when (and (org-mode-p)
6863 (not (memq state '(overview folded))))
6864 (save-excursion
6865 (let* ((globalp (memq state '(contents all)))
6866 (beg (if globalp (point-min) (point)))
6867 (end (if globalp (point-max) (org-end-of-subtree t))))
6868 (goto-char beg)
6869 (while (re-search-forward org-drawer-regexp end t)
6870 (org-flag-drawer t))))))
6872 (defun org-flag-drawer (flag)
6873 (save-excursion
6874 (beginning-of-line 1)
6875 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6876 (let ((b (match-end 0)))
6877 (if (re-search-forward
6878 "^[ \t]*:END:"
6879 (save-excursion (outline-next-heading) (point)) t)
6880 (outline-flag-region b (point-at-eol) flag)
6881 (error ":END: line missing"))))))
6883 (defun org-cycle-hide-archived-subtrees (state)
6884 "Re-hide all archived subtrees after a visibility state change."
6885 (when (and (not org-cycle-open-archived-trees)
6886 (not (memq state '(overview folded))))
6887 (save-excursion
6888 (let* ((globalp (memq state '(contents all)))
6889 (beg (if globalp (point-min) (point)))
6890 (end (if globalp (point-max) (org-end-of-subtree t))))
6891 (org-hide-archived-subtrees beg end)
6892 (goto-char beg)
6893 (if (looking-at (concat ".*:" org-archive-tag ":"))
6894 (message (substitute-command-keys
6895 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6897 (defun org-force-cycle-archived ()
6898 "Cycle subtree even if it is archived."
6899 (interactive)
6900 (setq this-command 'org-cycle)
6901 (let ((org-cycle-open-archived-trees t))
6902 (call-interactively 'org-cycle)))
6904 (defun org-hide-archived-subtrees (beg end)
6905 "Re-hide all archived subtrees after a visibility state change."
6906 (save-excursion
6907 (let* ((re (concat ":" org-archive-tag ":")))
6908 (goto-char beg)
6909 (while (re-search-forward re end t)
6910 (and (org-on-heading-p) (hide-subtree))
6911 (org-end-of-subtree t)))))
6913 (defun org-toggle-tag (tag &optional onoff)
6914 "Toggle the tag TAG for the current line.
6915 If ONOFF is `on' or `off', don't toggle but set to this state."
6916 (unless (org-on-heading-p t) (error "Not on headling"))
6917 (let (res current)
6918 (save-excursion
6919 (beginning-of-line)
6920 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6921 (point-at-eol) t)
6922 (progn
6923 (setq current (match-string 1))
6924 (replace-match ""))
6925 (setq current ""))
6926 (setq current (nreverse (org-split-string current ":")))
6927 (cond
6928 ((eq onoff 'on)
6929 (setq res t)
6930 (or (member tag current) (push tag current)))
6931 ((eq onoff 'off)
6932 (or (not (member tag current)) (setq current (delete tag current))))
6933 (t (if (member tag current)
6934 (setq current (delete tag current))
6935 (setq res t)
6936 (push tag current))))
6937 (end-of-line 1)
6938 (when current
6939 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6940 (org-set-tags nil t))
6941 res))
6943 (defun org-toggle-archive-tag (&optional arg)
6944 "Toggle the archive tag for the current headline.
6945 With prefix ARG, check all children of current headline and offer tagging
6946 the children that do not contain any open TODO items."
6947 (interactive "P")
6948 (if arg
6949 (org-archive-all-done 'tag)
6950 (let (set)
6951 (save-excursion
6952 (org-back-to-heading t)
6953 (setq set (org-toggle-tag org-archive-tag))
6954 (when set (hide-subtree)))
6955 (and set (beginning-of-line 1))
6956 (message "Subtree %s" (if set "archived" "unarchived")))))
6959 ;;;; Tables
6961 ;;; The table editor
6963 ;; Watch out: Here we are talking about two different kind of tables.
6964 ;; Most of the code is for the tables created with the Org-mode table editor.
6965 ;; Sometimes, we talk about tables created and edited with the table.el
6966 ;; Emacs package. We call the former org-type tables, and the latter
6967 ;; table.el-type tables.
6969 (defun org-before-change-function (beg end)
6970 "Every change indicates that a table might need an update."
6971 (setq org-table-may-need-update t))
6973 (defconst org-table-line-regexp "^[ \t]*|"
6974 "Detects an org-type table line.")
6975 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6976 "Detects an org-type table line.")
6977 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6978 "Detects a table line marked for automatic recalculation.")
6979 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6980 "Detects a table line marked for automatic recalculation.")
6981 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6982 "Detects a table line marked for automatic recalculation.")
6983 (defconst org-table-hline-regexp "^[ \t]*|-"
6984 "Detects an org-type table hline.")
6985 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6986 "Detects a table-type table hline.")
6987 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6988 "Detects an org-type or table-type table.")
6989 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6990 "Searching from within a table (any type) this finds the first line
6991 outside the table.")
6992 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6993 "Searching from within a table (any type) this finds the first line
6994 outside the table.")
6996 (defvar org-table-last-highlighted-reference nil)
6997 (defvar org-table-formula-history nil)
6999 (defvar org-table-column-names nil
7000 "Alist with column names, derived from the `!' line.")
7001 (defvar org-table-column-name-regexp nil
7002 "Regular expression matching the current column names.")
7003 (defvar org-table-local-parameters nil
7004 "Alist with parameter names, derived from the `$' line.")
7005 (defvar org-table-named-field-locations nil
7006 "Alist with locations of named fields.")
7008 (defvar org-table-current-line-types nil
7009 "Table row types, non-nil only for the duration of a comand.")
7010 (defvar org-table-current-begin-line nil
7011 "Table begin line, non-nil only for the duration of a comand.")
7012 (defvar org-table-current-begin-pos nil
7013 "Table begin position, non-nil only for the duration of a comand.")
7014 (defvar org-table-dlines nil
7015 "Vector of data line line numbers in the current table.")
7016 (defvar org-table-hlines nil
7017 "Vector of hline line numbers in the current table.")
7019 (defconst org-table-range-regexp
7020 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7021 ;; 1 2 3 4 5
7022 "Regular expression for matching ranges in formulas.")
7024 (defconst org-table-range-regexp2
7025 (concat
7026 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7027 "\\.\\."
7028 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7029 "Match a range for reference display.")
7031 (defconst org-table-translate-regexp
7032 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7033 "Match a reference that needs translation, for reference display.")
7035 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7037 (defun org-table-create-with-table.el ()
7038 "Use the table.el package to insert a new table.
7039 If there is already a table at point, convert between Org-mode tables
7040 and table.el tables."
7041 (interactive)
7042 (require 'table)
7043 (cond
7044 ((org-at-table.el-p)
7045 (if (y-or-n-p "Convert table to Org-mode table? ")
7046 (org-table-convert)))
7047 ((org-at-table-p)
7048 (if (y-or-n-p "Convert table to table.el table? ")
7049 (org-table-convert)))
7050 (t (call-interactively 'table-insert))))
7052 (defun org-table-create-or-convert-from-region (arg)
7053 "Convert region to table, or create an empty table.
7054 If there is an active region, convert it to a table, using the function
7055 `org-table-convert-region'.
7056 If there is no such region, create an empty table with `org-table-create'."
7057 (interactive "P")
7058 (if (org-region-active-p)
7059 (org-table-convert-region (region-beginning) (region-end) arg)
7060 (org-table-create arg)))
7062 (defun org-table-create (&optional size)
7063 "Query for a size and insert a table skeleton.
7064 SIZE is a string Columns x Rows like for example \"3x2\"."
7065 (interactive "P")
7066 (unless size
7067 (setq size (read-string
7068 (concat "Table size Columns x Rows [e.g. "
7069 org-table-default-size "]: ")
7070 "" nil org-table-default-size)))
7072 (let* ((pos (point))
7073 (indent (make-string (current-column) ?\ ))
7074 (split (org-split-string size " *x *"))
7075 (rows (string-to-number (nth 1 split)))
7076 (columns (string-to-number (car split)))
7077 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7078 "\n")))
7079 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7080 (point-at-bol) (point)))
7081 (beginning-of-line 1)
7082 (newline))
7083 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7084 (dotimes (i rows) (insert line))
7085 (goto-char pos)
7086 (if (> rows 1)
7087 ;; Insert a hline after the first row.
7088 (progn
7089 (end-of-line 1)
7090 (insert "\n|-")
7091 (goto-char pos)))
7092 (org-table-align)))
7094 (defun org-table-convert-region (beg0 end0 &optional nspace)
7095 "Convert region to a table.
7096 The region goes from BEG0 to END0, but these borders will be moved
7097 slightly, to make sure a beginning of line in the first line is included.
7098 When NSPACE is non-nil, it indicates the minimum number of spaces that
7099 separate columns. By default, the function first checks if every line
7100 contains at lease one TAB. If yes, it assumes that the material is TAB
7101 separated. If not, it assumes a single space as separator."
7102 (interactive "rP")
7103 (let* ((beg (min beg0 end0))
7104 (end (max beg0 end0))
7105 (tabsep t)
7107 (goto-char beg)
7108 (beginning-of-line 1)
7109 (setq beg (move-marker (make-marker) (point)))
7110 (goto-char end)
7111 (if (bolp) (backward-char 1) (end-of-line 1))
7112 (setq end (move-marker (make-marker) (point)))
7113 ;; Lets see if this is tab-separated material. If every nonempty line
7114 ;; contains a tab, we will assume that it is tab-separated material
7115 (if nspace
7116 (setq tabsep nil)
7117 (goto-char beg)
7118 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7119 (if nspace (setq tabsep nil))
7120 (if tabsep
7121 (setq re "^\\|\t")
7122 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7123 (max 1 (prefix-numeric-value nspace)))))
7124 (goto-char beg)
7125 (while (re-search-forward re end t)
7126 (replace-match "| " t t))
7127 (goto-char beg)
7128 (insert " ")
7129 (org-table-align)))
7131 (defun org-table-import (file arg)
7132 "Import FILE as a table.
7133 The file is assumed to be tab-separated. Such files can be produced by most
7134 spreadsheet and database applications. If no tabs (at least one per line)
7135 are found, lines will be split on whitespace into fields."
7136 (interactive "f\nP")
7137 (or (bolp) (newline))
7138 (let ((beg (point))
7139 (pm (point-max)))
7140 (insert-file-contents file)
7141 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7143 (defun org-table-export ()
7144 "Export table as a tab-separated file.
7145 Such a file can be imported into a spreadsheet program like Excel."
7146 (interactive)
7147 (let* ((beg (org-table-begin))
7148 (end (org-table-end))
7149 (table (buffer-substring beg end))
7150 (file (read-file-name "Export table to: "))
7151 buf)
7152 (unless (or (not (file-exists-p file))
7153 (y-or-n-p (format "Overwrite file %s? " file)))
7154 (error "Abort"))
7155 (with-current-buffer (find-file-noselect file)
7156 (setq buf (current-buffer))
7157 (erase-buffer)
7158 (fundamental-mode)
7159 (insert table)
7160 (goto-char (point-min))
7161 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7162 (replace-match "" t t)
7163 (end-of-line 1))
7164 (goto-char (point-min))
7165 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7166 (replace-match "" t t)
7167 (goto-char (min (1+ (point)) (point-max))))
7168 (goto-char (point-min))
7169 (while (re-search-forward "^-[-+]*$" nil t)
7170 (replace-match "")
7171 (if (looking-at "\n")
7172 (delete-char 1)))
7173 (goto-char (point-min))
7174 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7175 (replace-match "\t" t t))
7176 (save-buffer))
7177 (kill-buffer buf)))
7179 (defvar org-table-aligned-begin-marker (make-marker)
7180 "Marker at the beginning of the table last aligned.
7181 Used to check if cursor still is in that table, to minimize realignment.")
7182 (defvar org-table-aligned-end-marker (make-marker)
7183 "Marker at the end of the table last aligned.
7184 Used to check if cursor still is in that table, to minimize realignment.")
7185 (defvar org-table-last-alignment nil
7186 "List of flags for flushright alignment, from the last re-alignment.
7187 This is being used to correctly align a single field after TAB or RET.")
7188 (defvar org-table-last-column-widths nil
7189 "List of max width of fields in each column.
7190 This is being used to correctly align a single field after TAB or RET.")
7191 (defvar org-table-overlay-coordinates nil
7192 "Overlay coordinates after each align of a table.")
7193 (make-variable-buffer-local 'org-table-overlay-coordinates)
7195 (defvar org-last-recalc-line nil)
7196 (defconst org-narrow-column-arrow "=>"
7197 "Used as display property in narrowed table columns.")
7199 (defun org-table-align ()
7200 "Align the table at point by aligning all vertical bars."
7201 (interactive)
7202 (let* (
7203 ;; Limits of table
7204 (beg (org-table-begin))
7205 (end (org-table-end))
7206 ;; Current cursor position
7207 (linepos (org-current-line))
7208 (colpos (org-table-current-column))
7209 (winstart (window-start))
7210 (winstartline (org-current-line (min winstart (1- (point-max)))))
7211 lines (new "") lengths l typenums ty fields maxfields i
7212 column
7213 (indent "") cnt frac
7214 rfmt hfmt
7215 (spaces '(1 . 1))
7216 (sp1 (car spaces))
7217 (sp2 (cdr spaces))
7218 (rfmt1 (concat
7219 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7220 (hfmt1 (concat
7221 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7222 emptystrings links dates narrow fmax f1 len c e)
7223 (untabify beg end)
7224 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7225 ;; Check if we have links or dates
7226 (goto-char beg)
7227 (setq links (re-search-forward org-bracket-link-regexp end t))
7228 (goto-char beg)
7229 (setq dates (and org-display-custom-times
7230 (re-search-forward org-ts-regexp-both end t)))
7231 ;; Make sure the link properties are right
7232 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7233 ;; Make sure the date properties are right
7234 (when dates (goto-char beg) (while (org-activate-dates end)))
7236 ;; Check if we are narrowing any columns
7237 (goto-char beg)
7238 (setq narrow (and org-format-transports-properties-p
7239 (re-search-forward "<[0-9]+>" end t)))
7240 ;; Get the rows
7241 (setq lines (org-split-string
7242 (buffer-substring beg end) "\n"))
7243 ;; Store the indentation of the first line
7244 (if (string-match "^ *" (car lines))
7245 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7246 ;; Mark the hlines by setting the corresponding element to nil
7247 ;; At the same time, we remove trailing space.
7248 (setq lines (mapcar (lambda (l)
7249 (if (string-match "^ *|-" l)
7251 (if (string-match "[ \t]+$" l)
7252 (substring l 0 (match-beginning 0))
7253 l)))
7254 lines))
7255 ;; Get the data fields by splitting the lines.
7256 (setq fields (mapcar
7257 (lambda (l)
7258 (org-split-string l " *| *"))
7259 (delq nil (copy-sequence lines))))
7260 ;; How many fields in the longest line?
7261 (condition-case nil
7262 (setq maxfields (apply 'max (mapcar 'length fields)))
7263 (error
7264 (kill-region beg end)
7265 (org-table-create org-table-default-size)
7266 (error "Empty table - created default table")))
7267 ;; A list of empty strings to fill any short rows on output
7268 (setq emptystrings (make-list maxfields ""))
7269 ;; Check for special formatting.
7270 (setq i -1)
7271 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7272 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7273 ;; Check if there is an explicit width specified
7274 (when narrow
7275 (setq c column fmax nil)
7276 (while c
7277 (setq e (pop c))
7278 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7279 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7280 ;; Find fields that are wider than fmax, and shorten them
7281 (when fmax
7282 (loop for xx in column do
7283 (when (and (stringp xx)
7284 (> (org-string-width xx) fmax))
7285 (org-add-props xx nil
7286 'help-echo
7287 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7288 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7289 (unless (> f1 1)
7290 (error "Cannot narrow field starting with wide link \"%s\""
7291 (match-string 0 xx)))
7292 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7293 (add-text-properties (- f1 2) f1
7294 (list 'display org-narrow-column-arrow)
7295 xx)))))
7296 ;; Get the maximum width for each column
7297 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7298 ;; Get the fraction of numbers, to decide about alignment of the column
7299 (setq cnt 0 frac 0.0)
7300 (loop for x in column do
7301 (if (equal x "")
7303 (setq frac ( / (+ (* frac cnt)
7304 (if (string-match org-table-number-regexp x) 1 0))
7305 (setq cnt (1+ cnt))))))
7306 (push (>= frac org-table-number-fraction) typenums))
7307 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7309 ;; Store the alignment of this table, for later editing of single fields
7310 (setq org-table-last-alignment typenums
7311 org-table-last-column-widths lengths)
7313 ;; With invisible characters, `format' does not get the field width right
7314 ;; So we need to make these fields wide by hand.
7315 (when links
7316 (loop for i from 0 upto (1- maxfields) do
7317 (setq len (nth i lengths))
7318 (loop for j from 0 upto (1- (length fields)) do
7319 (setq c (nthcdr i (car (nthcdr j fields))))
7320 (if (and (stringp (car c))
7321 (string-match org-bracket-link-regexp (car c))
7322 (< (org-string-width (car c)) len))
7323 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7325 ;; Compute the formats needed for output of the table
7326 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7327 (while (setq l (pop lengths))
7328 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7329 (setq rfmt (concat rfmt (format rfmt1 ty l))
7330 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7331 (setq rfmt (concat rfmt "\n")
7332 hfmt (concat (substring hfmt 0 -1) "|\n"))
7334 (setq new (mapconcat
7335 (lambda (l)
7336 (if l (apply 'format rfmt
7337 (append (pop fields) emptystrings))
7338 hfmt))
7339 lines ""))
7340 ;; Replace the old one
7341 (delete-region beg end)
7342 (move-marker end nil)
7343 (move-marker org-table-aligned-begin-marker (point))
7344 (insert new)
7345 (move-marker org-table-aligned-end-marker (point))
7346 (when (and orgtbl-mode (not (org-mode-p)))
7347 (goto-char org-table-aligned-begin-marker)
7348 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7349 ;; Try to move to the old location
7350 (goto-line winstartline)
7351 (setq winstart (point-at-bol))
7352 (goto-line linepos)
7353 (set-window-start (selected-window) winstart 'noforce)
7354 (org-table-goto-column colpos)
7355 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7356 (setq org-table-may-need-update nil)
7359 (defun org-string-width (s)
7360 "Compute width of string, ignoring invisible characters.
7361 This ignores character with invisibility property `org-link', and also
7362 characters with property `org-cwidth', because these will become invisible
7363 upon the next fontification round."
7364 (let (b l)
7365 (when (or (eq t buffer-invisibility-spec)
7366 (assq 'org-link buffer-invisibility-spec))
7367 (while (setq b (text-property-any 0 (length s)
7368 'invisible 'org-link s))
7369 (setq s (concat (substring s 0 b)
7370 (substring s (or (next-single-property-change
7371 b 'invisible s) (length s)))))))
7372 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7373 (setq s (concat (substring s 0 b)
7374 (substring s (or (next-single-property-change
7375 b 'org-cwidth s) (length s))))))
7376 (setq l (string-width s) b -1)
7377 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7378 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7381 (defun org-table-begin (&optional table-type)
7382 "Find the beginning of the table and return its position.
7383 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7384 (save-excursion
7385 (if (not (re-search-backward
7386 (if table-type org-table-any-border-regexp
7387 org-table-border-regexp)
7388 nil t))
7389 (progn (goto-char (point-min)) (point))
7390 (goto-char (match-beginning 0))
7391 (beginning-of-line 2)
7392 (point))))
7394 (defun org-table-end (&optional table-type)
7395 "Find the end of the table and return its position.
7396 With argument TABLE-TYPE, go to the end of a table.el-type table."
7397 (save-excursion
7398 (if (not (re-search-forward
7399 (if table-type org-table-any-border-regexp
7400 org-table-border-regexp)
7401 nil t))
7402 (goto-char (point-max))
7403 (goto-char (match-beginning 0)))
7404 (point-marker)))
7406 (defun org-table-justify-field-maybe (&optional new)
7407 "Justify the current field, text to left, number to right.
7408 Optional argument NEW may specify text to replace the current field content."
7409 (cond
7410 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7411 ((org-at-table-hline-p))
7412 ((and (not new)
7413 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7414 (current-buffer)))
7415 (< (point) org-table-aligned-begin-marker)
7416 (>= (point) org-table-aligned-end-marker)))
7417 ;; This is not the same table, force a full re-align
7418 (setq org-table-may-need-update t))
7419 (t ;; realign the current field, based on previous full realign
7420 (let* ((pos (point)) s
7421 (col (org-table-current-column))
7422 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7423 l f n o e)
7424 (when (> col 0)
7425 (skip-chars-backward "^|\n")
7426 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7427 (progn
7428 (setq s (match-string 1)
7429 o (match-string 0)
7430 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7431 e (not (= (match-beginning 2) (match-end 2))))
7432 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7433 l (if e "|" (setq org-table-may-need-update t) ""))
7434 n (format f s))
7435 (if new
7436 (if (<= (length new) l) ;; FIXME: length -> str-width?
7437 (setq n (format f new))
7438 (setq n (concat new "|") org-table-may-need-update t)))
7439 (or (equal n o)
7440 (let (org-table-may-need-update)
7441 (replace-match n t t))))
7442 (setq org-table-may-need-update t))
7443 (goto-char pos))))))
7445 (defun org-table-next-field ()
7446 "Go to the next field in the current table, creating new lines as needed.
7447 Before doing so, re-align the table if necessary."
7448 (interactive)
7449 (org-table-maybe-eval-formula)
7450 (org-table-maybe-recalculate-line)
7451 (if (and org-table-automatic-realign
7452 org-table-may-need-update)
7453 (org-table-align))
7454 (let ((end (org-table-end)))
7455 (if (org-at-table-hline-p)
7456 (end-of-line 1))
7457 (condition-case nil
7458 (progn
7459 (re-search-forward "|" end)
7460 (if (looking-at "[ \t]*$")
7461 (re-search-forward "|" end))
7462 (if (and (looking-at "-")
7463 org-table-tab-jumps-over-hlines
7464 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7465 (goto-char (match-beginning 1)))
7466 (if (looking-at "-")
7467 (progn
7468 (beginning-of-line 0)
7469 (org-table-insert-row 'below))
7470 (if (looking-at " ") (forward-char 1))))
7471 (error
7472 (org-table-insert-row 'below)))))
7474 (defun org-table-previous-field ()
7475 "Go to the previous field in the table.
7476 Before doing so, re-align the table if necessary."
7477 (interactive)
7478 (org-table-justify-field-maybe)
7479 (org-table-maybe-recalculate-line)
7480 (if (and org-table-automatic-realign
7481 org-table-may-need-update)
7482 (org-table-align))
7483 (if (org-at-table-hline-p)
7484 (end-of-line 1))
7485 (re-search-backward "|" (org-table-begin))
7486 (re-search-backward "|" (org-table-begin))
7487 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7488 (re-search-backward "|" (org-table-begin)))
7489 (if (looking-at "| ?")
7490 (goto-char (match-end 0))))
7492 (defun org-table-next-row ()
7493 "Go to the next row (same column) in the current table.
7494 Before doing so, re-align the table if necessary."
7495 (interactive)
7496 (org-table-maybe-eval-formula)
7497 (org-table-maybe-recalculate-line)
7498 (if (or (looking-at "[ \t]*$")
7499 (save-excursion (skip-chars-backward " \t") (bolp)))
7500 (newline)
7501 (if (and org-table-automatic-realign
7502 org-table-may-need-update)
7503 (org-table-align))
7504 (let ((col (org-table-current-column)))
7505 (beginning-of-line 2)
7506 (if (or (not (org-at-table-p))
7507 (org-at-table-hline-p))
7508 (progn
7509 (beginning-of-line 0)
7510 (org-table-insert-row 'below)))
7511 (org-table-goto-column col)
7512 (skip-chars-backward "^|\n\r")
7513 (if (looking-at " ") (forward-char 1)))))
7515 (defun org-table-copy-down (n)
7516 "Copy a field down in the current column.
7517 If the field at the cursor is empty, copy into it the content of the nearest
7518 non-empty field above. With argument N, use the Nth non-empty field.
7519 If the current field is not empty, it is copied down to the next row, and
7520 the cursor is moved with it. Therefore, repeating this command causes the
7521 column to be filled row-by-row.
7522 If the variable `org-table-copy-increment' is non-nil and the field is an
7523 integer or a timestamp, it will be incremented while copying. In the case of
7524 a timestamp, if the cursor is on the year, change the year. If it is on the
7525 month or the day, change that. Point will stay on the current date field
7526 in order to easily repeat the interval."
7527 (interactive "p")
7528 (let* ((colpos (org-table-current-column))
7529 (col (current-column))
7530 (field (org-table-get-field))
7531 (non-empty (string-match "[^ \t]" field))
7532 (beg (org-table-begin))
7533 txt)
7534 (org-table-check-inside-data-field)
7535 (if non-empty
7536 (progn
7537 (setq txt (org-trim field))
7538 (org-table-next-row)
7539 (org-table-blank-field))
7540 (save-excursion
7541 (setq txt
7542 (catch 'exit
7543 (while (progn (beginning-of-line 1)
7544 (re-search-backward org-table-dataline-regexp
7545 beg t))
7546 (org-table-goto-column colpos t)
7547 (if (and (looking-at
7548 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7549 (= (setq n (1- n)) 0))
7550 (throw 'exit (match-string 1))))))))
7551 (if txt
7552 (progn
7553 (if (and org-table-copy-increment
7554 (string-match "^[0-9]+$" txt))
7555 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7556 (insert txt)
7557 (move-to-column col)
7558 (if (and org-table-copy-increment (org-at-timestamp-p t))
7559 (org-timestamp-up 1)
7560 (org-table-maybe-recalculate-line))
7561 (org-table-align)
7562 (move-to-column col))
7563 (error "No non-empty field found"))))
7565 (defun org-table-check-inside-data-field ()
7566 "Is point inside a table data field?
7567 I.e. not on a hline or before the first or after the last column?
7568 This actually throws an error, so it aborts the current command."
7569 (if (or (not (org-at-table-p))
7570 (= (org-table-current-column) 0)
7571 (org-at-table-hline-p)
7572 (looking-at "[ \t]*$"))
7573 (error "Not in table data field")))
7575 (defvar org-table-clip nil
7576 "Clipboard for table regions.")
7578 (defun org-table-blank-field ()
7579 "Blank the current table field or active region."
7580 (interactive)
7581 (org-table-check-inside-data-field)
7582 (if (and (interactive-p) (org-region-active-p))
7583 (let (org-table-clip)
7584 (org-table-cut-region (region-beginning) (region-end)))
7585 (skip-chars-backward "^|")
7586 (backward-char 1)
7587 (if (looking-at "|[^|\n]+")
7588 (let* ((pos (match-beginning 0))
7589 (match (match-string 0))
7590 (len (org-string-width match)))
7591 (replace-match (concat "|" (make-string (1- len) ?\ )))
7592 (goto-char (+ 2 pos))
7593 (substring match 1)))))
7595 (defun org-table-get-field (&optional n replace)
7596 "Return the value of the field in column N of current row.
7597 N defaults to current field.
7598 If REPLACE is a string, replace field with this value. The return value
7599 is always the old value."
7600 (and n (org-table-goto-column n))
7601 (skip-chars-backward "^|\n")
7602 (backward-char 1)
7603 (if (looking-at "|[^|\r\n]*")
7604 (let* ((pos (match-beginning 0))
7605 (val (buffer-substring (1+ pos) (match-end 0))))
7606 (if replace
7607 (replace-match (concat "|" replace) t t))
7608 (goto-char (min (point-at-eol) (+ 2 pos)))
7609 val)
7610 (forward-char 1) ""))
7612 (defun org-table-field-info (arg)
7613 "Show info about the current field, and highlight any reference at point."
7614 (interactive "P")
7615 (org-table-get-specials)
7616 (save-excursion
7617 (let* ((pos (point))
7618 (col (org-table-current-column))
7619 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7620 (name (car (rassoc (list (org-current-line) col)
7621 org-table-named-field-locations)))
7622 (eql (org-table-get-stored-formulas))
7623 (dline (org-table-current-dline))
7624 (ref (format "@%d$%d" dline col))
7625 (ref1 (org-table-convert-refs-to-an ref))
7626 (fequation (or (assoc name eql) (assoc ref eql)))
7627 (cequation (assoc (int-to-string col) eql))
7628 (eqn (or fequation cequation)))
7629 (goto-char pos)
7630 (condition-case nil
7631 (org-table-show-reference 'local)
7632 (error nil))
7633 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7634 dline col
7635 (if cname (concat " or $" cname) "")
7636 dline col ref1
7637 (if name (concat " or $" name) "")
7638 ;; FIXME: formula info not correct if special table line
7639 (if eqn
7640 (concat ", formula: "
7641 (org-table-formula-to-user
7642 (concat
7643 (if (string-match "^[$@]"(car eqn)) "" "$")
7644 (car eqn) "=" (cdr eqn))))
7645 "")))))
7647 (defun org-table-current-column ()
7648 "Find out which column we are in.
7649 When called interactively, column is also displayed in echo area."
7650 (interactive)
7651 (if (interactive-p) (org-table-check-inside-data-field))
7652 (save-excursion
7653 (let ((cnt 0) (pos (point)))
7654 (beginning-of-line 1)
7655 (while (search-forward "|" pos t)
7656 (setq cnt (1+ cnt)))
7657 (if (interactive-p) (message "This is table column %d" cnt))
7658 cnt)))
7660 (defun org-table-current-dline ()
7661 "Find out what table data line we are in.
7662 Only datalins count for this."
7663 (interactive)
7664 (if (interactive-p) (org-table-check-inside-data-field))
7665 (save-excursion
7666 (let ((cnt 0) (pos (point)))
7667 (goto-char (org-table-begin))
7668 (while (<= (point) pos)
7669 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7670 (beginning-of-line 2))
7671 (if (interactive-p) (message "This is table line %d" cnt))
7672 cnt)))
7674 (defun org-table-goto-column (n &optional on-delim force)
7675 "Move the cursor to the Nth column in the current table line.
7676 With optional argument ON-DELIM, stop with point before the left delimiter
7677 of the field.
7678 If there are less than N fields, just go to after the last delimiter.
7679 However, when FORCE is non-nil, create new columns if necessary."
7680 (interactive "p")
7681 (let ((pos (point-at-eol)))
7682 (beginning-of-line 1)
7683 (when (> n 0)
7684 (while (and (> (setq n (1- n)) -1)
7685 (or (search-forward "|" pos t)
7686 (and force
7687 (progn (end-of-line 1)
7688 (skip-chars-backward "^|")
7689 (insert " | "))))))
7690 ; (backward-char 2) t)))))
7691 (when (and force (not (looking-at ".*|")))
7692 (save-excursion (end-of-line 1) (insert " | ")))
7693 (if on-delim
7694 (backward-char 1)
7695 (if (looking-at " ") (forward-char 1))))))
7697 (defun org-at-table-p (&optional table-type)
7698 "Return t if the cursor is inside an org-type table.
7699 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7700 (if org-enable-table-editor
7701 (save-excursion
7702 (beginning-of-line 1)
7703 (looking-at (if table-type org-table-any-line-regexp
7704 org-table-line-regexp)))
7705 nil))
7707 (defun org-at-table.el-p ()
7708 "Return t if and only if we are at a table.el table."
7709 (and (org-at-table-p 'any)
7710 (save-excursion
7711 (goto-char (org-table-begin 'any))
7712 (looking-at org-table1-hline-regexp))))
7714 (defun org-table-recognize-table.el ()
7715 "If there is a table.el table nearby, recognize it and move into it."
7716 (if org-table-tab-recognizes-table.el
7717 (if (org-at-table.el-p)
7718 (progn
7719 (beginning-of-line 1)
7720 (if (looking-at org-table-dataline-regexp)
7722 (if (looking-at org-table1-hline-regexp)
7723 (progn
7724 (beginning-of-line 2)
7725 (if (looking-at org-table-any-border-regexp)
7726 (beginning-of-line -1)))))
7727 (if (re-search-forward "|" (org-table-end t) t)
7728 (progn
7729 (require 'table)
7730 (if (table--at-cell-p (point))
7732 (message "recognizing table.el table...")
7733 (table-recognize-table)
7734 (message "recognizing table.el table...done")))
7735 (error "This should not happen..."))
7737 nil)
7738 nil))
7740 (defun org-at-table-hline-p ()
7741 "Return t if the cursor is inside a hline in a table."
7742 (if org-enable-table-editor
7743 (save-excursion
7744 (beginning-of-line 1)
7745 (looking-at org-table-hline-regexp))
7746 nil))
7748 (defun org-table-insert-column ()
7749 "Insert a new column into the table."
7750 (interactive)
7751 (if (not (org-at-table-p))
7752 (error "Not at a table"))
7753 (org-table-find-dataline)
7754 (let* ((col (max 1 (org-table-current-column)))
7755 (beg (org-table-begin))
7756 (end (org-table-end))
7757 ;; Current cursor position
7758 (linepos (org-current-line))
7759 (colpos col))
7760 (goto-char beg)
7761 (while (< (point) end)
7762 (if (org-at-table-hline-p)
7764 (org-table-goto-column col t)
7765 (insert "| "))
7766 (beginning-of-line 2))
7767 (move-marker end nil)
7768 (goto-line linepos)
7769 (org-table-goto-column colpos)
7770 (org-table-align)
7771 (org-table-fix-formulas "$" nil (1- col) 1)))
7773 (defun org-table-find-dataline ()
7774 "Find a dataline in the current table, which is needed for column commands."
7775 (if (and (org-at-table-p)
7776 (not (org-at-table-hline-p)))
7778 (let ((col (current-column))
7779 (end (org-table-end)))
7780 (move-to-column col)
7781 (while (and (< (point) end)
7782 (or (not (= (current-column) col))
7783 (org-at-table-hline-p)))
7784 (beginning-of-line 2)
7785 (move-to-column col))
7786 (if (and (org-at-table-p)
7787 (not (org-at-table-hline-p)))
7789 (error
7790 "Please position cursor in a data line for column operations")))))
7792 (defun org-table-delete-column ()
7793 "Delete a column from the table."
7794 (interactive)
7795 (if (not (org-at-table-p))
7796 (error "Not at a table"))
7797 (org-table-find-dataline)
7798 (org-table-check-inside-data-field)
7799 (let* ((col (org-table-current-column))
7800 (beg (org-table-begin))
7801 (end (org-table-end))
7802 ;; Current cursor position
7803 (linepos (org-current-line))
7804 (colpos col))
7805 (goto-char beg)
7806 (while (< (point) end)
7807 (if (org-at-table-hline-p)
7809 (org-table-goto-column col t)
7810 (and (looking-at "|[^|\n]+|")
7811 (replace-match "|")))
7812 (beginning-of-line 2))
7813 (move-marker end nil)
7814 (goto-line linepos)
7815 (org-table-goto-column colpos)
7816 (org-table-align)
7817 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7818 col -1 col)))
7820 (defun org-table-move-column-right ()
7821 "Move column to the right."
7822 (interactive)
7823 (org-table-move-column nil))
7824 (defun org-table-move-column-left ()
7825 "Move column to the left."
7826 (interactive)
7827 (org-table-move-column 'left))
7829 (defun org-table-move-column (&optional left)
7830 "Move the current column to the right. With arg LEFT, move to the left."
7831 (interactive "P")
7832 (if (not (org-at-table-p))
7833 (error "Not at a table"))
7834 (org-table-find-dataline)
7835 (org-table-check-inside-data-field)
7836 (let* ((col (org-table-current-column))
7837 (col1 (if left (1- col) col))
7838 (beg (org-table-begin))
7839 (end (org-table-end))
7840 ;; Current cursor position
7841 (linepos (org-current-line))
7842 (colpos (if left (1- col) (1+ col))))
7843 (if (and left (= col 1))
7844 (error "Cannot move column further left"))
7845 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7846 (error "Cannot move column further right"))
7847 (goto-char beg)
7848 (while (< (point) end)
7849 (if (org-at-table-hline-p)
7851 (org-table-goto-column col1 t)
7852 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7853 (replace-match "|\\2|\\1|")))
7854 (beginning-of-line 2))
7855 (move-marker end nil)
7856 (goto-line linepos)
7857 (org-table-goto-column colpos)
7858 (org-table-align)
7859 (org-table-fix-formulas
7860 "$" (list (cons (number-to-string col) (number-to-string colpos))
7861 (cons (number-to-string colpos) (number-to-string col))))))
7863 (defun org-table-move-row-down ()
7864 "Move table row down."
7865 (interactive)
7866 (org-table-move-row nil))
7867 (defun org-table-move-row-up ()
7868 "Move table row up."
7869 (interactive)
7870 (org-table-move-row 'up))
7872 (defun org-table-move-row (&optional up)
7873 "Move the current table line down. With arg UP, move it up."
7874 (interactive "P")
7875 (let* ((col (current-column))
7876 (pos (point))
7877 (hline1p (save-excursion (beginning-of-line 1)
7878 (looking-at org-table-hline-regexp)))
7879 (dline1 (org-table-current-dline))
7880 (dline2 (+ dline1 (if up -1 1)))
7881 (tonew (if up 0 2))
7882 txt hline2p)
7883 (beginning-of-line tonew)
7884 (unless (org-at-table-p)
7885 (goto-char pos)
7886 (error "Cannot move row further"))
7887 (setq hline2p (looking-at org-table-hline-regexp))
7888 (goto-char pos)
7889 (beginning-of-line 1)
7890 (setq pos (point))
7891 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7892 (delete-region (point) (1+ (point-at-eol)))
7893 (beginning-of-line tonew)
7894 (insert txt)
7895 (beginning-of-line 0)
7896 (move-to-column col)
7897 (unless (or hline1p hline2p)
7898 (org-table-fix-formulas
7899 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7900 (cons (number-to-string dline2) (number-to-string dline1)))))))
7902 (defun org-table-insert-row (&optional arg)
7903 "Insert a new row above the current line into the table.
7904 With prefix ARG, insert below the current line."
7905 (interactive "P")
7906 (if (not (org-at-table-p))
7907 (error "Not at a table"))
7908 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7909 (new (org-table-clean-line line)))
7910 ;; Fix the first field if necessary
7911 (if (string-match "^[ \t]*| *[#$] *|" line)
7912 (setq new (replace-match (match-string 0 line) t t new)))
7913 (beginning-of-line (if arg 2 1))
7914 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7915 (beginning-of-line 0)
7916 (re-search-forward "| ?" (point-at-eol) t)
7917 (and (or org-table-may-need-update org-table-overlay-coordinates)
7918 (org-table-align))
7919 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7921 (defun org-table-insert-hline (&optional above)
7922 "Insert a horizontal-line below the current line into the table.
7923 With prefix ABOVE, insert above the current line."
7924 (interactive "P")
7925 (if (not (org-at-table-p))
7926 (error "Not at a table"))
7927 (let ((line (org-table-clean-line
7928 (buffer-substring (point-at-bol) (point-at-eol))))
7929 (col (current-column)))
7930 (while (string-match "|\\( +\\)|" line)
7931 (setq line (replace-match
7932 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7933 ?-) "|") t t line)))
7934 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7935 (beginning-of-line (if above 1 2))
7936 (insert line "\n")
7937 (beginning-of-line (if above 1 -1))
7938 (move-to-column col)
7939 (and org-table-overlay-coordinates (org-table-align))))
7941 (defun org-table-hline-and-move (&optional same-column)
7942 "Insert a hline and move to the row below that line."
7943 (interactive "P")
7944 (let ((col (org-table-current-column)))
7945 (org-table-maybe-eval-formula)
7946 (org-table-maybe-recalculate-line)
7947 (org-table-insert-hline)
7948 (end-of-line 2)
7949 (if (looking-at "\n[ \t]*|-")
7950 (progn (insert "\n|") (org-table-align))
7951 (org-table-next-field))
7952 (if same-column (org-table-goto-column col))))
7954 (defun org-table-clean-line (s)
7955 "Convert a table line S into a string with only \"|\" and space.
7956 In particular, this does handle wide and invisible characters."
7957 (if (string-match "^[ \t]*|-" s)
7958 ;; It's a hline, just map the characters
7959 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7960 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7961 (setq s (replace-match
7962 (concat "|" (make-string (org-string-width (match-string 1 s))
7963 ?\ ) "|")
7964 t t s)))
7967 (defun org-table-kill-row ()
7968 "Delete the current row or horizontal line from the table."
7969 (interactive)
7970 (if (not (org-at-table-p))
7971 (error "Not at a table"))
7972 (let ((col (current-column))
7973 (dline (org-table-current-dline)))
7974 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7975 (if (not (org-at-table-p)) (beginning-of-line 0))
7976 (move-to-column col)
7977 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7978 dline -1 dline)))
7981 (defun org-table-sort-lines (with-case &optional sorting-type)
7982 "Sort table lines according to the column at point.
7984 The position of point indicates the column to be used for
7985 sorting, and the range of lines is the range between the nearest
7986 horizontal separator lines, or the entire table of no such lines
7987 exist. If point is before the first column, you will be prompted
7988 for the sorting column. If there is an active region, the mark
7989 specifies the first line and the sorting column, while point
7990 should be in the last line to be included into the sorting.
7992 The command then prompts for the sorting type which can be
7993 alphabetically, numerically, or by time (as given in a time stamp
7994 in the field). Sorting in reverse order is also possible.
7996 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7998 If SORTING-TYPE is specified when this function is called from a Lisp
7999 program, no prompting will take place. SORTING-TYPE must be a character,
8000 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8001 should be done in reverse order."
8002 (interactive "P")
8003 (let* ((thisline (org-current-line))
8004 (thiscol (org-table-current-column))
8005 beg end bcol ecol tend tbeg column lns pos)
8006 (when (equal thiscol 0)
8007 (if (interactive-p)
8008 (setq thiscol
8009 (string-to-number
8010 (read-string "Use column N for sorting: ")))
8011 (setq thiscol 1))
8012 (org-table-goto-column thiscol))
8013 (org-table-check-inside-data-field)
8014 (if (org-region-active-p)
8015 (progn
8016 (setq beg (region-beginning) end (region-end))
8017 (goto-char beg)
8018 (setq column (org-table-current-column)
8019 beg (point-at-bol))
8020 (goto-char end)
8021 (setq end (point-at-bol 2)))
8022 (setq column (org-table-current-column)
8023 pos (point)
8024 tbeg (org-table-begin)
8025 tend (org-table-end))
8026 (if (re-search-backward org-table-hline-regexp tbeg t)
8027 (setq beg (point-at-bol 2))
8028 (goto-char tbeg)
8029 (setq beg (point-at-bol 1)))
8030 (goto-char pos)
8031 (if (re-search-forward org-table-hline-regexp tend t)
8032 (setq end (point-at-bol 1))
8033 (goto-char tend)
8034 (setq end (point-at-bol))))
8035 (setq beg (move-marker (make-marker) beg)
8036 end (move-marker (make-marker) end))
8037 (untabify beg end)
8038 (goto-char beg)
8039 (org-table-goto-column column)
8040 (skip-chars-backward "^|")
8041 (setq bcol (current-column))
8042 (org-table-goto-column (1+ column))
8043 (skip-chars-backward "^|")
8044 (setq ecol (1- (current-column)))
8045 (org-table-goto-column column)
8046 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8047 (org-split-string (buffer-substring beg end) "\n")))
8048 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8049 (delete-region beg end)
8050 (move-marker beg nil)
8051 (move-marker end nil)
8052 (insert (mapconcat 'cdr lns "\n") "\n")
8053 (goto-line thisline)
8054 (org-table-goto-column thiscol)
8055 (message "%d lines sorted, based on column %d" (length lns) column)))
8057 (defun org-table-cut-region (beg end)
8058 "Copy region in table to the clipboard and blank all relevant fields."
8059 (interactive "r")
8060 (org-table-copy-region beg end 'cut))
8062 (defun org-table-copy-region (beg end &optional cut)
8063 "Copy rectangular region in table to clipboard.
8064 A special clipboard is used which can only be accessed
8065 with `org-table-paste-rectangle'."
8066 (interactive "rP")
8067 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8068 region cols
8069 (rpl (if cut " " nil)))
8070 (goto-char beg)
8071 (org-table-check-inside-data-field)
8072 (setq l01 (org-current-line)
8073 c01 (org-table-current-column))
8074 (goto-char end)
8075 (org-table-check-inside-data-field)
8076 (setq l02 (org-current-line)
8077 c02 (org-table-current-column))
8078 (setq l1 (min l01 l02) l2 (max l01 l02)
8079 c1 (min c01 c02) c2 (max c01 c02))
8080 (catch 'exit
8081 (while t
8082 (catch 'nextline
8083 (if (> l1 l2) (throw 'exit t))
8084 (goto-line l1)
8085 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8086 (setq cols nil ic1 c1 ic2 c2)
8087 (while (< ic1 (1+ ic2))
8088 (push (org-table-get-field ic1 rpl) cols)
8089 (setq ic1 (1+ ic1)))
8090 (push (nreverse cols) region)
8091 (setq l1 (1+ l1)))))
8092 (setq org-table-clip (nreverse region))
8093 (if cut (org-table-align))
8094 org-table-clip))
8096 (defun org-table-paste-rectangle ()
8097 "Paste a rectangular region into a table.
8098 The upper right corner ends up in the current field. All involved fields
8099 will be overwritten. If the rectangle does not fit into the present table,
8100 the table is enlarged as needed. The process ignores horizontal separator
8101 lines."
8102 (interactive)
8103 (unless (and org-table-clip (listp org-table-clip))
8104 (error "First cut/copy a region to paste!"))
8105 (org-table-check-inside-data-field)
8106 (let* ((clip org-table-clip)
8107 (line (org-current-line))
8108 (col (org-table-current-column))
8109 (org-enable-table-editor t)
8110 (org-table-automatic-realign nil)
8111 c cols field)
8112 (while (setq cols (pop clip))
8113 (while (org-at-table-hline-p) (beginning-of-line 2))
8114 (if (not (org-at-table-p))
8115 (progn (end-of-line 0) (org-table-next-field)))
8116 (setq c col)
8117 (while (setq field (pop cols))
8118 (org-table-goto-column c nil 'force)
8119 (org-table-get-field nil field)
8120 (setq c (1+ c)))
8121 (beginning-of-line 2))
8122 (goto-line line)
8123 (org-table-goto-column col)
8124 (org-table-align)))
8126 (defun org-table-convert ()
8127 "Convert from `org-mode' table to table.el and back.
8128 Obviously, this only works within limits. When an Org-mode table is
8129 converted to table.el, all horizontal separator lines get lost, because
8130 table.el uses these as cell boundaries and has no notion of horizontal lines.
8131 A table.el table can be converted to an Org-mode table only if it does not
8132 do row or column spanning. Multiline cells will become multiple cells.
8133 Beware, Org-mode does not test if the table can be successfully converted - it
8134 blindly applies a recipe that works for simple tables."
8135 (interactive)
8136 (require 'table)
8137 (if (org-at-table.el-p)
8138 ;; convert to Org-mode table
8139 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8140 (end (move-marker (make-marker) (org-table-end t))))
8141 (table-unrecognize-region beg end)
8142 (goto-char beg)
8143 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8144 (replace-match ""))
8145 (goto-char beg))
8146 (if (org-at-table-p)
8147 ;; convert to table.el table
8148 (let ((beg (move-marker (make-marker) (org-table-begin)))
8149 (end (move-marker (make-marker) (org-table-end))))
8150 ;; first, get rid of all horizontal lines
8151 (goto-char beg)
8152 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8153 (replace-match ""))
8154 ;; insert a hline before first
8155 (goto-char beg)
8156 (org-table-insert-hline 'above)
8157 (beginning-of-line -1)
8158 ;; insert a hline after each line
8159 (while (progn (beginning-of-line 3) (< (point) end))
8160 (org-table-insert-hline))
8161 (goto-char beg)
8162 (setq end (move-marker end (org-table-end)))
8163 ;; replace "+" at beginning and ending of hlines
8164 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8165 (replace-match "\\1+-"))
8166 (goto-char beg)
8167 (while (re-search-forward "-|[ \t]*$" end t)
8168 (replace-match "-+"))
8169 (goto-char beg)))))
8171 (defun org-table-wrap-region (arg)
8172 "Wrap several fields in a column like a paragraph.
8173 This is useful if you'd like to spread the contents of a field over several
8174 lines, in order to keep the table compact.
8176 If there is an active region, and both point and mark are in the same column,
8177 the text in the column is wrapped to minimum width for the given number of
8178 lines. Generally, this makes the table more compact. A prefix ARG may be
8179 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8180 formats the selected text to two lines. If the region was longer than two
8181 lines, the remaining lines remain empty. A negative prefix argument reduces
8182 the current number of lines by that amount. The wrapped text is pasted back
8183 into the table. If you formatted it to more lines than it was before, fields
8184 further down in the table get overwritten - so you might need to make space in
8185 the table first.
8187 If there is no region, the current field is split at the cursor position and
8188 the text fragment to the right of the cursor is prepended to the field one
8189 line down.
8191 If there is no region, but you specify a prefix ARG, the current field gets
8192 blank, and the content is appended to the field above."
8193 (interactive "P")
8194 (org-table-check-inside-data-field)
8195 (if (org-region-active-p)
8196 ;; There is a region: fill as a paragraph
8197 (let* ((beg (region-beginning))
8198 (cline (save-excursion (goto-char beg) (org-current-line)))
8199 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8200 nlines)
8201 (org-table-cut-region (region-beginning) (region-end))
8202 (if (> (length (car org-table-clip)) 1)
8203 (error "Region must be limited to single column"))
8204 (setq nlines (if arg
8205 (if (< arg 1)
8206 (+ (length org-table-clip) arg)
8207 arg)
8208 (length org-table-clip)))
8209 (setq org-table-clip
8210 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8211 nil nlines)))
8212 (goto-line cline)
8213 (org-table-goto-column ccol)
8214 (org-table-paste-rectangle))
8215 ;; No region, split the current field at point
8216 (if arg
8217 ;; combine with field above
8218 (let ((s (org-table-blank-field))
8219 (col (org-table-current-column)))
8220 (beginning-of-line 0)
8221 (while (org-at-table-hline-p) (beginning-of-line 0))
8222 (org-table-goto-column col)
8223 (skip-chars-forward "^|")
8224 (skip-chars-backward " ")
8225 (insert " " (org-trim s))
8226 (org-table-align))
8227 ;; split field
8228 (when (looking-at "\\([^|]+\\)+|")
8229 (let ((s (match-string 1)))
8230 (replace-match " |")
8231 (goto-char (match-beginning 0))
8232 (org-table-next-row)
8233 (insert (org-trim s) " ")
8234 (org-table-align))))))
8236 (defvar org-field-marker nil)
8238 (defun org-table-edit-field (arg)
8239 "Edit table field in a different window.
8240 This is mainly useful for fields that contain hidden parts.
8241 When called with a \\[universal-argument] prefix, just make the full field visible so that
8242 it can be edited in place."
8243 (interactive "P")
8244 (if arg
8245 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8246 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8247 (remove-text-properties b e '(org-cwidth t invisible t
8248 display t intangible t))
8249 (if (and (boundp 'font-lock-mode) font-lock-mode)
8250 (font-lock-fontify-block)))
8251 (let ((pos (move-marker (make-marker) (point)))
8252 (field (org-table-get-field))
8253 (cw (current-window-configuration))
8255 (org-switch-to-buffer-other-window "*Org tmp*")
8256 (erase-buffer)
8257 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8258 (let ((org-inhibit-startup t)) (org-mode))
8259 (goto-char (setq p (point-max)))
8260 (insert (org-trim field))
8261 (remove-text-properties p (point-max)
8262 '(invisible t org-cwidth t display t
8263 intangible t))
8264 (goto-char p)
8265 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8266 (org-set-local 'org-window-configuration cw)
8267 (org-set-local 'org-field-marker pos)
8268 (message "Edit and finish with C-c C-c"))))
8270 (defun org-table-finish-edit-field ()
8271 "Finish editing a table data field.
8272 Remove all newline characters, insert the result into the table, realign
8273 the table and kill the editing buffer."
8274 (let ((pos org-field-marker)
8275 (cw org-window-configuration)
8276 (cb (current-buffer))
8277 text)
8278 (goto-char (point-min))
8279 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8280 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8281 (replace-match " "))
8282 (setq text (org-trim (buffer-string)))
8283 (set-window-configuration cw)
8284 (kill-buffer cb)
8285 (select-window (get-buffer-window (marker-buffer pos)))
8286 (goto-char pos)
8287 (move-marker pos nil)
8288 (org-table-check-inside-data-field)
8289 (org-table-get-field nil text)
8290 (org-table-align)
8291 (message "New field value inserted")))
8293 (defun org-trim (s)
8294 "Remove whitespace at beginning and end of string."
8295 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8296 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
8299 (defun org-wrap (string &optional width lines)
8300 "Wrap string to either a number of lines, or a width in characters.
8301 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8302 that costs. If there is a word longer than WIDTH, the text is actually
8303 wrapped to the length of that word.
8304 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8305 many lines, whatever width that takes.
8306 The return value is a list of lines, without newlines at the end."
8307 (let* ((words (org-split-string string "[ \t\n]+"))
8308 (maxword (apply 'max (mapcar 'org-string-width words)))
8309 w ll)
8310 (cond (width
8311 (org-do-wrap words (max maxword width)))
8312 (lines
8313 (setq w maxword)
8314 (setq ll (org-do-wrap words maxword))
8315 (if (<= (length ll) lines)
8317 (setq ll words)
8318 (while (> (length ll) lines)
8319 (setq w (1+ w))
8320 (setq ll (org-do-wrap words w)))
8321 ll))
8322 (t (error "Cannot wrap this")))))
8325 (defun org-do-wrap (words width)
8326 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8327 (let (lines line)
8328 (while words
8329 (setq line (pop words))
8330 (while (and words (< (+ (length line) (length (car words))) width))
8331 (setq line (concat line " " (pop words))))
8332 (setq lines (push line lines)))
8333 (nreverse lines)))
8335 (defun org-split-string (string &optional separators)
8336 "Splits STRING into substrings at SEPARATORS.
8337 No empty strings are returned if there are matches at the beginning
8338 and end of string."
8339 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8340 (start 0)
8341 notfirst
8342 (list nil))
8343 (while (and (string-match rexp string
8344 (if (and notfirst
8345 (= start (match-beginning 0))
8346 (< start (length string)))
8347 (1+ start) start))
8348 (< (match-beginning 0) (length string)))
8349 (setq notfirst t)
8350 (or (eq (match-beginning 0) 0)
8351 (and (eq (match-beginning 0) (match-end 0))
8352 (eq (match-beginning 0) start))
8353 (setq list
8354 (cons (substring string start (match-beginning 0))
8355 list)))
8356 (setq start (match-end 0)))
8357 (or (eq start (length string))
8358 (setq list
8359 (cons (substring string start)
8360 list)))
8361 (nreverse list)))
8363 (defun org-table-map-tables (function)
8364 "Apply FUNCTION to the start of all tables in the buffer."
8365 (save-excursion
8366 (save-restriction
8367 (widen)
8368 (goto-char (point-min))
8369 (while (re-search-forward org-table-any-line-regexp nil t)
8370 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8371 (beginning-of-line 1)
8372 (if (looking-at org-table-line-regexp)
8373 (save-excursion (funcall function)))
8374 (re-search-forward org-table-any-border-regexp nil 1))))
8375 (message "Mapping tables: done"))
8377 (defvar org-timecnt) ; dynamically scoped parameter
8379 (defun org-table-sum (&optional beg end nlast)
8380 "Sum numbers in region of current table column.
8381 The result will be displayed in the echo area, and will be available
8382 as kill to be inserted with \\[yank].
8384 If there is an active region, it is interpreted as a rectangle and all
8385 numbers in that rectangle will be summed. If there is no active
8386 region and point is located in a table column, sum all numbers in that
8387 column.
8389 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8390 numbers are assumed to be times as well (in decimal hours) and the
8391 numbers are added as such.
8393 If NLAST is a number, only the NLAST fields will actually be summed."
8394 (interactive)
8395 (save-excursion
8396 (let (col (org-timecnt 0) diff h m s org-table-clip)
8397 (cond
8398 ((and beg end)) ; beg and end given explicitly
8399 ((org-region-active-p)
8400 (setq beg (region-beginning) end (region-end)))
8402 (setq col (org-table-current-column))
8403 (goto-char (org-table-begin))
8404 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8405 (error "No table data"))
8406 (org-table-goto-column col)
8407 (setq beg (point))
8408 (goto-char (org-table-end))
8409 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8410 (error "No table data"))
8411 (org-table-goto-column col)
8412 (setq end (point))))
8413 (let* ((items (apply 'append (org-table-copy-region beg end)))
8414 (items1 (cond ((not nlast) items)
8415 ((>= nlast (length items)) items)
8416 (t (setq items (reverse items))
8417 (setcdr (nthcdr (1- nlast) items) nil)
8418 (nreverse items))))
8419 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8420 items1)))
8421 (res (apply '+ numbers))
8422 (sres (if (= org-timecnt 0)
8423 (format "%g" res)
8424 (setq diff (* 3600 res)
8425 h (floor (/ diff 3600)) diff (mod diff 3600)
8426 m (floor (/ diff 60)) diff (mod diff 60)
8427 s diff)
8428 (format "%d:%02d:%02d" h m s))))
8429 (kill-new sres)
8430 (if (interactive-p)
8431 (message "%s"
8432 (substitute-command-keys
8433 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8434 (length numbers) sres))))
8435 sres))))
8437 (defun org-table-get-number-for-summing (s)
8438 (let (n)
8439 (if (string-match "^ *|? *" s)
8440 (setq s (replace-match "" nil nil s)))
8441 (if (string-match " *|? *$" s)
8442 (setq s (replace-match "" nil nil s)))
8443 (setq n (string-to-number s))
8444 (cond
8445 ((and (string-match "0" s)
8446 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8447 ((string-match "\\`[ \t]+\\'" s) nil)
8448 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8449 (let ((h (string-to-number (or (match-string 1 s) "0")))
8450 (m (string-to-number (or (match-string 2 s) "0")))
8451 (s (string-to-number (or (match-string 4 s) "0"))))
8452 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8453 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8454 ((equal n 0) nil)
8455 (t n))))
8457 (defun org-table-current-field-formula (&optional key noerror)
8458 "Return the formula active for the current field.
8459 Assumes that specials are in place.
8460 If KEY is given, return the key to this formula.
8461 Otherwise return the formula preceeded with \"=\" or \":=\"."
8462 (let* ((name (car (rassoc (list (org-current-line)
8463 (org-table-current-column))
8464 org-table-named-field-locations)))
8465 (col (org-table-current-column))
8466 (scol (int-to-string col))
8467 (ref (format "@%d$%d" (org-table-current-dline) col))
8468 (stored-list (org-table-get-stored-formulas noerror))
8469 (ass (or (assoc name stored-list)
8470 (assoc ref stored-list)
8471 (assoc scol stored-list))))
8472 (if key
8473 (car ass)
8474 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8475 (cdr ass))))))
8477 (defun org-table-get-formula (&optional equation named)
8478 "Read a formula from the minibuffer, offer stored formula as default.
8479 When NAMED is non-nil, look for a named equation."
8480 (let* ((stored-list (org-table-get-stored-formulas))
8481 (name (car (rassoc (list (org-current-line)
8482 (org-table-current-column))
8483 org-table-named-field-locations)))
8484 (ref (format "@%d$%d" (org-table-current-dline)
8485 (org-table-current-column)))
8486 (refass (assoc ref stored-list))
8487 (scol (if named
8488 (if name name ref)
8489 (int-to-string (org-table-current-column))))
8490 (dummy (and (or name refass) (not named)
8491 (not (y-or-n-p "Replace field formula with column formula? " ))
8492 (error "Abort")))
8493 (name (or name ref))
8494 (org-table-may-need-update nil)
8495 (stored (cdr (assoc scol stored-list)))
8496 (eq (cond
8497 ((and stored equation (string-match "^ *=? *$" equation))
8498 stored)
8499 ((stringp equation)
8500 equation)
8501 (t (org-table-formula-from-user
8502 (read-string
8503 (org-table-formula-to-user
8504 (format "%s formula %s%s="
8505 (if named "Field" "Column")
8506 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8507 scol))
8508 (if stored (org-table-formula-to-user stored) "")
8509 'org-table-formula-history
8510 )))))
8511 mustsave)
8512 (when (not (string-match "\\S-" eq))
8513 ;; remove formula
8514 (setq stored-list (delq (assoc scol stored-list) stored-list))
8515 (org-table-store-formulas stored-list)
8516 (error "Formula removed"))
8517 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8518 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8519 (if (and name (not named))
8520 ;; We set the column equation, delete the named one.
8521 (setq stored-list (delq (assoc name stored-list) stored-list)
8522 mustsave t))
8523 (if stored
8524 (setcdr (assoc scol stored-list) eq)
8525 (setq stored-list (cons (cons scol eq) stored-list)))
8526 (if (or mustsave (not (equal stored eq)))
8527 (org-table-store-formulas stored-list))
8528 eq))
8530 (defun org-table-store-formulas (alist)
8531 "Store the list of formulas below the current table."
8532 (setq alist (sort alist 'org-table-formula-less-p))
8533 (save-excursion
8534 (goto-char (org-table-end))
8535 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8536 (progn
8537 ;; don't overwrite TBLFM, we might use text properties to store stuff
8538 (goto-char (match-beginning 2))
8539 (delete-region (match-beginning 2) (match-end 0)))
8540 (insert "#+TBLFM:"))
8541 (insert " "
8542 (mapconcat (lambda (x)
8543 (concat
8544 (if (equal (string-to-char (car x)) ?@) "" "$")
8545 (car x) "=" (cdr x)))
8546 alist "::")
8547 "\n")))
8549 (defsubst org-table-formula-make-cmp-string (a)
8550 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8551 (concat
8552 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8553 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8554 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8556 (defun org-table-formula-less-p (a b)
8557 "Compare two formulas for sorting."
8558 (let ((as (org-table-formula-make-cmp-string (car a)))
8559 (bs (org-table-formula-make-cmp-string (car b))))
8560 (and as bs (string< as bs))))
8562 (defun org-table-get-stored-formulas (&optional noerror)
8563 "Return an alist with the stored formulas directly after current table."
8564 (interactive)
8565 (let (scol eq eq-alist strings string seen)
8566 (save-excursion
8567 (goto-char (org-table-end))
8568 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8569 (setq strings (org-split-string (match-string 2) " *:: *"))
8570 (while (setq string (pop strings))
8571 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8572 (setq scol (if (match-end 2)
8573 (match-string 2 string)
8574 (match-string 1 string))
8575 eq (match-string 3 string)
8576 eq-alist (cons (cons scol eq) eq-alist))
8577 (if (member scol seen)
8578 (if noerror
8579 (progn
8580 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8581 (ding)
8582 (sit-for 2))
8583 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8584 (push scol seen))))))
8585 (nreverse eq-alist)))
8587 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8588 "Modify the equations after the table structure has been edited.
8589 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8590 For all numbers larger than LIMIT, shift them by DELTA."
8591 (save-excursion
8592 (goto-char (org-table-end))
8593 (when (looking-at "#\\+TBLFM:")
8594 (let ((re (concat key "\\([0-9]+\\)"))
8595 (re2
8596 (when remove
8597 (if (equal key "$")
8598 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8599 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8600 s n a)
8601 (when remove
8602 (while (re-search-forward re2 (point-at-eol) t)
8603 (replace-match "")))
8604 (while (re-search-forward re (point-at-eol) t)
8605 (setq s (match-string 1) n (string-to-number s))
8606 (cond
8607 ((setq a (assoc s replace))
8608 (replace-match (concat key (cdr a)) t t))
8609 ((and limit (> n limit))
8610 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8612 (defun org-table-get-specials ()
8613 "Get the column names and local parameters for this table."
8614 (save-excursion
8615 (let ((beg (org-table-begin)) (end (org-table-end))
8616 names name fields fields1 field cnt
8617 c v l line col types dlines hlines)
8618 (setq org-table-column-names nil
8619 org-table-local-parameters nil
8620 org-table-named-field-locations nil
8621 org-table-current-begin-line nil
8622 org-table-current-begin-pos nil
8623 org-table-current-line-types nil)
8624 (goto-char beg)
8625 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8626 (setq names (org-split-string (match-string 1) " *| *")
8627 cnt 1)
8628 (while (setq name (pop names))
8629 (setq cnt (1+ cnt))
8630 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8631 (push (cons name (int-to-string cnt)) org-table-column-names))))
8632 (setq org-table-column-names (nreverse org-table-column-names))
8633 (setq org-table-column-name-regexp
8634 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8635 (goto-char beg)
8636 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8637 (setq fields (org-split-string (match-string 1) " *| *"))
8638 (while (setq field (pop fields))
8639 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8640 (push (cons (match-string 1 field) (match-string 2 field))
8641 org-table-local-parameters))))
8642 (goto-char beg)
8643 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8644 (setq c (match-string 1)
8645 fields (org-split-string (match-string 2) " *| *"))
8646 (save-excursion
8647 (beginning-of-line (if (equal c "_") 2 0))
8648 (setq line (org-current-line) col 1)
8649 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8650 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8651 (while (and fields1 (setq field (pop fields)))
8652 (setq v (pop fields1) col (1+ col))
8653 (when (and (stringp field) (stringp v)
8654 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8655 (push (cons field v) org-table-local-parameters)
8656 (push (list field line col) org-table-named-field-locations))))
8657 ;; Analyse the line types
8658 (goto-char beg)
8659 (setq org-table-current-begin-line (org-current-line)
8660 org-table-current-begin-pos (point)
8661 l org-table-current-begin-line)
8662 (while (looking-at "[ \t]*|\\(-\\)?")
8663 (push (if (match-end 1) 'hline 'dline) types)
8664 (if (match-end 1) (push l hlines) (push l dlines))
8665 (beginning-of-line 2)
8666 (setq l (1+ l)))
8667 (setq org-table-current-line-types (apply 'vector (nreverse types))
8668 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8669 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8671 (defun org-table-maybe-eval-formula ()
8672 "Check if the current field starts with \"=\" or \":=\".
8673 If yes, store the formula and apply it."
8674 ;; We already know we are in a table. Get field will only return a formula
8675 ;; when appropriate. It might return a separator line, but no problem.
8676 (when org-table-formula-evaluate-inline
8677 (let* ((field (org-trim (or (org-table-get-field) "")))
8678 named eq)
8679 (when (string-match "^:?=\\(.*\\)" field)
8680 (setq named (equal (string-to-char field) ?:)
8681 eq (match-string 1 field))
8682 (if (or (fboundp 'calc-eval)
8683 (equal (substring eq 0 (min 2 (length eq))) "'("))
8684 (org-table-eval-formula (if named '(4) nil)
8685 (org-table-formula-from-user eq))
8686 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8688 (defvar org-recalc-commands nil
8689 "List of commands triggering the recalculation of a line.
8690 Will be filled automatically during use.")
8692 (defvar org-recalc-marks
8693 '((" " . "Unmarked: no special line, no automatic recalculation")
8694 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8695 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8696 ("!" . "Column name definition line. Reference in formula as $name.")
8697 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8698 ("_" . "Names for values in row below this one.")
8699 ("^" . "Names for values in row above this one.")))
8701 (defun org-table-rotate-recalc-marks (&optional newchar)
8702 "Rotate the recalculation mark in the first column.
8703 If in any row, the first field is not consistent with a mark,
8704 insert a new column for the markers.
8705 When there is an active region, change all the lines in the region,
8706 after prompting for the marking character.
8707 After each change, a message will be displayed indicating the meaning
8708 of the new mark."
8709 (interactive)
8710 (unless (org-at-table-p) (error "Not at a table"))
8711 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8712 (beg (org-table-begin))
8713 (end (org-table-end))
8714 (l (org-current-line))
8715 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8716 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8717 (have-col
8718 (save-excursion
8719 (goto-char beg)
8720 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8721 (col (org-table-current-column))
8722 (forcenew (car (assoc newchar org-recalc-marks)))
8723 epos new)
8724 (when l1
8725 (message "Change region to what mark? Type # * ! $ or SPC: ")
8726 (setq newchar (char-to-string (read-char-exclusive))
8727 forcenew (car (assoc newchar org-recalc-marks))))
8728 (if (and newchar (not forcenew))
8729 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8730 newchar))
8731 (if l1 (goto-line l1))
8732 (save-excursion
8733 (beginning-of-line 1)
8734 (unless (looking-at org-table-dataline-regexp)
8735 (error "Not at a table data line")))
8736 (unless have-col
8737 (org-table-goto-column 1)
8738 (org-table-insert-column)
8739 (org-table-goto-column (1+ col)))
8740 (setq epos (point-at-eol))
8741 (save-excursion
8742 (beginning-of-line 1)
8743 (org-table-get-field
8744 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8745 (concat " "
8746 (setq new (or forcenew
8747 (cadr (member (match-string 1) marks))))
8748 " ")
8749 " # ")))
8750 (if (and l1 l2)
8751 (progn
8752 (goto-line l1)
8753 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8754 (and (looking-at org-table-dataline-regexp)
8755 (org-table-get-field 1 (concat " " new " "))))
8756 (goto-line l1)))
8757 (if (not (= epos (point-at-eol))) (org-table-align))
8758 (goto-line l)
8759 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8761 (defun org-table-maybe-recalculate-line ()
8762 "Recompute the current line if marked for it, and if we haven't just done it."
8763 (interactive)
8764 (and org-table-allow-automatic-line-recalculation
8765 (not (and (memq last-command org-recalc-commands)
8766 (equal org-last-recalc-line (org-current-line))))
8767 (save-excursion (beginning-of-line 1)
8768 (looking-at org-table-auto-recalculate-regexp))
8769 (org-table-recalculate) t))
8771 (defvar org-table-formula-debug nil
8772 "Non-nil means, debug table formulas.
8773 When nil, simply write \"#ERROR\" in corrupted fields.")
8774 (make-variable-buffer-local 'org-table-formula-debug)
8776 (defvar modes)
8777 (defsubst org-set-calc-mode (var &optional value)
8778 (if (stringp var)
8779 (setq var (assoc var '(("D" calc-angle-mode deg)
8780 ("R" calc-angle-mode rad)
8781 ("F" calc-prefer-frac t)
8782 ("S" calc-symbolic-mode t)))
8783 value (nth 2 var) var (nth 1 var)))
8784 (if (memq var modes)
8785 (setcar (cdr (memq var modes)) value)
8786 (cons var (cons value modes)))
8787 modes)
8789 (defun org-table-eval-formula (&optional arg equation
8790 suppress-align suppress-const
8791 suppress-store suppress-analysis)
8792 "Replace the table field value at the cursor by the result of a calculation.
8794 This function makes use of Dave Gillespie's Calc package, in my view the
8795 most exciting program ever written for GNU Emacs. So you need to have Calc
8796 installed in order to use this function.
8798 In a table, this command replaces the value in the current field with the
8799 result of a formula. It also installs the formula as the \"current\" column
8800 formula, by storing it in a special line below the table. When called
8801 with a `C-u' prefix, the current field must ba a named field, and the
8802 formula is installed as valid in only this specific field.
8804 When called with two `C-u' prefixes, insert the active equation
8805 for the field back into the current field, so that it can be
8806 edited there. This is useful in order to use \\[org-table-show-reference]
8807 to check the referenced fields.
8809 When called, the command first prompts for a formula, which is read in
8810 the minibuffer. Previously entered formulas are available through the
8811 history list, and the last used formula is offered as a default.
8812 These stored formulas are adapted correctly when moving, inserting, or
8813 deleting columns with the corresponding commands.
8815 The formula can be any algebraic expression understood by the Calc package.
8816 For details, see the Org-mode manual.
8818 This function can also be called from Lisp programs and offers
8819 additional arguments: EQUATION can be the formula to apply. If this
8820 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8821 used to speed-up recursive calls by by-passing unnecessary aligns.
8822 SUPPRESS-CONST suppresses the interpretation of constants in the
8823 formula, assuming that this has been done already outside the function.
8824 SUPPRESS-STORE means the formula should not be stored, either because
8825 it is already stored, or because it is a modified equation that should
8826 not overwrite the stored one."
8827 (interactive "P")
8828 (org-table-check-inside-data-field)
8829 (or suppress-analysis (org-table-get-specials))
8830 (if (equal arg '(16))
8831 (let ((eq (org-table-current-field-formula)))
8832 (or eq (error "No equation active for current field"))
8833 (org-table-get-field nil eq)
8834 (org-table-align)
8835 (setq org-table-may-need-update t))
8836 (let* (fields
8837 (ndown (if (integerp arg) arg 1))
8838 (org-table-automatic-realign nil)
8839 (case-fold-search nil)
8840 (down (> ndown 1))
8841 (formula (if (and equation suppress-store)
8842 equation
8843 (org-table-get-formula equation (equal arg '(4)))))
8844 (n0 (org-table-current-column))
8845 (modes (copy-sequence org-calc-default-modes))
8846 (numbers nil) ; was a variable, now fixed default
8847 (keep-empty nil)
8848 n form form0 bw fmt x ev orig c lispp literal)
8849 ;; Parse the format string. Since we have a lot of modes, this is
8850 ;; a lot of work. However, I think calc still uses most of the time.
8851 (if (string-match ";" formula)
8852 (let ((tmp (org-split-string formula ";")))
8853 (setq formula (car tmp)
8854 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8855 (nth 1 tmp)))
8856 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8857 (setq c (string-to-char (match-string 1 fmt))
8858 n (string-to-number (match-string 2 fmt)))
8859 (if (= c ?p)
8860 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8861 (setq modes (org-set-calc-mode
8862 'calc-float-format
8863 (list (cdr (assoc c '((?n . float) (?f . fix)
8864 (?s . sci) (?e . eng))))
8865 n))))
8866 (setq fmt (replace-match "" t t fmt)))
8867 (if (string-match "[NT]" fmt)
8868 (setq numbers (equal (match-string 0 fmt) "N")
8869 fmt (replace-match "" t t fmt)))
8870 (if (string-match "L" fmt)
8871 (setq literal t
8872 fmt (replace-match "" t t fmt)))
8873 (if (string-match "E" fmt)
8874 (setq keep-empty t
8875 fmt (replace-match "" t t fmt)))
8876 (while (string-match "[DRFS]" fmt)
8877 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8878 (setq fmt (replace-match "" t t fmt)))
8879 (unless (string-match "\\S-" fmt)
8880 (setq fmt nil))))
8881 (if (and (not suppress-const) org-table-formula-use-constants)
8882 (setq formula (org-table-formula-substitute-names formula)))
8883 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8884 (while (> ndown 0)
8885 (setq fields (org-split-string
8886 (org-no-properties
8887 (buffer-substring (point-at-bol) (point-at-eol)))
8888 " *| *"))
8889 (if (eq numbers t)
8890 (setq fields (mapcar
8891 (lambda (x) (number-to-string (string-to-number x)))
8892 fields)))
8893 (setq ndown (1- ndown))
8894 (setq form (copy-sequence formula)
8895 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8896 (if (and lispp literal) (setq lispp 'literal))
8897 ;; Check for old vertical references
8898 (setq form (org-rewrite-old-row-references form))
8899 ;; Insert complex ranges
8900 (while (string-match org-table-range-regexp form)
8901 (setq form
8902 (replace-match
8903 (save-match-data
8904 (org-table-make-reference
8905 (org-table-get-range (match-string 0 form) nil n0)
8906 keep-empty numbers lispp))
8907 t t form)))
8908 ;; Insert simple ranges
8909 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8910 (setq form
8911 (replace-match
8912 (save-match-data
8913 (org-table-make-reference
8914 (org-sublist
8915 fields (string-to-number (match-string 1 form))
8916 (string-to-number (match-string 2 form)))
8917 keep-empty numbers lispp))
8918 t t form)))
8919 (setq form0 form)
8920 ;; Insert the references to fields in same row
8921 (while (string-match "\\$\\([0-9]+\\)" form)
8922 (setq n (string-to-number (match-string 1 form))
8923 x (nth (1- (if (= n 0) n0 n)) fields))
8924 (unless x (error "Invalid field specifier \"%s\""
8925 (match-string 0 form)))
8926 (setq form (replace-match
8927 (save-match-data
8928 (org-table-make-reference x nil numbers lispp))
8929 t t form)))
8931 (if lispp
8932 (setq ev (condition-case nil
8933 (eval (eval (read form)))
8934 (error "#ERROR"))
8935 ev (if (numberp ev) (number-to-string ev) ev))
8936 (or (fboundp 'calc-eval)
8937 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8938 (setq ev (calc-eval (cons form modes)
8939 (if numbers 'num))))
8941 (when org-table-formula-debug
8942 (with-output-to-temp-buffer "*Substitution History*"
8943 (princ (format "Substitution history of formula
8944 Orig: %s
8945 $xyz-> %s
8946 @r$c-> %s
8947 $1-> %s\n" orig formula form0 form))
8948 (if (listp ev)
8949 (princ (format " %s^\nError: %s"
8950 (make-string (car ev) ?\-) (nth 1 ev)))
8951 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8952 ev (or fmt "NONE")
8953 (if fmt (format fmt (string-to-number ev)) ev)))))
8954 (setq bw (get-buffer-window "*Substitution History*"))
8955 (shrink-window-if-larger-than-buffer bw)
8956 (unless (and (interactive-p) (not ndown))
8957 (unless (let (inhibit-redisplay)
8958 (y-or-n-p "Debugging Formula. Continue to next? "))
8959 (org-table-align)
8960 (error "Abort"))
8961 (delete-window bw)
8962 (message "")))
8963 (if (listp ev) (setq fmt nil ev "#ERROR"))
8964 (org-table-justify-field-maybe
8965 (if fmt (format fmt (string-to-number ev)) ev))
8966 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8967 (call-interactively 'org-return)
8968 (setq ndown 0)))
8969 (and down (org-table-maybe-recalculate-line))
8970 (or suppress-align (and org-table-may-need-update
8971 (org-table-align))))))
8973 (defun org-table-put-field-property (prop value)
8974 (save-excursion
8975 (put-text-property (progn (skip-chars-backward "^|") (point))
8976 (progn (skip-chars-forward "^|") (point))
8977 prop value)))
8979 (defun org-table-get-range (desc &optional tbeg col highlight)
8980 "Get a calc vector from a column, accorting to descriptor DESC.
8981 Optional arguments TBEG and COL can give the beginning of the table and
8982 the current column, to avoid unnecessary parsing.
8983 HIGHLIGHT means, just highlight the range."
8984 (if (not (equal (string-to-char desc) ?@))
8985 (setq desc (concat "@" desc)))
8986 (save-excursion
8987 (or tbeg (setq tbeg (org-table-begin)))
8988 (or col (setq col (org-table-current-column)))
8989 (let ((thisline (org-current-line))
8990 beg end c1 c2 r1 r2 rangep tmp)
8991 (unless (string-match org-table-range-regexp desc)
8992 (error "Invalid table range specifier `%s'" desc))
8993 (setq rangep (match-end 3)
8994 r1 (and (match-end 1) (match-string 1 desc))
8995 r2 (and (match-end 4) (match-string 4 desc))
8996 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8997 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8999 (and c1 (setq c1 (+ (string-to-number c1)
9000 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9001 (and c2 (setq c2 (+ (string-to-number c2)
9002 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9003 (if (equal r1 "") (setq r1 nil))
9004 (if (equal r2 "") (setq r2 nil))
9005 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9006 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9007 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9008 (if (not r1) (setq r1 thisline))
9009 (if (not r2) (setq r2 thisline))
9010 (if (not c1) (setq c1 col))
9011 (if (not c2) (setq c2 col))
9012 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9013 ;; just one field
9014 (progn
9015 (goto-line r1)
9016 (while (not (looking-at org-table-dataline-regexp))
9017 (beginning-of-line 2))
9018 (prog1 (org-trim (org-table-get-field c1))
9019 (if highlight (org-table-highlight-rectangle (point) (point)))))
9020 ;; A range, return a vector
9021 ;; First sort the numbers to get a regular ractangle
9022 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9023 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9024 (goto-line r1)
9025 (while (not (looking-at org-table-dataline-regexp))
9026 (beginning-of-line 2))
9027 (org-table-goto-column c1)
9028 (setq beg (point))
9029 (goto-line r2)
9030 (while (not (looking-at org-table-dataline-regexp))
9031 (beginning-of-line 0))
9032 (org-table-goto-column c2)
9033 (setq end (point))
9034 (if highlight
9035 (org-table-highlight-rectangle
9036 beg (progn (skip-chars-forward "^|\n") (point))))
9037 ;; return string representation of calc vector
9038 (mapcar 'org-trim
9039 (apply 'append (org-table-copy-region beg end)))))))
9041 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9042 "Analyze descriptor DESC and retrieve the corresponding line number.
9043 The cursor is currently in line CLINE, the table begins in line BLINE,
9044 and TABLE is a vector with line types."
9045 (if (string-match "^[0-9]+$" desc)
9046 (aref org-table-dlines (string-to-number desc))
9047 (setq cline (or cline (org-current-line))
9048 bline (or bline org-table-current-begin-line)
9049 table (or table org-table-current-line-types))
9050 (if (or
9051 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9052 ;; 1 2 3 4 5 6
9053 (and (not (match-end 3)) (not (match-end 6)))
9054 (and (match-end 3) (match-end 6) (not (match-end 5))))
9055 (error "invalid row descriptor `%s'" desc))
9056 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9057 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9058 (odir (and (match-end 5) (match-string 5 desc)))
9059 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9060 (i (- cline bline))
9061 (rel (and (match-end 6)
9062 (or (and (match-end 1) (not (match-end 3)))
9063 (match-end 5)))))
9064 (if (and hn (not hdir))
9065 (progn
9066 (setq i 0 hdir "+")
9067 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9068 (if (and (not hn) on (not odir))
9069 (error "should never happen");;(aref org-table-dlines on)
9070 (if (and hn (> hn 0))
9071 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9072 (if on
9073 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9074 (+ bline i)))))
9076 (defun org-find-row-type (table i type backwards relative n)
9077 (let ((l (length table)))
9078 (while (> n 0)
9079 (while (and (setq i (+ i (if backwards -1 1)))
9080 (>= i 0) (< i l)
9081 (not (eq (aref table i) type))
9082 (if (and relative (eq (aref table i) 'hline))
9083 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9084 t)))
9085 (setq n (1- n)))
9086 (if (or (< i 0) (>= i l))
9087 (error "Row descriptior leads outside table")
9088 i)))
9090 (defun org-rewrite-old-row-references (s)
9091 (if (string-match "&[-+0-9I]" s)
9092 (error "Formula contains old &row reference, please rewrite using @-syntax")
9095 (defun org-table-make-reference (elements keep-empty numbers lispp)
9096 "Convert list ELEMENTS to something appropriate to insert into formula.
9097 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9098 NUMBERS indicates that everything should be converted to numbers.
9099 LISPP means to return something appropriate for a Lisp list."
9100 (if (stringp elements) ; just a single val
9101 (if lispp
9102 (if (eq lispp 'literal)
9103 elements
9104 (prin1-to-string (if numbers (string-to-number elements) elements)))
9105 (if (equal elements "") (setq elements "0"))
9106 (if numbers (number-to-string (string-to-number elements)) elements))
9107 (unless keep-empty
9108 (setq elements
9109 (delq nil
9110 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9111 elements))))
9112 (setq elements (or elements '("0")))
9113 (if lispp
9114 (mapconcat
9115 (lambda (x)
9116 (if (eq lispp 'literal)
9118 (prin1-to-string (if numbers (string-to-number x) x))))
9119 elements " ")
9120 (concat "[" (mapconcat
9121 (lambda (x)
9122 (if numbers (number-to-string (string-to-number x)) x))
9123 elements
9124 ",") "]"))))
9126 (defun org-table-recalculate (&optional all noalign)
9127 "Recalculate the current table line by applying all stored formulas.
9128 With prefix arg ALL, do this for all lines in the table."
9129 (interactive "P")
9130 (or (memq this-command org-recalc-commands)
9131 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9132 (unless (org-at-table-p) (error "Not at a table"))
9133 (if (equal all '(16))
9134 (org-table-iterate)
9135 (org-table-get-specials)
9136 (let* ((eqlist (sort (org-table-get-stored-formulas)
9137 (lambda (a b) (string< (car a) (car b)))))
9138 (inhibit-redisplay (not debug-on-error))
9139 (line-re org-table-dataline-regexp)
9140 (thisline (org-current-line))
9141 (thiscol (org-table-current-column))
9142 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9143 ;; Insert constants in all formulas
9144 (setq eqlist
9145 (mapcar (lambda (x)
9146 (setcdr x (org-table-formula-substitute-names (cdr x)))
9148 eqlist))
9149 ;; Split the equation list
9150 (while (setq eq (pop eqlist))
9151 (if (<= (string-to-char (car eq)) ?9)
9152 (push eq eqlnum)
9153 (push eq eqlname)))
9154 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9155 (if all
9156 (progn
9157 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9158 (goto-char (setq beg (org-table-begin)))
9159 (if (re-search-forward org-table-calculate-mark-regexp end t)
9160 ;; This is a table with marked lines, compute selected lines
9161 (setq line-re org-table-recalculate-regexp)
9162 ;; Move forward to the first non-header line
9163 (if (and (re-search-forward org-table-dataline-regexp end t)
9164 (re-search-forward org-table-hline-regexp end t)
9165 (re-search-forward org-table-dataline-regexp end t))
9166 (setq beg (match-beginning 0))
9167 nil))) ;; just leave beg where it is
9168 (setq beg (point-at-bol)
9169 end (move-marker (make-marker) (1+ (point-at-eol)))))
9170 (goto-char beg)
9171 (and all (message "Re-applying formulas to full table..."))
9173 ;; First find the named fields, and mark them untouchanble
9174 (remove-text-properties beg end '(org-untouchable t))
9175 (while (setq eq (pop eqlname))
9176 (setq name (car eq)
9177 a (assoc name org-table-named-field-locations))
9178 (and (not a)
9179 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9180 (setq a (list name
9181 (aref org-table-dlines
9182 (string-to-number (match-string 1 name)))
9183 (string-to-number (match-string 2 name)))))
9184 (when (and a (or all (equal (nth 1 a) thisline)))
9185 (message "Re-applying formula to field: %s" name)
9186 (goto-line (nth 1 a))
9187 (org-table-goto-column (nth 2 a))
9188 (push (append a (list (cdr eq))) eqlname1)
9189 ;; FIXME (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
9190 ;; FIXME 'nostore 'noanalysis)
9191 (org-table-put-field-property :org-untouchable t)))
9193 ;; Now evauluate the column formulas, but skip fields covered by
9194 ;; field formulas
9195 (goto-char beg)
9196 (while (re-search-forward line-re end t)
9197 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9198 ;; Unprotected line, recalculate
9199 (and all (message "Re-applying formulas to full table...(line %d)"
9200 (setq cnt (1+ cnt))))
9201 (setq org-last-recalc-line (org-current-line))
9202 (setq eql eqlnum)
9203 (while (setq entry (pop eql))
9204 (goto-line org-last-recalc-line)
9205 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9206 (unless (get-text-property (point) :org-untouchable)
9207 (org-table-eval-formula nil (cdr entry)
9208 'noalign 'nocst 'nostore 'noanalysis)))))
9210 ;; Now evaluate the field formulas
9211 (while (setq eq (pop eqlname1))
9212 (message "Re-applying formula to field: %s" (car eq))
9213 (goto-line (nth 1 eq))
9214 (org-table-goto-column (nth 2 eq))
9215 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9216 'nostore 'noanalysis))
9218 (goto-line thisline)
9219 (org-table-goto-column thiscol)
9220 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9221 (or noalign (and org-table-may-need-update (org-table-align))
9222 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9224 ;; back to initial position
9225 (message "Re-applying formulas...done")
9226 (goto-line thisline)
9227 (org-table-goto-column thiscol)
9228 (or noalign (and org-table-may-need-update (org-table-align))
9229 (and all (message "Re-applying formulas...done"))))))
9231 (defun org-table-iterate (&optional arg)
9232 "Recalculate the table until it does not change anymore."
9233 (interactive "P")
9234 (let ((imax (if arg (prefix-numeric-value arg) 10))
9235 (i 0)
9236 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9237 thistbl)
9238 (catch 'exit
9239 (while (< i imax)
9240 (setq i (1+ i))
9241 (org-table-recalculate 'all)
9242 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9243 (if (not (string= lasttbl thistbl))
9244 (setq lasttbl thistbl)
9245 (if (> i 1)
9246 (message "Convergence after %d iterations" i)
9247 (message "Table was already stable"))
9248 (throw 'exit t)))
9249 (error "No convergence after %d iterations" i))))
9251 (defun org-table-formula-substitute-names (f)
9252 "Replace $const with values in string F."
9253 (let ((start 0) a (f1 f))
9254 ;; First, check for column names
9255 (while (setq start (string-match org-table-column-name-regexp f start))
9256 (setq start (1+ start))
9257 (setq a (assoc (match-string 1 f) org-table-column-names))
9258 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9259 ;; Parameters and constants
9260 (setq start 0)
9261 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9262 (setq start (1+ start))
9263 (if (setq a (save-match-data
9264 (org-table-get-constant (match-string 1 f))))
9265 (setq f (replace-match (concat "(" a ")") t t f))))
9266 (if org-table-formula-debug
9267 (put-text-property 0 (length f) :orig-formula f1 f))
9270 (defun org-table-get-constant (const)
9271 "Find the value for a parameter or constant in a formula.
9272 Parameters get priority."
9273 (or (cdr (assoc const org-table-local-parameters))
9274 (cdr (assoc const org-table-formula-constants-local))
9275 (cdr (assoc const org-table-formula-constants))
9276 (and (fboundp 'constants-get) (constants-get const))
9277 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9278 (org-entry-get nil (substring const 5) 'inherit))
9279 "#UNDEFINED_NAME"))
9281 (defvar org-table-fedit-map
9282 (let ((map (make-sparse-keymap)))
9283 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9284 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9285 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9286 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9287 (org-defkey map "\C-c?" 'org-table-show-reference)
9288 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9289 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9290 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9291 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9292 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9293 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9294 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9295 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9296 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9297 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9298 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9299 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9300 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9301 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9302 map))
9304 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9305 '("Edit-Formulas"
9306 ["Finish and Install" org-table-fedit-finish t]
9307 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9308 ["Abort" org-table-fedit-abort t]
9309 "--"
9310 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9311 ["Complete Lisp Symbol" lisp-complete-symbol t]
9312 "--"
9313 "Shift Reference at Point"
9314 ["Up" org-table-fedit-ref-up t]
9315 ["Down" org-table-fedit-ref-down t]
9316 ["Left" org-table-fedit-ref-left t]
9317 ["Right" org-table-fedit-ref-right t]
9319 "Change Test Row for Column Formulas"
9320 ["Up" org-table-fedit-line-up t]
9321 ["Down" org-table-fedit-line-down t]
9322 "--"
9323 ["Scroll Table Window" org-table-fedit-scroll t]
9324 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9325 ["Show Table Grid" org-table-fedit-toggle-coordinates
9326 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9327 org-table-overlay-coordinates)]
9328 "--"
9329 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9330 :style toggle :selected org-table-buffer-is-an]))
9332 (defvar org-pos)
9334 (defun org-table-edit-formulas ()
9335 "Edit the formulas of the current table in a separate buffer."
9336 (interactive)
9337 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9338 (beginning-of-line 0))
9339 (unless (org-at-table-p) (error "Not at a table"))
9340 (org-table-get-specials)
9341 (let ((key (org-table-current-field-formula 'key 'noerror))
9342 (eql (sort (org-table-get-stored-formulas 'noerror)
9343 'org-table-formula-less-p))
9344 (pos (move-marker (make-marker) (point)))
9345 (startline 1)
9346 (wc (current-window-configuration))
9347 (titles '((column . "# Column Formulas\n")
9348 (field . "# Field Formulas\n")
9349 (named . "# Named Field Formulas\n")))
9350 entry s type title)
9351 (org-switch-to-buffer-other-window "*Edit Formulas*")
9352 (erase-buffer)
9353 ;; Keep global-font-lock-mode from turning on font-lock-mode
9354 (let ((font-lock-global-modes '(not fundamental-mode)))
9355 (fundamental-mode))
9356 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9357 (org-set-local 'org-pos pos)
9358 (org-set-local 'org-window-configuration wc)
9359 (use-local-map org-table-fedit-map)
9360 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9361 (easy-menu-add org-table-fedit-menu)
9362 (setq startline (org-current-line))
9363 (while (setq entry (pop eql))
9364 (setq type (cond
9365 ((equal (string-to-char (car entry)) ?@) 'field)
9366 ((string-match "^[0-9]" (car entry)) 'column)
9367 (t 'named)))
9368 (when (setq title (assq type titles))
9369 (or (bobp) (insert "\n"))
9370 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9371 (setq titles (delq title titles)))
9372 (if (equal key (car entry)) (setq startline (org-current-line)))
9373 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9374 (car entry) " = " (cdr entry) "\n"))
9375 (remove-text-properties 0 (length s) '(face nil) s)
9376 (insert s))
9377 (if (eq org-table-use-standard-references t)
9378 (org-table-fedit-toggle-ref-type))
9379 (goto-line startline)
9380 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9382 (defun org-table-fedit-post-command ()
9383 (when (not (memq this-command '(lisp-complete-symbol)))
9384 (let ((win (selected-window)))
9385 (save-excursion
9386 (condition-case nil
9387 (org-table-show-reference)
9388 (error nil))
9389 (select-window win)))))
9391 (defun org-table-formula-to-user (s)
9392 "Convert a formula from internal to user representation."
9393 (if (eq org-table-use-standard-references t)
9394 (org-table-convert-refs-to-an s)
9397 (defun org-table-formula-from-user (s)
9398 "Convert a formula from user to internal representation."
9399 (if org-table-use-standard-references
9400 (org-table-convert-refs-to-rc s)
9403 (defun org-table-convert-refs-to-rc (s)
9404 "Convert spreadsheet references from AB7 to @7$28.
9405 Works for single references, but also for entire formulas and even the
9406 full TBLFM line."
9407 (let ((start 0))
9408 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9409 (cond
9410 ((match-end 3)
9411 ;; format match, just advance
9412 (setq start (match-end 0)))
9413 ((and (> (match-beginning 0) 0)
9414 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9415 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9416 ;; 3.e5 or something like this. FIXME: is this ok????
9417 (setq start (match-end 0)))
9419 (setq start (match-beginning 0)
9420 s (replace-match
9421 (if (equal (match-string 2 s) "&")
9422 (format "$%d" (org-letters-to-number (match-string 1 s)))
9423 (format "@%d$%d"
9424 (string-to-number (match-string 2 s))
9425 (org-letters-to-number (match-string 1 s))))
9426 t t s)))))
9429 (defun org-table-convert-refs-to-an (s)
9430 "Convert spreadsheet references from to @7$28 to AB7.
9431 Works for single references, but also for entire formulas and even the
9432 full TBLFM line."
9433 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9434 (setq s (replace-match
9435 (format "%s%d"
9436 (org-number-to-letters
9437 (string-to-number (match-string 2 s)))
9438 (string-to-number (match-string 1 s)))
9439 t t s)))
9440 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9441 (setq s (replace-match (concat "\\1"
9442 (org-number-to-letters
9443 (string-to-number (match-string 2 s))) "&")
9444 t nil s)))
9447 (defun org-letters-to-number (s)
9448 "Convert a base 26 number represented by letters into an integer.
9449 For example: AB -> 28."
9450 (let ((n 0))
9451 (setq s (upcase s))
9452 (while (> (length s) 0)
9453 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9454 s (substring s 1)))
9457 (defun org-number-to-letters (n)
9458 "Convert an integer into a base 26 number represented by letters.
9459 For example: 28 -> AB."
9460 (let ((s ""))
9461 (while (> n 0)
9462 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9463 n (/ (1- n) 26)))
9466 (defun org-table-fedit-convert-buffer (function)
9467 "Convert all references in this buffer, using FUNTION."
9468 (let ((line (org-current-line)))
9469 (goto-char (point-min))
9470 (while (not (eobp))
9471 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9472 (delete-region (point) (point-at-eol))
9473 (or (eobp) (forward-char 1)))
9474 (goto-line line)))
9476 (defun org-table-fedit-toggle-ref-type ()
9477 "Convert all references in the buffer from B3 to @3$2 and back."
9478 (interactive)
9479 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9480 (org-table-fedit-convert-buffer
9481 (if org-table-buffer-is-an
9482 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9483 (message "Reference type switched to %s"
9484 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9486 (defun org-table-fedit-ref-up ()
9487 "Shift the reference at point one row/hline up."
9488 (interactive)
9489 (org-table-fedit-shift-reference 'up))
9490 (defun org-table-fedit-ref-down ()
9491 "Shift the reference at point one row/hline down."
9492 (interactive)
9493 (org-table-fedit-shift-reference 'down))
9494 (defun org-table-fedit-ref-left ()
9495 "Shift the reference at point one field to the left."
9496 (interactive)
9497 (org-table-fedit-shift-reference 'left))
9498 (defun org-table-fedit-ref-right ()
9499 "Shift the reference at point one field to the right."
9500 (interactive)
9501 (org-table-fedit-shift-reference 'right))
9503 (defun org-table-fedit-shift-reference (dir)
9504 (cond
9505 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9506 (if (memq dir '(left right))
9507 (org-rematch-and-replace 1 (eq dir 'left))
9508 (error "Cannot shift reference in this direction")))
9509 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9510 ;; A B3-like reference
9511 (if (memq dir '(up down))
9512 (org-rematch-and-replace 2 (eq dir 'up))
9513 (org-rematch-and-replace 1 (eq dir 'left))))
9514 ((org-at-regexp-p
9515 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9516 ;; An internal reference
9517 (if (memq dir '(up down))
9518 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9519 (org-rematch-and-replace 5 (eq dir 'left))))))
9521 (defun org-rematch-and-replace (n &optional decr hline)
9522 "Re-match the group N, and replace it with the shifted refrence."
9523 (or (match-end n) (error "Cannot shift reference in this direction"))
9524 (goto-char (match-beginning n))
9525 (and (looking-at (regexp-quote (match-string n)))
9526 (replace-match (org-shift-refpart (match-string 0) decr hline)
9527 t t)))
9529 (defun org-shift-refpart (ref &optional decr hline)
9530 "Shift a refrence part REF.
9531 If DECR is set, decrease the references row/column, else increase.
9532 If HLINE is set, this may be a hline reference, it certainly is not
9533 a translation reference."
9534 (save-match-data
9535 (let* ((sign (string-match "^[-+]" ref)) n)
9537 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9538 (cond
9539 ((and hline (string-match "^I+" ref))
9540 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9541 (setq n (+ n (if decr -1 1)))
9542 (if (= n 0) (setq n (+ n (if decr -1 1))))
9543 (if sign
9544 (setq sign (if (< n 0) "-" "+") n (abs n))
9545 (setq n (max 1 n)))
9546 (concat sign (make-string n ?I)))
9548 ((string-match "^[0-9]+" ref)
9549 (setq n (string-to-number (concat sign ref)))
9550 (setq n (+ n (if decr -1 1)))
9551 (if sign
9552 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9553 (number-to-string (max 1 n))))
9555 ((string-match "^[a-zA-Z]+" ref)
9556 (org-number-to-letters
9557 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9559 (t (error "Cannot shift reference"))))))
9561 (defun org-table-fedit-toggle-coordinates ()
9562 "Toggle the display of coordinates in the refrenced table."
9563 (interactive)
9564 (let ((pos (marker-position org-pos)))
9565 (with-current-buffer (marker-buffer org-pos)
9566 (save-excursion
9567 (goto-char pos)
9568 (org-table-toggle-coordinate-overlays)))))
9570 (defun org-table-fedit-finish (&optional arg)
9571 "Parse the buffer for formula definitions and install them.
9572 With prefix ARG, apply the new formulas to the table."
9573 (interactive "P")
9574 (org-table-remove-rectangle-highlight)
9575 (if org-table-use-standard-references
9576 (progn
9577 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9578 (setq org-table-buffer-is-an nil)))
9579 (let ((pos org-pos) eql var form)
9580 (goto-char (point-min))
9581 (while (re-search-forward
9582 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9583 nil t)
9584 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9585 form (match-string 3))
9586 (setq form (org-trim form))
9587 (when (not (equal form ""))
9588 (while (string-match "[ \t]*\n[ \t]*" form)
9589 (setq form (replace-match " " t t form)))
9590 (when (assoc var eql)
9591 (error "Double formulas for %s" var))
9592 (push (cons var form) eql)))
9593 (setq org-pos nil)
9594 (set-window-configuration org-window-configuration)
9595 (select-window (get-buffer-window (marker-buffer pos)))
9596 (goto-char pos)
9597 (unless (org-at-table-p)
9598 (error "Lost table position - cannot install formulae"))
9599 (org-table-store-formulas eql)
9600 (move-marker pos nil)
9601 (kill-buffer "*Edit Formulas*")
9602 (if arg
9603 (org-table-recalculate 'all)
9604 (message "New formulas installed - press C-u C-c C-c to apply."))))
9606 (defun org-table-fedit-abort ()
9607 "Abort editing formulas, without installing the changes."
9608 (interactive)
9609 (org-table-remove-rectangle-highlight)
9610 (let ((pos org-pos))
9611 (set-window-configuration org-window-configuration)
9612 (select-window (get-buffer-window (marker-buffer pos)))
9613 (goto-char pos)
9614 (move-marker pos nil)
9615 (message "Formula editing aborted without installing changes")))
9617 (defun org-table-fedit-lisp-indent ()
9618 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9619 (interactive)
9620 (let ((pos (point)) beg end ind)
9621 (beginning-of-line 1)
9622 (cond
9623 ((looking-at "[ \t]")
9624 (goto-char pos)
9625 (call-interactively 'lisp-indent-line))
9626 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9627 ((not (fboundp 'pp-buffer))
9628 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9629 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9630 (goto-char (- (match-end 0) 2))
9631 (setq beg (point))
9632 (setq ind (make-string (current-column) ?\ ))
9633 (condition-case nil (forward-sexp 1)
9634 (error
9635 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9636 (setq end (point))
9637 (save-restriction
9638 (narrow-to-region beg end)
9639 (if (eq last-command this-command)
9640 (progn
9641 (goto-char (point-min))
9642 (setq this-command nil)
9643 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9644 (replace-match " ")))
9645 (pp-buffer)
9646 (untabify (point-min) (point-max))
9647 (goto-char (1+ (point-min)))
9648 (while (re-search-forward "^." nil t)
9649 (beginning-of-line 1)
9650 (insert ind))
9651 (goto-char (point-max))
9652 (backward-delete-char 1)))
9653 (goto-char beg))
9654 (t nil))))
9656 (defvar org-show-positions nil)
9658 (defun org-table-show-reference (&optional local)
9659 "Show the location/value of the $ expression at point."
9660 (interactive)
9661 (org-table-remove-rectangle-highlight)
9662 (catch 'exit
9663 (let ((pos (if local (point) org-pos))
9664 (face2 'highlight)
9665 (org-inhibit-highlight-removal t)
9666 (win (selected-window))
9667 (org-show-positions nil)
9668 var name e what match dest)
9669 (if local (org-table-get-specials))
9670 (setq what (cond
9671 ((or (org-at-regexp-p org-table-range-regexp2)
9672 (org-at-regexp-p org-table-translate-regexp)
9673 (org-at-regexp-p org-table-range-regexp))
9674 (setq match
9675 (save-match-data
9676 (org-table-convert-refs-to-rc (match-string 0))))
9677 'range)
9678 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9679 ((org-at-regexp-p "\\$[0-9]+") 'column)
9680 ((not local) nil)
9681 (t (error "No reference at point")))
9682 match (and what (or match (match-string 0))))
9683 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9684 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9685 'secondary-selection))
9686 (org-add-hook 'before-change-functions
9687 'org-table-remove-rectangle-highlight)
9688 (if (eq what 'name) (setq var (substring match 1)))
9689 (when (eq what 'range)
9690 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9691 (setq match (org-table-formula-substitute-names match)))
9692 (unless local
9693 (save-excursion
9694 (end-of-line 1)
9695 (re-search-backward "^\\S-" nil t)
9696 (beginning-of-line 1)
9697 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9698 (setq dest
9699 (save-match-data
9700 (org-table-convert-refs-to-rc (match-string 1))))
9701 (org-table-add-rectangle-overlay
9702 (match-beginning 1) (match-end 1) face2))))
9703 (if (and (markerp pos) (marker-buffer pos))
9704 (if (get-buffer-window (marker-buffer pos))
9705 (select-window (get-buffer-window (marker-buffer pos)))
9706 (org-switch-to-buffer-other-window (get-buffer-window
9707 (marker-buffer pos)))))
9708 (goto-char pos)
9709 (org-table-force-dataline)
9710 (when dest
9711 (setq name (substring dest 1))
9712 (cond
9713 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9714 (setq e (assoc name org-table-named-field-locations))
9715 (goto-line (nth 1 e))
9716 (org-table-goto-column (nth 2 e)))
9717 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9718 (let ((l (string-to-number (match-string 1 dest)))
9719 (c (string-to-number (match-string 2 dest))))
9720 (goto-line (aref org-table-dlines l))
9721 (org-table-goto-column c)))
9722 (t (org-table-goto-column (string-to-number name))))
9723 (move-marker pos (point))
9724 (org-table-highlight-rectangle nil nil face2))
9725 (cond
9726 ((equal dest match))
9727 ((not match))
9728 ((eq what 'range)
9729 (condition-case nil
9730 (save-excursion
9731 (org-table-get-range match nil nil 'highlight))
9732 (error nil)))
9733 ((setq e (assoc var org-table-named-field-locations))
9734 (goto-line (nth 1 e))
9735 (org-table-goto-column (nth 2 e))
9736 (org-table-highlight-rectangle (point) (point))
9737 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9738 ((setq e (assoc var org-table-column-names))
9739 (org-table-goto-column (string-to-number (cdr e)))
9740 (org-table-highlight-rectangle (point) (point))
9741 (goto-char (org-table-begin))
9742 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9743 (org-table-end) t)
9744 (progn
9745 (goto-char (match-beginning 1))
9746 (org-table-highlight-rectangle)
9747 (message "Named column (column %s)" (cdr e)))
9748 (error "Column name not found")))
9749 ((eq what 'column)
9750 ;; column number
9751 (org-table-goto-column (string-to-number (substring match 1)))
9752 (org-table-highlight-rectangle (point) (point))
9753 (message "Column %s" (substring match 1)))
9754 ((setq e (assoc var org-table-local-parameters))
9755 (goto-char (org-table-begin))
9756 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9757 (progn
9758 (goto-char (match-beginning 1))
9759 (org-table-highlight-rectangle)
9760 (message "Local parameter."))
9761 (error "Parameter not found")))
9763 (cond
9764 ((not var) (error "No reference at point"))
9765 ((setq e (assoc var org-table-formula-constants-local))
9766 (message "Local Constant: $%s=%s in #+CONSTANTS line."
9767 var (cdr e)))
9768 ((setq e (assoc var org-table-formula-constants))
9769 (message "Constant: $%s=%s in `org-table-formula-constants'."
9770 var (cdr e)))
9771 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9772 (message "Constant: $%s=%s, from `constants.el'%s."
9773 var e (format " (%s units)" constants-unit-system)))
9774 (t (error "Undefined name $%s" var)))))
9775 (goto-char pos)
9776 (when (and org-show-positions
9777 (not (memq this-command '(org-table-fedit-scroll
9778 org-table-fedit-scroll-down))))
9779 (push pos org-show-positions)
9780 (push org-table-current-begin-pos org-show-positions)
9781 (let ((min (apply 'min org-show-positions))
9782 (max (apply 'max org-show-positions)))
9783 (goto-char min) (recenter 0)
9784 (goto-char max)
9785 (or (pos-visible-in-window-p max) (recenter -1))))
9786 (select-window win))))
9788 (defun org-table-force-dataline ()
9789 "Make sure the cursor is in a dataline in a table."
9790 (unless (save-excursion
9791 (beginning-of-line 1)
9792 (looking-at org-table-dataline-regexp))
9793 (let* ((re org-table-dataline-regexp)
9794 (p1 (save-excursion (re-search-forward re nil 'move)))
9795 (p2 (save-excursion (re-search-backward re nil 'move))))
9796 (cond ((and p1 p2)
9797 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9798 p1 p2)))
9799 ((or p1 p2) (goto-char (or p1 p2)))
9800 (t (error "No table dataline around here"))))))
9802 (defun org-table-fedit-line-up ()
9803 "Move cursor one line up in the window showing the table."
9804 (interactive)
9805 (org-table-fedit-move 'previous-line))
9807 (defun org-table-fedit-line-down ()
9808 "Move cursor one line down in the window showing the table."
9809 (interactive)
9810 (org-table-fedit-move 'next-line))
9812 (defun org-table-fedit-move (command)
9813 "Move the cursor in the window shoinw the table.
9814 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9815 (let ((org-table-allow-automatic-line-recalculation nil)
9816 (pos org-pos) (win (selected-window)) p)
9817 (select-window (get-buffer-window (marker-buffer org-pos)))
9818 (setq p (point))
9819 (call-interactively command)
9820 (while (and (org-at-table-p)
9821 (org-at-table-hline-p))
9822 (call-interactively command))
9823 (or (org-at-table-p) (goto-char p))
9824 (move-marker pos (point))
9825 (select-window win)))
9827 (defun org-table-fedit-scroll (N)
9828 (interactive "p")
9829 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9830 (scroll-other-window N)))
9832 (defun org-table-fedit-scroll-down (N)
9833 (interactive "p")
9834 (org-table-fedit-scroll (- N)))
9836 (defvar org-table-rectangle-overlays nil)
9838 (defun org-table-add-rectangle-overlay (beg end &optional face)
9839 "Add a new overlay."
9840 (let ((ov (org-make-overlay beg end)))
9841 (org-overlay-put ov 'face (or face 'secondary-selection))
9842 (push ov org-table-rectangle-overlays)))
9844 (defun org-table-highlight-rectangle (&optional beg end face)
9845 "Highlight rectangular region in a table."
9846 (setq beg (or beg (point)) end (or end (point)))
9847 (let ((b (min beg end))
9848 (e (max beg end))
9849 l1 c1 l2 c2 tmp)
9850 (and (boundp 'org-show-positions)
9851 (setq org-show-positions (cons b (cons e org-show-positions))))
9852 (goto-char (min beg end))
9853 (setq l1 (org-current-line)
9854 c1 (org-table-current-column))
9855 (goto-char (max beg end))
9856 (setq l2 (org-current-line)
9857 c2 (org-table-current-column))
9858 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9859 (goto-line l1)
9860 (beginning-of-line 1)
9861 (loop for line from l1 to l2 do
9862 (when (looking-at org-table-dataline-regexp)
9863 (org-table-goto-column c1)
9864 (skip-chars-backward "^|\n") (setq beg (point))
9865 (org-table-goto-column c2)
9866 (skip-chars-forward "^|\n") (setq end (point))
9867 (org-table-add-rectangle-overlay beg end face))
9868 (beginning-of-line 2))
9869 (goto-char b))
9870 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9872 (defun org-table-remove-rectangle-highlight (&rest ignore)
9873 "Remove the rectangle overlays."
9874 (unless org-inhibit-highlight-removal
9875 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9876 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9877 (setq org-table-rectangle-overlays nil)))
9879 (defvar org-table-coordinate-overlays nil
9880 "Collects the cooordinate grid overlays, so that they can be removed.")
9881 (make-variable-buffer-local 'org-table-coordinate-overlays)
9883 (defun org-table-overlay-coordinates ()
9884 "Add overlays to the table at point, to show row/column coordinates."
9885 (interactive)
9886 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9887 (setq org-table-coordinate-overlays nil)
9888 (save-excursion
9889 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9890 (goto-char (org-table-begin))
9891 (while (org-at-table-p)
9892 (setq eol (point-at-eol))
9893 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9894 (push ov org-table-coordinate-overlays)
9895 (setq hline (looking-at org-table-hline-regexp))
9896 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9897 (format "%4d" (setq id (1+ id)))))
9898 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9899 (when hline
9900 (setq ic 0)
9901 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9902 (setq beg (1+ (match-beginning 0))
9903 ic (1+ ic)
9904 s1 (concat "$" (int-to-string ic))
9905 s2 (org-number-to-letters ic)
9906 str (if (eq org-table-use-standard-references t) s2 s1))
9907 (setq ov (org-make-overlay beg (+ beg (length str))))
9908 (push ov org-table-coordinate-overlays)
9909 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9910 (beginning-of-line 2)))))
9912 (defun org-table-toggle-coordinate-overlays ()
9913 "Toggle the display of Row/Column numbers in tables."
9914 (interactive)
9915 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9916 (message "Row/Column number display turned %s"
9917 (if org-table-overlay-coordinates "on" "off"))
9918 (if (and (org-at-table-p) org-table-overlay-coordinates)
9919 (org-table-align))
9920 (unless org-table-overlay-coordinates
9921 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9922 (setq org-table-coordinate-overlays nil)))
9924 (defun org-table-toggle-formula-debugger ()
9925 "Toggle the formula debugger in tables."
9926 (interactive)
9927 (setq org-table-formula-debug (not org-table-formula-debug))
9928 (message "Formula debugging has been turned %s"
9929 (if org-table-formula-debug "on" "off")))
9931 ;;; The orgtbl minor mode
9933 ;; Define a minor mode which can be used in other modes in order to
9934 ;; integrate the org-mode table editor.
9936 ;; This is really a hack, because the org-mode table editor uses several
9937 ;; keys which normally belong to the major mode, for example the TAB and
9938 ;; RET keys. Here is how it works: The minor mode defines all the keys
9939 ;; necessary to operate the table editor, but wraps the commands into a
9940 ;; function which tests if the cursor is currently inside a table. If that
9941 ;; is the case, the table editor command is executed. However, when any of
9942 ;; those keys is used outside a table, the function uses `key-binding' to
9943 ;; look up if the key has an associated command in another currently active
9944 ;; keymap (minor modes, major mode, global), and executes that command.
9945 ;; There might be problems if any of the keys used by the table editor is
9946 ;; otherwise used as a prefix key.
9948 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9949 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9950 ;; addresses this by checking explicitly for both bindings.
9952 ;; The optimized version (see variable `orgtbl-optimized') takes over
9953 ;; all keys which are bound to `self-insert-command' in the *global map*.
9954 ;; Some modes bind other commands to simple characters, for example
9955 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9956 ;; active, this binding is ignored inside tables and replaced with a
9957 ;; modified self-insert.
9959 (defvar orgtbl-mode nil
9960 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9961 table editor in arbitrary modes.")
9962 (make-variable-buffer-local 'orgtbl-mode)
9964 (defvar orgtbl-mode-map (make-keymap)
9965 "Keymap for `orgtbl-mode'.")
9967 ;;;###autoload
9968 (defun turn-on-orgtbl ()
9969 "Unconditionally turn on `orgtbl-mode'."
9970 (orgtbl-mode 1))
9972 (defvar org-old-auto-fill-inhibit-regexp nil
9973 "Local variable used by `orgtbl-mode'")
9975 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9976 "Matches a line belonging to an orgtbl.")
9978 (defconst orgtbl-extra-font-lock-keywords
9979 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9980 0 (quote 'org-table) 'prepend))
9981 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9983 ;;;###autoload
9984 (defun orgtbl-mode (&optional arg)
9985 "The `org-mode' table editor as a minor mode for use in other modes."
9986 (interactive)
9987 (if (org-mode-p)
9988 ;; Exit without error, in case some hook functions calls this
9989 ;; by accident in org-mode.
9990 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9991 (setq orgtbl-mode
9992 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9993 (if orgtbl-mode
9994 (progn
9995 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9996 ;; Make sure we are first in minor-mode-map-alist
9997 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9998 (and c (setq minor-mode-map-alist
9999 (cons c (delq c minor-mode-map-alist)))))
10000 (org-set-local (quote org-table-may-need-update) t)
10001 (org-add-hook 'before-change-functions 'org-before-change-function
10002 nil 'local)
10003 (org-set-local 'org-old-auto-fill-inhibit-regexp
10004 auto-fill-inhibit-regexp)
10005 (org-set-local 'auto-fill-inhibit-regexp
10006 (if auto-fill-inhibit-regexp
10007 (concat orgtbl-line-start-regexp "\\|"
10008 auto-fill-inhibit-regexp)
10009 orgtbl-line-start-regexp))
10010 (org-add-to-invisibility-spec '(org-cwidth))
10011 (when (fboundp 'font-lock-add-keywords)
10012 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10013 (org-restart-font-lock))
10014 (easy-menu-add orgtbl-mode-menu)
10015 (run-hooks 'orgtbl-mode-hook))
10016 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10017 (org-cleanup-narrow-column-properties)
10018 (org-remove-from-invisibility-spec '(org-cwidth))
10019 (remove-hook 'before-change-functions 'org-before-change-function t)
10020 (when (fboundp 'font-lock-remove-keywords)
10021 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10022 (org-restart-font-lock))
10023 (easy-menu-remove orgtbl-mode-menu)
10024 (force-mode-line-update 'all))))
10026 (defun org-cleanup-narrow-column-properties ()
10027 "Remove all properties related to narrow-column invisibility."
10028 (let ((s 1))
10029 (while (setq s (text-property-any s (point-max)
10030 'display org-narrow-column-arrow))
10031 (remove-text-properties s (1+ s) '(display t)))
10032 (setq s 1)
10033 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10034 (remove-text-properties s (1+ s) '(org-cwidth t)))
10035 (setq s 1)
10036 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10037 (remove-text-properties s (1+ s) '(invisible t)))))
10039 ;; Install it as a minor mode.
10040 (put 'orgtbl-mode :included t)
10041 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10042 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10044 (defun orgtbl-make-binding (fun n &rest keys)
10045 "Create a function for binding in the table minor mode.
10046 FUN is the command to call inside a table. N is used to create a unique
10047 command name. KEYS are keys that should be checked in for a command
10048 to execute outside of tables."
10049 (eval
10050 (list 'defun
10051 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10052 '(arg)
10053 (concat "In tables, run `" (symbol-name fun) "'.\n"
10054 "Outside of tables, run the binding of `"
10055 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10056 "'.")
10057 '(interactive "p")
10058 (list 'if
10059 '(org-at-table-p)
10060 (list 'call-interactively (list 'quote fun))
10061 (list 'let '(orgtbl-mode)
10062 (list 'call-interactively
10063 (append '(or)
10064 (mapcar (lambda (k)
10065 (list 'key-binding k))
10066 keys)
10067 '('orgtbl-error))))))))
10069 (defun orgtbl-error ()
10070 "Error when there is no default binding for a table key."
10071 (interactive)
10072 (error "This key is has no function outside tables"))
10074 (defun orgtbl-setup ()
10075 "Setup orgtbl keymaps."
10076 (let ((nfunc 0)
10077 (bindings
10078 (list
10079 '([(meta shift left)] org-table-delete-column)
10080 '([(meta left)] org-table-move-column-left)
10081 '([(meta right)] org-table-move-column-right)
10082 '([(meta shift right)] org-table-insert-column)
10083 '([(meta shift up)] org-table-kill-row)
10084 '([(meta shift down)] org-table-insert-row)
10085 '([(meta up)] org-table-move-row-up)
10086 '([(meta down)] org-table-move-row-down)
10087 '("\C-c\C-w" org-table-cut-region)
10088 '("\C-c\M-w" org-table-copy-region)
10089 '("\C-c\C-y" org-table-paste-rectangle)
10090 '("\C-c-" org-table-insert-hline)
10091 '("\C-c}" org-table-toggle-coordinate-overlays)
10092 '("\C-c{" org-table-toggle-formula-debugger)
10093 '("\C-m" org-table-next-row)
10094 '([(shift return)] org-table-copy-down)
10095 '("\C-c\C-q" org-table-wrap-region)
10096 '("\C-c?" org-table-field-info)
10097 '("\C-c " org-table-blank-field)
10098 '("\C-c+" org-table-sum)
10099 '("\C-c=" org-table-eval-formula)
10100 '("\C-c'" org-table-edit-formulas)
10101 '("\C-c`" org-table-edit-field)
10102 '("\C-c*" org-table-recalculate)
10103 '("\C-c|" org-table-create-or-convert-from-region)
10104 '("\C-c^" org-table-sort-lines)
10105 '([(control ?#)] org-table-rotate-recalc-marks)))
10106 elt key fun cmd)
10107 (while (setq elt (pop bindings))
10108 (setq nfunc (1+ nfunc))
10109 (setq key (org-key (car elt))
10110 fun (nth 1 elt)
10111 cmd (orgtbl-make-binding fun nfunc key))
10112 (org-defkey orgtbl-mode-map key cmd))
10114 ;; Special treatment needed for TAB and RET
10115 (org-defkey orgtbl-mode-map [(return)]
10116 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10117 (org-defkey orgtbl-mode-map "\C-m"
10118 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10120 (org-defkey orgtbl-mode-map [(tab)]
10121 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10122 (org-defkey orgtbl-mode-map "\C-i"
10123 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10125 (org-defkey orgtbl-mode-map [(shift tab)]
10126 (orgtbl-make-binding 'org-table-previous-field 104
10127 [(shift tab)] [(tab)] "\C-i"))
10129 (org-defkey orgtbl-mode-map "\M-\C-m"
10130 (orgtbl-make-binding 'org-table-wrap-region 105
10131 "\M-\C-m" [(meta return)]))
10132 (org-defkey orgtbl-mode-map [(meta return)]
10133 (orgtbl-make-binding 'org-table-wrap-region 106
10134 [(meta return)] "\M-\C-m"))
10136 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10137 (when orgtbl-optimized
10138 ;; If the user wants maximum table support, we need to hijack
10139 ;; some standard editing functions
10140 (org-remap orgtbl-mode-map
10141 'self-insert-command 'orgtbl-self-insert-command
10142 'delete-char 'org-delete-char
10143 'delete-backward-char 'org-delete-backward-char)
10144 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10145 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10146 '("OrgTbl"
10147 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10148 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10149 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10150 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10151 "--"
10152 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10153 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10154 ["Copy Field from Above"
10155 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10156 "--"
10157 ("Column"
10158 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10159 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10160 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10161 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10162 ("Row"
10163 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10164 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10165 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10166 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10167 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10168 "--"
10169 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10170 ("Rectangle"
10171 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10172 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10173 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10174 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10175 "--"
10176 ("Radio tables"
10177 ["Insert table template" orgtbl-insert-radio-table
10178 (assq major-mode orgtbl-radio-table-templates)]
10179 ["Comment/uncomment table" orgtbl-toggle-comment t])
10180 "--"
10181 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10182 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10183 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10184 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10185 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10186 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10187 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10188 ["Sum Column/Rectangle" org-table-sum
10189 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10190 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10191 ["Debug Formulas"
10192 org-table-toggle-formula-debugger :active (org-at-table-p)
10193 :keys "C-c {"
10194 :style toggle :selected org-table-formula-debug]
10195 ["Show Col/Row Numbers"
10196 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10197 :keys "C-c }"
10198 :style toggle :selected org-table-overlay-coordinates]
10202 (defun orgtbl-ctrl-c-ctrl-c (arg)
10203 "If the cursor is inside a table, realign the table.
10204 It it is a table to be sent away to a receiver, do it.
10205 With prefix arg, also recompute table."
10206 (interactive "P")
10207 (let ((pos (point)) action)
10208 (save-excursion
10209 (beginning-of-line 1)
10210 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10211 ((looking-at "[ \t]*|") pos)
10212 ((looking-at "#\\+TBLFM:") 'recalc))))
10213 (cond
10214 ((integerp action)
10215 (goto-char action)
10216 (org-table-maybe-eval-formula)
10217 (if arg
10218 (call-interactively 'org-table-recalculate)
10219 (org-table-maybe-recalculate-line))
10220 (call-interactively 'org-table-align)
10221 (orgtbl-send-table 'maybe))
10222 ((eq action 'recalc)
10223 (save-excursion
10224 (beginning-of-line 1)
10225 (skip-chars-backward " \r\n\t")
10226 (if (org-at-table-p)
10227 (org-call-with-arg 'org-table-recalculate t))))
10228 (t (let (orgtbl-mode)
10229 (call-interactively (key-binding "\C-c\C-c")))))))
10231 (defun orgtbl-tab (arg)
10232 "Justification and field motion for `orgtbl-mode'."
10233 (interactive "P")
10234 (if arg (org-table-edit-field t)
10235 (org-table-justify-field-maybe)
10236 (org-table-next-field)))
10238 (defun orgtbl-ret ()
10239 "Justification and field motion for `orgtbl-mode'."
10240 (interactive)
10241 (org-table-justify-field-maybe)
10242 (org-table-next-row))
10244 (defun orgtbl-self-insert-command (N)
10245 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10246 If the cursor is in a table looking at whitespace, the whitespace is
10247 overwritten, and the table is not marked as requiring realignment."
10248 (interactive "p")
10249 (if (and (org-at-table-p)
10251 (and org-table-auto-blank-field
10252 (member last-command
10253 '(orgtbl-hijacker-command-100
10254 orgtbl-hijacker-command-101
10255 orgtbl-hijacker-command-102
10256 orgtbl-hijacker-command-103
10257 orgtbl-hijacker-command-104
10258 orgtbl-hijacker-command-105))
10259 (org-table-blank-field))
10261 (eq N 1)
10262 (looking-at "[^|\n]* +|"))
10263 (let (org-table-may-need-update)
10264 (goto-char (1- (match-end 0)))
10265 (delete-backward-char 1)
10266 (goto-char (match-beginning 0))
10267 (self-insert-command N))
10268 (setq org-table-may-need-update t)
10269 (let (orgtbl-mode)
10270 (call-interactively (key-binding (vector last-input-event))))))
10272 (defun org-force-self-insert (N)
10273 "Needed to enforce self-insert under remapping."
10274 (interactive "p")
10275 (self-insert-command N))
10277 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10278 "Regula expression matching exponentials as produced by calc.")
10280 (defvar org-table-clean-did-remove-column nil)
10282 (defun orgtbl-export (table target)
10283 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10284 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10285 org-table-last-alignment org-table-last-column-widths
10286 maxcol column)
10287 (if (not (fboundp func))
10288 (error "Cannot export orgtbl table to %s" target))
10289 (setq lines (org-table-clean-before-export lines))
10290 (setq table
10291 (mapcar
10292 (lambda (x)
10293 (if (string-match org-table-hline-regexp x)
10294 'hline
10295 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10296 lines))
10297 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10298 table)))
10299 (loop for i from (1- maxcol) downto 0 do
10300 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10301 (setq column (delq nil column))
10302 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10303 (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))
10304 (funcall func table nil)))
10306 (defun orgtbl-send-table (&optional maybe)
10307 "Send a tranformed version of this table to the receiver position.
10308 With argument MAYBE, fail quietly if no transformation is defined for
10309 this table."
10310 (interactive)
10311 (catch 'exit
10312 (unless (org-at-table-p) (error "Not at a table"))
10313 ;; when non-interactive, we assume align has just happened.
10314 (when (interactive-p) (org-table-align))
10315 (save-excursion
10316 (goto-char (org-table-begin))
10317 (beginning-of-line 0)
10318 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10319 (if maybe
10320 (throw 'exit nil)
10321 (error "Don't know how to transform this table."))))
10322 (let* ((name (match-string 1))
10324 (transform (intern (match-string 2)))
10325 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10326 (skip (plist-get params :skip))
10327 (skipcols (plist-get params :skipcols))
10328 (txt (buffer-substring-no-properties
10329 (org-table-begin) (org-table-end)))
10330 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10331 (lines (org-table-clean-before-export lines))
10332 (i0 (if org-table-clean-did-remove-column 2 1))
10333 (table (mapcar
10334 (lambda (x)
10335 (if (string-match org-table-hline-regexp x)
10336 'hline
10337 (org-remove-by-index
10338 (org-split-string (org-trim x) "\\s-*|\\s-*")
10339 skipcols i0)))
10340 lines))
10341 (fun (if (= i0 2) 'cdr 'identity))
10342 (org-table-last-alignment
10343 (org-remove-by-index (funcall fun org-table-last-alignment)
10344 skipcols i0))
10345 (org-table-last-column-widths
10346 (org-remove-by-index (funcall fun org-table-last-column-widths)
10347 skipcols i0)))
10349 (unless (fboundp transform)
10350 (error "No such transformation function %s" transform))
10351 (setq txt (funcall transform table params))
10352 ;; Find the insertion place
10353 (save-excursion
10354 (goto-char (point-min))
10355 (unless (re-search-forward
10356 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10357 (error "Don't know where to insert translated table"))
10358 (goto-char (match-beginning 0))
10359 (beginning-of-line 2)
10360 (setq beg (point))
10361 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10362 (error "Cannot find end of insertion region"))
10363 (beginning-of-line 1)
10364 (delete-region beg (point))
10365 (goto-char beg)
10366 (insert txt "\n"))
10367 (message "Table converted and installed at receiver location"))))
10369 (defun org-remove-by-index (list indices &optional i0)
10370 "Remove the elements in LIST with indices in INDICES.
10371 First element has index 0, or I0 if given."
10372 (if (not indices)
10373 list
10374 (if (integerp indices) (setq indices (list indices)))
10375 (setq i0 (1- (or i0 0)))
10376 (delq :rm (mapcar (lambda (x)
10377 (setq i0 (1+ i0))
10378 (if (memq i0 indices) :rm x))
10379 list))))
10381 (defun orgtbl-toggle-comment ()
10382 "Comment or uncomment the orgtbl at point."
10383 (interactive)
10384 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10385 (re2 (concat "^" orgtbl-line-start-regexp))
10386 (commented (save-excursion (beginning-of-line 1)
10387 (cond ((looking-at re1) t)
10388 ((looking-at re2) nil)
10389 (t (error "Not at an org table")))))
10390 (re (if commented re1 re2))
10391 beg end)
10392 (save-excursion
10393 (beginning-of-line 1)
10394 (while (looking-at re) (beginning-of-line 0))
10395 (beginning-of-line 2)
10396 (setq beg (point))
10397 (while (looking-at re) (beginning-of-line 2))
10398 (setq end (point)))
10399 (comment-region beg end (if commented '(4) nil))))
10401 (defun orgtbl-insert-radio-table ()
10402 "Insert a radio table template appropriate for this major mode."
10403 (interactive)
10404 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10405 (txt (nth 1 e))
10406 name pos)
10407 (unless e (error "No radio table setup defined for %s" major-mode))
10408 (setq name (read-string "Table name: "))
10409 (while (string-match "%n" txt)
10410 (setq txt (replace-match name t t txt)))
10411 (or (bolp) (insert "\n"))
10412 (setq pos (point))
10413 (insert txt)
10414 (goto-char pos)))
10416 (defun org-get-param (params header i sym &optional hsym)
10417 "Get parameter value for symbol SYM.
10418 If this is a header line, actually get the value for the symbol with an
10419 additional \"h\" inserted after the colon.
10420 If the value is a protperty list, get the element for the current column.
10421 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10422 (let ((val (plist-get params sym)))
10423 (and hsym header (setq val (or (plist-get params hsym) val)))
10424 (if (consp val) (plist-get val i) val)))
10426 (defun orgtbl-to-generic (table params)
10427 "Convert the orgtbl-mode TABLE to some other format.
10428 This generic routine can be used for many standard cases.
10429 TABLE is a list, each entry either the symbol `hline' for a horizontal
10430 separator line, or a list of fields for that line.
10431 PARAMS is a property list of parameters that can influence the conversion.
10432 For the generic converter, some parameters are obligatory: You need to
10433 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10434 :splice, you must have :tstart and :tend.
10436 Valid parameters are
10438 :tstart String to start the table. Ignored when :splice is t.
10439 :tend String to end the table. Ignored when :splice is t.
10441 :splice When set to t, return only table body lines, don't wrap
10442 them into :tstart and :tend. Default is nil.
10444 :hline String to be inserted on horizontal separation lines.
10445 May be nil to ignore hlines.
10447 :lstart String to start a new table line.
10448 :lend String to end a table line
10449 :sep Separator between two fields
10450 :lfmt Format for entire line, with enough %s to capture all fields.
10451 If this is present, :lstart, :lend, and :sep are ignored.
10452 :fmt A format to be used to wrap the field, should contain
10453 %s for the original field value. For example, to wrap
10454 everything in dollars, you could use :fmt \"$%s$\".
10455 This may also be a property list with column numbers and
10456 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10458 :hlstart :hlend :hlsep :hlfmt :hfmt
10459 Same as above, specific for the header lines in the table.
10460 All lines before the first hline are treated as header.
10461 If any of these is not present, the data line value is used.
10463 :efmt Use this format to print numbers with exponentials.
10464 The format should have %s twice for inserting mantissa
10465 and exponent, for example \"%s\\\\times10^{%s}\". This
10466 may also be a property list with column numbers and
10467 formats. :fmt will still be applied after :efmt.
10469 In addition to this, the parameters :skip and :skipcols are always handled
10470 directly by `orgtbl-send-table'. See manual."
10471 (interactive)
10472 (let* ((p params)
10473 (splicep (plist-get p :splice))
10474 (hline (plist-get p :hline))
10475 rtn line i fm efm lfmt h)
10477 ;; Do we have a header?
10478 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10479 (setq h t))
10481 ;; Put header
10482 (unless splicep
10483 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10485 ;; Now loop over all lines
10486 (while (setq line (pop table))
10487 (if (eq line 'hline)
10488 ;; A horizontal separator line
10489 (progn (if hline (push hline rtn))
10490 (setq h nil)) ; no longer in header
10491 ;; A normal line. Convert the fields, push line onto the result list
10492 (setq i 0)
10493 (setq line
10494 (mapcar
10495 (lambda (f)
10496 (setq i (1+ i)
10497 fm (org-get-param p h i :fmt :hfmt)
10498 efm (org-get-param p h i :efmt))
10499 (if (and efm (string-match orgtbl-exp-regexp f))
10500 (setq f (format
10501 efm (match-string 1 f) (match-string 2 f))))
10502 (if fm (setq f (format fm f)))
10504 line))
10505 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10506 (push (apply 'format lfmt line) rtn)
10507 (push (concat
10508 (org-get-param p h i :lstart :hlstart)
10509 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10510 (org-get-param p h i :lend :hlend))
10511 rtn))))
10513 (unless splicep
10514 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10516 (mapconcat 'identity (nreverse rtn) "\n")))
10518 (defun orgtbl-to-latex (table params)
10519 "Convert the orgtbl-mode TABLE to LaTeX.
10520 TABLE is a list, each entry either the symbol `hline' for a horizontal
10521 separator line, or a list of fields for that line.
10522 PARAMS is a property list of parameters that can influence the conversion.
10523 Supports all parameters from `orgtbl-to-generic'. Most important for
10524 LaTeX are:
10526 :splice When set to t, return only table body lines, don't wrap
10527 them into a tabular environment. Default is nil.
10529 :fmt A format to be used to wrap the field, should contain %s for the
10530 original field value. For example, to wrap everything in dollars,
10531 use :fmt \"$%s$\". This may also be a property list with column
10532 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10534 :efmt Format for transforming numbers with exponentials. The format
10535 should have %s twice for inserting mantissa and exponent, for
10536 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10537 This may also be a property list with column numbers and formats.
10539 The general parameters :skip and :skipcols have already been applied when
10540 this function is called."
10541 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10542 org-table-last-alignment ""))
10543 (params2
10544 (list
10545 :tstart (concat "\\begin{tabular}{" alignment "}")
10546 :tend "\\end{tabular}"
10547 :lstart "" :lend " \\\\" :sep " & "
10548 :efmt "%s\\,(%s)" :hline "\\hline")))
10549 (orgtbl-to-generic table (org-combine-plists params2 params))))
10551 (defun orgtbl-to-html (table params)
10552 "Convert the orgtbl-mode TABLE to LaTeX.
10553 TABLE is a list, each entry either the symbol `hline' for a horizontal
10554 separator line, or a list of fields for that line.
10555 PARAMS is a property list of parameters that can influence the conversion.
10556 Currently this function recognizes the following parameters:
10558 :splice When set to t, return only table body lines, don't wrap
10559 them into a <table> environment. Default is nil.
10561 The general parameters :skip and :skipcols have already been applied when
10562 this function is called. The function does *not* use `orgtbl-to-generic',
10563 so you cannot specify parameters for it."
10564 (let* ((splicep (plist-get params :splice))
10565 html)
10566 ;; Just call the formatter we already have
10567 ;; We need to make text lines for it, so put the fields back together.
10568 (setq html (org-format-org-table-html
10569 (mapcar
10570 (lambda (x)
10571 (if (eq x 'hline)
10572 "|----+----|"
10573 (concat "| " (mapconcat 'identity x " | ") " |")))
10574 table)
10575 splicep))
10576 (if (string-match "\n+\\'" html)
10577 (setq html (replace-match "" t t html)))
10578 html))
10580 (defun orgtbl-to-texinfo (table params)
10581 "Convert the orgtbl-mode TABLE to TeXInfo.
10582 TABLE is a list, each entry either the symbol `hline' for a horizontal
10583 separator line, or a list of fields for that line.
10584 PARAMS is a property list of parameters that can influence the conversion.
10585 Supports all parameters from `orgtbl-to-generic'. Most important for
10586 TeXInfo are:
10588 :splice nil/t When set to t, return only table body lines, don't wrap
10589 them into a multitable environment. Default is nil.
10591 :fmt fmt A format to be used to wrap the field, should contain
10592 %s for the original field value. For example, to wrap
10593 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10594 This may also be a property list with column numbers and
10595 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10597 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10598 are computed automatically from the width of the columns
10599 under org-mode.
10601 The general parameters :skip and :skipcols have already been applied when
10602 this function is called."
10603 (let* ((total (float (apply '+ org-table-last-column-widths)))
10604 (colfrac (or (plist-get params :cf)
10605 (mapconcat
10606 (lambda (x) (format "%.3f" (/ (float x) total)))
10607 org-table-last-column-widths " ")))
10608 (params2
10609 (list
10610 :tstart (concat "@multitable @columnfractions " colfrac)
10611 :tend "@end multitable"
10612 :lstart "@item " :lend "" :sep " @tab "
10613 :hlstart "@headitem ")))
10614 (orgtbl-to-generic table (org-combine-plists params2 params))))
10616 ;;;; Link Stuff
10618 ;;; Link abbreviations
10620 (defun org-link-expand-abbrev (link)
10621 "Apply replacements as defined in `org-link-abbrev-alist."
10622 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
10623 (let* ((key (match-string 1 link))
10624 (as (or (assoc key org-link-abbrev-alist-local)
10625 (assoc key org-link-abbrev-alist)))
10626 (tag (and (match-end 2) (match-string 3 link)))
10627 rpl)
10628 (if (not as)
10629 link
10630 (setq rpl (cdr as))
10631 (cond
10632 ((symbolp rpl) (funcall rpl tag))
10633 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10634 (t (concat rpl tag)))))
10635 link))
10637 ;;; Storing and inserting links
10639 (defvar org-insert-link-history nil
10640 "Minibuffer history for links inserted with `org-insert-link'.")
10642 (defvar org-stored-links nil
10643 "Contains the links stored with `org-store-link'.")
10645 (defvar org-store-link-plist nil
10646 "Plist with info about the most recently link created with `org-store-link'.")
10648 (defvar org-link-protocols nil
10649 "Link protocols added to Org-mode using `org-add-link-type'.")
10651 (defvar org-store-link-functions nil
10652 "List of functions that are called to create and store a link.
10653 Each function will be called in turn until one returns a non-nil
10654 value. Each function should check if it is responsible for creating
10655 this link (for example by looking at the major mode).
10656 If not, it must exit and return nil.
10657 If yes, it should return a non-nil value after a calling
10658 `org-store-link-properties' with a list of properties and values.
10659 Special properties are:
10661 :type The link prefix. like \"http\". This must be given.
10662 :link The link, like \"http://www.astro.uva.nl/~dominik\".
10663 This is obligatory as well.
10664 :description Optional default description for the second pair
10665 of brackets in an Org-mode link. The user can still change
10666 this when inserting this link into an Org-mode buffer.
10668 In addition to these, any additional properties can be specified
10669 and then used in remember templates.")
10671 (defun org-add-link-type (type &optional follow publish)
10672 "Add TYPE to the list of `org-link-types'.
10673 Re-compute all regular expressions depending on `org-link-types'
10674 FOLLOW and PUBLISH are two functions. Both take the link path as
10675 an argument.
10676 FOLLOW should do whatever is necessary to follow the link, for example
10677 to find a file or display a mail message.
10678 PUBLISH takes the path and retuns the string that should be used when
10679 this document is published."
10680 (add-to-list 'org-link-types type t)
10681 (org-make-link-regexps)
10682 (add-to-list 'org-link-protocols
10683 (list type follow publish)))
10685 (defun org-add-agenda-custom-command (entry)
10686 "Replace or add a command in `org-agenda-custom-commands'.
10687 This is mostly for hacking and trying a new command - once the command
10688 works you probably want to add it to `org-agenda-custom-commands' for good."
10689 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
10690 (if ass
10691 (setcdr ass (cdr entry))
10692 (push entry org-agenda-custom-commands))))
10694 ;;;###autoload
10695 (defun org-store-link (arg)
10696 "\\<org-mode-map>Store an org-link to the current location.
10697 This link can later be inserted into an org-buffer with
10698 \\[org-insert-link].
10699 For some link types, a prefix arg is interpreted:
10700 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10701 For file links, arg negates `org-context-in-file-links'."
10702 (interactive "P")
10703 (setq org-store-link-plist nil) ; reset
10704 (let (link cpltxt desc description search txt)
10705 (cond
10707 ((run-hook-with-args-until-success 'org-store-link-functions)
10708 (setq link (plist-get org-store-link-plist :link)
10709 desc (or (plist-get org-store-link-plist :description) link)))
10711 ((eq major-mode 'bbdb-mode)
10712 (let ((name (bbdb-record-name (bbdb-current-record)))
10713 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10714 (setq cpltxt (concat "bbdb:" (or name company))
10715 link (org-make-link cpltxt))
10716 (org-store-link-props :type "bbdb" :name name :company company)))
10718 ((eq major-mode 'Info-mode)
10719 (setq link (org-make-link "info:"
10720 (file-name-nondirectory Info-current-file)
10721 ":" Info-current-node))
10722 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10723 ":" Info-current-node))
10724 (org-store-link-props :type "info" :file Info-current-file
10725 :node Info-current-node))
10727 ((eq major-mode 'calendar-mode)
10728 (let ((cd (calendar-cursor-to-date)))
10729 (setq link
10730 (format-time-string
10731 (car org-time-stamp-formats)
10732 (apply 'encode-time
10733 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10734 nil nil nil))))
10735 (org-store-link-props :type "calendar" :date cd)))
10737 ((or (eq major-mode 'vm-summary-mode)
10738 (eq major-mode 'vm-presentation-mode))
10739 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10740 (vm-follow-summary-cursor)
10741 (save-excursion
10742 (vm-select-folder-buffer)
10743 (let* ((message (car vm-message-pointer))
10744 (folder buffer-file-name)
10745 (subject (vm-su-subject message))
10746 (to (vm-get-header-contents message "To"))
10747 (from (vm-get-header-contents message "From"))
10748 (message-id (vm-su-message-id message)))
10749 (org-store-link-props :type "vm" :from from :to to :subject subject
10750 :message-id message-id)
10751 (setq message-id (org-remove-angle-brackets message-id))
10752 (setq folder (abbreviate-file-name folder))
10753 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10754 folder)
10755 (setq folder (replace-match "" t t folder)))
10756 (setq cpltxt (org-email-link-description))
10757 (setq link (org-make-link "vm:" folder "#" message-id)))))
10759 ((eq major-mode 'wl-summary-mode)
10760 (let* ((msgnum (wl-summary-message-number))
10761 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10762 msgnum 'message-id))
10763 (wl-message-entity
10764 (if (fboundp 'elmo-message-entity)
10765 (elmo-message-entity
10766 wl-summary-buffer-elmo-folder msgnum)
10767 (elmo-msgdb-overview-get-entity
10768 msgnum (wl-summary-buffer-msgdb))))
10769 (from (wl-summary-line-from))
10770 (to (car (elmo-message-entity-field wl-message-entity 'to)))
10771 (subject (let (wl-thr-indent-string wl-parent-message-entity)
10772 (wl-summary-line-subject))))
10773 (org-store-link-props :type "wl" :from from :to to
10774 :subject subject :message-id message-id)
10775 (setq message-id (org-remove-angle-brackets message-id))
10776 (setq cpltxt (org-email-link-description))
10777 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10778 "#" message-id))))
10780 ((or (equal major-mode 'mh-folder-mode)
10781 (equal major-mode 'mh-show-mode))
10782 (let ((from (org-mhe-get-header "From:"))
10783 (to (org-mhe-get-header "To:"))
10784 (message-id (org-mhe-get-header "Message-Id:"))
10785 (subject (org-mhe-get-header "Subject:")))
10786 (org-store-link-props :type "mh" :from from :to to
10787 :subject subject :message-id message-id)
10788 (setq cpltxt (org-email-link-description))
10789 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10790 (org-remove-angle-brackets message-id)))))
10792 ((eq major-mode 'rmail-mode)
10793 (save-excursion
10794 (save-restriction
10795 (rmail-narrow-to-non-pruned-header)
10796 (let ((folder buffer-file-name)
10797 (message-id (mail-fetch-field "message-id"))
10798 (from (mail-fetch-field "from"))
10799 (to (mail-fetch-field "to"))
10800 (subject (mail-fetch-field "subject")))
10801 (org-store-link-props
10802 :type "rmail" :from from :to to
10803 :subject subject :message-id message-id)
10804 (setq message-id (org-remove-angle-brackets message-id))
10805 (setq cpltxt (org-email-link-description))
10806 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10808 ((eq major-mode 'gnus-group-mode)
10809 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10810 (gnus-group-group-name)) ; version
10811 ((fboundp 'gnus-group-name)
10812 (gnus-group-name))
10813 (t "???"))))
10814 (unless group (error "Not on a group"))
10815 (org-store-link-props :type "gnus" :group group)
10816 (setq cpltxt (concat
10817 (if (org-xor arg org-usenet-links-prefer-google)
10818 "http://groups.google.com/groups?group="
10819 "gnus:")
10820 group)
10821 link (org-make-link cpltxt))))
10823 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10824 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10825 (let* ((group gnus-newsgroup-name)
10826 (article (gnus-summary-article-number))
10827 (header (gnus-summary-article-header article))
10828 (from (mail-header-from header))
10829 (message-id (mail-header-id header))
10830 (date (mail-header-date header))
10831 (subject (gnus-summary-subject-string)))
10832 (org-store-link-props :type "gnus" :from from :subject subject
10833 :message-id message-id :group group)
10834 (setq cpltxt (org-email-link-description))
10835 (if (org-xor arg org-usenet-links-prefer-google)
10836 (setq link
10837 (concat
10838 cpltxt "\n "
10839 (format "http://groups.google.com/groups?as_umsgid=%s"
10840 (org-fixup-message-id-for-http message-id))))
10841 (setq link (org-make-link "gnus:" group
10842 "#" (number-to-string article))))))
10844 ((eq major-mode 'w3-mode)
10845 (setq cpltxt (url-view-url t)
10846 link (org-make-link cpltxt))
10847 (org-store-link-props :type "w3" :url (url-view-url t)))
10849 ((eq major-mode 'w3m-mode)
10850 (setq cpltxt (or w3m-current-title w3m-current-url)
10851 link (org-make-link w3m-current-url))
10852 (org-store-link-props :type "w3m" :url (url-view-url t)))
10854 ((setq search (run-hook-with-args-until-success
10855 'org-create-file-search-functions))
10856 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10857 "::" search))
10858 (setq cpltxt (or description link)))
10860 ((eq major-mode 'image-mode)
10861 (setq cpltxt (concat "file:"
10862 (abbreviate-file-name buffer-file-name))
10863 link (org-make-link cpltxt))
10864 (org-store-link-props :type "image" :file buffer-file-name))
10866 ((eq major-mode 'dired-mode)
10867 ;; link to the file in the current line
10868 (setq cpltxt (concat "file:"
10869 (abbreviate-file-name
10870 (expand-file-name
10871 (dired-get-filename nil t))))
10872 link (org-make-link cpltxt)))
10874 ((and buffer-file-name (org-mode-p))
10875 ;; Just link to current headline
10876 (setq cpltxt (concat "file:"
10877 (abbreviate-file-name buffer-file-name)))
10878 ;; Add a context search string
10879 (when (org-xor org-context-in-file-links arg)
10880 ;; Check if we are on a target
10881 (if (org-in-regexp "<<\\(.*?\\)>>")
10882 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10883 (setq txt (cond
10884 ((org-on-heading-p) nil)
10885 ((org-region-active-p)
10886 (buffer-substring (region-beginning) (region-end)))
10887 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10888 (when (or (null txt) (string-match "\\S-" txt))
10889 (setq cpltxt
10890 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10891 desc "NONE"))))
10892 (if (string-match "::\\'" cpltxt)
10893 (setq cpltxt (substring cpltxt 0 -2)))
10894 (setq link (org-make-link cpltxt)))
10896 (buffer-file-name
10897 ;; Just link to this file here.
10898 (setq cpltxt (concat "file:"
10899 (abbreviate-file-name buffer-file-name)))
10900 ;; Add a context string
10901 (when (org-xor org-context-in-file-links arg)
10902 (setq txt (if (org-region-active-p)
10903 (buffer-substring (region-beginning) (region-end))
10904 (buffer-substring (point-at-bol) (point-at-eol))))
10905 ;; Only use search option if there is some text.
10906 (when (string-match "\\S-" txt)
10907 (setq cpltxt
10908 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10909 desc "NONE")))
10910 (setq link (org-make-link cpltxt)))
10912 ((interactive-p)
10913 (error "Cannot link to a buffer which is not visiting a file"))
10915 (t (setq link nil)))
10917 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10918 (setq link (or link cpltxt)
10919 desc (or desc cpltxt))
10920 (if (equal desc "NONE") (setq desc nil))
10922 (if (and (interactive-p) link)
10923 (progn
10924 (setq org-stored-links
10925 (cons (list cpltxt link desc) org-stored-links))
10926 (message "Stored: %s" (or cpltxt link)))
10927 (and link (org-make-link-string link desc)))))
10929 (defun org-store-link-props (&rest plist)
10930 "Store link properties, extract names and addresses."
10931 (let (x adr)
10932 (when (setq x (plist-get plist :from))
10933 (setq adr (mail-extract-address-components x))
10934 (plist-put plist :fromname (car adr))
10935 (plist-put plist :fromaddress (nth 1 adr)))
10936 (when (setq x (plist-get plist :to))
10937 (setq adr (mail-extract-address-components x))
10938 (plist-put plist :toname (car adr))
10939 (plist-put plist :toaddress (nth 1 adr))))
10940 (let ((from (plist-get plist :from))
10941 (to (plist-get plist :to)))
10942 (when (and from to org-from-is-user-regexp)
10943 (plist-put plist :fromto
10944 (if (string-match org-from-is-user-regexp from)
10945 (concat "to %t")
10946 (concat "from %f")))))
10947 (setq org-store-link-plist plist))
10949 (defun org-email-link-description (&optional fmt)
10950 "Return the description part of an email link.
10951 This takes information from `org-store-link-plist' and formats it
10952 according to FMT (default from `org-email-link-description-format')."
10953 (setq fmt (or fmt org-email-link-description-format))
10954 (let* ((p org-store-link-plist)
10955 (to (plist-get p :toaddress))
10956 (from (plist-get p :fromaddress))
10957 (table
10958 (list
10959 (cons "%c" (plist-get p :fromto))
10960 (cons "%F" (plist-get p :from))
10961 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10962 (cons "%T" (plist-get p :to))
10963 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10964 (cons "%s" (plist-get p :subject))
10965 (cons "%m" (plist-get p :message-id)))))
10966 (when (string-match "%c" fmt)
10967 ;; Check if the user wrote this message
10968 (if (and org-from-is-user-regexp from to
10969 (save-match-data (string-match org-from-is-user-regexp from)))
10970 (setq fmt (replace-match "to %t" t t fmt))
10971 (setq fmt (replace-match "from %f" t t fmt))))
10972 (org-replace-escapes fmt table)))
10974 (defun org-make-org-heading-search-string (&optional string heading)
10975 "Make search string for STRING or current headline."
10976 (interactive)
10977 (let ((s (or string (org-get-heading))))
10978 (unless (and string (not heading))
10979 ;; We are using a headline, clean up garbage in there.
10980 (if (string-match org-todo-regexp s)
10981 (setq s (replace-match "" t t s)))
10982 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
10983 (setq s (replace-match "" t t s)))
10984 (setq s (org-trim s))
10985 (if (string-match (concat "^\\(" org-quote-string "\\|"
10986 org-comment-string "\\)") s)
10987 (setq s (replace-match "" t t s)))
10988 (while (string-match org-ts-regexp s)
10989 (setq s (replace-match "" t t s))))
10990 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10991 (setq s (replace-match " " t t s)))
10992 (or string (setq s (concat "*" s))) ; Add * for headlines
10993 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10995 (defun org-make-link (&rest strings)
10996 "Concatenate STRINGS."
10997 (apply 'concat strings))
10999 (defun org-make-link-string (link &optional description)
11000 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11001 (unless (string-match "\\S-" link)
11002 (error "Empty link"))
11003 (when (stringp description)
11004 ;; Remove brackets from the description, they are fatal.
11005 (while (string-match "\\[\\|\\]" description)
11006 (setq description (replace-match "" t t description))))
11007 (when (equal (org-link-escape link) description)
11008 ;; No description needed, it is identical
11009 (setq description nil))
11010 (when (and (not description)
11011 (not (equal link (org-link-escape link))))
11012 (setq description link))
11013 (concat "[[" (org-link-escape link) "]"
11014 (if description (concat "[" description "]") "")
11015 "]"))
11017 (defconst org-link-escape-chars
11018 '((" " . "%20")
11019 ("\340" . "%E0") ; `a
11020 ("\342" . "%E2") ; ^a
11021 ("\347" . "%E7") ; ,c
11022 ("\350" . "%E8") ; `e
11023 ("\351" . "%E9") ; 'e
11024 ("\352" . "%EA") ; ^e
11025 ("\356" . "%EE") ; ^i
11026 ("\364" . "%F4") ; ^o
11027 ("\371" . "%F9") ; `u
11028 ("\373" . "%FB") ; ^u
11029 (";" . "%3B")
11030 ("?" . "%3F")
11031 ("=" . "%3D")
11032 ("+" . "%2B")
11034 "Association list of escapes for some characters problematic in links.")
11036 (defun org-link-escape (text)
11037 "Escape charaters in TEXT that are problematic for links."
11038 (when text
11039 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11040 org-link-escape-chars "\\|")))
11041 (while (string-match re text)
11042 (setq text
11043 (replace-match
11044 (cdr (assoc (match-string 0 text) org-link-escape-chars))
11045 t t text)))
11046 text)))
11048 (defun org-link-unescape (text)
11049 "Reverse the action of `org-link-escape'."
11050 (when text
11051 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11052 org-link-escape-chars "\\|")))
11053 (while (string-match re text)
11054 (setq text
11055 (replace-match
11056 (car (rassoc (match-string 0 text) org-link-escape-chars))
11057 t t text)))
11058 text)))
11060 (defun org-xor (a b)
11061 "Exclusive or."
11062 (if a (not b) b))
11064 (defun org-get-header (header)
11065 "Find a header field in the current buffer."
11066 (save-excursion
11067 (goto-char (point-min))
11068 (let ((case-fold-search t) s)
11069 (cond
11070 ((eq header 'from)
11071 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11072 (setq s (match-string 1)))
11073 (while (string-match "\"" s)
11074 (setq s (replace-match "" t t s)))
11075 (if (string-match "[<(].*" s)
11076 (setq s (replace-match "" t t s))))
11077 ((eq header 'message-id)
11078 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11079 (setq s (match-string 1))))
11080 ((eq header 'subject)
11081 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11082 (setq s (match-string 1)))))
11083 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11084 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11085 s)))
11088 (defun org-fixup-message-id-for-http (s)
11089 "Replace special characters in a message id, so it can be used in an http query."
11090 (while (string-match "<" s)
11091 (setq s (replace-match "%3C" t t s)))
11092 (while (string-match ">" s)
11093 (setq s (replace-match "%3E" t t s)))
11094 (while (string-match "@" s)
11095 (setq s (replace-match "%40" t t s)))
11098 ;;;###autoload
11099 (defun org-insert-link-global ()
11100 "Insert a link like Org-mode does.
11101 This command can be called in any mode to insert a link in Org-mode syntax."
11102 (interactive)
11103 (org-run-like-in-org-mode 'org-insert-link))
11105 (defun org-insert-link (&optional complete-file)
11106 "Insert a link. At the prompt, enter the link.
11108 Completion can be used to select a link previously stored with
11109 `org-store-link'. When the empty string is entered (i.e. if you just
11110 press RET at the prompt), the link defaults to the most recently
11111 stored link. As SPC triggers completion in the minibuffer, you need to
11112 use M-SPC or C-q SPC to force the insertion of a space character.
11114 You will also be prompted for a description, and if one is given, it will
11115 be displayed in the buffer instead of the link.
11117 If there is already a link at point, this command will allow you to edit link
11118 and description parts.
11120 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11121 selected using completion. The path to the file will be relative to
11122 the current directory if the file is in the current directory or a
11123 subdirectory. Otherwise, the link will be the absolute path as
11124 completed in the minibuffer (i.e. normally ~/path/to/file).
11126 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11127 is in the current directory or below.
11128 With three \\[universal-argument] prefixes, negate the meaning of
11129 `org-keep-stored-link-after-insertion'."
11130 (interactive "P")
11131 (let ((wcf (current-window-configuration))
11132 (region (if (org-region-active-p)
11133 (prog1 (buffer-substring (region-beginning) (region-end))
11134 (delete-region (region-beginning) (region-end)))))
11135 tmphist ; byte-compile incorrectly complains about this
11136 link desc entry remove file)
11137 (cond
11138 ((org-in-regexp org-bracket-link-regexp 1)
11139 ;; We do have a link at point, and we are going to edit it.
11140 (setq remove (list (match-beginning 0) (match-end 0)))
11141 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11142 (setq link (read-string "Link: "
11143 (org-link-unescape
11144 (org-match-string-no-properties 1)))))
11145 ((or (org-in-regexp org-angle-link-re)
11146 (org-in-regexp org-plain-link-re))
11147 ;; Convert to bracket link
11148 (setq remove (list (match-beginning 0) (match-end 0))
11149 link (read-string "Link: "
11150 (org-remove-angle-brackets (match-string 0)))))
11151 ((equal complete-file '(4))
11152 ;; Completing read for file names.
11153 (setq file (read-file-name "File: "))
11154 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11155 (pwd1 (file-name-as-directory (abbreviate-file-name
11156 (expand-file-name ".")))))
11157 (cond
11158 ((equal complete-file '(16))
11159 (setq link (org-make-link
11160 "file:"
11161 (abbreviate-file-name (expand-file-name file)))))
11162 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11163 (setq link (org-make-link "file:" (match-string 1 file))))
11164 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11165 (expand-file-name file))
11166 (setq link (org-make-link
11167 "file:" (match-string 1 (expand-file-name file)))))
11168 (t (setq link (org-make-link "file:" file))))))
11170 ;; Read link, with completion for stored links.
11171 (with-output-to-temp-buffer "*Org Links*"
11172 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11173 (when org-stored-links
11174 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
11175 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
11176 (let ((cw (selected-window)))
11177 (select-window (get-buffer-window "*Org Links*"))
11178 (shrink-window-if-larger-than-buffer)
11179 (setq truncate-lines t)
11180 (select-window cw))
11181 ;; Fake a link history, containing the stored links.
11182 (setq tmphist (append (mapcar 'car org-stored-links)
11183 org-insert-link-history))
11184 (unwind-protect
11185 (setq link (org-completing-read
11186 "Link: "
11187 (append
11188 (mapcar (lambda (x) (list (concat (car x) ":")))
11189 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11190 (mapcar (lambda (x) (list (concat x ":")))
11191 org-link-types))
11192 nil nil nil
11193 'tmphist
11194 (or (car (car org-stored-links)))))
11195 (set-window-configuration wcf)
11196 (kill-buffer "*Org Links*"))
11197 (setq entry (assoc link org-stored-links))
11198 (or entry (push link org-insert-link-history))
11199 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11200 (not org-keep-stored-link-after-insertion))
11201 (setq org-stored-links (delq (assoc link org-stored-links)
11202 org-stored-links)))
11203 (setq link (if entry (nth 1 entry) link)
11204 desc (or region desc (nth 2 entry)))))
11206 (if (string-match org-plain-link-re link)
11207 ;; URL-like link, normalize the use of angular brackets.
11208 (setq link (org-make-link (org-remove-angle-brackets link))))
11210 ;; Check if we are linking to the current file with a search option
11211 ;; If yes, simplify the link by using only the search option.
11212 (when (and buffer-file-name
11213 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11214 (let* ((path (match-string 1 link))
11215 (case-fold-search nil)
11216 (search (match-string 2 link)))
11217 (save-match-data
11218 (if (equal (file-truename buffer-file-name) (file-truename path))
11219 ;; We are linking to this same file, with a search option
11220 (setq link search)))))
11222 ;; Check if we can/should use a relative path. If yes, simplify the link
11223 (when (string-match "\\<file:\\(.*\\)" link)
11224 (let* ((path (match-string 1 link))
11225 (case-fold-search nil))
11226 (cond
11227 ((eq org-link-file-path-type 'absolute)
11228 (setq path (abbreviate-file-name (expand-file-name path))))
11229 ((eq org-link-file-path-type 'noabbrev)
11230 (setq path (expand-file-name path)))
11231 ((eq org-link-file-path-type 'relative)
11232 (setq path (file-relative-name path)))
11234 (save-match-data
11235 (if (string-match (concat "^" (regexp-quote
11236 (file-name-as-directory
11237 (expand-file-name "."))))
11238 (expand-file-name path))
11239 ;; We are linking a file with relative path name.
11240 (setq path (substring (expand-file-name path)
11241 (match-end 0)))))))
11242 (setq link (concat "file:" path))))
11244 (setq desc (read-string "Description: " desc))
11245 (unless (string-match "\\S-" desc) (setq desc nil))
11246 (if remove (apply 'delete-region remove))
11247 (insert (org-make-link-string link desc))))
11249 (defun org-completing-read (&rest args)
11250 (let ((minibuffer-local-completion-map
11251 (copy-keymap minibuffer-local-completion-map)))
11252 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11253 (apply 'completing-read args)))
11255 ;;; Opening/following a link
11256 (defvar org-link-search-failed nil)
11258 (defun org-next-link ()
11259 "Move forward to the next link.
11260 If the link is in hidden text, expose it."
11261 (interactive)
11262 (when (and org-link-search-failed (eq this-command last-command))
11263 (goto-char (point-min))
11264 (message "Link search wrapped back to beginning of buffer"))
11265 (setq org-link-search-failed nil)
11266 (let* ((pos (point))
11267 (ct (org-context))
11268 (a (assoc :link ct)))
11269 (if a (goto-char (nth 2 a)))
11270 (if (re-search-forward org-any-link-re nil t)
11271 (progn
11272 (goto-char (match-beginning 0))
11273 (if (org-invisible-p) (org-show-context)))
11274 (goto-char pos)
11275 (setq org-link-search-failed t)
11276 (error "No further link found"))))
11278 (defun org-previous-link ()
11279 "Move backward to the previous link.
11280 If the link is in hidden text, expose it."
11281 (interactive)
11282 (when (and org-link-search-failed (eq this-command last-command))
11283 (goto-char (point-max))
11284 (message "Link search wrapped back to end of buffer"))
11285 (setq org-link-search-failed nil)
11286 (let* ((pos (point))
11287 (ct (org-context))
11288 (a (assoc :link ct)))
11289 (if a (goto-char (nth 1 a)))
11290 (if (re-search-backward org-any-link-re nil t)
11291 (progn
11292 (goto-char (match-beginning 0))
11293 (if (org-invisible-p) (org-show-context)))
11294 (goto-char pos)
11295 (setq org-link-search-failed t)
11296 (error "No further link found"))))
11298 (defun org-find-file-at-mouse (ev)
11299 "Open file link or URL at mouse."
11300 (interactive "e")
11301 (mouse-set-point ev)
11302 (org-open-at-point 'in-emacs))
11304 (defun org-open-at-mouse (ev)
11305 "Open file link or URL at mouse."
11306 (interactive "e")
11307 (mouse-set-point ev)
11308 (org-open-at-point))
11310 (defvar org-window-config-before-follow-link nil
11311 "The window configuration before following a link.
11312 This is saved in case the need arises to restore it.")
11314 (defvar org-open-link-marker (make-marker)
11315 "Marker pointing to the location where `org-open-at-point; was called.")
11317 ;;;###autoload
11318 (defun org-open-at-point-global ()
11319 "Follow a link like Org-mode does.
11320 This command can be called in any mode to follow a link that has
11321 Org-mode syntax."
11322 (interactive)
11323 (org-run-like-in-org-mode 'org-open-at-point))
11325 (defun org-open-at-point (&optional in-emacs)
11326 "Open link at or after point.
11327 If there is no link at point, this function will search forward up to
11328 the end of the current subtree.
11329 Normally, files will be opened by an appropriate application. If the
11330 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11331 (interactive "P")
11332 (move-marker org-open-link-marker (point))
11333 (setq org-window-config-before-follow-link (current-window-configuration))
11334 (org-remove-occur-highlights nil nil t)
11335 (if (org-at-timestamp-p t)
11336 (org-follow-timestamp-link)
11337 (let (type path link line search (pos (point)))
11338 (catch 'match
11339 (save-excursion
11340 (skip-chars-forward "^]\n\r")
11341 (when (org-in-regexp org-bracket-link-regexp)
11342 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11343 (while (string-match " *\n *" link)
11344 (setq link (replace-match " " t t link)))
11345 (setq link (org-link-expand-abbrev link))
11346 (if (string-match org-link-re-with-space2 link)
11347 (setq type (match-string 1 link) path (match-string 2 link))
11348 (setq type "thisfile" path link))
11349 (throw 'match t)))
11351 (when (get-text-property (point) 'org-linked-text)
11352 (setq type "thisfile"
11353 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11354 (1+ (point)) (point))
11355 path (buffer-substring
11356 (previous-single-property-change pos 'org-linked-text)
11357 (next-single-property-change pos 'org-linked-text)))
11358 (throw 'match t))
11360 (save-excursion
11361 (when (or (org-in-regexp org-angle-link-re)
11362 (org-in-regexp org-plain-link-re))
11363 (setq type (match-string 1) path (match-string 2))
11364 (throw 'match t)))
11365 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11366 (setq type "tree-match"
11367 path (match-string 1))
11368 (throw 'match t))
11369 (save-excursion
11370 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11371 (setq type "tags"
11372 path (match-string 1))
11373 (while (string-match ":" path)
11374 (setq path (replace-match "+" t t path)))
11375 (throw 'match t))))
11376 (unless path
11377 (error "No link found"))
11378 ;; Remove any trailing spaces in path
11379 (if (string-match " +\\'" path)
11380 (setq path (replace-match "" t t path)))
11382 (cond
11384 ((assoc type org-link-protocols)
11385 (funcall (nth 1 (assoc type org-link-protocols)) path))
11387 ((equal type "mailto")
11388 (let ((cmd (car org-link-mailto-program))
11389 (args (cdr org-link-mailto-program)) args1
11390 (address path) (subject "") a)
11391 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11392 (setq address (match-string 1 path)
11393 subject (org-link-escape (match-string 2 path))))
11394 (while args
11395 (cond
11396 ((not (stringp (car args))) (push (pop args) args1))
11397 (t (setq a (pop args))
11398 (if (string-match "%a" a)
11399 (setq a (replace-match address t t a)))
11400 (if (string-match "%s" a)
11401 (setq a (replace-match subject t t a)))
11402 (push a args1))))
11403 (apply cmd (nreverse args1))))
11405 ((member type '("http" "https" "ftp" "news"))
11406 (browse-url (concat type ":" path)))
11408 ((string= type "tags")
11409 (org-tags-view in-emacs path))
11410 ((string= type "thisfile")
11411 (if in-emacs
11412 (switch-to-buffer-other-window
11413 (org-get-buffer-for-internal-link (current-buffer)))
11414 (org-mark-ring-push))
11415 (let ((cmd `(org-link-search
11416 ,path
11417 ,(cond ((equal in-emacs '(4)) 'occur)
11418 ((equal in-emacs '(16)) 'org-occur)
11419 (t nil))
11420 ,pos)))
11421 (condition-case nil (eval cmd)
11422 (error (progn (widen) (eval cmd))))))
11424 ((string= type "tree-match")
11425 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11427 ((string= type "file")
11428 (if (string-match "::\\([0-9]+\\)\\'" path)
11429 (setq line (string-to-number (match-string 1 path))
11430 path (substring path 0 (match-beginning 0)))
11431 (if (string-match "::\\(.+\\)\\'" path)
11432 (setq search (match-string 1 path)
11433 path (substring path 0 (match-beginning 0)))))
11434 (org-open-file path in-emacs line search))
11436 ((string= type "news")
11437 (org-follow-gnus-link path))
11439 ((string= type "bbdb")
11440 (org-follow-bbdb-link path))
11442 ((string= type "info")
11443 (org-follow-info-link path))
11445 ((string= type "gnus")
11446 (let (group article)
11447 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11448 (error "Error in Gnus link"))
11449 (setq group (match-string 1 path)
11450 article (match-string 3 path))
11451 (org-follow-gnus-link group article)))
11453 ((string= type "vm")
11454 (let (folder article)
11455 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11456 (error "Error in VM link"))
11457 (setq folder (match-string 1 path)
11458 article (match-string 3 path))
11459 ;; in-emacs is the prefix arg, will be interpreted as read-only
11460 (org-follow-vm-link folder article in-emacs)))
11462 ((string= type "wl")
11463 (let (folder article)
11464 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11465 (error "Error in Wanderlust link"))
11466 (setq folder (match-string 1 path)
11467 article (match-string 3 path))
11468 (org-follow-wl-link folder article)))
11470 ((string= type "mhe")
11471 (let (folder article)
11472 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11473 (error "Error in MHE link"))
11474 (setq folder (match-string 1 path)
11475 article (match-string 3 path))
11476 (org-follow-mhe-link folder article)))
11478 ((string= type "rmail")
11479 (let (folder article)
11480 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11481 (error "Error in RMAIL link"))
11482 (setq folder (match-string 1 path)
11483 article (match-string 3 path))
11484 (org-follow-rmail-link folder article)))
11486 ((string= type "shell")
11487 (let ((cmd path))
11488 ;; FIXME: the following is only for backward compatibility
11489 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11490 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11491 (if (or (not org-confirm-shell-link-function)
11492 (funcall org-confirm-shell-link-function
11493 (format "Execute \"%s\" in shell? "
11494 (org-add-props cmd nil
11495 'face 'org-warning))))
11496 (progn
11497 (message "Executing %s" cmd)
11498 (shell-command cmd))
11499 (error "Abort"))))
11501 ((string= type "elisp")
11502 (let ((cmd path))
11503 (if (or (not org-confirm-elisp-link-function)
11504 (funcall org-confirm-elisp-link-function
11505 (format "Execute \"%s\" as elisp? "
11506 (org-add-props cmd nil
11507 'face 'org-warning))))
11508 (message "%s => %s" cmd (eval (read cmd)))
11509 (error "Abort"))))
11512 (browse-url-at-point)))))
11513 (move-marker org-open-link-marker nil))
11516 ;;; File search
11518 (defvar org-create-file-search-functions nil
11519 "List of functions to construct the right search string for a file link.
11520 These functions are called in turn with point at the location to
11521 which the link should point.
11523 A function in the hook should first test if it would like to
11524 handle this file type, for example by checking the major-mode or
11525 the file extension. If it decides not to handle this file, it
11526 should just return nil to give other functions a chance. If it
11527 does handle the file, it must return the search string to be used
11528 when following the link. The search string will be part of the
11529 file link, given after a double colon, and `org-open-at-point'
11530 will automatically search for it. If special measures must be
11531 taken to make the search successful, another function should be
11532 added to the companion hook `org-execute-file-search-functions',
11533 which see.
11535 A function in this hook may also use `setq' to set the variable
11536 `description' to provide a suggestion for the descriptive text to
11537 be used for this link when it gets inserted into an Org-mode
11538 buffer with \\[org-insert-link].")
11540 (defvar org-execute-file-search-functions nil
11541 "List of functions to execute a file search triggered by a link.
11543 Functions added to this hook must accept a single argument, the
11544 search string that was part of the file link, the part after the
11545 double colon. The function must first check if it would like to
11546 handle this search, for example by checking the major-mode or the
11547 file extension. If it decides not to handle this search, it
11548 should just return nil to give other functions a chance. If it
11549 does handle the search, it must return a non-nil value to keep
11550 other functions from trying.
11552 Each function can access the current prefix argument through the
11553 variable `current-prefix-argument'. Note that a single prefix is
11554 used to force opening a link in Emacs, so it may be good to only
11555 use a numeric or double prefix to guide the search function.
11557 In case this is needed, a function in this hook can also restore
11558 the window configuration before `org-open-at-point' was called using:
11560 (set-window-configuration org-window-config-before-follow-link)")
11562 (defun org-link-search (s &optional type avoid-pos)
11563 "Search for a link search option.
11564 If S is surrounded by forward slashes, it is interpreted as a
11565 regular expression. In org-mode files, this will create an `org-occur'
11566 sparse tree. In ordinary files, `occur' will be used to list matches.
11567 If the current buffer is in `dired-mode', grep will be used to search
11568 in all files. If AVOID-POS is given, ignore matches near that position."
11569 (let ((case-fold-search t)
11570 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11571 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11572 (append '(("") (" ") ("\t") ("\n"))
11573 org-emphasis-alist)
11574 "\\|") "\\)"))
11575 (pos (point))
11576 (pre "") (post "")
11577 words re0 re1 re2 re3 re4 re5 re2a reall)
11578 (cond
11579 ;; First check if there are any special
11580 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11581 ;; Now try the builtin stuff
11582 ((save-excursion
11583 (goto-char (point-min))
11584 (and
11585 (re-search-forward
11586 (concat "<<" (regexp-quote s0) ">>") nil t)
11587 (setq pos (match-beginning 0))))
11588 ;; There is an exact target for this
11589 (goto-char pos))
11590 ((string-match "^/\\(.*\\)/$" s)
11591 ;; A regular expression
11592 (cond
11593 ((org-mode-p)
11594 (org-occur (match-string 1 s)))
11595 ;;((eq major-mode 'dired-mode)
11596 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11597 (t (org-do-occur (match-string 1 s)))))
11599 ;; A normal search strings
11600 (when (equal (string-to-char s) ?*)
11601 ;; Anchor on headlines, post may include tags.
11602 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11603 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11604 s (substring s 1)))
11605 (remove-text-properties
11606 0 (length s)
11607 '(face nil mouse-face nil keymap nil fontified nil) s)
11608 ;; Make a series of regular expressions to find a match
11609 (setq words (org-split-string s "[ \n\r\t]+")
11610 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11611 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11612 "\\)" markers)
11613 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11614 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11615 re1 (concat pre re2 post)
11616 re3 (concat pre re4 post)
11617 re5 (concat pre ".*" re4)
11618 re2 (concat pre re2)
11619 re2a (concat pre re2a)
11620 re4 (concat pre re4)
11621 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11622 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11623 re5 "\\)"
11625 (cond
11626 ((eq type 'org-occur) (org-occur reall))
11627 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11628 (t (goto-char (point-min))
11629 (if (or (org-search-not-self 1 re0 nil t)
11630 (org-search-not-self 1 re1 nil t)
11631 (org-search-not-self 1 re2 nil t)
11632 (org-search-not-self 1 re2a nil t)
11633 (org-search-not-self 1 re3 nil t)
11634 (org-search-not-self 1 re4 nil t)
11635 (org-search-not-self 1 re5 nil t)
11637 (goto-char (match-beginning 1))
11638 (goto-char pos)
11639 (error "No match")))))
11641 ;; Normal string-search
11642 (goto-char (point-min))
11643 (if (search-forward s nil t)
11644 (goto-char (match-beginning 0))
11645 (error "No match"))))
11646 (and (org-mode-p) (org-show-context 'link-search))))
11648 (defun org-search-not-self (group &rest args)
11649 "Execute `re-search-forward', but only accept matches that do not
11650 enclose the position of `org-open-link-marker'."
11651 (let ((m org-open-link-marker))
11652 (catch 'exit
11653 (while (apply 're-search-forward args)
11654 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11655 (goto-char (match-end group))
11656 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11657 (> (match-beginning 0) (marker-position m))
11658 (< (match-end 0) (marker-position m)))
11659 (save-match-data
11660 (or (not (org-in-regexp
11661 org-bracket-link-analytic-regexp 1))
11662 (not (match-end 4)) ; no description
11663 (and (<= (match-beginning 4) (point))
11664 (>= (match-end 4) (point))))))
11665 (throw 'exit (point))))))))
11667 (defun org-get-buffer-for-internal-link (buffer)
11668 "Return a buffer to be used for displaying the link target of internal links."
11669 (cond
11670 ((not org-display-internal-link-with-indirect-buffer)
11671 buffer)
11672 ((string-match "(Clone)$" (buffer-name buffer))
11673 (message "Buffer is already a clone, not making another one")
11674 ;; we also do not modify visibility in this case
11675 buffer)
11676 (t ; make a new indirect buffer for displaying the link
11677 (let* ((bn (buffer-name buffer))
11678 (ibn (concat bn "(Clone)"))
11679 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11680 (with-current-buffer ib (org-overview))
11681 ib))))
11683 (defun org-do-occur (regexp &optional cleanup)
11684 "Call the Emacs command `occur'.
11685 If CLEANUP is non-nil, remove the printout of the regular expression
11686 in the *Occur* buffer. This is useful if the regex is long and not useful
11687 to read."
11688 (occur regexp)
11689 (when cleanup
11690 (let ((cwin (selected-window)) win beg end)
11691 (when (setq win (get-buffer-window "*Occur*"))
11692 (select-window win))
11693 (goto-char (point-min))
11694 (when (re-search-forward "match[a-z]+" nil t)
11695 (setq beg (match-end 0))
11696 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11697 (setq end (1- (match-beginning 0)))))
11698 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11699 (goto-char (point-min))
11700 (select-window cwin))))
11702 ;;; The mark ring for links jumps
11704 (defvar org-mark-ring nil
11705 "Mark ring for positions before jumps in Org-mode.")
11706 (defvar org-mark-ring-last-goto nil
11707 "Last position in the mark ring used to go back.")
11708 ;; Fill and close the ring
11709 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11710 (loop for i from 1 to org-mark-ring-length do
11711 (push (make-marker) org-mark-ring))
11712 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11713 org-mark-ring)
11715 (defun org-mark-ring-push (&optional pos buffer)
11716 "Put the current position or POS into the mark ring and rotate it."
11717 (interactive)
11718 (setq pos (or pos (point)))
11719 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11720 (move-marker (car org-mark-ring)
11721 (or pos (point))
11722 (or buffer (current-buffer)))
11723 (message
11724 (substitute-command-keys
11725 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11727 (defun org-mark-ring-goto (&optional n)
11728 "Jump to the previous position in the mark ring.
11729 With prefix arg N, jump back that many stored positions. When
11730 called several times in succession, walk through the entire ring.
11731 Org-mode commands jumping to a different position in the current file,
11732 or to another Org-mode file, automatically push the old position
11733 onto the ring."
11734 (interactive "p")
11735 (let (p m)
11736 (if (eq last-command this-command)
11737 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11738 (setq p org-mark-ring))
11739 (setq org-mark-ring-last-goto p)
11740 (setq m (car p))
11741 (switch-to-buffer (marker-buffer m))
11742 (goto-char m)
11743 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11745 (defun org-remove-angle-brackets (s)
11746 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11747 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11749 (defun org-add-angle-brackets (s)
11750 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11751 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11754 ;;; Following specific links
11756 (defun org-follow-timestamp-link ()
11757 (cond
11758 ((org-at-date-range-p t)
11759 (let ((org-agenda-start-on-weekday)
11760 (t1 (match-string 1))
11761 (t2 (match-string 2)))
11762 (setq t1 (time-to-days (org-time-string-to-time t1))
11763 t2 (time-to-days (org-time-string-to-time t2)))
11764 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11765 ((org-at-timestamp-p t)
11766 (org-agenda-list nil (time-to-days (org-time-string-to-time
11767 (substring (match-string 1) 0 10)))
11769 (t (error "This should not happen"))))
11772 (defun org-follow-bbdb-link (name)
11773 "Follow a BBDB link to NAME."
11774 (require 'bbdb)
11775 (let ((inhibit-redisplay (not debug-on-error))
11776 (bbdb-electric-p nil))
11777 (catch 'exit
11778 ;; Exact match on name
11779 (bbdb-name (concat "\\`" name "\\'") nil)
11780 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11781 ;; Exact match on name
11782 (bbdb-company (concat "\\`" name "\\'") nil)
11783 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11784 ;; Partial match on name
11785 (bbdb-name name nil)
11786 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11787 ;; Partial match on company
11788 (bbdb-company name nil)
11789 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11790 ;; General match including network address and notes
11791 (bbdb name nil)
11792 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11793 (delete-window (get-buffer-window "*BBDB*"))
11794 (error "No matching BBDB record")))))
11796 (defun org-follow-info-link (name)
11797 "Follow an info file & node link to NAME."
11798 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11799 (string-match "\\(.*\\)" name))
11800 (progn
11801 (require 'info)
11802 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11803 (Info-find-node (match-string 1 name) (match-string 2 name))
11804 (Info-find-node (match-string 1 name) "Top")))
11805 (message (concat "Could not open: " name))))
11807 (defun org-follow-gnus-link (&optional group article)
11808 "Follow a Gnus link to GROUP and ARTICLE."
11809 (require 'gnus)
11810 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11811 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11812 (cond ((and group article)
11813 (gnus-group-read-group 1 nil group)
11814 (gnus-summary-goto-article (string-to-number article) nil t))
11815 (group (gnus-group-jump-to-group group))))
11817 (defun org-follow-vm-link (&optional folder article readonly)
11818 "Follow a VM link to FOLDER and ARTICLE."
11819 (require 'vm)
11820 (setq article (org-add-angle-brackets article))
11821 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11822 ;; ange-ftp or efs or tramp access
11823 (let ((user (or (match-string 1 folder) (user-login-name)))
11824 (host (match-string 2 folder))
11825 (file (match-string 3 folder)))
11826 (cond
11827 ((featurep 'tramp)
11828 ;; use tramp to access the file
11829 (if (featurep 'xemacs)
11830 (setq folder (format "[%s@%s]%s" user host file))
11831 (setq folder (format "/%s@%s:%s" user host file))))
11833 ;; use ange-ftp or efs
11834 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11835 (setq folder (format "/%s@%s:%s" user host file))))))
11836 (when folder
11837 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11838 (sit-for 0.1)
11839 (when article
11840 (vm-select-folder-buffer)
11841 (widen)
11842 (let ((case-fold-search t))
11843 (goto-char (point-min))
11844 (if (not (re-search-forward
11845 (concat "^" "message-id: *" (regexp-quote article))))
11846 (error "Could not find the specified message in this folder"))
11847 (vm-isearch-update)
11848 (vm-isearch-narrow)
11849 (vm-beginning-of-message)
11850 (vm-summarize)))))
11852 (defun org-follow-wl-link (folder article)
11853 "Follow a Wanderlust link to FOLDER and ARTICLE."
11854 (if (and (string= folder "%")
11855 article
11856 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11857 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11858 ;; Thus, we recompose folder and article ids.
11859 (setq folder (format "%s#%s" folder (match-string 1 article))
11860 article (match-string 3 article)))
11861 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11862 (error "No such folder: %s" folder))
11863 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11864 (and article
11865 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11866 (wl-summary-redisplay)))
11868 (defun org-follow-rmail-link (folder article)
11869 "Follow an RMAIL link to FOLDER and ARTICLE."
11870 (setq article (org-add-angle-brackets article))
11871 (let (message-number)
11872 (save-excursion
11873 (save-window-excursion
11874 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11875 (setq message-number
11876 (save-restriction
11877 (widen)
11878 (goto-char (point-max))
11879 (if (re-search-backward
11880 (concat "^Message-ID:\\s-+" (regexp-quote
11881 (or article "")))
11882 nil t)
11883 (rmail-what-message))))))
11884 (if message-number
11885 (progn
11886 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11887 (rmail-show-message message-number)
11888 message-number)
11889 (error "Message not found"))))
11891 ;;; mh-e integration based on planner-mode
11892 (defun org-mhe-get-message-real-folder ()
11893 "Return the name of the current message real folder, so if you use
11894 sequences, it will now work."
11895 (save-excursion
11896 (let* ((folder
11897 (if (equal major-mode 'mh-folder-mode)
11898 mh-current-folder
11899 ;; Refer to the show buffer
11900 mh-show-folder-buffer))
11901 (end-index
11902 (if (boundp 'mh-index-folder)
11903 (min (length mh-index-folder) (length folder))))
11905 ;; a simple test on mh-index-data does not work, because
11906 ;; mh-index-data is always nil in a show buffer.
11907 (if (and (boundp 'mh-index-folder)
11908 (string= mh-index-folder (substring folder 0 end-index)))
11909 (if (equal major-mode 'mh-show-mode)
11910 (save-window-excursion
11911 (let (pop-up-frames)
11912 (when (buffer-live-p (get-buffer folder))
11913 (progn
11914 (pop-to-buffer folder)
11915 (org-mhe-get-message-folder-from-index)
11918 (org-mhe-get-message-folder-from-index)
11920 folder
11924 (defun org-mhe-get-message-folder-from-index ()
11925 "Returns the name of the message folder in a index folder buffer."
11926 (save-excursion
11927 (mh-index-previous-folder)
11928 (re-search-forward "^\\(+.*\\)$" nil t)
11929 (message (match-string 1))))
11931 (defun org-mhe-get-message-folder ()
11932 "Return the name of the current message folder. Be careful if you
11933 use sequences."
11934 (save-excursion
11935 (if (equal major-mode 'mh-folder-mode)
11936 mh-current-folder
11937 ;; Refer to the show buffer
11938 mh-show-folder-buffer)))
11940 (defun org-mhe-get-message-num ()
11941 "Return the number of the current message. Be careful if you
11942 use sequences."
11943 (save-excursion
11944 (if (equal major-mode 'mh-folder-mode)
11945 (mh-get-msg-num nil)
11946 ;; Refer to the show buffer
11947 (mh-show-buffer-message-number))))
11949 (defun org-mhe-get-header (header)
11950 "Return a header of the message in folder mode. This will create a
11951 show buffer for the corresponding message. If you have a more clever
11952 idea..."
11953 (let* ((folder (org-mhe-get-message-folder))
11954 (num (org-mhe-get-message-num))
11955 (buffer (get-buffer-create (concat "show-" folder)))
11956 (header-field))
11957 (with-current-buffer buffer
11958 (mh-display-msg num folder)
11959 (if (equal major-mode 'mh-folder-mode)
11960 (mh-header-display)
11961 (mh-show-header-display))
11962 (set-buffer buffer)
11963 (setq header-field (mh-get-header-field header))
11964 (if (equal major-mode 'mh-folder-mode)
11965 (mh-show)
11966 (mh-show-show))
11967 header-field)))
11969 (defun org-follow-mhe-link (folder article)
11970 "Follow an MHE link to FOLDER and ARTICLE.
11971 If ARTICLE is nil FOLDER is shown. If the configuration variable
11972 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11973 ARTICLE is searched in all folders. Indexed searches (swish++,
11974 namazu, and others supported by MH-E) will always search in all
11975 folders."
11976 (require 'mh-e)
11977 (require 'mh-search)
11978 (require 'mh-utils)
11979 (mh-find-path)
11980 (if (not article)
11981 (mh-visit-folder (mh-normalize-folder-name folder))
11982 (setq article (org-add-angle-brackets article))
11983 (mh-search-choose)
11984 (if (equal mh-searcher 'pick)
11985 (progn
11986 (mh-search folder (list "--message-id" article))
11987 (when (and org-mhe-search-all-folders
11988 (not (org-mhe-get-message-real-folder)))
11989 (kill-this-buffer)
11990 (mh-search "+" (list "--message-id" article))))
11991 (mh-search "+" article))
11992 (if (org-mhe-get-message-real-folder)
11993 (mh-show-msg 1)
11994 (kill-this-buffer)
11995 (error "Message not found"))))
11997 ;;; BibTeX links
11999 ;; Use the custom search meachnism to construct and use search strings for
12000 ;; file links to BibTeX database entries.
12002 (defun org-create-file-search-in-bibtex ()
12003 "Create the search string and description for a BibTeX database entry."
12004 (when (eq major-mode 'bibtex-mode)
12005 ;; yes, we want to construct this search string.
12006 ;; Make a good description for this entry, using names, year and the title
12007 ;; Put it into the `description' variable which is dynamically scoped.
12008 (let ((bibtex-autokey-names 1)
12009 (bibtex-autokey-names-stretch 1)
12010 (bibtex-autokey-name-case-convert-function 'identity)
12011 (bibtex-autokey-name-separator " & ")
12012 (bibtex-autokey-additional-names " et al.")
12013 (bibtex-autokey-year-length 4)
12014 (bibtex-autokey-name-year-separator " ")
12015 (bibtex-autokey-titlewords 3)
12016 (bibtex-autokey-titleword-separator " ")
12017 (bibtex-autokey-titleword-case-convert-function 'identity)
12018 (bibtex-autokey-titleword-length 'infty)
12019 (bibtex-autokey-year-title-separator ": "))
12020 (setq description (bibtex-generate-autokey)))
12021 ;; Now parse the entry, get the key and return it.
12022 (save-excursion
12023 (bibtex-beginning-of-entry)
12024 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12026 (defun org-execute-file-search-in-bibtex (s)
12027 "Find the link search string S as a key for a database entry."
12028 (when (eq major-mode 'bibtex-mode)
12029 ;; Yes, we want to do the search in this file.
12030 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12031 (goto-char (point-min))
12032 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12033 (regexp-quote s) "[ \t\n]*,") nil t)
12034 (goto-char (match-beginning 0)))
12035 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12036 ;; Use double prefix to indicate that any web link should be browsed
12037 (let ((b (current-buffer)) (p (point)))
12038 ;; Restore the window configuration because we just use the web link
12039 (set-window-configuration org-window-config-before-follow-link)
12040 (save-excursion (set-buffer b) (goto-char p)
12041 (bibtex-url)))
12042 (recenter 0)) ; Move entry start to beginning of window
12043 ;; return t to indicate that the search is done.
12046 ;; Finally add the functions to the right hooks.
12047 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12048 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12050 ;; end of Bibtex link setup
12052 ;;; Following file links
12054 (defun org-open-file (path &optional in-emacs line search)
12055 "Open the file at PATH.
12056 First, this expands any special file name abbreviations. Then the
12057 configuration variable `org-file-apps' is checked if it contains an
12058 entry for this file type, and if yes, the corresponding command is launched.
12059 If no application is found, Emacs simply visits the file.
12060 With optional argument IN-EMACS, Emacs will visit the file.
12061 Optional LINE specifies a line to go to, optional SEARCH a string to
12062 search for. If LINE or SEARCH is given, the file will always be
12063 opened in Emacs.
12064 If the file does not exist, an error is thrown."
12065 (setq in-emacs (or in-emacs line search))
12066 (let* ((file (if (equal path "")
12067 buffer-file-name
12068 (substitute-in-file-name (expand-file-name path))))
12069 (apps (append org-file-apps (org-default-apps)))
12070 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12071 (dirp (if remp nil (file-directory-p file)))
12072 (dfile (downcase file))
12073 (old-buffer (current-buffer))
12074 (old-pos (point))
12075 (old-mode major-mode)
12076 ext cmd)
12077 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12078 (setq ext (match-string 1 dfile))
12079 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12080 (setq ext (match-string 1 dfile))))
12081 (if in-emacs
12082 (setq cmd 'emacs)
12083 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12084 (and dirp (cdr (assoc 'directory apps)))
12085 (cdr (assoc ext apps))
12086 (cdr (assoc t apps)))))
12087 (when (eq cmd 'mailcap)
12088 (require 'mailcap)
12089 (mailcap-parse-mailcaps)
12090 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12091 (command (mailcap-mime-info mime-type)))
12092 (if (stringp command)
12093 (setq cmd command)
12094 (setq cmd 'emacs))))
12095 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12096 (not (file-exists-p file))
12097 (not org-open-non-existing-files))
12098 (error "No such file: %s" file))
12099 (cond
12100 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12101 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12102 (if (string-match "['\"]%s['\"]" cmd)
12103 (setq cmd (replace-match "%s" t t cmd)))
12104 (setq cmd (format cmd (shell-quote-argument file)))
12105 (save-window-excursion
12106 (shell-command (concat cmd " &"))))
12107 ((or (stringp cmd)
12108 (eq cmd 'emacs))
12109 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12110 (widen)
12111 (if line (goto-line line)
12112 (if search (org-link-search search))))
12113 ((consp cmd)
12114 (eval cmd))
12115 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12116 (and (org-mode-p) (eq old-mode 'org-mode)
12117 (or (not (equal old-buffer (current-buffer)))
12118 (not (equal old-pos (point))))
12119 (org-mark-ring-push old-pos old-buffer))))
12121 (defun org-default-apps ()
12122 "Return the default applications for this operating system."
12123 (cond
12124 ((eq system-type 'darwin)
12125 org-file-apps-defaults-macosx)
12126 ((eq system-type 'windows-nt)
12127 org-file-apps-defaults-windowsnt)
12128 (t org-file-apps-defaults-gnu)))
12130 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12131 (defun org-file-remote-p (file)
12132 "Test whether FILE specifies a location on a remote system.
12133 Return non-nil if the location is indeed remote.
12135 For example, the filename \"/user@host:/foo\" specifies a location
12136 on the system \"/user@host:\"."
12137 (cond ((fboundp 'file-remote-p)
12138 (file-remote-p file))
12139 ((fboundp 'tramp-handle-file-remote-p)
12140 (tramp-handle-file-remote-p file))
12141 ((and (boundp 'ange-ftp-name-format)
12142 (string-match (car ange-ftp-name-format) file))
12144 (t nil)))
12147 ;;;; Hooks for remember.el
12149 ;;;###autoload
12150 (defun org-remember-annotation ()
12151 "Return a link to the current location as an annotation for remember.el.
12152 If you are using Org-mode files as target for data storage with
12153 remember.el, then the annotations should include a link compatible with the
12154 conventions in Org-mode. This function returns such a link."
12155 (org-store-link nil))
12157 (defconst org-remember-help
12158 "Select a destination location for the note.
12159 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12160 RET at beg-of-buf -> Append to file as level 2 headline
12161 RET on headline -> Store as sublevel entry to current headline
12162 <left>/<right> -> before/after current headline, same headings level")
12164 ;;;###autoload
12165 (defun org-remember-apply-template (&optional use-char skip-interactive)
12166 "Initialize *remember* buffer with template, invoke `org-mode'.
12167 This function should be placed into `remember-mode-hook' and in fact requires
12168 to be run from that hook to fucntion properly."
12169 (if org-remember-templates
12171 (let* ((char (or use-char
12172 (if (= (length org-remember-templates) 1)
12173 (caar org-remember-templates)
12174 (message "Select template: %s"
12175 (mapconcat
12176 (lambda (x) (char-to-string (car x)))
12177 org-remember-templates " "))
12178 (read-char-exclusive))))
12179 (entry (cdr (assoc char org-remember-templates)))
12180 (tpl (car entry))
12181 (plist-p (if org-store-link-plist t nil))
12182 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12183 (string-match "\\S-" (nth 1 entry)))
12184 (nth 1 entry)
12185 org-default-notes-file))
12186 (headline (nth 2 entry))
12187 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12188 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12189 (v-u (concat "[" (substring v-t 1 -1) "]"))
12190 (v-U (concat "[" (substring v-T 1 -1) "]"))
12191 (v-i initial) ; defined in `remember-mode'
12192 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
12193 (v-n user-full-name)
12194 (org-startup-folded nil)
12195 org-time-was-given org-end-time-was-given x prompt char time)
12196 (setq org-store-link-plist
12197 (append (list :annotation v-a :initial v-i)
12198 org-store-link-plist))
12199 (unless tpl (setq tpl "") (message "No template") (ding))
12200 (erase-buffer)
12201 (insert (substitute-command-keys
12202 (format
12203 "## `%sC-c C-c' to file directly, `%sC-c C-c' to file interactively.
12204 ## Target file \"%s\", headline \"%s\"
12205 ## To switch templates, use `\\[org-remember]'.\n\n"
12206 (if org-remember-store-without-prompt "" "C-u ")
12207 (if org-remember-store-without-prompt "C-u " "")
12208 (abbreviate-file-name (or file org-default-notes-file))
12209 (or headline ""))))
12210 (insert tpl) (goto-char (point-min))
12211 ;; Simple %-escapes
12212 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
12213 (when (and initial (equal (match-string 0) "%i"))
12214 (save-match-data
12215 (let* ((lead (buffer-substring
12216 (point-at-bol) (match-beginning 0))))
12217 (setq v-i (mapconcat 'identity
12218 (org-split-string initial "\n")
12219 (concat "\n" lead))))))
12220 (replace-match
12221 (or (eval (intern (concat "v-" (match-string 1)))) "")
12222 t t))
12223 ;; From the property list
12224 (when plist-p
12225 (goto-char (point-min))
12226 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12227 (and (setq x (plist-get org-store-link-plist
12228 (intern (match-string 1))))
12229 (replace-match x t t))))
12230 ;; Turn on org-mode in the remember buffer, set local variables
12231 (org-mode)
12232 (org-set-local 'org-finish-function 'remember-buffer)
12233 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12234 (org-set-local 'org-default-notes-file file))
12235 (if (and headline (stringp headline) (string-match "\\S-" headline))
12236 (org-set-local 'org-remember-default-headline headline))
12237 ;; Interactive template entries
12238 (goto-char (point-min))
12239 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12240 (setq char (if (match-end 3) (match-string 3))
12241 prompt (if (match-end 2) (match-string 2)))
12242 (goto-char (match-beginning 0))
12243 (replace-match "")
12244 (cond
12245 ((member char '("G" "g"))
12246 (let* ((org-last-tags-completion-table
12247 (org-global-tags-completion-table
12248 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12249 (org-add-colon-after-tag-completion t)
12250 (ins (completing-read
12251 (if prompt (concat prompt ": ") "Tags: ")
12252 'org-tags-completion-function nil nil nil
12253 'org-tags-history)))
12254 (setq ins (mapconcat 'identity
12255 (org-split-string ins (org-re "[^[:alnum:]]+"))
12256 ":"))
12257 (when (string-match "\\S-" ins)
12258 (or (equal (char-before) ?:) (insert ":"))
12259 (insert ins)
12260 (or (equal (char-after) ?:) (insert ":")))))
12261 (char
12262 (setq org-time-was-given (equal (upcase char) char))
12263 (setq time (org-read-date (equal (upcase char) "U") t nil
12264 prompt))
12265 (org-insert-time-stamp time org-time-was-given
12266 (member char '("u" "U"))
12267 nil nil (list org-end-time-was-given)))
12269 (insert (read-string
12270 (if prompt (concat prompt ": ") "Enter string"))))))
12271 (goto-char (point-min))
12272 (if (re-search-forward "%\\?" nil t)
12273 (replace-match "")
12274 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12275 (org-mode)
12276 (org-set-local 'org-finish-function 'remember-buffer)))
12278 ;;;###autoload
12279 (defun org-remember ()
12280 "Call `remember'. If this is already a remember buffer, re-apply template.
12281 If there is an active region, make sure remember uses it as initial content
12282 of the remember buffer."
12283 (interactive)
12284 (if (eq org-finish-function 'remember-buffer)
12285 (progn
12286 (when (< (length org-remember-templates) 2)
12287 (error "No other template available"))
12288 (erase-buffer)
12289 (let ((annotation (plist-get org-store-link-plist :annotation))
12290 (initial (plist-get org-store-link-plist :initial)))
12291 (org-remember-apply-template))
12292 (message "Press C-c C-c to remember data"))
12293 (if (org-region-active-p)
12294 (remember (buffer-substring (point) (mark)))
12295 (call-interactively 'remember))))
12297 ;;;###autoload
12298 (defun org-remember-handler ()
12299 "Store stuff from remember.el into an org file.
12300 First prompts for an org file. If the user just presses return, the value
12301 of `org-default-notes-file' is used.
12302 Then the command offers the headings tree of the selected file in order to
12303 file the text at a specific location.
12304 You can either immediately press RET to get the note appended to the
12305 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12306 find a better place. Then press RET or <left> or <right> in insert the note.
12308 Key Cursor position Note gets inserted
12309 -----------------------------------------------------------------------------
12310 RET buffer-start as level 2 heading at end of file
12311 RET on headline as sublevel of the heading at cursor
12312 RET no heading at cursor position, level taken from context.
12313 Or use prefix arg to specify level manually.
12314 <left> on headline as same level, before current heading
12315 <right> on headline as same level, after current heading
12317 So the fastest way to store the note is to press RET RET to append it to
12318 the default file. This way your current train of thought is not
12319 interrupted, in accordance with the principles of remember.el.
12320 You can also get the fast execution without prompting by using
12321 C-u C-c C-c to exit the remember buffer. See also the variable
12322 `org-remember-store-without-prompt'.
12324 Before being stored away, the function ensures that the text has a
12325 headline, i.e. a first line that starts with a \"*\". If not, a headline
12326 is constructed from the current date and some additional data.
12328 If the variable `org-adapt-indentation' is non-nil, the entire text is
12329 also indented so that it starts in the same column as the headline
12330 \(i.e. after the stars).
12332 See also the variable `org-reverse-note-order'."
12333 (goto-char (point-min))
12334 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12335 (replace-match ""))
12336 (catch 'quit
12337 (let* ((txt (buffer-substring (point-min) (point-max)))
12338 (fastp (org-xor (equal current-prefix-arg '(4))
12339 org-remember-store-without-prompt))
12340 (file (if fastp org-default-notes-file (org-get-org-file)))
12341 (heading org-remember-default-headline)
12342 (visiting (org-find-base-buffer-visiting file))
12343 (org-startup-folded nil)
12344 (org-startup-align-all-tables nil)
12345 (org-goto-start-pos 1)
12346 spos level indent reversed)
12347 (setq current-prefix-arg nil)
12348 ;; Modify text so that it becomes a nice subtree which can be inserted
12349 ;; into an org tree.
12350 (let* ((lines (split-string txt "\n"))
12351 first)
12352 (setq first (car lines) lines (cdr lines))
12353 (if (string-match "^\\*+ " first)
12354 ;; Is already a headline
12355 (setq indent nil)
12356 ;; We need to add a headline: Use time and first buffer line
12357 (setq lines (cons first lines)
12358 first (concat "* " (current-time-string)
12359 " (" (remember-buffer-desc) ")")
12360 indent " "))
12361 (if (and org-adapt-indentation indent)
12362 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12363 (setq txt (concat first "\n"
12364 (mapconcat 'identity lines "\n"))))
12365 ;; Find the file
12366 (if (not visiting) (find-file-noselect file))
12367 (with-current-buffer (or visiting (get-file-buffer file))
12368 (save-excursion
12369 (save-restriction
12370 (widen)
12371 (and (goto-char (point-min))
12372 (not (re-search-forward "^\\* " nil t))
12373 (insert "\n* Notes\n"))
12374 (setq reversed (org-notes-order-reversed-p))
12376 ;; Find the default location
12377 (when (and heading (stringp heading) (string-match "\\S-" heading))
12378 (goto-char (point-min))
12379 (if (re-search-forward
12380 (concat "^\\*+[ \t]+" (regexp-quote heading)
12381 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12382 nil t)
12383 (setq org-goto-start-pos (match-beginning 0))))
12385 ;; Ask the User for a location
12386 (setq spos (if fastp
12387 org-goto-start-pos
12388 (org-get-location (current-buffer) org-remember-help)))
12389 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12390 ; not handle this note
12391 (goto-char spos)
12392 (cond ((and (bobp) (not reversed))
12393 ;; Put it at the end, one level below level 1
12394 (save-restriction
12395 (widen)
12396 (goto-char (point-max))
12397 (if (not (bolp)) (newline))
12398 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12399 ((and (bobp) reversed)
12400 ;; Put it at the start, as level 1
12401 (save-restriction
12402 (widen)
12403 (goto-char (point-min))
12404 (re-search-forward "^\\*+ " nil t)
12405 (beginning-of-line 1)
12406 (org-paste-subtree 1 txt)))
12407 ((and (org-on-heading-p t) (not current-prefix-arg))
12408 ;; Put it below this entry, at the beg/end of the subtree
12409 (org-back-to-heading t)
12410 (setq level (funcall outline-level))
12411 (if reversed
12412 (outline-next-heading)
12413 (org-end-of-subtree t))
12414 (if (not (bolp)) (newline))
12415 (beginning-of-line 1)
12416 (org-paste-subtree (org-get-legal-level level 1) txt))
12418 ;; Put it right there, with automatic level determined by
12419 ;; org-paste-subtree or from prefix arg
12420 (org-paste-subtree
12421 (if (numberp current-prefix-arg) current-prefix-arg)
12422 txt)))
12423 (when remember-save-after-remembering
12424 (save-buffer)
12425 (if (not visiting) (kill-buffer (current-buffer)))))))))
12426 t) ;; return t to indicate that we took care of this note.
12428 (defun org-get-org-file ()
12429 "Read a filename, with default directory `org-directory'."
12430 (let ((default (or org-default-notes-file remember-data-file)))
12431 (read-file-name (format "File name [%s]: " default)
12432 (file-name-as-directory org-directory)
12433 default)))
12435 (defun org-notes-order-reversed-p ()
12436 "Check if the current file should receive notes in reversed order."
12437 (cond
12438 ((not org-reverse-note-order) nil)
12439 ((eq t org-reverse-note-order) t)
12440 ((not (listp org-reverse-note-order)) nil)
12441 (t (catch 'exit
12442 (let ((all org-reverse-note-order)
12443 entry)
12444 (while (setq entry (pop all))
12445 (if (string-match (car entry) buffer-file-name)
12446 (throw 'exit (cdr entry))))
12447 nil)))))
12449 ;;;; Dynamic blocks
12451 (defun org-find-dblock (name)
12452 "Find the first dynamic block with name NAME in the buffer.
12453 If not found, stay at current position and return nil."
12454 (let (pos)
12455 (save-excursion
12456 (goto-char (point-min))
12457 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12458 nil t)
12459 (match-beginning 0))))
12460 (if pos (goto-char pos))
12461 pos))
12463 (defconst org-dblock-start-re
12464 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12465 "Matches the startline of a dynamic block, with parameters.")
12467 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12468 "Matches the end of a dyhamic block.")
12470 (defun org-create-dblock (plist)
12471 "Create a dynamic block section, with parameters taken from PLIST.
12472 PLIST must containe a :name entry which is used as name of the block."
12473 (unless (bolp) (newline))
12474 (let ((name (plist-get plist :name)))
12475 (insert "#+BEGIN: " name)
12476 (while plist
12477 (if (eq (car plist) :name)
12478 (setq plist (cddr plist))
12479 (insert " " (prin1-to-string (pop plist)))))
12480 (insert "\n\n#+END:\n")
12481 (beginning-of-line -2)))
12483 (defun org-prepare-dblock ()
12484 "Prepare dynamic block for refresh.
12485 This empties the block, puts the cursor at the insert position and returns
12486 the property list including an extra property :name with the block name."
12487 (unless (looking-at org-dblock-start-re)
12488 (error "Not at a dynamic block"))
12489 (let* ((begdel (1+ (match-end 0)))
12490 (name (match-string 1))
12491 (params (append (list :name name)
12492 (read (concat "(" (match-string 3) ")")))))
12493 (unless (re-search-forward org-dblock-end-re nil t)
12494 (error "Dynamic block not terminated"))
12495 (delete-region begdel (match-beginning 0))
12496 (goto-char begdel)
12497 (open-line 1)
12498 params))
12500 (defun org-map-dblocks (&optional command)
12501 "Apply COMMAND to all dynamic blocks in the current buffer.
12502 If COMMAND is not given, use `org-update-dblock'."
12503 (let ((cmd (or command 'org-update-dblock))
12504 pos)
12505 (save-excursion
12506 (goto-char (point-min))
12507 (while (re-search-forward org-dblock-start-re nil t)
12508 (goto-char (setq pos (match-beginning 0)))
12509 (condition-case nil
12510 (funcall cmd)
12511 (error (message "Error during update of dynamic block")))
12512 (goto-char pos)
12513 (unless (re-search-forward org-dblock-end-re nil t)
12514 (error "Dynamic block not terminated"))))))
12516 (defun org-dblock-update (&optional arg)
12517 "User command for updating dynamic blocks.
12518 Update the dynamic block at point. With prefix ARG, update all dynamic
12519 blocks in the buffer."
12520 (interactive "P")
12521 (if arg
12522 (org-update-all-dblocks)
12523 (or (looking-at org-dblock-start-re)
12524 (org-beginning-of-dblock))
12525 (org-update-dblock)))
12527 (defun org-update-dblock ()
12528 "Update the dynamic block at point
12529 This means to empty the block, parse for parameters and then call
12530 the correct writing function."
12531 (let* ((pos (point))
12532 (params (org-prepare-dblock))
12533 (name (plist-get params :name))
12534 (cmd (intern (concat "org-dblock-write:" name))))
12535 (funcall cmd params)
12536 (goto-char pos)))
12538 (defun org-beginning-of-dblock ()
12539 "Find the beginning of the dynamic block at point.
12540 Error if there is no scuh block at point."
12541 (let ((pos (point))
12542 beg)
12543 (end-of-line 1)
12544 (if (and (re-search-backward org-dblock-start-re nil t)
12545 (setq beg (match-beginning 0))
12546 (re-search-forward org-dblock-end-re nil t)
12547 (> (match-end 0) pos))
12548 (goto-char beg)
12549 (goto-char pos)
12550 (error "Not in a dynamic block"))))
12552 (defun org-update-all-dblocks ()
12553 "Update all dynamic blocks in the buffer.
12554 This function can be used in a hook."
12555 (when (org-mode-p)
12556 (org-map-dblocks 'org-update-dblock)))
12559 ;;;; Completion
12561 (defun org-complete (&optional arg)
12562 "Perform completion on word at point.
12563 At the beginning of a headline, this completes TODO keywords as given in
12564 `org-todo-keywords'.
12565 If the current word is preceded by a backslash, completes the TeX symbols
12566 that are supported for HTML support.
12567 If the current word is preceded by \"#+\", completes special words for
12568 setting file options.
12569 In the line after \"#+STARTUP:, complete valid keywords.\"
12570 At all other locations, this simply calls `ispell-complete-word'."
12571 (interactive "P")
12572 (catch 'exit
12573 (let* ((end (point))
12574 (beg1 (save-excursion
12575 (skip-chars-backward (org-re "[:alnum:]_@"))
12576 (point)))
12577 (beg (save-excursion
12578 (skip-chars-backward "a-zA-Z0-9_:$")
12579 (point)))
12580 (confirm (lambda (x) (stringp (car x))))
12581 (searchhead (equal (char-before beg) ?*))
12582 (tag (and (equal (char-before beg1) ?:)
12583 (equal (char-after (point-at-bol)) ?*)))
12584 (prop (and (equal (char-before beg1) ?:)
12585 (not (equal (char-after (point-at-bol)) ?*))))
12586 (texp (equal (char-before beg) ?\\))
12587 (link (equal (char-before beg) ?\[))
12588 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12589 beg)
12590 "#+"))
12591 (startup (string-match "^#\\+STARTUP:.*"
12592 (buffer-substring (point-at-bol) (point))))
12593 (completion-ignore-case opt)
12594 (type nil)
12595 (tbl nil)
12596 (table (cond
12597 (opt
12598 (setq type :opt)
12599 (mapcar (lambda (x)
12600 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12601 (cons (match-string 2 x) (match-string 1 x)))
12602 (org-split-string (org-get-current-options) "\n")))
12603 (startup
12604 (setq type :startup)
12605 org-startup-options)
12606 (link (append org-link-abbrev-alist-local
12607 org-link-abbrev-alist))
12608 (texp
12609 (setq type :tex)
12610 org-html-entities)
12611 ((string-match "\\`\\*+[ \t]+\\'"
12612 (buffer-substring (point-at-bol) beg))
12613 (setq type :todo)
12614 (mapcar 'list org-todo-keywords-1))
12615 (searchhead
12616 (setq type :searchhead)
12617 (save-excursion
12618 (goto-char (point-min))
12619 (while (re-search-forward org-todo-line-regexp nil t)
12620 (push (list
12621 (org-make-org-heading-search-string
12622 (match-string 3) t))
12623 tbl)))
12624 tbl)
12625 (tag (setq type :tag beg beg1)
12626 (or org-tag-alist (org-get-buffer-tags)))
12627 (prop (setq type :prop beg beg1)
12628 (mapcar 'list (org-buffer-property-keys)))
12629 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
12630 (pattern (buffer-substring-no-properties beg end))
12631 (completion (try-completion pattern table confirm)))
12632 (cond ((eq completion t)
12633 (if (equal type :opt)
12634 (insert (substring (cdr (assoc (upcase pattern) table))
12635 (length pattern)))
12636 (if (memq type '(:tag :prop)) (insert ":"))))
12637 ((null completion)
12638 (message "Can't find completion for \"%s\"" pattern)
12639 (ding))
12640 ((not (string= pattern completion))
12641 (delete-region beg end)
12642 (if (string-match " +$" completion)
12643 (setq completion (replace-match "" t t completion)))
12644 (insert completion)
12645 (if (get-buffer-window "*Completions*")
12646 (delete-window (get-buffer-window "*Completions*")))
12647 (if (assoc completion table)
12648 (if (eq type :todo) (insert " ")
12649 (if (memq type '(:tag :prop)) (insert ":"))))
12650 (if (and (equal type :opt) (assoc completion table))
12651 (message "%s" (substitute-command-keys
12652 "Press \\[org-complete] again to insert example settings"))))
12654 (message "Making completion list...")
12655 (let ((list (sort (all-completions pattern table confirm)
12656 'string<)))
12657 (with-output-to-temp-buffer "*Completions*"
12658 (condition-case nil
12659 ;; Protection needed for XEmacs and emacs 21
12660 (display-completion-list list pattern)
12661 (error (display-completion-list list)))))
12662 (message "Making completion list...%s" "done"))))))
12664 ;;;; TODO, DEADLINE, Comments
12666 (defun org-toggle-comment ()
12667 "Change the COMMENT state of an entry."
12668 (interactive)
12669 (save-excursion
12670 (org-back-to-heading)
12671 (if (looking-at (concat outline-regexp
12672 "\\( *\\<" org-comment-string "\\>\\)"))
12673 (replace-match "" t t nil 1)
12674 (if (looking-at outline-regexp)
12675 (progn
12676 (goto-char (match-end 0))
12677 (insert org-comment-string " "))))))
12679 (defvar org-last-todo-state-is-todo nil
12680 "This is non-nil when the last TODO state change led to a TODO state.
12681 If the last change removed the TODO tag or switched to DONE, then
12682 this is nil.")
12684 (defvar org-setting-tags nil) ; dynamically skiped
12686 (defun org-todo (&optional arg)
12687 "Change the TODO state of an item.
12688 The state of an item is given by a keyword at the start of the heading,
12689 like
12690 *** TODO Write paper
12691 *** DONE Call mom
12693 The different keywords are specified in the variable `org-todo-keywords'.
12694 By default the available states are \"TODO\" and \"DONE\".
12695 So for this example: when the item starts with TODO, it is changed to DONE.
12696 When it starts with DONE, the DONE is removed. And when neither TODO nor
12697 DONE are present, add TODO at the beginning of the heading.
12699 With C-u prefix arg, use completion to determine the new state.
12700 With numeric prefix arg, switch to that state.
12702 For calling through lisp, arg is also interpreted in the following way:
12703 'none -> empty state
12704 \"\"(empty string) -> switch to empty state
12705 'done -> switch to DONE
12706 'nextset -> switch to the next set of keywords
12707 'previousset -> switch to the previous set of keywords
12708 \"WAITING\" -> switch to the specified keyword, but only if it
12709 really is a member of `org-todo-keywords'."
12710 (interactive "P")
12711 (save-excursion
12712 (org-back-to-heading)
12713 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
12714 (or (looking-at (concat " +" org-todo-regexp " *"))
12715 (looking-at " *"))
12716 (let* ((this (match-string 1))
12717 (head (org-get-todo-sequence-head this))
12718 (ass (assoc head org-todo-kwd-alist))
12719 (interpret (nth 1 ass))
12720 (done-word (nth 3 ass))
12721 (final-done-word (nth 4 ass))
12722 (last-state (or this ""))
12723 (completion-ignore-case t)
12724 (member (member this org-todo-keywords-1))
12725 (tail (cdr member))
12726 (state (cond
12727 ((equal arg '(4))
12728 ;; Read a state with completion
12729 (completing-read "State: " (mapcar (lambda(x) (list x))
12730 org-todo-keywords-1)
12731 nil t))
12732 ((eq arg 'right)
12733 (if this
12734 (if tail (car tail) nil)
12735 (car org-todo-keywords-1)))
12736 ((eq arg 'left)
12737 (if (equal member org-todo-keywords-1)
12739 (if this
12740 (nth (- (length org-todo-keywords-1) (length tail) 2)
12741 org-todo-keywords-1)
12742 (org-last org-todo-keywords-1))))
12743 (arg
12744 ;; user or caller requests a specific state
12745 (cond
12746 ((equal arg "") nil)
12747 ((eq arg 'none) nil)
12748 ((eq arg 'done) (or done-word (car org-done-keywords)))
12749 ((eq arg 'nextset)
12750 (or (car (cdr (member head org-todo-heads)))
12751 (car org-todo-heads)))
12752 ((eq arg 'previousset)
12753 (let ((org-todo-heads (reverse org-todo-heads)))
12754 (or (car (cdr (member head org-todo-heads)))
12755 (car org-todo-heads))))
12756 ((car (member arg org-todo-keywords-1)))
12757 ((nth (1- (prefix-numeric-value arg))
12758 org-todo-keywords-1))))
12759 ((null member) (or head (car org-todo-keywords-1)))
12760 ((equal this final-done-word) nil) ;; -> make empty
12761 ((null tail) nil) ;; -> first entry
12762 ((eq interpret 'sequence)
12763 (car tail))
12764 ((memq interpret '(type priority))
12765 (if (eq this-command last-command)
12766 (car tail)
12767 (if (> (length tail) 0)
12768 (or done-word (car org-done-keywords))
12769 nil)))
12770 (t nil)))
12771 (next (if state (concat " " state " ") " "))
12772 dostates)
12773 (replace-match next t t)
12774 (unless head
12775 (setq head (org-get-todo-sequence-head state)
12776 ass (assoc head org-todo-kwd-alist)
12777 interpret (nth 1 ass)
12778 done-word (nth 3 ass)
12779 final-done-word (nth 4 ass)))
12780 (when (memq arg '(nextset previousset))
12781 (message "Keyword-Set %d/%d: %s"
12782 (- (length org-todo-sets) -1
12783 (length (memq (assoc state org-todo-sets) org-todo-sets)))
12784 (length org-todo-sets)
12785 (mapconcat 'identity (assoc state org-todo-sets) " ")))
12786 (setq org-last-todo-state-is-todo
12787 (not (member state org-done-keywords)))
12788 (when (and org-log-done (not (memq arg '(nextset previousset))))
12789 (setq dostates (and (eq interpret 'sequence)
12790 (listp org-log-done) (memq 'state org-log-done)))
12791 (cond
12792 ((and state (not this))
12793 ;; FIXME: should we remove CLOSED already then state is nil?
12794 (org-add-planning-info nil nil 'closed)
12795 (and dostates (org-add-log-maybe 'state state 'findpos)))
12796 ((and state dostates)
12797 (org-add-log-maybe 'state state 'findpos))
12798 ((member state org-done-keywords)
12799 ;; Planning info calls the note-setting command.
12800 ;; FIXME: We used to remove scheduling info....
12801 ; (org-add-planning-info 'closed (org-current-time)
12802 ; (if (org-get-repeat) nil 'scheduled))
12803 (org-add-planning-info 'closed (org-current-time))
12804 (org-add-log-maybe 'done state 'findpos))))
12805 ;; Fixup tag positioning
12806 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12807 (run-hooks 'org-after-todo-state-change-hook)
12808 (and (member state org-done-keywords) (org-auto-repeat-maybe))
12809 (if (and arg (not (member state org-done-keywords)))
12810 (setq head (org-get-todo-sequence-head state)))
12811 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
12812 ;; Fixup cursor location if close to the keyword
12813 (if (and (outline-on-heading-p)
12814 (not (bolp))
12815 (save-excursion (beginning-of-line 1)
12816 (looking-at org-todo-line-regexp))
12817 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12818 (progn
12819 (goto-char (or (match-end 2) (match-end 1)))
12820 (just-one-space))))
12822 (defun org-get-todo-sequence-head (kwd)
12823 "Return the head of the TODO sequence to which KWD belongs.
12824 If KWD is not set, check if there is a text property remembering the
12825 right sequence."
12826 (let (p)
12827 (cond
12828 ((not kwd)
12829 (or (get-text-property (point-at-bol) 'org-todo-head)
12830 (progn
12831 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12832 nil (point-at-eol)))
12833 (get-text-property p 'org-todo-head))))
12834 ((not (member kwd org-todo-keywords-1))
12835 (car org-todo-keywords-1))
12836 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12838 (defun org-get-repeat ()
12839 "Check if tere is a deadline/schedule with repeater in this entry."
12840 (save-match-data
12841 (save-excursion
12842 (org-back-to-heading t)
12843 (if (re-search-forward
12844 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
12845 (match-string 1)))))
12847 (defvar org-last-changed-timestamp)
12848 (defvar org-log-post-message)
12849 (defun org-auto-repeat-maybe ()
12850 "Check if the current headline contains a repeated deadline/schedule.
12851 If yes, set TODO state back to what it was and change the base date
12852 of repeating deadline/scheduled time stamps to new date.
12853 This function should be run in the `org-after-todo-state-change-hook'."
12854 ;; last-state is dynamically scoped into this function
12855 (let* ((repeat (org-get-repeat))
12856 (aa (assoc last-state org-todo-kwd-alist))
12857 (interpret (nth 1 aa))
12858 (head (nth 2 aa))
12859 (done-word (nth 3 aa))
12860 (whata '(("d" . day) ("m" . month) ("y" . year)))
12861 (msg "Entry repeats: ")
12862 (org-log-done)
12863 re type n what ts)
12864 (when repeat
12865 (org-todo (if (eq interpret 'type) last-state head))
12866 (when (and org-log-repeat
12867 (not (memq 'org-add-log-note
12868 (default-value 'post-command-hook))))
12869 ;; Make sure a note is taken
12870 (let ((org-log-done '(done)))
12871 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12872 'findpos)))
12873 (org-back-to-heading t)
12874 (org-add-planning-info nil nil 'closed)
12875 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12876 org-deadline-time-regexp "\\)"))
12877 (while (re-search-forward
12878 re (save-excursion (outline-next-heading) (point)) t)
12879 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12880 ts (match-string (if (match-end 2) 2 4)))
12881 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12882 (setq n (string-to-number (match-string 1 ts))
12883 what (match-string 2 ts))
12884 (if (equal what "w") (setq n (* n 7) what "d"))
12885 (org-timestamp-change n (cdr (assoc what whata))))
12886 (setq msg (concat msg type org-last-changed-timestamp " ")))
12887 (setq org-log-post-message msg)
12888 (message msg))))
12890 (defun org-show-todo-tree (arg)
12891 "Make a compact tree which shows all headlines marked with TODO.
12892 The tree will show the lines where the regexp matches, and all higher
12893 headlines above the match.
12894 With \\[universal-argument] prefix, also show the DONE entries.
12895 With a numeric prefix N, construct a sparse tree for the Nth element
12896 of `org-todo-keywords-1'."
12897 (interactive "P")
12898 (let ((case-fold-search nil)
12899 (kwd-re
12900 (cond ((null arg) org-not-done-regexp)
12901 ((equal arg '(4))
12902 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12903 (mapcar 'list org-todo-keywords-1))))
12904 (concat "\\("
12905 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12906 "\\)\\>")))
12907 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12908 (regexp-quote (nth (1- (prefix-numeric-value arg))
12909 org-todo-keywords-1)))
12910 (t (error "Invalid prefix argument: %s" arg)))))
12911 (message "%d TODO entries found"
12912 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
12914 (defun org-deadline ()
12915 "Insert the DEADLINE: string to make a deadline.
12916 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12917 to modify it to the correct date."
12918 (interactive)
12919 (org-add-planning-info 'deadline nil 'closed))
12921 (defun org-schedule ()
12922 "Insert the SCHEDULED: string to schedule a TODO item.
12923 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12924 to modify it to the correct date."
12925 (interactive)
12926 (org-add-planning-info 'scheduled nil 'closed))
12928 (defun org-add-planning-info (what &optional time &rest remove)
12929 "Insert new timestamp with keyword in the line directly after the headline.
12930 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12931 If non is given, the user is prompted for a date.
12932 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12933 be removed."
12934 (interactive)
12935 (let (org-time-was-given org-end-time-was-given)
12936 (when what (setq time (or time (org-read-date nil 'to-time))))
12937 (when (and org-insert-labeled-timestamps-at-point
12938 (member what '(scheduled deadline)))
12939 (insert
12940 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12941 (org-insert-time-stamp time org-time-was-given
12942 nil nil nil (list org-end-time-was-given))
12943 (setq what nil))
12944 (save-excursion
12945 (save-restriction
12946 (let (col list elt ts buffer-invisibility-spec)
12947 (org-back-to-heading t)
12948 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12949 (goto-char (match-end 1))
12950 (setq col (current-column))
12951 (goto-char (match-end 0))
12952 (if (eobp) (insert "\n"))
12953 (forward-char 1)
12954 (when (and (not org-insert-labeled-timestamps-before-properties-drawer)
12955 (looking-at "[ \t]*:PROPERTIES:[ \t]*$"))
12956 (goto-char (match-end 0))
12957 (if (eobp) (insert "\n"))
12958 (forward-char 1))
12959 (if (and (not (looking-at outline-regexp))
12960 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12961 "[^\r\n]*"))
12962 (not (equal (match-string 1) org-clock-string)))
12963 (narrow-to-region (match-beginning 0) (match-end 0))
12964 (insert-before-markers "\n")
12965 (backward-char 1)
12966 (narrow-to-region (point) (point))
12967 (indent-to-column col))
12968 ;; Check if we have to remove something.
12969 (setq list (cons what remove))
12970 (while list
12971 (setq elt (pop list))
12972 (goto-char (point-min))
12973 (when (or (and (eq elt 'scheduled)
12974 (re-search-forward org-scheduled-time-regexp nil t))
12975 (and (eq elt 'deadline)
12976 (re-search-forward org-deadline-time-regexp nil t))
12977 (and (eq elt 'closed)
12978 (re-search-forward org-closed-time-regexp nil t)))
12979 (replace-match "")
12980 (if (looking-at "--+<[^>]+>") (replace-match ""))
12981 (if (looking-at " +") (replace-match ""))))
12982 (goto-char (point-max))
12983 (when what
12984 (insert
12985 (if (not (equal (char-before) ?\ )) " " "")
12986 (cond ((eq what 'scheduled) org-scheduled-string)
12987 ((eq what 'deadline) org-deadline-string)
12988 ((eq what 'closed) org-closed-string))
12989 " ")
12990 (org-insert-time-stamp
12991 time
12992 (or org-time-was-given
12993 (and (eq what 'closed) org-log-done-with-time))
12994 (eq what 'closed)
12995 nil nil (list org-end-time-was-given))
12996 (end-of-line 1))
12997 (goto-char (point-min))
12998 (widen)
12999 (if (looking-at "[ \t]+\r?\n")
13000 (replace-match ""))
13001 ts)))))
13003 (defvar org-log-note-marker (make-marker))
13004 (defvar org-log-note-purpose nil)
13005 (defvar org-log-note-state nil)
13006 (defvar org-log-note-window-configuration nil)
13007 (defvar org-log-note-return-to (make-marker))
13008 (defvar org-log-post-message nil
13009 "Message to be displayed after a log note has been stored.
13010 The auto-repeater uses this.")
13012 (defun org-add-log-maybe (&optional purpose state findpos)
13013 "Set up the post command hook to take a note."
13014 (save-excursion
13015 (when (and (listp org-log-done)
13016 (memq purpose org-log-done))
13017 (when findpos
13018 (org-back-to-heading t)
13019 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13020 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13021 "[^\r\n]*\\)?"))
13022 (goto-char (match-end 0))
13023 (unless org-log-states-order-reversed
13024 (and (= (char-after) ?\n) (forward-char 1))
13025 (org-skip-over-state-notes)
13026 (skip-chars-backward " \t\n\r")))
13027 (move-marker org-log-note-marker (point))
13028 (setq org-log-note-purpose purpose)
13029 (setq org-log-note-state state)
13030 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13032 (defun org-skip-over-state-notes ()
13033 "Skip past the list of State notes in an entry."
13034 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13035 (while (looking-at "[ \t]*- State")
13036 (condition-case nil
13037 (org-next-item)
13038 (error (org-end-of-item)))))
13040 (defun org-add-log-note (&optional purpose)
13041 "Pop up a window for taking a note, and add this note later at point."
13042 (remove-hook 'post-command-hook 'org-add-log-note)
13043 (setq org-log-note-window-configuration (current-window-configuration))
13044 (delete-other-windows)
13045 (move-marker org-log-note-return-to (point))
13046 (switch-to-buffer (marker-buffer org-log-note-marker))
13047 (goto-char org-log-note-marker)
13048 (org-switch-to-buffer-other-window "*Org Note*")
13049 (erase-buffer)
13050 (let ((org-inhibit-startup t)) (org-mode))
13051 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
13052 (cond
13053 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13054 ((eq org-log-note-purpose 'done) "closed todo item")
13055 ((eq org-log-note-purpose 'state) "state change")
13056 (t (error "This should not happen")))))
13057 (org-set-local 'org-finish-function 'org-store-log-note))
13059 (defun org-store-log-note ()
13060 "Finish taking a log note, and insert it to where it belongs."
13061 (let ((txt (buffer-string))
13062 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13063 lines ind)
13064 (kill-buffer (current-buffer))
13065 (if (string-match "^#.*\n[ \t\n]*" txt)
13066 (setq txt (replace-match "" t t txt)))
13067 (if (string-match "\\s-+\\'" txt)
13068 (setq txt (replace-match "" t t txt)))
13069 (setq lines (org-split-string txt "\n"))
13070 (when (and note (string-match "\\S-" note))
13071 (setq note
13072 (org-replace-escapes
13073 note
13074 (list (cons "%u" (user-login-name))
13075 (cons "%U" user-full-name)
13076 (cons "%t" (format-time-string
13077 (org-time-stamp-format 'long 'inactive)
13078 (current-time)))
13079 (cons "%s" (if org-log-note-state
13080 (concat "\"" org-log-note-state "\"")
13081 "")))))
13082 (if lines (setq note (concat note " \\\\")))
13083 (push note lines))
13084 (when lines
13085 (save-excursion
13086 (set-buffer (marker-buffer org-log-note-marker))
13087 (save-excursion
13088 (goto-char org-log-note-marker)
13089 (move-marker org-log-note-marker nil)
13090 (end-of-line 1)
13091 (if (not (bolp)) (insert "\n")) (indent-relative nil)
13092 (insert " - " (pop lines))
13093 (org-indent-line-function)
13094 (beginning-of-line 1)
13095 (looking-at "[ \t]*")
13096 (setq ind (concat (match-string 0) " "))
13097 (end-of-line 1)
13098 (while lines (insert "\n" ind (pop lines)))))))
13099 (set-window-configuration org-log-note-window-configuration)
13100 (with-current-buffer (marker-buffer org-log-note-return-to)
13101 (goto-char org-log-note-return-to))
13102 (move-marker org-log-note-return-to nil)
13103 (and org-log-post-message (message org-log-post-message)))
13105 (defvar org-occur-highlights nil)
13106 (make-variable-buffer-local 'org-occur-highlights)
13108 (defun org-occur (regexp &optional keep-previous callback)
13109 "Make a compact tree which shows all matches of REGEXP.
13110 The tree will show the lines where the regexp matches, and all higher
13111 headlines above the match. It will also show the heading after the match,
13112 to make sure editing the matching entry is easy.
13113 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13114 call to `org-occur' will be kept, to allow stacking of calls to this
13115 command.
13116 If CALLBACK is non-nil, it is a function which is called to confirm
13117 that the match should indeed be shown."
13118 (interactive "sRegexp: \nP")
13119 (or keep-previous (org-remove-occur-highlights nil nil t))
13120 (let ((cnt 0))
13121 (save-excursion
13122 (goto-char (point-min))
13123 (if (or (not keep-previous) ; do not want to keep
13124 (not org-occur-highlights)) ; no previous matches
13125 ;; hide everything
13126 (org-overview))
13127 (while (re-search-forward regexp nil t)
13128 (when (or (not callback)
13129 (save-match-data (funcall callback)))
13130 (setq cnt (1+ cnt))
13131 (when org-highlight-sparse-tree-matches
13132 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13133 (org-show-context 'occur-tree))))
13134 (when org-remove-highlights-with-change
13135 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13136 nil 'local))
13137 (unless org-sparse-tree-open-archived-trees
13138 (org-hide-archived-subtrees (point-min) (point-max)))
13139 (run-hooks 'org-occur-hook)
13140 (if (interactive-p)
13141 (message "%d match(es) for regexp %s" cnt regexp))
13142 cnt))
13144 (defun org-show-context (&optional key)
13145 "Make sure point and context and visible.
13146 How much context is shown depends upon the variables
13147 `org-show-hierarchy-above', `org-show-following-heading'. and
13148 `org-show-siblings'."
13149 (let ((heading-p (org-on-heading-p t))
13150 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13151 (following-p (org-get-alist-option org-show-following-heading key))
13152 (siblings-p (org-get-alist-option org-show-siblings key)))
13153 (catch 'exit
13154 ;; Show heading or entry text
13155 (if heading-p
13156 (org-flag-heading nil) ; only show the heading
13157 (and (or (org-invisible-p) (org-invisible-p2))
13158 (org-show-hidden-entry))) ; show entire entry
13159 (when following-p
13160 ;; Show next sibling, or heading below text
13161 (save-excursion
13162 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13163 (org-flag-heading nil))))
13164 (when siblings-p (org-show-siblings))
13165 (when hierarchy-p
13166 ;; show all higher headings, possibly with siblings
13167 (save-excursion
13168 (while (and (condition-case nil
13169 (progn (org-up-heading-all 1) t)
13170 (error nil))
13171 (not (bobp)))
13172 (org-flag-heading nil)
13173 (when siblings-p (org-show-siblings))))))))
13175 (defun org-reveal (&optional siblings)
13176 "Show current entry, hierarchy above it, and the following headline.
13177 This can be used to show a consistent set of context around locations
13178 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13179 not t for the search context.
13181 With optional argument SIBLINGS, on each level of the hierarchy all
13182 siblings are shown. This repairs the tree structure to what it would
13183 look like when opened with hierarchical calls to `org-cycle'."
13184 (interactive "P")
13185 (let ((org-show-hierarchy-above t)
13186 (org-show-following-heading t)
13187 (org-show-siblings (if siblings t org-show-siblings)))
13188 (org-show-context nil)))
13190 (defun org-highlight-new-match (beg end)
13191 "Highlight from BEG to END and mark the highlight is an occur headline."
13192 (let ((ov (org-make-overlay beg end)))
13193 (org-overlay-put ov 'face 'secondary-selection)
13194 (push ov org-occur-highlights)))
13196 (defun org-remove-occur-highlights (&optional beg end noremove)
13197 "Remove the occur highlights from the buffer.
13198 BEG and END are ignored. If NOREMOVE is nil, remove this function
13199 from the `before-change-functions' in the current buffer."
13200 (interactive)
13201 (unless org-inhibit-highlight-removal
13202 (mapc 'org-delete-overlay org-occur-highlights)
13203 (setq org-occur-highlights nil)
13204 (unless noremove
13205 (remove-hook 'before-change-functions
13206 'org-remove-occur-highlights 'local))))
13208 ;;;; Priorities
13210 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13211 "Regular expression matching the priority indicator.")
13213 (defvar org-remove-priority-next-time nil)
13215 (defun org-priority-up ()
13216 "Increase the priority of the current item."
13217 (interactive)
13218 (org-priority 'up))
13220 (defun org-priority-down ()
13221 "Decrease the priority of the current item."
13222 (interactive)
13223 (org-priority 'down))
13225 (defun org-priority (&optional action)
13226 "Change the priority of an item by ARG.
13227 ACTION can be `set', `up', `down', or a character."
13228 (interactive)
13229 (setq action (or action 'set))
13230 (let (current new news have remove)
13231 (save-excursion
13232 (org-back-to-heading)
13233 (if (looking-at org-priority-regexp)
13234 (setq current (string-to-char (match-string 2))
13235 have t)
13236 (setq current org-default-priority))
13237 (cond
13238 ((or (eq action 'set) (integerp action))
13239 (if (integerp action)
13240 (setq new action)
13241 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
13242 (setq new (read-char-exclusive)))
13243 (cond ((equal new ?\ ) (setq remove t))
13244 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13245 (error "Priority must be between `%c' and `%c'"
13246 org-highest-priority org-lowest-priority))))
13247 ((eq action 'up)
13248 (setq new (1- current)))
13249 ((eq action 'down)
13250 (setq new (1+ current)))
13251 (t (error "Invalid action")))
13252 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
13253 (setq news (format "%c" new))
13254 (if have
13255 (if remove
13256 (replace-match "" t t nil 1)
13257 (replace-match news t t nil 2))
13258 (if remove
13259 (error "No priority cookie found in line")
13260 (looking-at org-todo-line-regexp)
13261 (if (match-end 2)
13262 (progn
13263 (goto-char (match-end 2))
13264 (insert " [#" news "]"))
13265 (goto-char (match-beginning 3))
13266 (insert "[#" news "] ")))))
13267 (org-preserve-lc (org-set-tags nil 'align))
13268 (if remove
13269 (message "Priority removed")
13270 (message "Priority of current item set to %s" news))))
13273 (defun org-get-priority (s)
13274 "Find priority cookie and return priority."
13275 (save-match-data
13276 (if (not (string-match org-priority-regexp s))
13277 (* 1000 (- org-lowest-priority org-default-priority))
13278 (* 1000 (- org-lowest-priority
13279 (string-to-char (match-string 2 s)))))))
13281 ;;;; Tags
13283 (defun org-scan-tags (action matcher &optional todo-only)
13284 "Scan headline tags with inheritance and produce output ACTION.
13285 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
13286 evaluated, testing if a given set of tags qualifies a headline for
13287 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
13288 are included in the output."
13289 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
13290 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
13291 (org-re
13292 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
13293 (props (list 'face nil
13294 'done-face 'org-done
13295 'undone-face nil
13296 'mouse-face 'highlight
13297 'org-not-done-regexp org-not-done-regexp
13298 'org-todo-regexp org-todo-regexp
13299 'keymap org-agenda-keymap
13300 'help-echo
13301 (format "mouse-2 or RET jump to org file %s"
13302 (abbreviate-file-name buffer-file-name))))
13303 (case-fold-search nil)
13304 lspos
13305 tags tags-list tags-alist (llast 0) rtn level category i txt
13306 todo marker entry priority)
13307 (save-excursion
13308 (goto-char (point-min))
13309 (when (eq action 'sparse-tree) (org-overview))
13310 (while (re-search-forward re nil t)
13311 (catch :skip
13312 (setq todo (if (match-end 1) (match-string 2))
13313 tags (if (match-end 4) (match-string 4)))
13314 (goto-char (setq lspos (1+ (match-beginning 0))))
13315 (setq level (org-reduced-level (funcall outline-level))
13316 category (org-get-category))
13317 (setq i llast llast level)
13318 ;; remove tag lists from same and sublevels
13319 (while (>= i level)
13320 (when (setq entry (assoc i tags-alist))
13321 (setq tags-alist (delete entry tags-alist)))
13322 (setq i (1- i)))
13323 ;; add the nex tags
13324 (when tags
13325 (setq tags (mapcar 'downcase (org-split-string tags ":"))
13326 tags-alist
13327 (cons (cons level tags) tags-alist)))
13328 ;; compile tags for current headline
13329 (setq tags-list
13330 (if org-use-tag-inheritance
13331 (apply 'append (mapcar 'cdr tags-alist))
13332 tags))
13333 (when (and (or (not todo-only) (member todo org-not-done-keywords))
13334 (eval matcher)
13335 (or (not org-agenda-skip-archived-trees)
13336 (not (member org-archive-tag tags-list))))
13337 (and (eq action 'agenda) (org-agenda-skip))
13338 ;; list this headline
13339 (if (eq action 'sparse-tree)
13340 (progn
13341 (org-show-context 'tags-tree))
13342 (setq txt (org-format-agenda-item
13344 (concat
13345 (if org-tags-match-list-sublevels
13346 (make-string (1- level) ?.) "")
13347 (org-get-heading))
13348 category tags-list)
13349 priority (org-get-priority txt))
13350 (goto-char lspos)
13351 (setq marker (org-agenda-new-marker))
13352 (org-add-props txt props
13353 'org-marker marker 'org-hd-marker marker 'org-category category
13354 'priority priority 'type "tagsmatch")
13355 (push txt rtn))
13356 ;; if we are to skip sublevels, jump to end of subtree
13357 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
13358 (when (and (eq action 'sparse-tree)
13359 (not org-sparse-tree-open-archived-trees))
13360 (org-hide-archived-subtrees (point-min) (point-max)))
13361 (nreverse rtn)))
13363 (defvar todo-only) ;; dynamically scoped
13365 (defun org-tags-sparse-tree (&optional todo-only match)
13366 "Create a sparse tree according to tags string MATCH.
13367 MATCH can contain positive and negative selection of tags, like
13368 \"+WORK+URGENT-WITHBOSS\".
13369 If optional argument TODO_ONLY is non-nil, only select lines that are
13370 also TODO lines."
13371 (interactive "P")
13372 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
13374 (defvar org-cached-props nil)
13375 (defun org-cached-entry-get (pom property)
13376 (cdr (assoc property (or org-cached-props
13377 (setq org-cached-props
13378 (org-entry-properties pom))))))
13380 (defun org-global-tags-completion-table (&optional files)
13381 "Return the list of all tags in all agenda buffer/files."
13382 (save-excursion
13383 (org-uniquify
13384 (apply 'append
13385 (mapcar
13386 (lambda (file)
13387 (set-buffer (find-file-noselect file))
13388 (org-get-buffer-tags))
13389 (if (and files (car files))
13390 files
13391 (org-agenda-files)))))))
13393 (defun org-make-tags-matcher (match)
13394 "Create the TAGS//TODO matcher form for the selection string MATCH."
13395 ;; todo-only is scoped dynamically into this function, and the function
13396 ;; may change it it the matcher asksk for it.
13397 (unless match
13398 ;; Get a new match request, with completion
13399 (let ((org-last-tags-completion-table
13400 (org-global-tags-completion-table)))
13401 (setq match (completing-read
13402 "Match: " 'org-tags-completion-function nil nil nil
13403 'org-tags-history))))
13405 ;; Parse the string and create a lisp form
13406 (let ((match0 match)
13407 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13408 minus tag mm
13409 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13410 orterms term orlist re-p level-p prop-p pn pv)
13411 (if (string-match "/+" match)
13412 ;; match contains also a todo-matching request
13413 (progn
13414 (setq tagsmatch (substring match 0 (match-beginning 0))
13415 todomatch (substring match (match-end 0)))
13416 (if (string-match "^!" todomatch)
13417 (setq todo-only t todomatch (substring todomatch 1)))
13418 (if (string-match "^\\s-*$" todomatch)
13419 (setq todomatch nil)))
13420 ;; only matching tags
13421 (setq tagsmatch match todomatch nil))
13423 ;; Make the tags matcher
13424 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13425 (setq tagsmatcher t)
13426 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13427 (while (setq term (pop orterms))
13428 (while (and (equal (substring term -1) "\\") orterms)
13429 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13430 (while (string-match re term)
13431 (setq minus (and (match-end 1)
13432 (equal (match-string 1 term) "-"))
13433 tag (match-string 2 term)
13434 re-p (equal (string-to-char tag) ?{)
13435 level-p (match-end 3)
13436 prop-p (match-end 4)
13437 mm (cond
13438 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13439 (level-p `(= level ,(string-to-number
13440 (match-string 3 term))))
13441 (prop-p
13442 (setq pn (match-string 4 term)
13443 pv (match-string 5 term)
13444 re-p (equal (string-to-char pv) ?{)
13445 pv (substring pv 1 -1))
13446 (if re-p
13447 `(string-match ,pv (org-cached-entry-get nil ,pn))
13448 `(equal ,pv (org-cached-entry-get nil ,pn))))
13449 (t `(member ,(downcase tag) tags-list)))
13450 mm (if minus (list 'not mm) mm)
13451 term (substring term (match-end 0)))
13452 (push mm tagsmatcher))
13453 (push (if (> (length tagsmatcher) 1)
13454 (cons 'and tagsmatcher)
13455 (car tagsmatcher))
13456 orlist)
13457 (setq tagsmatcher nil))
13458 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13459 (setq tagsmatcher
13460 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13462 ;; Make the todo matcher
13463 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13464 (setq todomatcher t)
13465 (setq orterms (org-split-string todomatch "|") orlist nil)
13466 (while (setq term (pop orterms))
13467 (while (string-match re term)
13468 (setq minus (and (match-end 1)
13469 (equal (match-string 1 term) "-"))
13470 kwd (match-string 2 term)
13471 re-p (equal (string-to-char kwd) ?{)
13472 term (substring term (match-end 0))
13473 mm (if re-p
13474 `(string-match ,(substring kwd 1 -1) todo)
13475 (list 'equal 'todo kwd))
13476 mm (if minus (list 'not mm) mm))
13477 (push mm todomatcher))
13478 (push (if (> (length todomatcher) 1)
13479 (cons 'and todomatcher)
13480 (car todomatcher))
13481 orlist)
13482 (setq todomatcher nil))
13483 (setq todomatcher (if (> (length orlist) 1)
13484 (cons 'or orlist) (car orlist))))
13486 ;; Return the string and lisp forms of the matcher
13487 (setq matcher (if todomatcher
13488 (list 'and tagsmatcher todomatcher)
13489 tagsmatcher))
13490 (cons match0 matcher)))
13492 (defun org-match-any-p (re list)
13493 "Does re match any element of list?"
13494 (setq list (mapcar (lambda (x) (string-match re x)) list))
13495 (delq nil list))
13497 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13498 (defvar org-tags-overlay (org-make-overlay 1 1))
13499 (org-detach-overlay org-tags-overlay)
13501 (defun org-align-tags-here (to-col)
13502 ;; Assumes that this is a headline
13503 (let ((pos (point)) (col (current-column)) tags)
13504 (beginning-of-line 1)
13505 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13506 (< pos (match-beginning 2)))
13507 (progn
13508 (setq tags (match-string 2))
13509 (goto-char (match-beginning 1))
13510 (insert " ")
13511 (delete-region (point) (1+ (match-end 0)))
13512 (backward-char 1)
13513 (move-to-column
13514 (max (1+ (current-column))
13515 (1+ col)
13516 (if (> to-col 0)
13517 to-col
13518 (- (abs to-col) (length tags))))
13520 (insert tags)
13521 (move-to-column (min (current-column) col) t))
13522 (goto-char pos))))
13524 (defun org-set-tags (&optional arg just-align)
13525 "Set the tags for the current headline.
13526 With prefix ARG, realign all tags in headings in the current buffer."
13527 (interactive "P")
13528 (let* ((re (concat "^" outline-regexp))
13529 (current (org-get-tags))
13530 (col (current-column))
13531 (org-setting-tags t)
13532 table current-tags inherited-tags ; computed below when needed
13533 tags p0 c0 c1 rpl)
13534 (if arg
13535 (save-excursion
13536 (goto-char (point-min))
13537 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13538 (while (re-search-forward re nil t)
13539 (org-set-tags nil t)
13540 (end-of-line 1)))
13541 (message "All tags realigned to column %d" org-tags-column))
13542 (if just-align
13543 (setq tags current)
13544 ;; Get a new set of tags from the user
13545 (save-excursion
13546 (setq table (or org-tag-alist (org-get-buffer-tags))
13547 org-last-tags-completion-table table
13548 current-tags (org-split-string current ":")
13549 inherited-tags (nreverse
13550 (nthcdr (length current-tags)
13551 (nreverse (org-get-tags-at))))
13552 tags
13553 (if (or (eq t org-use-fast-tag-selection)
13554 (and org-use-fast-tag-selection
13555 (delq nil (mapcar 'cdr table))))
13556 (org-fast-tag-selection current-tags inherited-tags
13557 table org-todo-tag-alist)
13558 (let ((org-add-colon-after-tag-completion t))
13559 (org-trim
13560 (completing-read "Tags: " 'org-tags-completion-function
13561 nil nil current 'org-tags-history))))))
13562 (while (string-match "[-+&]+" tags)
13563 ;; No boolean logic, just a list
13564 (setq tags (replace-match ":" t t tags))))
13566 (if (string-match "\\`[\t ]*\\'" tags)
13567 (setq tags "")
13568 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13569 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13571 ;; Insert new tags at the correct column
13572 (beginning-of-line 1)
13573 (cond
13574 ((and (equal current "") (equal tags "")))
13575 ((re-search-forward
13576 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13577 (point-at-eol) t)
13578 (if (equal tags "")
13579 (setq rpl "")
13580 (goto-char (match-beginning 0))
13581 (setq c0 (current-column) p0 (point)
13582 c1 (max (1+ c0) (if (> org-tags-column 0)
13583 org-tags-column
13584 (- (- org-tags-column) (length tags))))
13585 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13586 (replace-match rpl t t)
13587 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
13588 tags)
13589 (t (error "Tags alignment failed")))
13590 (move-to-column col))))
13592 (defun org-change-tag-in-region (beg end tag off)
13593 "Add or remove TAG for each entry in the region.
13594 This works in the agenda, and also in an org-mode buffer."
13595 (interactive
13596 (list (region-beginning) (region-end)
13597 (let ((org-last-tags-completion-table
13598 (if (org-mode-p)
13599 (org-get-buffer-tags)
13600 (org-global-tags-completion-table))))
13601 (completing-read
13602 "Tag: " 'org-tags-completion-function nil nil nil
13603 'org-tags-history))
13604 (progn
13605 (message "[s]et or [r]emove? ")
13606 (equal (read-char-exclusive) ?r))))
13607 (if (fboundp 'deactivate-mark) (deactivate-mark))
13608 (let ((agendap (equal major-mode 'org-agenda-mode))
13609 l1 l2 m buf pos newhead (cnt 0))
13610 (goto-char end)
13611 (setq l2 (1- (org-current-line)))
13612 (goto-char beg)
13613 (setq l1 (org-current-line))
13614 (loop for l from l1 to l2 do
13615 (goto-line l)
13616 (setq m (get-text-property (point) 'org-hd-marker))
13617 (when (or (and (org-mode-p) (org-on-heading-p))
13618 (and agendap m))
13619 (setq buf (if agendap (marker-buffer m) (current-buffer))
13620 pos (if agendap m (point)))
13621 (with-current-buffer buf
13622 (save-excursion
13623 (save-restriction
13624 (goto-char pos)
13625 (setq cnt (1+ cnt))
13626 (org-toggle-tag tag (if off 'off 'on))
13627 (setq newhead (org-get-heading)))))
13628 (and agendap (org-agenda-change-all-lines newhead m))))
13629 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
13631 (defun org-tags-completion-function (string predicate &optional flag)
13632 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13633 (confirm (lambda (x) (stringp (car x)))))
13634 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
13635 (setq s1 (match-string 1 string)
13636 s2 (match-string 2 string))
13637 (setq s1 "" s2 string))
13638 (cond
13639 ((eq flag nil)
13640 ;; try completion
13641 (setq rtn (try-completion s2 ctable confirm))
13642 (if (stringp rtn)
13643 (setq rtn
13644 (concat s1 s2 (substring rtn (length s2))
13645 (if (and org-add-colon-after-tag-completion
13646 (assoc rtn ctable))
13647 ":" ""))))
13648 rtn)
13649 ((eq flag t)
13650 ;; all-completions
13651 (all-completions s2 ctable confirm)
13653 ((eq flag 'lambda)
13654 ;; exact match?
13655 (assoc s2 ctable)))
13658 (defun org-fast-tag-insert (kwd tags face &optional end)
13659 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
13660 (insert (format "%-12s" (concat kwd ":"))
13661 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13662 (or end "")))
13664 (defun org-fast-tag-show-exit (flag)
13665 (save-excursion
13666 (goto-line 3)
13667 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13668 (replace-match ""))
13669 (when flag
13670 (end-of-line 1)
13671 (move-to-column (- (window-width) 19) t)
13672 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13674 (defun org-set-current-tags-overlay (current prefix)
13675 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13676 (if (featurep 'xemacs)
13677 (org-overlay-display org-tags-overlay (concat prefix s)
13678 'secondary-selection)
13679 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13680 (org-overlay-display org-tags-overlay (concat prefix s)))))
13682 (defun org-fast-tag-selection (current inherited table &optional todo-table)
13683 "Fast tag selection with single keys.
13684 CURRENT is the current list of tags in the headline, INHERITED is the
13685 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13686 possibly with grouping information. TODO-TABLE is a similar table with
13687 TODO keywords, should these have keys assigned to them.
13688 If the keys are nil, a-z are automatically assigned.
13689 Returns the new tags string, or nil to not change the current settings."
13690 (let* ((fulltable (append table todo-table))
13691 (maxlen (apply 'max (mapcar
13692 (lambda (x)
13693 (if (stringp (car x)) (string-width (car x)) 0))
13694 fulltable)))
13695 (buf (current-buffer))
13696 (expert (eq org-fast-tag-selection-single-key 'expert))
13697 (buffer-tags nil)
13698 (fwidth (+ maxlen 3 1 3))
13699 (ncol (/ (- (window-width) 4) fwidth))
13700 (i-face 'org-done)
13701 (c-face 'org-todo)
13702 tg cnt e c char c1 c2 ntable tbl rtn
13703 ov-start ov-end ov-prefix
13704 (exit-after-next org-fast-tag-selection-single-key)
13705 groups ingroup)
13706 (save-excursion
13707 (beginning-of-line 1)
13708 (if (looking-at
13709 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13710 (setq ov-start (match-beginning 1)
13711 ov-end (match-end 1)
13712 ov-prefix "")
13713 (setq ov-start (1- (point-at-eol))
13714 ov-end (1+ ov-start))
13715 (skip-chars-forward "^\n\r")
13716 (setq ov-prefix
13717 (concat
13718 (buffer-substring (1- (point)) (point))
13719 (if (> (current-column) org-tags-column)
13721 (make-string (- org-tags-column (current-column)) ?\ ))))))
13722 (org-move-overlay org-tags-overlay ov-start ov-end)
13723 (save-window-excursion
13724 (if expert
13725 (set-buffer (get-buffer-create " *Org tags*"))
13726 (delete-other-windows)
13727 (split-window-vertically)
13728 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13729 (erase-buffer)
13730 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13731 (org-fast-tag-insert "Current" current c-face "\n\n")
13732 (org-fast-tag-show-exit exit-after-next)
13733 (org-set-current-tags-overlay current ov-prefix)
13734 (setq tbl fulltable char ?a cnt 0)
13735 (while (setq e (pop tbl))
13736 (cond
13737 ((equal e '(:startgroup))
13738 (push '() groups) (setq ingroup t)
13739 (when (not (= cnt 0))
13740 (setq cnt 0)
13741 (insert "\n"))
13742 (insert "{ "))
13743 ((equal e '(:endgroup))
13744 (setq ingroup nil cnt 0)
13745 (insert "}\n"))
13747 (setq tg (car e) c2 nil)
13748 (if (cdr e)
13749 (setq c (cdr e))
13750 ;; automatically assign a character.
13751 (setq c1 (string-to-char
13752 (downcase (substring
13753 tg (if (= (string-to-char tg) ?@) 1 0)))))
13754 (if (or (rassoc c1 ntable) (rassoc c1 table))
13755 (while (or (rassoc char ntable) (rassoc char table))
13756 (setq char (1+ char)))
13757 (setq c2 c1))
13758 (setq c (or c2 char)))
13759 (if ingroup (push tg (car groups)))
13760 (setq tg (org-add-props tg nil 'face
13761 (cond
13762 ((member tg current) c-face)
13763 ((member tg inherited) i-face)
13764 (t nil))))
13765 (if (and (= cnt 0) (not ingroup)) (insert " "))
13766 (insert "[" c "] " tg (make-string
13767 (- fwidth 4 (length tg)) ?\ ))
13768 (push (cons tg c) ntable)
13769 (when (= (setq cnt (1+ cnt)) ncol)
13770 (insert "\n")
13771 (if ingroup (insert " "))
13772 (setq cnt 0)))))
13773 (setq ntable (nreverse ntable))
13774 (insert "\n")
13775 (goto-char (point-min))
13776 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13777 (fit-window-to-buffer))
13778 (setq rtn
13779 (catch 'exit
13780 (while t
13781 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
13782 (if groups " [!] no groups" " [!]groups")
13783 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13784 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13785 (cond
13786 ((= c ?\r) (throw 'exit t))
13787 ((= c ?!)
13788 (setq groups (not groups))
13789 (goto-char (point-min))
13790 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13791 ((= c ?\C-c)
13792 (if (not expert)
13793 (org-fast-tag-show-exit
13794 (setq exit-after-next (not exit-after-next)))
13795 (setq expert nil)
13796 (delete-other-windows)
13797 (split-window-vertically)
13798 (org-switch-to-buffer-other-window " *Org tags*")
13799 (and (fboundp 'fit-window-to-buffer)
13800 (fit-window-to-buffer))))
13801 ((or (= c ?\C-g)
13802 (and (= c ?q) (not (rassoc c ntable))))
13803 (org-detach-overlay org-tags-overlay)
13804 (setq quit-flag t))
13805 ((= c ?\ )
13806 (setq current nil)
13807 (if exit-after-next (setq exit-after-next 'now)))
13808 ((= c ?\t)
13809 (condition-case nil
13810 (setq tg (completing-read
13811 "Tag: "
13812 (or buffer-tags
13813 (with-current-buffer buf
13814 (org-get-buffer-tags)))))
13815 (quit (setq tg "")))
13816 (when (string-match "\\S-" tg)
13817 (add-to-list 'buffer-tags (list tg))
13818 (if (member tg current)
13819 (setq current (delete tg current))
13820 (push tg current)))
13821 (if exit-after-next (setq exit-after-next 'now)))
13822 ((setq e (rassoc c todo-table) tg (car e))
13823 (with-current-buffer buf
13824 (save-excursion (org-todo tg)))
13825 (if exit-after-next (setq exit-after-next 'now)))
13826 ((setq e (rassoc c ntable) tg (car e))
13827 (if (member tg current)
13828 (setq current (delete tg current))
13829 (loop for g in groups do
13830 (if (member tg g)
13831 (mapcar (lambda (x)
13832 (setq current (delete x current)))
13833 g)))
13834 (push tg current))
13835 (if exit-after-next (setq exit-after-next 'now))))
13837 ;; Create a sorted list
13838 (setq current
13839 (sort current
13840 (lambda (a b)
13841 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13842 (if (eq exit-after-next 'now) (throw 'exit t))
13843 (goto-char (point-min))
13844 (beginning-of-line 2)
13845 (delete-region (point) (point-at-eol))
13846 (org-fast-tag-insert "Current" current c-face)
13847 (org-set-current-tags-overlay current ov-prefix)
13848 (while (re-search-forward
13849 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13850 (setq tg (match-string 1))
13851 (add-text-properties (match-beginning 1) (match-end 1)
13852 (list 'face
13853 (cond
13854 ((member tg current) c-face)
13855 ((member tg inherited) i-face)
13856 (t nil)))))
13857 (goto-char (point-min)))))
13858 (org-detach-overlay org-tags-overlay)
13859 (if rtn
13860 (mapconcat 'identity current ":")
13861 nil))))
13863 (defun org-get-tags ()
13864 "Get the TAGS string in the current headline."
13865 (unless (org-on-heading-p t)
13866 (error "Not on a heading"))
13867 (save-excursion
13868 (beginning-of-line 1)
13869 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13870 (org-match-string-no-properties 1)
13871 "")))
13873 (defun org-get-buffer-tags ()
13874 "Get a table of all tags used in the buffer, for completion."
13875 (let (tags)
13876 (save-excursion
13877 (goto-char (point-min))
13878 (while (re-search-forward
13879 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13880 (when (equal (char-after (point-at-bol 0)) ?*)
13881 (mapc (lambda (x) (add-to-list 'tags x))
13882 (org-split-string (org-match-string-no-properties 1) ":")))))
13883 (mapcar 'list tags)))
13886 ;;;; Properties
13888 ;;; Setting and retrieving properties
13890 (defconst org-special-properties
13891 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED"
13892 "CLOCK" "PRIORITY")
13893 "The special properties valid in Org-mode.
13895 These are properties that are not defined in the property drawer,
13896 but in some other way.")
13898 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13899 "Regular expression matching the first line of a property drawer.")
13901 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13902 "Regular expression matching the first line of a property drawer.")
13904 (defun org-property-action ()
13905 "Do an action on properties."
13906 (interactive)
13907 (let (c prop)
13908 (org-at-property-p)
13909 (setq prop (match-string 2))
13910 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
13911 (setq c (read-char-exclusive))
13912 (cond
13913 ((equal c ?s)
13914 (call-interactively 'org-set-property))
13915 ((equal c ?d)
13916 (call-interactively 'org-delete-property))
13917 ((equal c ?D)
13918 (call-interactively 'org-delete-property-globally))
13919 ((equal c ?c)
13920 (call-interactively 'org-compute-property-at-point))
13921 (t (error "No such property action %c" c)))))
13923 (defun org-at-property-p ()
13924 "Is the cursor in a property line?"
13925 ;; FIXME: Does not check if we are actually in the drawer.
13926 ;; FIXME: also returns true on any drawers.....
13927 ;; This is used by C-c C-c for property action.
13928 (save-excursion
13929 (beginning-of-line 1)
13930 (looking-at "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(.*\\)")))
13932 (defmacro org-with-point-at (pom &rest body)
13933 "Move to buffer and point of point-or-marker POM for the duration of BODY."
13934 (declare (indent 1) (debug t))
13935 `(save-excursion
13936 (if (markerp pom) (set-buffer (marker-buffer pom)))
13937 (save-excursion
13938 (goto-char (or pom (point)))
13939 ,@body)))
13941 (defun org-get-property-block (&optional beg end force)
13942 "Return the (beg . end) range of the body of the property drawer.
13943 BEG and END can be beginning and end of subtree, if not given
13944 they will be found.
13945 If the drawer does not exist and FORCE is non-nil, create the drawer."
13946 (catch 'exit
13947 (save-excursion
13948 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13949 (end (or end (progn (outline-next-heading) (point)))))
13950 (goto-char beg)
13951 (if (re-search-forward org-property-start-re end t)
13952 (setq beg (1+ (match-end 0)))
13953 (if force
13954 (save-excursion
13955 (org-insert-property-drawer)
13956 (setq end (progn (outline-next-heading) (point))))
13957 (throw 'exit nil))
13958 (goto-char beg)
13959 (if (re-search-forward org-property-start-re end t)
13960 (setq beg (1+ (match-end 0)))))
13961 (if (re-search-forward org-property-end-re end t)
13962 (setq end (match-beginning 0))
13963 (or force (throw 'exit nil))
13964 (goto-char beg)
13965 (setq end beg)
13966 (org-indent-line-function)
13967 (insert ":END:\n"))
13968 (cons beg end)))))
13970 (defun org-entry-properties (&optional pom which)
13971 "Get all properties of the entry at point-or-marker POM.
13972 This includes the TODO keyword, the tags, time strings for deadline,
13973 scheduled, and clocking, and any additional properties defined in the
13974 entry. The return value is an alist, keys may occur multiple times
13975 if the property key was used several times.
13976 POM may also be nil, in which case the current entry is used.
13977 If WHICH is nil or `all', get all properties. If WHICH is
13978 `special' or `standard', only get that subclass."
13979 (setq which (or which 'all))
13980 (org-with-point-at pom
13981 (let ((clockstr (substring org-clock-string 0 -1))
13982 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
13983 beg end range props sum-props key value)
13984 (save-excursion
13985 (when (condition-case nil (org-back-to-heading t) (error nil))
13986 (setq beg (point))
13987 (setq sum-props (get-text-property (point) 'org-summaries))
13988 (outline-next-heading)
13989 (setq end (point))
13990 (when (memq which '(all special))
13991 ;; Get the special properties, like TODO and tags
13992 (goto-char beg)
13993 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13994 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13995 (when (looking-at org-priority-regexp)
13996 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13997 (when (and (setq value (org-get-tags)) (string-match "\\S-" value))
13998 (push (cons "TAGS" value) props))
13999 (when (setq value (org-get-tags-at))
14000 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14001 props))
14002 (while (re-search-forward org-keyword-time-regexp end t)
14003 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14004 (unless (member key excluded) (push key excluded))
14005 (push (cons key
14006 (if (equal key clockstr)
14007 (org-no-properties
14008 (org-trim
14009 (buffer-substring
14010 (match-beginning 2) (point-at-eol))))
14011 (org-match-string-no-properties 2)))
14012 props)))
14013 (when (memq which '(all standard))
14014 ;; Get the standard properties, like :PORP: ...
14015 (setq range (org-get-property-block beg end))
14016 (when range
14017 (goto-char (car range))
14018 (while (re-search-forward
14019 "^[ \t]*:\\([a-zA-Z][a-zA-Z_0-9]*\\):[ \t]*\\(\\S-.*\\)?"
14020 (cdr range) t)
14021 (setq key (org-match-string-no-properties 1)
14022 value (org-trim (or (org-match-string-no-properties 2) "")))
14023 (unless (member key excluded)
14024 (push (cons key (or value "")) props)))))
14025 (append sum-props (nreverse props)))))))
14027 (defun org-entry-get (pom property &optional inherit)
14028 "Get value of PROPERTY for entry at point-or-marker POM.
14029 If INHERIT is non-nil and the entry does not have the property,
14030 then also check higher levels of the hierarchy.
14031 If the property is present but empty, the return value is the empty string.
14032 If the property is not present at all, nil is returned."
14033 (org-with-point-at pom
14034 (if inherit
14035 (org-entry-get-with-inheritance property)
14036 (if (member property org-special-properties)
14037 ;; We need a special property. Use brute force, get all properties.
14038 (cdr (assoc property (org-entry-properties nil 'special)))
14039 (let ((range (org-get-property-block)))
14040 (if (and range
14041 (goto-char (car range))
14042 (re-search-forward
14043 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14044 (cdr range) t))
14045 ;; Found the property, return it.
14046 (if (match-end 1)
14047 (org-match-string-no-properties 1)
14048 "")))))))
14050 (defun org-entry-delete (pom property)
14051 "Delete the property PROPERTY from entry at point-or-marker POM."
14052 (org-with-point-at pom
14053 (if (member property org-special-properties)
14054 nil ; cannot delete these properties.
14055 (let ((range (org-get-property-block)))
14056 (if (and range
14057 (goto-char (car range))
14058 (re-search-forward
14059 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14060 (cdr range) t))
14061 (progn
14062 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14064 nil)))))
14066 (defvar org-entry-property-inherited-from (make-marker))
14068 (defun org-entry-get-with-inheritance (property)
14069 "Get entry property, and search higher levels if not present."
14070 (let (tmp)
14071 (save-excursion
14072 (catch 'ex
14073 (while t
14074 (when (setq tmp (org-entry-get nil property))
14075 (org-back-to-heading t)
14076 (move-marker org-entry-property-inherited-from (point))
14077 (throw 'ex tmp))
14078 (condition-case nil
14079 (org-up-heading-all 1)
14080 (error (throw 'ex nil))))))
14081 (or tmp (cdr (assoc property org-local-properties))
14082 (cdr (assoc property org-global-properties)))))
14084 (defun org-entry-put (pom property value)
14085 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14086 (org-with-point-at pom
14087 (org-back-to-heading t)
14088 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14089 range)
14090 (cond
14091 ((equal property "TODO")
14092 (when (and (stringp value) (string-match "\\S-" value)
14093 (not (member value org-todo-keywords-1)))
14094 (error "\"%s\" is not a valid TODO state" value))
14095 (if (or (not value)
14096 (not (string-match "\\S-" value)))
14097 (setq value 'none))
14098 (org-todo value)
14099 (org-set-tags nil 'align))
14100 ((equal property "PRIORITY")
14101 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14102 (string-to-char value) ?\ ))
14103 (org-set-tags nil 'align))
14104 ((equal property "SCHEDULED")
14105 (if (re-search-forward org-scheduled-time-regexp end t)
14106 (cond
14107 ((eq value 'earlier) (org-timestamp-change -1 'day))
14108 ((eq value 'later) (org-timestamp-change 1 'day))
14109 (t (call-interactively 'org-schedule)))
14110 (call-interactively 'org-schedule)))
14111 ((equal property "DEADLINE")
14112 (if (re-search-forward org-deadline-time-regexp end t)
14113 (cond
14114 ((eq value 'earlier) (org-timestamp-change -1 'day))
14115 ((eq value 'later) (org-timestamp-change 1 'day))
14116 (t (call-interactively 'org-deadline)))
14117 (call-interactively 'org-deadline)))
14118 ((member property org-special-properties)
14119 (error "The %s property can not yet be set with `org-entry-put'"
14120 property))
14121 (t ; a non-special property
14122 (setq range (org-get-property-block beg end 'force))
14123 (goto-char (car range))
14124 (if (re-search-forward
14125 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
14126 (progn
14127 (delete-region (match-beginning 1) (match-end 1))
14128 (goto-char (match-beginning 1)))
14129 (goto-char (cdr range))
14130 (insert "\n")
14131 (backward-char 1)
14132 (org-indent-line-function)
14133 (insert ":" property ":"))
14134 (and value (insert " " value))
14135 (org-indent-line-function))))))
14137 (defun org-buffer-property-keys (&optional include-specials)
14138 "Get all property keys in the current buffer."
14139 (let (rtn range)
14140 (save-excursion
14141 (save-restriction
14142 (widen)
14143 (goto-char (point-min))
14144 (while (re-search-forward org-property-start-re nil t)
14145 (setq range (org-get-property-block))
14146 (goto-char (car range))
14147 (while (re-search-forward "^[ \t]*:\\([a-zA-Z0-9]+\\):" (cdr range) t)
14148 (add-to-list 'rtn (org-match-string-no-properties 1)))
14149 (outline-next-heading))))
14150 (when include-specials
14151 (setq rtn (append org-special-properties rtn)))
14152 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
14154 (defun org-insert-property-drawer ()
14155 "Insert a property drawer into the current entry."
14156 (interactive)
14157 (org-back-to-heading t)
14158 (let ((beg (point))
14159 (re (concat "^[ \t]*" org-keyword-time-regexp))
14160 end hiddenp)
14161 (outline-next-heading)
14162 (setq end (point))
14163 (goto-char beg)
14164 (while (re-search-forward re end t))
14165 (setq hiddenp (org-invisible-p))
14166 (end-of-line 1)
14167 (and (= (char-after) ?\n) (forward-char 1))
14168 (org-skip-over-state-notes)
14169 (end-of-line 0)
14170 (insert "\n:PROPERTIES:\n:END:")
14171 (beginning-of-line 0)
14172 (org-indent-line-function)
14173 (beginning-of-line 2)
14174 (org-indent-line-function)
14175 (beginning-of-line 0)
14176 (if hiddenp
14177 (save-excursion
14178 (org-back-to-heading t)
14179 (hide-entry))
14180 (org-flag-drawer t))))
14182 (defun org-set-property (property value)
14183 "In the current entry, set PROPERTY to VALUE."
14184 (interactive
14185 (let* ((prop (completing-read "Property: "
14186 (mapcar 'list (org-buffer-property-keys))))
14187 (cur (org-entry-get nil prop))
14188 (allowed (org-property-get-allowed-values nil prop 'table))
14189 (val (if allowed
14190 (completing-read "Value: " allowed nil 'req-match)
14191 (read-string
14192 (concat "Value" (if (and cur (string-match "\\S-" cur))
14193 (concat "[" cur "]") "")
14194 ": ")
14195 "" cur))))
14196 (list prop (if (equal val "") cur val))))
14197 (unless (equal (org-entry-get nil property) value)
14198 (org-entry-put nil property value)))
14200 (defun org-delete-property (property)
14201 "In the current entry, delete PROPERTY."
14202 (interactive
14203 (let* ((prop (completing-read
14204 "Property: " (org-entry-properties nil 'standard))))
14205 (list prop)))
14206 (message (concat "Property " property
14207 (if (org-entry-delete nil property)
14208 " deleted"
14209 " was not present in the entry"))))
14211 (defun org-delete-property-globally (property)
14212 "Remove PROPERTY globally, from all entries."
14213 (interactive
14214 (let* ((prop (completing-read
14215 "Globally remove property: "
14216 (mapcar 'list (org-buffer-property-keys)))))
14217 (list prop)))
14218 (save-excursion
14219 (save-restriction
14220 (widen)
14221 (goto-char (point-min))
14222 (let ((cnt 0))
14223 (while (re-search-forward
14224 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
14225 nil t)
14226 (setq cnt (1+ cnt))
14227 (replace-match ""))
14228 (message "Property \"%s\" removed from %d entries" property cnt)))))
14230 (defvar org-columns-current-fmt-compiled) ; defined below
14232 (defun org-compute-property-at-point ()
14233 "FIXME:"
14234 (interactive)
14235 (unless (org-at-property-p)
14236 (error "Not at a property"))
14237 (let ((prop (org-match-string-no-properties 2)))
14238 (org-columns-get-format-and-top-level)
14239 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
14240 (error "No operator defined for property %s" prop))
14241 (org-columns-compute prop)))
14243 (defun org-property-get-allowed-values (pom property &optional table)
14244 "Get allowed values for the property PROPERTY.
14245 When TABLE is non-nil, return an alist that can directly be used for
14246 completion."
14247 (let (vals)
14248 (cond
14249 ((equal property "TODO")
14250 (setq vals (org-with-point-at pom
14251 (append org-todo-keywords-1 '("")))))
14252 ((equal property "PRIORITY")
14253 (let ((n org-lowest-priority))
14254 (while (>= n org-highest-priority)
14255 (push (char-to-string n) vals)
14256 (setq n (1- n)))))
14257 ((member property org-special-properties))
14259 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
14261 (when (and vals (string-match "\\S-" vals))
14262 (setq vals (car (read-from-string (concat "(" vals ")"))))
14263 (setq vals (mapcar (lambda (x)
14264 (cond ((stringp x) x)
14265 ((numberp x) (number-to-string x))
14266 ((symbolp x) (symbol-name x))
14267 (t "???")))
14268 vals)))))
14269 (if table (mapcar 'list vals) vals)))
14271 (defun org-property-previous-allowed-value (&optional previous)
14272 "Switch to the next allowed value for this property."
14273 (interactive)
14274 (org-property-next-allowed-value t))
14276 (defun org-property-next-allowed-value (&optional previous)
14277 "Switch to the next allowed value for this property."
14278 (interactive)
14279 (unless (org-at-property-p)
14280 (error "Not at a property"))
14281 (let* ((key (match-string 2))
14282 (value (match-string 3))
14283 (allowed (or (org-property-get-allowed-values (point) key)
14284 (and (member value '("[ ]" "[-]" "[X]"))
14285 '("[ ]" "[X]"))))
14286 nval)
14287 (unless allowed
14288 (error "Allowed values for this property have not been defined"))
14289 (if previous (setq allowed (reverse allowed)))
14290 (if (member value allowed)
14291 (setq nval (car (cdr (member value allowed)))))
14292 (setq nval (or nval (car allowed)))
14293 (if (equal nval value)
14294 (error "Only one allowed value for this property"))
14295 (org-at-property-p)
14296 (replace-match (concat " :" key ": " nval) t t)
14297 (org-indent-line-function)
14298 (beginning-of-line 1)
14299 (skip-chars-forward " \t")))
14301 ;;; Column View
14303 (defvar org-columns-overlays nil
14304 "Holds the list of current column overlays.")
14306 (defvar org-columns-current-fmt nil
14307 "Local variable, holds the currently active column format.")
14308 (defvar org-columns-current-fmt-compiled nil
14309 "Local variable, holds the currently active column format.
14310 This is the compiled version of the format.")
14311 (defvar org-columns-current-maxwidths nil
14312 "Loval variable, holds the currently active maximum column widths.")
14313 (defvar org-columns-begin-marker (make-marker)
14314 "Points to the position where last a column creation command was called.")
14315 (defvar org-columns-top-level-marker (make-marker)
14316 "Points to the position where current columns region starts.")
14318 (defvar org-columns-map (make-sparse-keymap)
14319 "The keymap valid in column display.")
14321 (defun org-columns-content ()
14322 "Switch to contents view while in columns view."
14323 (interactive)
14324 (org-overview)
14325 (org-content))
14327 (org-defkey org-columns-map "c" 'org-columns-content)
14328 (org-defkey org-columns-map "o" 'org-overview)
14329 (org-defkey org-columns-map "e" 'org-columns-edit-value)
14330 (org-defkey org-columns-map "v" 'org-columns-show-value)
14331 (org-defkey org-columns-map "q" 'org-columns-quit)
14332 (org-defkey org-columns-map "r" 'org-columns-redo)
14333 (org-defkey org-columns-map [left] 'backward-char)
14334 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
14335 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
14336 (org-defkey org-columns-map [right] 'forward-char)
14337 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
14338 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
14339 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
14340 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
14341 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
14342 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
14343 (org-defkey org-columns-map "<" 'org-columns-narrow)
14344 (org-defkey org-columns-map ">" 'org-columns-widen)
14345 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
14346 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
14347 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
14348 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
14350 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
14351 '("Column"
14352 ["Edit property" org-columns-edit-value t]
14353 ["Next allowed value" org-columns-next-allowed-value t]
14354 ["Previous allowed value" org-columns-previous-allowed-value t]
14355 ["Show full value" org-columns-show-value t]
14356 ["Edit allowed" org-columns-edit-allowed t]
14357 "--"
14358 ["Edit column attributes" org-columns-edit-attributes t]
14359 ["Increase column width" org-columns-widen t]
14360 ["Decrease column width" org-columns-narrow t]
14361 "--"
14362 ["Move column right" org-columns-move-right t]
14363 ["Move column left" org-columns-move-left t]
14364 ["Add column" org-columns-new t]
14365 ["Delete column" org-columns-delete t]
14366 "--"
14367 ["CONTENTS" org-columns-content t]
14368 ["OVERVIEW" org-overview t]
14369 ["Refresh columns display" org-columns-redo t]
14370 "--"
14371 ["Quit" org-columns-quit t]))
14373 (defun org-columns-new-overlay (beg end &optional string face)
14374 "Create a new column overlay and add it to the list."
14375 (let ((ov (org-make-overlay beg end)))
14376 (org-overlay-put ov 'face (or face 'secondary-selection))
14377 (org-overlay-display ov string face)
14378 (push ov org-columns-overlays)
14379 ov))
14381 (defun org-columns-display-here (&optional props)
14382 "Overlay the current line with column display."
14383 (interactive)
14384 (let* ((fmt org-columns-current-fmt-compiled)
14385 (beg (point-at-bol))
14386 (level-face (save-excursion
14387 (beginning-of-line 1)
14388 (looking-at "\\(\\**\\)\\(\\* \\)")
14389 (org-get-level-face 2)))
14390 (color (list :foreground
14391 (face-attribute (or level-face 'default) :foreground)))
14392 props pom property ass width f string ov column)
14393 ;; Check if the entry is in another buffer.
14394 (unless props
14395 (if (eq major-mode 'org-agenda-mode)
14396 (setq pom (or (get-text-property (point) 'org-hd-marker)
14397 (get-text-property (point) 'org-marker))
14398 props (if pom (org-entry-properties pom) nil))
14399 (setq props (org-entry-properties nil))))
14400 ;; Walk the format
14401 (while (setq column (pop fmt))
14402 (setq property (car column)
14403 ass (if (equal property "ITEM")
14404 (cons "ITEM"
14405 (save-match-data
14406 (org-no-properties
14407 (org-remove-tabs
14408 (buffer-substring-no-properties
14409 (point-at-bol) (point-at-eol))))))
14410 (assoc property props))
14411 width (or (cdr (assoc property org-columns-current-maxwidths))
14412 (nth 2 column))
14413 f (format "%%-%d.%ds | " width width)
14414 string (format f (or (cdr ass) "")))
14415 ;; Create the overlay
14416 (org-unmodified
14417 (setq ov (org-columns-new-overlay
14418 beg (setq beg (1+ beg)) string
14419 (list color 'org-column)))
14420 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
14421 (org-overlay-put ov 'keymap org-columns-map)
14422 (org-overlay-put ov 'org-columns-key property)
14423 (org-overlay-put ov 'org-columns-value (cdr ass))
14424 (org-overlay-put ov 'org-columns-pom pom)
14425 (org-overlay-put ov 'org-columns-format f))
14426 (if (or (not (char-after beg))
14427 (equal (char-after beg) ?\n))
14428 (let ((inhibit-read-only t))
14429 (save-excursion
14430 (goto-char beg)
14431 (insert " ")))))
14432 ;; Make the rest of the line disappear.
14433 (org-unmodified
14434 (setq ov (org-columns-new-overlay beg (point-at-eol)))
14435 (org-overlay-put ov 'invisible t)
14436 (org-overlay-put ov 'keymap org-columns-map)
14437 (org-overlay-put ov 'intangible t)
14438 (push ov org-columns-overlays)
14439 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
14440 (org-overlay-put ov 'keymap org-columns-map)
14441 (push ov org-columns-overlays)
14442 (let ((inhibit-read-only t))
14443 (put-text-property (max (point-min) (1- (point-at-bol)))
14444 (min (point-max) (1+ (point-at-eol)))
14445 'read-only "Type `e' to edit property")))))
14447 (defvar org-previous-header-line-format nil
14448 "The header line format before column view was turned on.")
14449 (defvar org-columns-inhibit-recalculation nil
14450 "Inhibit recomputing of columns on column view startup.")
14452 (defvar header-line-format)
14453 (defun org-columns-display-here-title ()
14454 "Overlay the newline before the current line with the table title."
14455 (interactive)
14456 (let ((fmt org-columns-current-fmt-compiled)
14457 string (title "")
14458 property width f column str)
14459 (while (setq column (pop fmt))
14460 (setq property (car column)
14461 str (or (nth 1 column) property)
14462 width (or (cdr (assoc property org-columns-current-maxwidths))
14463 (nth 2 column))
14464 f (format "%%-%d.%ds | " width width)
14465 string (format f str)
14466 title (concat title string)))
14467 (setq title (concat
14468 (org-add-props " " nil 'display '(space :align-to 0))
14469 (org-add-props title nil 'face '(:weight bold :underline t))))
14470 (org-set-local 'org-previous-header-line-format header-line-format)
14471 (setq header-line-format title)))
14473 (defun org-columns-remove-overlays ()
14474 "Remove all currently active column overlays."
14475 (interactive)
14476 (when (marker-buffer org-columns-begin-marker)
14477 (with-current-buffer (marker-buffer org-columns-begin-marker)
14478 (when (local-variable-p 'org-previous-header-line-format)
14479 (setq header-line-format org-previous-header-line-format)
14480 (kill-local-variable 'org-previous-header-line-format))
14481 (move-marker org-columns-begin-marker nil)
14482 (move-marker org-columns-top-level-marker nil)
14483 (org-unmodified
14484 (mapc 'org-delete-overlay org-columns-overlays)
14485 (setq org-columns-overlays nil)
14486 (let ((inhibit-read-only t))
14487 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
14489 (defun org-columns-show-value ()
14490 "Show the full value of the property."
14491 (interactive)
14492 (let ((value (get-char-property (point) 'org-columns-value)))
14493 (message "Value is: %s" (or value ""))))
14495 (defun org-columns-quit ()
14496 "Remove the column overlays and in this way exit column editing."
14497 (interactive)
14498 (org-unmodified
14499 (org-columns-remove-overlays)
14500 (let ((inhibit-read-only t))
14501 ;; FIXME: is this safe???
14502 ;; or are there other reasons why there may be a read-only property????
14503 (remove-text-properties (point-min) (point-max) '(read-only t))))
14504 (when (eq major-mode 'org-agenda-mode)
14505 (message "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
14507 (defun org-columns-edit-value ()
14508 "Edit the value of the property at point in column view.
14509 Where possible, use the standard interface for changing this line."
14510 (interactive)
14511 (let* ((col (current-column))
14512 (key (get-char-property (point) 'org-columns-key))
14513 (value (get-char-property (point) 'org-columns-value))
14514 (bol (point-at-bol)) (eol (point-at-eol))
14515 (pom (or (get-text-property bol 'org-hd-marker)
14516 (point))) ; keep despite of compiler waring
14517 (line-overlays
14518 (delq nil (mapcar (lambda (x)
14519 (and (eq (overlay-buffer x) (current-buffer))
14520 (>= (overlay-start x) bol)
14521 (<= (overlay-start x) eol)
14523 org-columns-overlays)))
14524 nval eval allowed)
14525 (when (equal key "ITEM")
14526 (error "Cannot edit item headline from here"))
14528 (cond
14529 ((equal key "TODO")
14530 (setq eval '(org-with-point-at pom
14531 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14532 ((equal key "PRIORITY")
14533 (setq eval '(org-with-point-at pom
14534 (call-interactively 'org-priority))))
14535 ((equal key "TAGS")
14536 (setq eval '(org-with-point-at pom
14537 (let ((org-fast-tag-selection-single-key
14538 (if (eq org-fast-tag-selection-single-key 'expert)
14539 t org-fast-tag-selection-single-key)))
14540 (call-interactively 'org-set-tags)))))
14541 ((equal key "DEADLINE")
14542 (setq eval '(org-with-point-at pom
14543 (call-interactively 'org-deadline))))
14544 ((equal key "SCHEDULED")
14545 (setq eval '(org-with-point-at pom
14546 (call-interactively 'org-schedule))))
14548 (setq allowed (org-property-get-allowed-values pom key 'table))
14549 (if allowed
14550 (setq nval (completing-read "Value: " allowed nil t))
14551 (setq nval (read-string "Edit: " value)))
14552 (setq nval (org-trim nval))
14553 (when (not (equal nval value))
14554 (setq eval '(org-entry-put pom key nval)))))
14555 (when eval
14556 (let ((inhibit-read-only t))
14557 (remove-text-properties (1- bol) eol '(read-only t))
14558 (unwind-protect
14559 (progn
14560 (setq org-columns-overlays
14561 (org-delete-all line-overlays org-columns-overlays))
14562 (mapc 'org-delete-overlay line-overlays)
14563 (org-columns-eval eval))
14564 (org-columns-display-here))))
14565 (move-to-column col)
14566 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14567 (org-columns-update key))))
14569 (defun org-columns-edit-allowed ()
14570 "Edit the list of allowed values for the current property."
14571 (interactive)
14572 (let* ((col (current-column))
14573 (key (get-char-property (point) 'org-columns-key))
14574 (key1 (concat key "_ALL"))
14575 (value (get-char-property (point) 'org-columns-value))
14576 (allowed (org-entry-get (point) key1 t))
14577 nval)
14578 (setq nval (read-string "Allowed: " allowed))
14579 (org-entry-put
14580 (cond ((marker-position org-entry-property-inherited-from)
14581 org-entry-property-inherited-from)
14582 ((marker-position org-columns-top-level-marker)
14583 org-columns-top-level-marker))
14584 key1 nval)))
14586 (defun org-columns-eval (form)
14587 (let (hidep)
14588 (save-excursion
14589 (beginning-of-line 1)
14590 (next-line 1)
14591 (setq hidep (org-on-heading-p 1)))
14592 (eval form)
14593 (and hidep (hide-entry))))
14595 (defun org-columns-previous-allowed-value ()
14596 "Switch to the previous allowed value for this column."
14597 (interactive)
14598 (org-columns-next-allowed-value t))
14600 (defun org-columns-next-allowed-value (&optional previous)
14601 "Switch to the next allowed value for this column."
14602 (interactive)
14603 (let* ((col (current-column))
14604 (key (get-char-property (point) 'org-columns-key))
14605 (value (get-char-property (point) 'org-columns-value))
14606 (bol (point-at-bol)) (eol (point-at-eol))
14607 (pom (or (get-text-property bol 'org-hd-marker)
14608 (point))) ; keep despite of compiler waring
14609 (line-overlays
14610 (delq nil (mapcar (lambda (x)
14611 (and (eq (overlay-buffer x) (current-buffer))
14612 (>= (overlay-start x) bol)
14613 (<= (overlay-start x) eol)
14615 org-columns-overlays)))
14616 (allowed (or (org-property-get-allowed-values pom key)
14617 (and (equal
14618 (nth 4 (assoc key org-columns-current-fmt-compiled))
14619 'checkbox) '("[ ]" "[X]"))))
14620 nval)
14621 (when (equal key "ITEM")
14622 (error "Cannot edit item headline from here"))
14623 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
14624 (error "Allowed values for this property have not been defined"))
14625 (if (member key '("SCHEDULED" "DEADLINE"))
14626 (setq nval (if previous 'earlier 'later))
14627 (if previous (setq allowed (reverse allowed)))
14628 (if (member value allowed)
14629 (setq nval (car (cdr (member value allowed)))))
14630 (setq nval (or nval (car allowed)))
14631 (if (equal nval value)
14632 (error "Only one allowed value for this property")))
14633 (let ((inhibit-read-only t))
14634 (remove-text-properties (1- bol) eol '(read-only t))
14635 (unwind-protect
14636 (progn
14637 (setq org-columns-overlays
14638 (org-delete-all line-overlays org-columns-overlays))
14639 (mapc 'org-delete-overlay line-overlays)
14640 (org-columns-eval '(org-entry-put pom key nval)))
14641 (org-columns-display-here)))
14642 (move-to-column col)
14643 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14644 (org-columns-update key))))
14646 (defun org-verify-version (task)
14647 (cond
14648 ((eq task 'columns)
14649 (if (or (featurep 'xemacs)
14650 (< emacs-major-version 22))
14651 (error "Emacs 22 is required for the columns feature")))))
14653 (defun org-columns-get-format-and-top-level ()
14654 (let (fmt)
14655 (when (condition-case nil (org-back-to-heading) (error nil))
14656 (move-marker org-entry-property-inherited-from nil)
14657 (setq fmt (org-entry-get nil "COLUMNS" t)))
14658 (setq fmt (or fmt org-columns-default-format))
14659 (org-set-local 'org-columns-current-fmt fmt)
14660 (org-columns-compile-format fmt)
14661 (if (marker-position org-entry-property-inherited-from)
14662 (move-marker org-columns-top-level-marker
14663 org-entry-property-inherited-from)
14664 (move-marker org-columns-top-level-marker (point)))
14665 fmt))
14667 (defun org-columns ()
14668 "Turn on column view on an org-mode file."
14669 (interactive)
14670 (org-verify-version 'columns)
14671 (org-columns-remove-overlays)
14672 (move-marker org-columns-begin-marker (point))
14673 (let (beg end fmt cache maxwidths)
14674 (setq fmt (org-columns-get-format-and-top-level))
14675 (save-excursion
14676 (goto-char org-columns-top-level-marker)
14677 (setq beg (point))
14678 (unless org-columns-inhibit-recalculation
14679 (org-columns-compute-all))
14680 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
14681 (point-max)))
14682 (goto-char beg)
14683 ;; Get and cache the properties
14684 (while (re-search-forward (concat "^" outline-regexp) end t)
14685 (push (cons (org-current-line) (org-entry-properties)) cache))
14686 (when cache
14687 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14688 (org-set-local 'org-columns-current-maxwidths maxwidths)
14689 (org-columns-display-here-title)
14690 (mapc (lambda (x)
14691 (goto-line (car x))
14692 (org-columns-display-here (cdr x)))
14693 cache)))))
14695 (defun org-columns-new (&optional prop title width op fmt)
14696 "Insert a new column, to the leeft o the current column."
14697 (interactive)
14698 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
14699 cell)
14700 (setq prop (completing-read
14701 "Property: " (mapcar 'list (org-buffer-property-keys t))
14702 nil nil prop))
14703 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
14704 (setq width (read-string "Column width: " (if width (number-to-string width))))
14705 (if (string-match "\\S-" width)
14706 (setq width (string-to-number width))
14707 (setq width nil))
14708 (setq fmt (completing-read "Summary [none]: "
14709 '(("none") ("add_numbers") ("add_times") ("checkbox"))
14710 nil t))
14711 (if (string-match "\\S-" fmt)
14712 (setq fmt (intern fmt))
14713 (setq fmt nil))
14714 (if (eq fmt 'none) (setq fmt nil))
14715 (if editp
14716 (progn
14717 (setcar editp prop)
14718 (setcdr editp (list title width nil fmt)))
14719 (setq cell (nthcdr (1- (current-column))
14720 org-columns-current-fmt-compiled))
14721 (setcdr cell (cons (list prop title width nil fmt)
14722 (cdr cell))))
14723 (org-columns-store-format)
14724 (org-columns-redo)))
14726 (defun org-columns-delete ()
14727 "Delete the column at point from columns view."
14728 (interactive)
14729 (let* ((n (current-column))
14730 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
14731 (when (y-or-n-p
14732 (format "Are you sure you want to remove column \"%s\"? " title))
14733 (setq org-columns-current-fmt-compiled
14734 (delq (nth n org-columns-current-fmt-compiled)
14735 org-columns-current-fmt-compiled))
14736 (org-columns-store-format)
14737 (org-columns-redo)
14738 (if (>= (current-column) (length org-columns-current-fmt-compiled))
14739 (backward-char 1)))))
14741 (defun org-columns-edit-attributes ()
14742 "Edit the attributes of the current column."
14743 (interactive)
14744 (let* ((n (current-column))
14745 (info (nth n org-columns-current-fmt-compiled)))
14746 (apply 'org-columns-new info)))
14748 (defun org-columns-widen (arg)
14749 "Make the column wider by ARG characters."
14750 (interactive "p")
14751 (let* ((n (current-column))
14752 (entry (nth n org-columns-current-fmt-compiled))
14753 (width (or (nth 2 entry)
14754 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
14755 (setq width (max 1 (+ width arg)))
14756 (setcar (nthcdr 2 entry) width)
14757 (org-columns-store-format)
14758 (org-columns-redo)))
14760 (defun org-columns-narrow (arg)
14761 "Make the column nrrower by ARG characters."
14762 (interactive "p")
14763 (org-columns-widen (- arg)))
14765 (defun org-columns-move-right ()
14766 "Swap this column with the one to the right."
14767 (interactive)
14768 (let* ((n (current-column))
14769 (cell (nthcdr n org-columns-current-fmt-compiled))
14771 (when (>= n (1- (length org-columns-current-fmt-compiled)))
14772 (error "Cannot shift this column further to the right"))
14773 (setq e (car cell))
14774 (setcar cell (car (cdr cell)))
14775 (setcdr cell (cons e (cdr (cdr cell))))
14776 (org-columns-store-format)
14777 (org-columns-redo)
14778 (forward-char 1)))
14780 (defun org-columns-move-left ()
14781 "Swap this column with the one to the left."
14782 (interactive)
14783 (let* ((n (current-column)))
14784 (when (= n 0)
14785 (error "Cannot shift this column further to the left"))
14786 (backward-char 1)
14787 (org-columns-move-right)
14788 (backward-char 1)))
14790 (defun org-columns-store-format ()
14791 "Store the text version of the current columns format in appropriate place.
14792 This is either in the COLUMNS property of the node starting the current column
14793 display, or in the #+COLUMNS line of the current buffer."
14794 (let (fmt)
14795 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
14796 (if (marker-position org-columns-top-level-marker)
14797 (save-excursion
14798 (goto-char org-columns-top-level-marker)
14799 (if (org-entry-get nil "COLUMNS")
14800 (org-entry-put nil "COLUMNS" fmt)
14801 (goto-char (point-min))
14802 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
14803 (replace-match (concat "#+COLUMNS: " fmt t t)))))
14804 (setq org-columns-current-fmt fmt))))
14806 (defvar org-overriding-columns-format nil
14807 "When set, overrides any other definition.")
14808 (defvar org-agenda-view-columns-initially nil
14809 "When set, switch to columns view immediately after creating the agenda.")
14811 (defun org-agenda-columns ()
14812 "Turn on column view in the agenda."
14813 (interactive)
14814 (org-verify-version 'columns)
14815 (org-columns-remove-overlays)
14816 (move-marker org-columns-begin-marker (point))
14817 (let (fmt cache maxwidths m)
14818 (cond
14819 ((and (local-variable-p 'org-overriding-columns-format)
14820 org-overriding-columns-format)
14821 (setq fmt org-overriding-columns-format))
14822 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
14823 (setq fmt (org-entry-get m "COLUMNS" t)))
14824 ((and (boundp 'org-columns-current-fmt)
14825 (local-variable-p 'org-columns-current-fmt)
14826 org-columns-current-fmt)
14827 (setq fmt org-columns-current-fmt))
14828 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
14829 (setq m (get-text-property m 'org-hd-marker))
14830 (setq fmt (org-entry-get m "COLUMNS" t))))
14831 (setq fmt (or fmt org-columns-default-format))
14832 (org-set-local 'org-columns-current-fmt fmt)
14833 (org-columns-compile-format fmt)
14834 (save-excursion
14835 ;; Get and cache the properties
14836 (goto-char (point-min))
14837 (while (not (eobp))
14838 (when (setq m (or (get-text-property (point) 'org-hd-marker)
14839 (get-text-property (point) 'org-marker)))
14840 (push (cons (org-current-line) (org-entry-properties m)) cache))
14841 (beginning-of-line 2))
14842 (when cache
14843 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14844 (org-set-local 'org-columns-current-maxwidths maxwidths)
14845 (org-columns-display-here-title)
14846 (mapc (lambda (x)
14847 (goto-line (car x))
14848 (org-columns-display-here (cdr x)))
14849 cache)))))
14851 (defun org-columns-get-autowidth-alist (s cache)
14852 "Derive the maximum column widths from the format and the cache."
14853 (let ((start 0) rtn)
14854 (while (string-match "%\\([a-zA-Z]\\S-*\\)" s start)
14855 (push (cons (match-string 1 s) 1) rtn)
14856 (setq start (match-end 0)))
14857 (mapc (lambda (x)
14858 (setcdr x (apply 'max
14859 (mapcar
14860 (lambda (y)
14861 (length (or (cdr (assoc (car x) (cdr y))) " ")))
14862 cache))))
14863 rtn)
14864 rtn))
14866 (defun org-columns-compute-all ()
14867 "Compute all columns that have operators defined."
14868 (org-unmodified
14869 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
14870 (let ((columns org-columns-current-fmt-compiled) col)
14871 (while (setq col (pop columns))
14872 (when (nth 3 col)
14873 (save-excursion
14874 (org-columns-compute (car col)))))))
14876 (defun org-columns-update (property)
14877 "Recompute PROPERTY, and update the columns display for it."
14878 (org-columns-compute property)
14879 (let (fmt val pos)
14880 (save-excursion
14881 (mapc (lambda (ov)
14882 (when (equal (org-overlay-get ov 'org-columns-key) property)
14883 (setq pos (org-overlay-start ov))
14884 (goto-char pos)
14885 (when (setq val (cdr (assoc property
14886 (get-text-property (point-at-bol) 'org-summaries))))
14887 (setq fmt (org-overlay-get ov 'org-columns-format))
14888 (org-overlay-put ov 'display (format fmt val)))))
14889 org-columns-overlays))))
14891 (defun org-columns-compute (property)
14892 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
14893 (interactive)
14894 (let* ((re (concat "^" outline-regexp))
14895 (lmax 30) ; Does anyone use deeper levels???
14896 (lsum (make-vector lmax 0))
14897 (level 0)
14898 (ass (assoc property org-columns-current-fmt-compiled))
14899 (format (nth 4 ass))
14900 (beg org-columns-top-level-marker)
14901 last-level val end sumpos sum-alist sum str)
14902 (save-excursion
14903 ;; Find the region to compute
14904 (goto-char beg)
14905 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
14906 (goto-char end)
14907 ;; Walk the tree from the back and do the computations
14908 (while (re-search-backward re beg t)
14909 (setq sumpos (match-beginning 0)
14910 last-level level
14911 level (org-outline-level)
14912 val (org-entry-get nil property))
14913 (cond
14914 ((< level last-level)
14915 ;; put the sum of lower levels here as a property
14916 (setq sum (aref lsum last-level)
14917 str (org-column-number-to-string sum format)
14918 sum-alist (get-text-property sumpos 'org-summaries))
14919 (if (assoc property sum-alist)
14920 (setcdr (assoc property sum-alist) str)
14921 (push (cons property str) sum-alist)
14922 (org-unmodified
14923 (add-text-properties sumpos (1+ sumpos)
14924 (list 'org-summaries sum-alist))))
14925 (when val ;?????????????????????????????????? and force?????
14926 (org-entry-put nil property str))
14927 ;; add current to current level accumulator
14928 (aset lsum level (+ (aref lsum level) sum))
14929 ;; clear accumulators for deeper levels
14930 (loop for l from (1+ level) to (1- lmax) do (aset lsum l 0)))
14931 ((>= level last-level)
14932 ;; add what we have here to the accumulator for this level
14933 (aset lsum level (+ (aref lsum level)
14934 (org-column-string-to-number (or val "0") format))))
14935 (t (error "This should not happen")))))))
14937 (defun org-columns-redo ()
14938 "Construct the column display again."
14939 (interactive)
14940 (message "Recomputing columns...")
14941 (save-excursion
14942 (if (marker-position org-columns-begin-marker)
14943 (goto-char org-columns-begin-marker))
14944 (org-columns-remove-overlays)
14945 (if (org-mode-p)
14946 (call-interactively 'org-columns)
14947 (call-interactively 'org-agenda-columns)))
14948 (message "Recomputing columns...done"))
14950 (defun org-columns-not-in-agenda ()
14951 (if (eq major-mode 'org-agenda-mode)
14952 (error "This command is only allowed in Org-mode buffers")))
14955 (defun org-string-to-number (s)
14956 "Convert string to number, and interpret hh:mm:ss."
14957 (if (not (string-match ":" s))
14958 (string-to-number s)
14959 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14960 (while l
14961 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14962 sum)))
14964 (defun org-column-number-to-string (n fmt)
14965 "Convert a computed column number to a string value, according to FMT."
14966 (cond
14967 ((eq fmt 'add_times)
14968 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
14969 (format "%d:%02d" h m)))
14970 ((eq fmt 'checkbox)
14971 (cond ((= n (floor n)) "[X]")
14972 ((> n 1.) "[-]")
14973 (t "[ ]")))
14974 (t (number-to-string n))))
14976 (defun org-column-string-to-number (s fmt)
14977 "Convert a column value to a number that can be used for column computing."
14978 (cond
14979 ((string-match ":" s)
14980 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14981 (while l
14982 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14983 sum))
14984 ((eq fmt 'checkbox)
14985 (if (equal s "[X]") 1. 0.000001))
14986 (t (string-to-number s))))
14988 (defun org-columns-uncompile-format (cfmt)
14989 "Turn the compiled columns format back into a string representation."
14990 (let ((rtn "") e s prop title op width fmt)
14991 (while (setq e (pop cfmt))
14992 (setq prop (car e)
14993 title (nth 1 e)
14994 width (nth 2 e)
14995 op (nth 3 e)
14996 fmt (nth 4 e))
14997 (cond
14998 ((eq fmt 'add_times) (setq op ":"))
14999 ((eq fmt 'checkbox) (setq op "X"))
15000 ((eq fmt 'add_numbers) (setq op "+")))
15001 (if (equal title prop) (setq title nil))
15002 (setq s (concat "%" (if width (number-to-string width))
15003 prop
15004 (if title (concat "(" title ")"))
15005 (if op (concat "{" op "}"))))
15006 (setq rtn (concat rtn " " s)))
15007 (org-trim rtn)))
15009 (defun org-columns-compile-format (fmt)
15010 "FIXME"
15011 (let ((start 0) width prop title op f)
15012 (setq org-columns-current-fmt-compiled nil)
15013 (while (string-match "%\\([0-9]+\\)?\\([a-zA-Z_0-9]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*"
15014 fmt start)
15015 (setq start (match-end 0)
15016 width (match-string 1 fmt)
15017 prop (match-string 2 fmt)
15018 title (or (match-string 3 fmt) prop)
15019 op (match-string 4 fmt)
15020 f nil)
15021 (if width (setq width (string-to-number width)))
15022 (cond
15023 ((equal op "+") (setq f 'add_numbers))
15024 ((equal op ":") (setq f 'add_times))
15025 ((equal op "X") (setq f 'checkbox)))
15026 (push (list prop title width op f) org-columns-current-fmt-compiled))
15027 (setq org-columns-current-fmt-compiled
15028 (nreverse org-columns-current-fmt-compiled))))
15030 ;;;; Timestamps
15032 (defvar org-last-changed-timestamp nil)
15033 (defvar org-time-was-given) ; dynamically scoped parameter
15034 (defvar org-end-time-was-given) ; dynamically scoped parameter
15035 (defvar org-ts-what) ; dynamically scoped parameter
15037 (defun org-time-stamp (arg)
15038 "Prompt for a date/time and insert a time stamp.
15039 If the user specifies a time like HH:MM, or if this command is called
15040 with a prefix argument, the time stamp will contain date and time.
15041 Otherwise, only the date will be included. All parts of a date not
15042 specified by the user will be filled in from the current date/time.
15043 So if you press just return without typing anything, the time stamp
15044 will represent the current date/time. If there is already a timestamp
15045 at the cursor, it will be modified."
15046 (interactive "P")
15047 (let (org-time-was-given org-end-time-was-given time)
15048 (cond
15049 ((and (org-at-timestamp-p)
15050 (eq last-command 'org-time-stamp)
15051 (eq this-command 'org-time-stamp))
15052 (insert "--")
15053 (setq time (let ((this-command this-command))
15054 (org-read-date arg 'totime)))
15055 (org-insert-time-stamp time (or org-time-was-given arg)))
15056 ((org-at-timestamp-p)
15057 (setq time (let ((this-command this-command))
15058 (org-read-date arg 'totime)))
15059 (when (org-at-timestamp-p) ; just to get the match data
15060 (replace-match "")
15061 (setq org-last-changed-timestamp
15062 (org-insert-time-stamp
15063 time (or org-time-was-given arg)
15064 nil nil nil (list org-end-time-was-given))))
15065 (message "Timestamp updated"))
15067 (setq time (let ((this-command this-command))
15068 (org-read-date arg 'totime)))
15069 (org-insert-time-stamp time (or org-time-was-given arg)
15070 nil nil nil (list org-end-time-was-given))))))
15072 (defun org-time-stamp-inactive (&optional arg)
15073 "Insert an inactive time stamp.
15074 An inactive time stamp is enclosed in square brackets instead of angle
15075 brackets. It is inactive in the sense that it does not trigger agenda entries,
15076 does not link to the calendar and cannot be changed with the S-cursor keys.
15077 So these are more for recording a certain time/date."
15078 (interactive "P")
15079 (let (org-time-was-given org-end-time-was-given time)
15080 (setq time (org-read-date arg 'totime))
15081 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
15082 nil nil (list org-end-time-was-given))))
15084 (defvar org-date-ovl (org-make-overlay 1 1))
15085 (org-overlay-put org-date-ovl 'face 'org-warning)
15086 (org-detach-overlay org-date-ovl)
15088 (defvar org-ans1) ; dynamically scoped parameter
15089 (defvar org-ans2) ; dynamically scoped parameter
15091 (defvar org-plain-time-of-day-regexp) ; defined below
15092 (defun org-read-date (&optional with-time to-time from-string prompt)
15093 "Read a date and make things smooth for the user.
15094 The prompt will suggest to enter an ISO date, but you can also enter anything
15095 which will at least partially be understood by `parse-time-string'.
15096 Unrecognized parts of the date will default to the current day, month, year,
15097 hour and minute. For example,
15098 3-2-5 --> 2003-02-05
15099 feb 15 --> currentyear-02-15
15100 sep 12 9 --> 2009-09-12
15101 12:45 --> today 12:45
15102 22 sept 0:34 --> currentyear-09-22 0:34
15103 12 --> currentyear-currentmonth-12
15104 Fri --> nearest Friday (today or later)
15105 +4 --> four days from today (only if +N is the only thing given)
15106 etc.
15107 The function understands only English month and weekday abbreviations,
15108 but this can be configured with the variables `parse-time-months' and
15109 `parse-time-weekdays'.
15111 While prompting, a calendar is popped up - you can also select the
15112 date with the mouse (button 1). The calendar shows a period of three
15113 months. To scroll it to other months, use the keys `>' and `<'.
15114 If you don't like the calendar, turn it off with
15115 \(setq org-popup-calendar-for-date-prompt nil)
15117 With optional argument TO-TIME, the date will immediately be converted
15118 to an internal time.
15119 With an optional argument WITH-TIME, the prompt will suggest to also
15120 insert a time. Note that when WITH-TIME is not set, you can still
15121 enter a time, and this function will inform the calling routine about
15122 this change. The calling routine may then choose to change the format
15123 used to insert the time stamp into the buffer to include the time."
15124 (require 'parse-time)
15125 (let* ((org-time-stamp-rounding-minutes
15126 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
15127 (ct (org-current-time))
15128 (default-time
15129 ;; Default time is either today, or, when entering a range,
15130 ;; the range start.
15131 (if (save-excursion
15132 (re-search-backward
15133 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
15134 (- (point) 20) t))
15135 (apply
15136 'encode-time
15137 (mapcar (lambda(x) (or x 0))
15138 (parse-time-string (match-string 1))))
15139 ct))
15140 (calendar-move-hook nil)
15141 (view-diary-entries-initially nil)
15142 (view-calendar-holidays-initially nil)
15143 (timestr (format-time-string
15144 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
15145 (prompt (concat (if prompt (concat prompt " ") "")
15146 (format "Date and/or time (default [%s]): " timestr)))
15147 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
15148 second minute hour day month year tl wday wday1 pm)
15150 (cond
15151 (from-string (setq ans from-string))
15152 (org-popup-calendar-for-date-prompt
15153 (save-excursion
15154 (save-window-excursion
15155 (calendar)
15156 (calendar-forward-day (- (time-to-days default-time)
15157 (calendar-absolute-from-gregorian
15158 (calendar-current-date))))
15159 (org-eval-in-calendar nil t)
15160 (let* ((old-map (current-local-map))
15161 (map (copy-keymap calendar-mode-map))
15162 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
15163 (org-defkey map (kbd "RET") 'org-calendar-select)
15164 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
15165 'org-calendar-select-mouse)
15166 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
15167 'org-calendar-select-mouse)
15168 (org-defkey minibuffer-local-map [(meta shift left)]
15169 (lambda () (interactive)
15170 (org-eval-in-calendar '(calendar-backward-month 1))))
15171 (org-defkey minibuffer-local-map [(meta shift right)]
15172 (lambda () (interactive)
15173 (org-eval-in-calendar '(calendar-forward-month 1))))
15174 (org-defkey minibuffer-local-map [(shift up)]
15175 (lambda () (interactive)
15176 (org-eval-in-calendar '(calendar-backward-week 1))))
15177 (org-defkey minibuffer-local-map [(shift down)]
15178 (lambda () (interactive)
15179 (org-eval-in-calendar '(calendar-forward-week 1))))
15180 (org-defkey minibuffer-local-map [(shift left)]
15181 (lambda () (interactive)
15182 (org-eval-in-calendar '(calendar-backward-day 1))))
15183 (org-defkey minibuffer-local-map [(shift right)]
15184 (lambda () (interactive)
15185 (org-eval-in-calendar '(calendar-forward-day 1))))
15186 (org-defkey minibuffer-local-map ">"
15187 (lambda () (interactive)
15188 (org-eval-in-calendar '(scroll-calendar-left 1))))
15189 (org-defkey minibuffer-local-map "<"
15190 (lambda () (interactive)
15191 (org-eval-in-calendar '(scroll-calendar-right 1))))
15192 (unwind-protect
15193 (progn
15194 (use-local-map map)
15195 (setq org-ans0 (read-string prompt "" nil nil))
15196 ;; org-ans0: from prompt
15197 ;; org-ans1: from mouse click
15198 ;; org-ans2: from calendar motion
15199 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
15200 (use-local-map old-map))))))
15201 (t ; Naked prompt only
15202 (setq ans (read-string prompt "" nil timestr))))
15203 (org-detach-overlay org-date-ovl)
15205 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
15206 (setq deltadays (string-to-number ans) ans ""))
15208 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
15209 (when (string-match
15210 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
15211 (setq year (if (match-end 2)
15212 (string-to-number (match-string 2 ans))
15213 (string-to-number (format-time-string "%Y")))
15214 month (string-to-number (match-string 3 ans))
15215 day (string-to-number (match-string 4 ans)))
15216 (if (< year 100) (setq year (+ 2000 year)))
15217 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
15218 t nil ans)))
15219 ;; Help matching am/pm times, because `parse-time-string' does not do that.
15220 ;; If there is a time with am/pm, and *no* time without it, we convert
15221 ;; so that matching will be successful.
15222 ;; FIXME: make this replace twice, so that we catch the end time.
15223 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
15224 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
15225 (setq hour (string-to-number (match-string 1 ans))
15226 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
15227 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
15228 (if (and (= hour 12) (not pm))
15229 (setq hour 0)
15230 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
15231 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
15233 ;; Check if there is a time range
15234 (when (and (boundp 'org-end-time-was-given)
15235 (string-match org-plain-time-of-day-regexp ans)
15236 (match-end 8))
15237 (setq org-end-time-was-given (match-string 8 ans))
15238 (setq ans (concat (substring ans 0 (match-beginning 7))
15239 (substring ans (match-end 7)))))
15241 (setq tl (parse-time-string ans)
15242 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
15243 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
15244 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
15245 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
15246 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
15247 second (or (nth 0 tl) 0)
15248 wday (nth 6 tl))
15249 (setq day (+ day deltadays))
15250 (when (and wday (not (nth 3 tl)))
15251 ;; Weekday was given, but no day, so pick that day in the week
15252 ;; on or after the derived date.
15253 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
15254 (unless (equal wday wday1)
15255 (setq day (+ day (% (- wday wday1 -7) 7)))))
15256 (if (and (boundp 'org-time-was-given)
15257 (nth 2 tl))
15258 (setq org-time-was-given t))
15259 (if (< year 100) (setq year (+ 2000 year)))
15260 (if to-time
15261 (encode-time second minute hour day month year)
15262 (if (or (nth 1 tl) (nth 2 tl))
15263 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
15264 (format "%04d-%02d-%02d" year month day)))))
15266 (defun org-eval-in-calendar (form &optional keepdate)
15267 "Eval FORM in the calendar window and return to current window.
15268 Also, store the cursor date in variable org-ans2."
15269 (let ((sw (selected-window)))
15270 (select-window (get-buffer-window "*Calendar*"))
15271 (eval form)
15272 (when (and (not keepdate) (calendar-cursor-to-date))
15273 (let* ((date (calendar-cursor-to-date))
15274 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15275 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
15276 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
15277 (select-window sw)
15278 ;; Update the prompt to show new default date
15279 (save-excursion
15280 (goto-char (point-min))
15281 (when (and org-ans2
15282 (re-search-forward "\\[[-0-9]+\\]" nil t)
15283 (get-text-property (match-end 0) 'field))
15284 (let ((inhibit-read-only t))
15285 (replace-match (concat "[" org-ans2 "]") t t)
15286 (add-text-properties (point-min) (1+ (match-end 0))
15287 (text-properties-at (1+ (point-min)))))))))
15289 (defun org-calendar-select ()
15290 "Return to `org-read-date' with the date currently selected.
15291 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15292 (interactive)
15293 (when (calendar-cursor-to-date)
15294 (let* ((date (calendar-cursor-to-date))
15295 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15296 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15297 (if (active-minibuffer-window) (exit-minibuffer))))
15299 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
15300 "Insert a date stamp for the date given by the internal TIME.
15301 WITH-HM means, use the stamp format that includes the time of the day.
15302 INACTIVE means use square brackets instead of angular ones, so that the
15303 stamp will not contribute to the agenda.
15304 PRE and POST are optional strings to be inserted before and after the
15305 stamp.
15306 The command returns the inserted time stamp."
15307 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
15308 stamp)
15309 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
15310 (insert (or pre ""))
15311 (insert (setq stamp (format-time-string fmt time)))
15312 (when (listp extra)
15313 (setq extra (car extra))
15314 (if (and (stringp extra)
15315 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
15316 (setq extra (format "-%02d:%02d"
15317 (string-to-number (match-string 1 extra))
15318 (string-to-number (match-string 2 extra))))
15319 (setq extra nil)))
15320 (when extra
15321 (backward-char 1)
15322 (insert extra)
15323 (forward-char 1))
15324 (insert (or post ""))
15325 stamp))
15327 (defun org-toggle-time-stamp-overlays ()
15328 "Toggle the use of custom time stamp formats."
15329 (interactive)
15330 (setq org-display-custom-times (not org-display-custom-times))
15331 (unless org-display-custom-times
15332 (let ((p (point-min)) (bmp (buffer-modified-p)))
15333 (while (setq p (next-single-property-change p 'display))
15334 (if (and (get-text-property p 'display)
15335 (eq (get-text-property p 'face) 'org-date))
15336 (remove-text-properties
15337 p (setq p (next-single-property-change p 'display))
15338 '(display t))))
15339 (set-buffer-modified-p bmp)))
15340 (if (featurep 'xemacs)
15341 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
15342 (org-restart-font-lock)
15343 (setq org-table-may-need-update t)
15344 (if org-display-custom-times
15345 (message "Time stamps are overlayed with custom format")
15346 (message "Time stamp overlays removed")))
15348 (defun org-display-custom-time (beg end)
15349 "Overlay modified time stamp format over timestamp between BED and END."
15350 (let* ((ts (buffer-substring beg end))
15351 t1 w1 with-hm tf time str w2 (off 0))
15352 (save-match-data
15353 (setq t1 (org-parse-time-string ts t))
15354 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
15355 (setq off (- (match-end 0) (match-beginning 0)))))
15356 (setq end (- end off))
15357 (setq w1 (- end beg)
15358 with-hm (and (nth 1 t1) (nth 2 t1))
15359 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
15360 time (org-fix-decoded-time t1)
15361 str (org-add-props
15362 (format-time-string
15363 (substring tf 1 -1) (apply 'encode-time time))
15364 nil 'mouse-face 'highlight)
15365 w2 (length str))
15366 (if (not (= w2 w1))
15367 (add-text-properties (1+ beg) (+ 2 beg)
15368 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
15369 (if (featurep 'xemacs)
15370 (progn
15371 (put-text-property beg end 'invisible t)
15372 (put-text-property beg end 'end-glyph (make-glyph str)))
15373 (put-text-property beg end 'display str))))
15375 (defun org-translate-time (string)
15376 "Translate all timestamps in STRING to custom format.
15377 But do this only if the variable `org-display-custom-times' is set."
15378 (when org-display-custom-times
15379 (save-match-data
15380 (let* ((start 0)
15381 (re org-ts-regexp-both)
15382 t1 with-hm inactive tf time str beg end)
15383 (while (setq start (string-match re string start))
15384 (setq beg (match-beginning 0)
15385 end (match-end 0)
15386 t1 (save-match-data
15387 (org-parse-time-string (substring string beg end) t))
15388 with-hm (and (nth 1 t1) (nth 2 t1))
15389 inactive (equal (substring string beg (1+ beg)) "[")
15390 tf (funcall (if with-hm 'cdr 'car)
15391 org-time-stamp-custom-formats)
15392 time (org-fix-decoded-time t1)
15393 str (format-time-string
15394 (concat
15395 (if inactive "[" "<") (substring tf 1 -1)
15396 (if inactive "]" ">"))
15397 (apply 'encode-time time))
15398 string (replace-match str t t string)
15399 start (+ start (length str)))))))
15400 string)
15402 (defun org-fix-decoded-time (time)
15403 "Set 0 instead of nil for the first 6 elements of time.
15404 Don't touch the rest."
15405 (let ((n 0))
15406 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
15408 (defun org-days-to-time (timestamp-string)
15409 "Difference between TIMESTAMP-STRING and now in days."
15410 (- (time-to-days (org-time-string-to-time timestamp-string))
15411 (time-to-days (current-time))))
15413 (defun org-deadline-close (timestamp-string &optional ndays)
15414 "Is the time in TIMESTAMP-STRING close to the current date?"
15415 (and (< (org-days-to-time timestamp-string)
15416 (or ndays org-deadline-warning-days))
15417 (not (org-entry-is-done-p))))
15419 (defun org-calendar-select-mouse (ev)
15420 "Return to `org-read-date' with the date currently selected.
15421 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
15422 (interactive "e")
15423 (mouse-set-point ev)
15424 (when (calendar-cursor-to-date)
15425 (let* ((date (calendar-cursor-to-date))
15426 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15427 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
15428 (if (active-minibuffer-window) (exit-minibuffer))))
15430 (defun org-check-deadlines (ndays)
15431 "Check if there are any deadlines due or past due.
15432 A deadline is considered due if it happens within `org-deadline-warning-days'
15433 days from today's date. If the deadline appears in an entry marked DONE,
15434 it is not shown. The prefix arg NDAYS can be used to test that many
15435 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
15436 (interactive "P")
15437 (let* ((org-warn-days
15438 (cond
15439 ((equal ndays '(4)) 100000)
15440 (ndays (prefix-numeric-value ndays))
15441 (t org-deadline-warning-days)))
15442 (case-fold-search nil)
15443 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
15444 (callback
15445 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
15447 (message "%d deadlines past-due or due within %d days"
15448 (org-occur regexp nil callback)
15449 org-warn-days)))
15451 (defun org-evaluate-time-range (&optional to-buffer)
15452 "Evaluate a time range by computing the difference between start and end.
15453 Normally the result is just printed in the echo area, but with prefix arg
15454 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
15455 If the time range is actually in a table, the result is inserted into the
15456 next column.
15457 For time difference computation, a year is assumed to be exactly 365
15458 days in order to avoid rounding problems."
15459 (interactive "P")
15461 (org-clock-update-time-maybe)
15462 (save-excursion
15463 (unless (org-at-date-range-p)
15464 (goto-char (point-at-bol))
15465 (re-search-forward org-tr-regexp (point-at-eol) t))
15466 (if (not (org-at-date-range-p))
15467 (error "Not at a time-stamp range, and none found in current line")))
15468 (let* ((ts1 (match-string 1))
15469 (ts2 (match-string 2))
15470 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
15471 (match-end (match-end 0))
15472 (time1 (org-time-string-to-time ts1))
15473 (time2 (org-time-string-to-time ts2))
15474 (t1 (time-to-seconds time1))
15475 (t2 (time-to-seconds time2))
15476 (diff (abs (- t2 t1)))
15477 (negative (< (- t2 t1) 0))
15478 ;; (ys (floor (* 365 24 60 60)))
15479 (ds (* 24 60 60))
15480 (hs (* 60 60))
15481 (fy "%dy %dd %02d:%02d")
15482 (fy1 "%dy %dd")
15483 (fd "%dd %02d:%02d")
15484 (fd1 "%dd")
15485 (fh "%02d:%02d")
15486 y d h m align)
15487 (if havetime
15488 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15490 d (floor (/ diff ds)) diff (mod diff ds)
15491 h (floor (/ diff hs)) diff (mod diff hs)
15492 m (floor (/ diff 60)))
15493 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
15495 d (floor (+ (/ diff ds) 0.5))
15496 h 0 m 0))
15497 (if (not to-buffer)
15498 (message (org-make-tdiff-string y d h m))
15499 (when (org-at-table-p)
15500 (goto-char match-end)
15501 (setq align t)
15502 (and (looking-at " *|") (goto-char (match-end 0))))
15503 (if (looking-at
15504 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
15505 (replace-match ""))
15506 (if negative (insert " -"))
15507 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
15508 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
15509 (insert " " (format fh h m))))
15510 (if align (org-table-align))
15511 (message "Time difference inserted")))))
15513 (defun org-make-tdiff-string (y d h m)
15514 (let ((fmt "")
15515 (l nil))
15516 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
15517 l (push y l)))
15518 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
15519 l (push d l)))
15520 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15521 l (push h l)))
15522 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15523 l (push m l)))
15524 (apply 'format fmt (nreverse l))))
15526 (defun org-time-string-to-time (s)
15527 (apply 'encode-time (org-parse-time-string s)))
15529 (defun org-time-string-to-absolute (s &optional daynr)
15530 "Convert a time stamp to an absolute day number.
15531 If there is a specifyer for a cyclic time stamp, get the closest date to
15532 DAYNR."
15533 (cond
15534 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15535 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15536 daynr
15537 (+ daynr 1000)))
15538 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15539 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15540 (time-to-days (current-time))) (match-string 0 s)))
15541 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15543 (defun org-calendar-holiday ()
15544 "List of holidays, for Diary display in Org-mode."
15545 (let ((hl (check-calendar-holidays date)))
15546 (if hl (mapconcat 'identity hl "; "))))
15548 (defun org-diary-sexp-entry (sexp entry date)
15549 "Process a SEXP diary ENTRY for DATE."
15550 (require 'diary-lib)
15551 (let ((result (if calendar-debug-sexp
15552 (let ((stack-trace-on-error t))
15553 (eval (car (read-from-string sexp))))
15554 (condition-case nil
15555 (eval (car (read-from-string sexp)))
15556 (error
15557 (beep)
15558 (message "Bad sexp at line %d in %s: %s"
15559 (org-current-line)
15560 (buffer-file-name) sexp)
15561 (sleep-for 2))))))
15562 (cond ((stringp result) result)
15563 ((and (consp result)
15564 (stringp (cdr result))) (cdr result))
15565 (result entry)
15566 (t nil))))
15568 (defun org-diary-to-ical-string (frombuf)
15569 "FIXME"
15570 (let* ((tmpdir (if (featurep 'xemacs)
15571 (temp-directory)
15572 temporary-file-directory))
15573 (tmpfile (make-temp-name
15574 (expand-file-name "orgics" tmpdir)))
15575 buf rtn b e)
15576 (save-excursion
15577 (set-buffer frombuf)
15578 (icalendar-export-region (point-min) (point-max) tmpfile)
15579 (setq buf (find-buffer-visiting tmpfile))
15580 (set-buffer buf)
15581 (goto-char (point-min))
15582 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15583 (setq b (match-beginning 0)))
15584 (goto-char (point-max))
15585 (if (re-search-backward "^END:VEVENT" nil t)
15586 (setq e (match-end 0)))
15587 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15588 (kill-buffer buf)
15589 (kill-buffer frombuf)
15590 (delete-file tmpfile)
15591 rtn))
15593 (defun org-closest-date (start current change)
15594 "Find the date closest to CURRENT that is consistent with START and CHANGE."
15595 ;; Make the proper lists from the dates
15596 (catch 'exit
15597 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15598 dn dw sday cday n1 n2
15599 d m y y1 y2 date1 date2 nmonths nm ny m2)
15601 (setq start (org-date-to-gregorian start)
15602 current (org-date-to-gregorian
15603 (if org-agenda-repeating-timestamp-show-all
15604 current
15605 (time-to-days (current-time))))
15606 sday (calendar-absolute-from-gregorian start)
15607 cday (calendar-absolute-from-gregorian current))
15609 (if (<= cday sday) (throw 'exit sday))
15611 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15612 (setq dn (string-to-number (match-string 1 change))
15613 dw (cdr (assoc (match-string 2 change) a1)))
15614 (error "Invalid change specifyer: %s" change))
15615 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15616 (cond
15617 ((eq dw 'day)
15618 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15619 n2 (+ n1 dn)))
15620 ((eq dw 'year)
15621 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15622 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15623 (setq date1 (list m d y1)
15624 n1 (calendar-absolute-from-gregorian date1)
15625 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15626 n2 (calendar-absolute-from-gregorian date2)))
15627 ((eq dw 'month)
15628 ;; approx number of month between the tow dates
15629 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15630 ;; How often does dn fit in there?
15631 (setq d (nth 1 start) m (car start) y (nth 2 start)
15632 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15633 m (+ m nm)
15634 ny (floor (/ m 12))
15635 y (+ y ny)
15636 m (- m (* ny 12)))
15637 (while (> m 12) (setq m (- m 12) y (1+ y)))
15638 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15639 (setq m2 (+ m dn) y2 y)
15640 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15641 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15642 (while (< n2 cday)
15643 (setq n1 n2 m m2 y y2)
15644 (setq m2 (+ m dn) y2 y)
15645 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15646 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15648 (if org-agenda-repeating-timestamp-show-all
15649 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
15650 (if (= cday n1) n1 n2)))))
15652 (defun org-date-to-gregorian (date)
15653 "Turn any specification of DATE into a gregorian date for the calendar."
15654 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15655 ((and (listp date) (= (length date) 3)) date)
15656 ((stringp date)
15657 (setq date (org-parse-time-string date))
15658 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15659 ((listp date)
15660 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15662 (defun org-parse-time-string (s &optional nodefault)
15663 "Parse the standard Org-mode time string.
15664 This should be a lot faster than the normal `parse-time-string'.
15665 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15666 hour and minute fields will be nil if not given."
15667 (if (string-match org-ts-regexp0 s)
15668 (list 0
15669 (if (or (match-beginning 8) (not nodefault))
15670 (string-to-number (or (match-string 8 s) "0")))
15671 (if (or (match-beginning 7) (not nodefault))
15672 (string-to-number (or (match-string 7 s) "0")))
15673 (string-to-number (match-string 4 s))
15674 (string-to-number (match-string 3 s))
15675 (string-to-number (match-string 2 s))
15676 nil nil nil)
15677 (make-list 9 0)))
15679 (defun org-timestamp-up (&optional arg)
15680 "Increase the date item at the cursor by one.
15681 If the cursor is on the year, change the year. If it is on the month or
15682 the day, change that.
15683 With prefix ARG, change by that many units."
15684 (interactive "p")
15685 (org-timestamp-change (prefix-numeric-value arg)))
15687 (defun org-timestamp-down (&optional arg)
15688 "Decrease the date item at the cursor by one.
15689 If the cursor is on the year, change the year. If it is on the month or
15690 the day, change that.
15691 With prefix ARG, change by that many units."
15692 (interactive "p")
15693 (org-timestamp-change (- (prefix-numeric-value arg))))
15695 (defun org-timestamp-up-day (&optional arg)
15696 "Increase the date in the time stamp by one day.
15697 With prefix ARG, change that many days."
15698 (interactive "p")
15699 (if (and (not (org-at-timestamp-p t))
15700 (org-on-heading-p))
15701 (org-todo 'up)
15702 (org-timestamp-change (prefix-numeric-value arg) 'day)))
15704 (defun org-timestamp-down-day (&optional arg)
15705 "Decrease the date in the time stamp by one day.
15706 With prefix ARG, change that many days."
15707 (interactive "p")
15708 (if (and (not (org-at-timestamp-p t))
15709 (org-on-heading-p))
15710 (org-todo 'down)
15711 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
15713 (defsubst org-pos-in-match-range (pos n)
15714 (and (match-beginning n)
15715 (<= (match-beginning n) pos)
15716 (>= (match-end n) pos)))
15718 (defun org-at-timestamp-p (&optional inactive-ok)
15719 "Determine if the cursor is in or at a timestamp."
15720 (interactive)
15721 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15722 (pos (point))
15723 (ans (or (looking-at tsr)
15724 (save-excursion
15725 (skip-chars-backward "^[<\n\r\t")
15726 (if (> (point) 1) (backward-char 1))
15727 (and (looking-at tsr)
15728 (> (- (match-end 0) pos) -1))))))
15729 (and (boundp 'org-ts-what)
15730 (setq org-ts-what
15731 (cond
15732 ((org-pos-in-match-range pos 2) 'year)
15733 ((org-pos-in-match-range pos 3) 'month)
15734 ((org-pos-in-match-range pos 7) 'hour)
15735 ((org-pos-in-match-range pos 8) 'minute)
15736 ((or (org-pos-in-match-range pos 4)
15737 (org-pos-in-match-range pos 5)) 'day)
15738 ((and (> pos (or (match-end 8) (match-end 5)))
15739 (< pos (match-end 0)))
15740 (- pos (or (match-end 8) (match-end 5))))
15741 (t 'day))))
15742 ans))
15744 (defun org-timestamp-change (n &optional what)
15745 "Change the date in the time stamp at point.
15746 The date will be changed by N times WHAT. WHAT can be `day', `month',
15747 `year', `minute', `second'. If WHAT is not given, the cursor position
15748 in the timestamp determines what will be changed."
15749 (let ((pos (point))
15750 with-hm inactive
15751 org-ts-what
15752 extra
15753 ts time time0)
15754 (if (not (org-at-timestamp-p t))
15755 (error "Not at a timestamp"))
15756 (if (and (not what) (not (eq org-ts-what 'day))
15757 org-display-custom-times
15758 (get-text-property (point) 'display)
15759 (not (get-text-property (1- (point)) 'display)))
15760 (setq org-ts-what 'day))
15761 (setq org-ts-what (or what org-ts-what)
15762 inactive (= (char-after (match-beginning 0)) ?\[)
15763 ts (match-string 0))
15764 (replace-match "")
15765 (if (string-match
15766 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
15768 (setq extra (match-string 1 ts)))
15769 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15770 (setq with-hm t))
15771 (setq time0 (org-parse-time-string ts))
15772 (setq time
15773 (apply 'encode-time
15774 (append
15775 (list (or (car time0) 0))
15776 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
15777 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
15778 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
15779 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
15780 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
15781 (nthcdr 6 time0))))
15782 (when (integerp org-ts-what)
15783 (setq extra (org-modify-ts-extra extra org-ts-what n)))
15784 (if (eq what 'calendar)
15785 (let ((cal-date
15786 (save-excursion
15787 (save-match-data
15788 (set-buffer "*Calendar*")
15789 (calendar-cursor-to-date)))))
15790 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15791 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15792 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15793 (setcar time0 (or (car time0) 0))
15794 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15795 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
15796 (setq time (apply 'encode-time time0))))
15797 (setq org-last-changed-timestamp
15798 (org-insert-time-stamp time with-hm inactive nil nil extra))
15799 (org-clock-update-time-maybe)
15800 (goto-char pos)
15801 ;; Try to recenter the calendar window, if any
15802 (if (and org-calendar-follow-timestamp-change
15803 (get-buffer-window "*Calendar*" t)
15804 (memq org-ts-what '(day month year)))
15805 (org-recenter-calendar (time-to-days time)))))
15807 (defun org-modify-ts-extra (s pos n)
15808 "FIXME"
15809 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15810 ng h m new)
15811 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15812 (cond
15813 ((or (org-pos-in-match-range pos 2)
15814 (org-pos-in-match-range pos 3))
15815 (setq m (string-to-number (match-string 3 s))
15816 h (string-to-number (match-string 2 s)))
15817 (if (org-pos-in-match-range pos 2)
15818 (setq h (+ h n))
15819 (setq m (+ m n)))
15820 (if (< m 0) (setq m (+ m 60) h (1- h)))
15821 (if (> m 59) (setq m (- m 60) h (1+ h)))
15822 (setq h (min 24 (max 0 h)))
15823 (setq ng 1 new (format "-%02d:%02d" h m)))
15824 ((org-pos-in-match-range pos 6)
15825 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15826 ((org-pos-in-match-range pos 5)
15827 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
15829 (when ng
15830 (setq s (concat
15831 (substring s 0 (match-beginning ng))
15833 (substring s (match-end ng))))))
15836 (defun org-recenter-calendar (date)
15837 "If the calendar is visible, recenter it to DATE."
15838 (let* ((win (selected-window))
15839 (cwin (get-buffer-window "*Calendar*" t))
15840 (calendar-move-hook nil))
15841 (when cwin
15842 (select-window cwin)
15843 (calendar-goto-date (if (listp date) date
15844 (calendar-gregorian-from-absolute date)))
15845 (select-window win))))
15847 (defun org-goto-calendar (&optional arg)
15848 "Go to the Emacs calendar at the current date.
15849 If there is a time stamp in the current line, go to that date.
15850 A prefix ARG can be used to force the current date."
15851 (interactive "P")
15852 (let ((tsr org-ts-regexp) diff
15853 (calendar-move-hook nil)
15854 (view-calendar-holidays-initially nil)
15855 (view-diary-entries-initially nil))
15856 (if (or (org-at-timestamp-p)
15857 (save-excursion
15858 (beginning-of-line 1)
15859 (looking-at (concat ".*" tsr))))
15860 (let ((d1 (time-to-days (current-time)))
15861 (d2 (time-to-days
15862 (org-time-string-to-time (match-string 1)))))
15863 (setq diff (- d2 d1))))
15864 (calendar)
15865 (calendar-goto-today)
15866 (if (and diff (not arg)) (calendar-forward-day diff))))
15868 (defun org-date-from-calendar ()
15869 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15870 If there is already a time stamp at the cursor position, update it."
15871 (interactive)
15872 (org-timestamp-change 0 'calendar))
15874 ;;; The clock for measuring work time.
15876 (defvar org-mode-line-string "")
15877 (put 'org-mode-line-string 'risky-local-variable t)
15879 (defvar org-mode-line-timer nil)
15880 (defvar org-clock-heading "")
15881 (defvar org-clock-start-time "")
15883 (defun org-update-mode-line ()
15884 (let* ((delta (- (time-to-seconds (current-time))
15885 (time-to-seconds org-clock-start-time)))
15886 (h (floor delta 3600))
15887 (m (floor (- delta (* 3600 h)) 60)))
15888 (setq org-mode-line-string
15889 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
15890 'help-echo "Org-mode clock is running"))
15891 (force-mode-line-update)))
15893 (defvar org-clock-marker (make-marker)
15894 "Marker recording the last clock-in.")
15895 (defvar org-clock-mode-line-entry nil
15896 "Information for the modeline about the running clock.")
15898 (defun org-clock-in ()
15899 "Start the clock on the current item.
15900 If necessary, clock-out of the currently active clock."
15901 (interactive)
15902 (org-clock-out t)
15903 (let (ts)
15904 (save-excursion
15905 (org-back-to-heading t)
15906 (if (looking-at org-todo-line-regexp)
15907 (setq org-clock-heading (match-string 3))
15908 (setq org-clock-heading "???"))
15909 (setq org-clock-heading (propertize org-clock-heading 'face nil))
15910 (beginning-of-line 2)
15911 (while
15912 (or (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15913 (not (equal (match-string 1) org-clock-string)))
15914 (and (looking-at "[ \t]*:PROPERTIES:")
15915 (not org-insert-labeled-timestamps-before-properties-drawer)))
15916 ;; Scheduling info, or properties drawer, move one line further
15917 (beginning-of-line 2)
15918 (or (bolp) (newline)))
15919 (insert "\n") (backward-char 1)
15920 (indent-relative)
15921 (insert org-clock-string " ")
15922 (setq org-clock-start-time (current-time))
15923 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15924 (move-marker org-clock-marker (point) (buffer-base-buffer))
15925 (or global-mode-string (setq global-mode-string '("")))
15926 (or (memq 'org-mode-line-string global-mode-string)
15927 (setq global-mode-string
15928 (append global-mode-string '(org-mode-line-string))))
15929 (org-update-mode-line)
15930 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
15931 (message "Clock started at %s" ts))))
15933 (defun org-clock-out (&optional fail-quietly)
15934 "Stop the currently running clock.
15935 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
15936 (interactive)
15937 (catch 'exit
15938 (if (not (marker-buffer org-clock-marker))
15939 (if fail-quietly (throw 'exit t) (error "No active clock")))
15940 (let (ts te s h m)
15941 (save-excursion
15942 (set-buffer (marker-buffer org-clock-marker))
15943 (goto-char org-clock-marker)
15944 (beginning-of-line 1)
15945 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15946 (equal (match-string 1) org-clock-string))
15947 (setq ts (match-string 2))
15948 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
15949 (goto-char (match-end 0))
15950 (delete-region (point) (point-at-eol))
15951 (insert "--")
15952 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15953 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
15954 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
15955 h (floor (/ s 3600))
15956 s (- s (* 3600 h))
15957 m (floor (/ s 60))
15958 s (- s (* 60 s)))
15959 (insert " => " (format "%2d:%02d" h m))
15960 (move-marker org-clock-marker nil)
15961 (org-add-log-maybe 'clock-out)
15962 (when org-mode-line-timer
15963 (cancel-timer org-mode-line-timer)
15964 (setq org-mode-line-timer nil))
15965 (setq global-mode-string
15966 (delq 'org-mode-line-string global-mode-string))
15967 (force-mode-line-update)
15968 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
15970 (defun org-clock-cancel ()
15971 "Cancel the running clock be removing the start timestamp."
15972 (interactive)
15973 (if (not (marker-buffer org-clock-marker))
15974 (error "No active clock"))
15975 (save-excursion
15976 (set-buffer (marker-buffer org-clock-marker))
15977 (goto-char org-clock-marker)
15978 (delete-region (1- (point-at-bol)) (point-at-eol)))
15979 (message "Clock canceled"))
15981 (defvar org-clock-file-total-minutes nil
15982 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
15983 (make-variable-buffer-local 'org-clock-file-total-minutes)
15985 (defun org-clock-sum (&optional tstart tend)
15986 "Sum the times for each subtree.
15987 Puts the resulting times in minutes as a text property on each headline."
15988 (interactive)
15989 (let* ((bmp (buffer-modified-p))
15990 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
15991 org-clock-string
15992 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
15993 (lmax 30)
15994 (ltimes (make-vector lmax 0))
15995 (t1 0)
15996 (level 0)
15997 ts te dt
15998 time)
15999 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
16000 (save-excursion
16001 (goto-char (point-max))
16002 (while (re-search-backward re nil t)
16003 (cond
16004 ((match-end 2)
16005 ;; Two time stamps
16006 (setq ts (match-string 2)
16007 te (match-string 3)
16008 ts (time-to-seconds
16009 (apply 'encode-time (org-parse-time-string ts)))
16010 te (time-to-seconds
16011 (apply 'encode-time (org-parse-time-string te)))
16012 ts (if tstart (max ts tstart) ts)
16013 te (if tend (min te tend) te)
16014 dt (- te ts)
16015 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
16016 ((match-end 4)
16017 ;; A naket time
16018 (setq t1 (+ t1 (string-to-number (match-string 5))
16019 (* 60 (string-to-number (match-string 4))))))
16020 (t ;; A headline
16021 (setq level (- (match-end 1) (match-beginning 1)))
16022 (when (or (> t1 0) (> (aref ltimes level) 0))
16023 (loop for l from 0 to level do
16024 (aset ltimes l (+ (aref ltimes l) t1)))
16025 (setq t1 0 time (aref ltimes level))
16026 (loop for l from level to (1- lmax) do
16027 (aset ltimes l 0))
16028 (goto-char (match-beginning 0))
16029 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
16030 (setq org-clock-file-total-minutes (aref ltimes 0)))
16031 (set-buffer-modified-p bmp)))
16033 (defun org-clock-display (&optional total-only)
16034 "Show subtree times in the entire buffer.
16035 If TOTAL-ONLY is non-nil, only show the total time for the entire file
16036 in the echo area."
16037 (interactive)
16038 (org-remove-clock-overlays)
16039 (let (time h m p)
16040 (org-clock-sum)
16041 (unless total-only
16042 (save-excursion
16043 (goto-char (point-min))
16044 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16045 (goto-char p)
16046 (when (setq time (get-text-property p :org-clock-minutes))
16047 (org-put-clock-overlay time (funcall outline-level))))
16048 (setq h (/ org-clock-file-total-minutes 60)
16049 m (- org-clock-file-total-minutes (* 60 h)))
16050 ;; Arrange to remove the overlays upon next change.
16051 (when org-remove-highlights-with-change
16052 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
16053 nil 'local))))
16054 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
16056 (defvar org-clock-overlays nil)
16057 (make-variable-buffer-local 'org-clock-overlays)
16059 (defun org-put-clock-overlay (time &optional level)
16060 "Put an overlays on the current line, displaying TIME.
16061 If LEVEL is given, prefix time with a corresponding number of stars.
16062 This creates a new overlay and stores it in `org-clock-overlays', so that it
16063 will be easy to remove."
16064 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
16065 (l (if level (org-get-legal-level level 0) 0))
16066 (off 0)
16067 ov tx)
16068 (move-to-column c)
16069 (unless (eolp) (skip-chars-backward "^ \t"))
16070 (skip-chars-backward " \t")
16071 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
16072 tx (concat (buffer-substring (1- (point)) (point))
16073 (make-string (+ off (max 0 (- c (current-column)))) ?.)
16074 (org-add-props (format "%s %2d:%02d%s"
16075 (make-string l ?*) h m
16076 (make-string (- 10 l) ?\ ))
16077 '(face secondary-selection))
16078 ""))
16079 (if (not (featurep 'xemacs))
16080 (org-overlay-put ov 'display tx)
16081 (org-overlay-put ov 'invisible t)
16082 (org-overlay-put ov 'end-glyph (make-glyph tx)))
16083 (push ov org-clock-overlays)))
16085 (defun org-remove-clock-overlays (&optional beg end noremove)
16086 "Remove the occur highlights from the buffer.
16087 BEG and END are ignored. If NOREMOVE is nil, remove this function
16088 from the `before-change-functions' in the current buffer."
16089 (interactive)
16090 (unless org-inhibit-highlight-removal
16091 (mapc 'org-delete-overlay org-clock-overlays)
16092 (setq org-clock-overlays nil)
16093 (unless noremove
16094 (remove-hook 'before-change-functions
16095 'org-remove-clock-overlays 'local))))
16097 (defun org-clock-out-if-current ()
16098 "Clock out if the current entry contains the running clock.
16099 This is used to stop the clock after a TODO entry is marked DONE,
16100 and is only done if the variable `org-clock-out-when-done' is not nil."
16101 (when (and org-clock-out-when-done
16102 (member state org-done-keywords)
16103 (equal (marker-buffer org-clock-marker) (current-buffer))
16104 (< (point) org-clock-marker)
16105 (> (save-excursion (outline-next-heading) (point))
16106 org-clock-marker))
16107 ;; Clock out, but don't accept a logging message for this.
16108 (let ((org-log-done (if (and (listp org-log-done)
16109 (member 'clock-out org-log-done))
16110 '(done)
16111 org-log-done)))
16112 (org-clock-out))))
16114 (add-hook 'org-after-todo-state-change-hook
16115 'org-clock-out-if-current)
16117 (defun org-check-running-clock ()
16118 "Check if the current buffer contains the running clock.
16119 If yes, offer to stop it and to save the buffer with the changes."
16120 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
16121 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
16122 (buffer-name))))
16123 (org-clock-out)
16124 (when (y-or-n-p "Save changed buffer?")
16125 (save-buffer))))
16127 (defun org-clock-report ()
16128 "Create a table containing a report about clocked time.
16129 If the buffer contains lines
16130 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
16132 #+END: clocktable
16133 then the table will be inserted between these lines, replacing whatever
16134 is was there before. If these lines are not in the buffer, the table
16135 is inserted at point, surrounded by the special lines.
16136 The BEGIN line can contain parameters. Allowed are:
16137 :maxlevel The maximum level to be included in the table. Default is 3.
16138 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
16139 (interactive)
16140 (org-remove-clock-overlays)
16141 (unless (org-find-dblock "clocktable")
16142 (org-create-dblock (list :name "clocktable"
16143 :maxlevel 2 :emphasize nil)))
16144 (org-update-dblock))
16146 (defun org-clock-update-time-maybe ()
16147 "If this is a CLOCK line, update it and return t.
16148 Otherwise, return nil."
16149 (interactive)
16150 (save-excursion
16151 (beginning-of-line 1)
16152 (skip-chars-forward " \t")
16153 (when (looking-at org-clock-string)
16154 (let ((re (concat "[ \t]*" org-clock-string
16155 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
16156 "\\([ \t]*=>.*\\)?"))
16157 ts te h m s)
16158 (if (not (looking-at re))
16160 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
16161 (end-of-line 1)
16162 (setq ts (match-string 1)
16163 te (match-string 2))
16164 (setq s (- (time-to-seconds
16165 (apply 'encode-time (org-parse-time-string te)))
16166 (time-to-seconds
16167 (apply 'encode-time (org-parse-time-string ts))))
16168 h (floor (/ s 3600))
16169 s (- s (* 3600 h))
16170 m (floor (/ s 60))
16171 s (- s (* 60 s)))
16172 (insert " => " (format "%2d:%02d" h m))
16173 t)))))
16175 (defun org-clock-special-range (key &optional time as-strings)
16176 "Return two times bordering a special time range.
16177 Key is a symbol specifying the range and can be one of `today', `yesterday',
16178 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
16179 A week starts Monday 0:00 and ends Sunday 24:00.
16180 The range is determined relative to TIME. TIME defaults to the current time.
16181 The return value is a cons cell with two internal times like the ones
16182 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
16183 the returned times will be formatted strings."
16184 (let* ((tm (decode-time (or time (current-time))))
16185 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
16186 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
16187 (dow (nth 6 tm))
16188 s1 m1 h1 d1 month1 y1 diff ts te fm)
16189 (cond
16190 ((eq key 'today)
16191 (setq h 0 m 0 h1 24 m1 0))
16192 ((eq key 'yesterday)
16193 (setq d (1- d) h 0 m 0 h1 24 m1 0))
16194 ((eq key 'thisweek)
16195 (setq diff (if (= dow 0) 6 (1- dow))
16196 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16197 ((eq key 'lastweek)
16198 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
16199 m 0 h 0 d (- d diff) d1 (+ 7 d)))
16200 ((eq key 'thismonth)
16201 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
16202 ((eq key 'lastmonth)
16203 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
16204 ((eq key 'thisyear)
16205 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
16206 ((eq key 'lastyear)
16207 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
16208 (t (error "No such time block %s" key)))
16209 (setq ts (encode-time s m h d month y)
16210 te (encode-time (or s1 s) (or m1 m) (or h1 h)
16211 (or d1 d) (or month1 month) (or y1 y)))
16212 (setq fm (cdr org-time-stamp-formats))
16213 (if as-strings
16214 (cons (format-time-string fm ts) (format-time-string fm te))
16215 (cons ts te))))
16217 (defun org-dblock-write:clocktable (params)
16218 "Write the standard clocktable."
16219 (let ((hlchars '((1 . "*") (2 . ?/)))
16220 (emph nil)
16221 (ins (make-marker))
16222 ipos time h m p level hlc hdl maxlevel
16223 ts te cc block)
16224 (setq maxlevel (or (plist-get params :maxlevel) 3)
16225 emph (plist-get params :emphasize)
16226 ts (plist-get params :tstart)
16227 te (plist-get params :tend)
16228 block (plist-get params :block))
16229 (when block
16230 (setq cc (org-clock-special-range block nil t)
16231 ts (car cc) te (cdr cc)))
16232 (if ts (setq ts (time-to-seconds
16233 (apply 'encode-time (org-parse-time-string ts)))))
16234 (if te (setq te (time-to-seconds
16235 (apply 'encode-time (org-parse-time-string te)))))
16236 (move-marker ins (point))
16237 (setq ipos (point))
16238 (insert-before-markers "Clock summary at ["
16239 (substring
16240 (format-time-string (cdr org-time-stamp-formats))
16241 1 -1)
16242 "]."
16243 (if block
16244 (format " Considered range is /%s/." block)
16246 "\n\n|L|Headline|Time|\n")
16247 (org-clock-sum ts te)
16248 (setq h (/ org-clock-file-total-minutes 60)
16249 m (- org-clock-file-total-minutes (* 60 h)))
16250 (insert-before-markers "|-\n|0|" "*Total file time*| "
16251 (format "*%d:%02d*" h m)
16252 "|\n")
16253 (goto-char (point-min))
16254 (while (setq p (next-single-property-change (point) :org-clock-minutes))
16255 (goto-char p)
16256 (when (setq time (get-text-property p :org-clock-minutes))
16257 (save-excursion
16258 (beginning-of-line 1)
16259 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
16260 (setq level (- (match-end 1) (match-beginning 1)))
16261 (<= level maxlevel))
16262 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
16263 hdl (match-string 2)
16264 h (/ time 60)
16265 m (- time (* 60 h)))
16266 (goto-char ins)
16267 (if (= level 1) (insert-before-markers "|-\n"))
16268 (insert-before-markers
16269 "| " (int-to-string level) "|" hlc hdl hlc " |"
16270 (make-string (1- level) ?|)
16272 (format "%d:%02d" h m)
16274 " |\n")))))
16275 (goto-char ins)
16276 (backward-delete-char 1)
16277 (goto-char ipos)
16278 (skip-chars-forward "^|")
16279 (org-table-align)))
16281 ;; FIXME: I don't think anybody uses this, ask David
16282 (defun org-collect-clock-time-entries ()
16283 "Return an internal list with clocking information.
16284 This list has one entry for each CLOCK interval.
16285 FIXME: describe the elements."
16286 (interactive)
16287 (let ((re (concat "^[ \t]*" org-clock-string
16288 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
16289 rtn beg end next cont level title total closedp leafp
16290 clockpos titlepos h m donep)
16291 (save-excursion
16292 (org-clock-sum)
16293 (goto-char (point-min))
16294 (while (re-search-forward re nil t)
16295 (setq clockpos (match-beginning 0)
16296 beg (match-string 1) end (match-string 2)
16297 cont (match-end 0))
16298 (setq beg (apply 'encode-time (org-parse-time-string beg))
16299 end (apply 'encode-time (org-parse-time-string end)))
16300 (org-back-to-heading t)
16301 (setq donep (org-entry-is-done-p))
16302 (setq titlepos (point)
16303 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
16304 h (/ total 60) m (- total (* 60 h))
16305 total (cons h m))
16306 (looking-at "\\(\\*+\\) +\\(.*\\)")
16307 (setq level (- (match-end 1) (match-beginning 1))
16308 title (org-match-string-no-properties 2))
16309 (save-excursion (outline-next-heading) (setq next (point)))
16310 (setq closedp (re-search-forward org-closed-time-regexp next t))
16311 (goto-char next)
16312 (setq leafp (and (looking-at "^\\*+ ")
16313 (<= (- (match-end 0) (point)) level)))
16314 (push (list beg end clockpos closedp donep
16315 total title titlepos level leafp)
16316 rtn)
16317 (goto-char cont)))
16318 (nreverse rtn)))
16320 ;;;; Agenda, and Diary Integration
16322 ;;; Define the Org-agenda-mode
16324 (defvar org-agenda-mode-map (make-sparse-keymap)
16325 "Keymap for `org-agenda-mode'.")
16327 (defvar org-agenda-menu) ; defined later in this file.
16328 (defvar org-agenda-follow-mode nil)
16329 (defvar org-agenda-show-log nil)
16330 (defvar org-agenda-redo-command nil)
16331 (defvar org-agenda-mode-hook nil)
16332 (defvar org-agenda-type nil)
16333 (defvar org-agenda-force-single-file nil)
16335 (defun org-agenda-mode ()
16336 "Mode for time-sorted view on action items in Org-mode files.
16338 The following commands are available:
16340 \\{org-agenda-mode-map}"
16341 (interactive)
16342 (kill-all-local-variables)
16343 (setq org-agenda-undo-list nil
16344 org-agenda-pending-undo-list nil)
16345 (setq major-mode 'org-agenda-mode)
16346 ;; Keep global-font-lock-mode from turning on font-lock-mode
16347 (org-set-local 'font-lock-global-modes (list 'not major-mode))
16348 (setq mode-name "Org-Agenda")
16349 (use-local-map org-agenda-mode-map)
16350 (easy-menu-add org-agenda-menu)
16351 (if org-startup-truncated (setq truncate-lines t))
16352 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
16353 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
16354 ;; Make sure properties are removed when copying text
16355 (when (boundp 'buffer-substring-filters)
16356 (org-set-local 'buffer-substring-filters
16357 (cons (lambda (x)
16358 (set-text-properties 0 (length x) nil x) x)
16359 buffer-substring-filters)))
16360 (unless org-agenda-keep-modes
16361 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
16362 org-agenda-show-log nil))
16363 (easy-menu-change
16364 '("Agenda") "Agenda Files"
16365 (append
16366 (list
16367 (vector
16368 (if (get 'org-agenda-files 'org-restrict)
16369 "Restricted to single file"
16370 "Edit File List")
16371 '(org-edit-agenda-file-list)
16372 (not (get 'org-agenda-files 'org-restrict)))
16373 "--")
16374 (mapcar 'org-file-menu-entry (org-agenda-files))))
16375 (org-agenda-set-mode-name)
16376 (apply
16377 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
16378 (list 'org-agenda-mode-hook)))
16380 (substitute-key-definition 'undo 'org-agenda-undo
16381 org-agenda-mode-map global-map)
16382 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
16383 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
16384 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
16385 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
16386 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
16387 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
16388 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
16389 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
16390 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
16391 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
16392 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
16393 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
16394 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
16395 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
16396 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
16397 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
16398 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
16399 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
16400 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
16401 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
16402 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
16403 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
16404 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
16405 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
16406 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
16407 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
16408 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
16409 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
16410 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
16412 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
16413 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
16414 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
16415 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
16416 (while l (org-defkey org-agenda-mode-map
16417 (int-to-string (pop l)) 'digit-argument)))
16419 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
16420 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
16421 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
16422 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
16423 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
16424 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
16425 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
16426 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
16427 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
16428 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
16429 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
16430 (org-defkey org-agenda-mode-map "n" 'next-line)
16431 (org-defkey org-agenda-mode-map "p" 'previous-line)
16432 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
16433 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
16434 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
16435 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
16436 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
16437 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
16438 (eval-after-load "calendar"
16439 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
16440 'org-calendar-goto-agenda))
16441 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
16442 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
16443 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
16444 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
16445 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
16446 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
16447 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
16448 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
16449 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
16450 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
16451 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
16452 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
16453 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
16454 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
16455 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
16456 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
16457 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
16459 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
16460 "Local keymap for agenda entries from Org-mode.")
16462 (org-defkey org-agenda-keymap
16463 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
16464 (org-defkey org-agenda-keymap
16465 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
16466 (when org-agenda-mouse-1-follows-link
16467 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
16468 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
16469 '("Agenda"
16470 ("Agenda Files")
16471 "--"
16472 ["Show" org-agenda-show t]
16473 ["Go To (other window)" org-agenda-goto t]
16474 ["Go To (this window)" org-agenda-switch-to t]
16475 ["Follow Mode" org-agenda-follow-mode
16476 :style toggle :selected org-agenda-follow-mode :active t]
16477 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
16478 "--"
16479 ["Cycle TODO" org-agenda-todo t]
16480 ["Archive subtree" org-agenda-archive t]
16481 ["Delete subtree" org-agenda-kill t]
16482 "--"
16483 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
16484 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
16485 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
16486 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
16487 "--"
16488 ("Tags and Properties"
16489 ["Show all Tags" org-agenda-show-tags t]
16490 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
16491 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
16492 "--"
16493 ["Column View" org-columns t])
16494 ("Date/Schedule"
16495 ["Schedule" org-agenda-schedule t]
16496 ["Set Deadline" org-agenda-deadline t]
16497 "--"
16498 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
16499 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
16500 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
16501 ("Priority"
16502 ["Set Priority" org-agenda-priority t]
16503 ["Increase Priority" org-agenda-priority-up t]
16504 ["Decrease Priority" org-agenda-priority-down t]
16505 ["Show Priority" org-agenda-show-priority t])
16506 ("Calendar/Diary"
16507 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
16508 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
16509 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
16510 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
16511 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
16512 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
16513 "--"
16514 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
16515 "--"
16516 ("View"
16517 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
16518 :style radio :selected (equal org-agenda-ndays 1)]
16519 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
16520 :style radio :selected (equal org-agenda-ndays 7)]
16521 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
16522 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
16523 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
16524 :style radio :selected (member org-agenda-ndays '(365 366))]
16525 "--"
16526 ["Show Logbook entries" org-agenda-log-mode
16527 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
16528 ["Include Diary" org-agenda-toggle-diary
16529 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
16530 ["Use Time Grid" org-agenda-toggle-time-grid
16531 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
16532 ["Write view to file" org-write-agenda t]
16533 ["Rebuild buffer" org-agenda-redo t]
16534 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
16535 "--"
16536 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
16537 "--"
16538 ["Quit" org-agenda-quit t]
16539 ["Exit and Release Buffers" org-agenda-exit t]
16542 ;;; Agenda undo
16544 (defvar org-agenda-allow-remote-undo t
16545 "Non-nil means, allow remote undo from the agenda buffer.")
16546 (defvar org-agenda-undo-list nil
16547 "List of undoable operations in the agenda since last refresh.")
16548 (defvar org-agenda-undo-has-started-in nil
16549 "Buffers that have already seen `undo-start' in the current undo sequence.")
16550 (defvar org-agenda-pending-undo-list nil
16551 "In a series of undo commands, this is the list of remaning undo items.")
16553 (defmacro org-if-unprotected (&rest body)
16554 "Execute BODY if there is no `org-protected' text property at point."
16555 (declare (debug t))
16556 `(unless (get-text-property (point) 'org-protected)
16557 ,@body))
16559 (defmacro org-with-remote-undo (_buffer &rest _body)
16560 "Execute BODY while recording undo information in two buffers."
16561 (declare (indent 1) (debug t))
16562 `(let ((_cline (org-current-line))
16563 (_cmd this-command)
16564 (_buf1 (current-buffer))
16565 (_buf2 ,_buffer)
16566 (_undo1 buffer-undo-list)
16567 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
16568 _c1 _c2)
16569 ,@_body
16570 (when org-agenda-allow-remote-undo
16571 (setq _c1 (org-verify-change-for-undo
16572 _undo1 (with-current-buffer _buf1 buffer-undo-list))
16573 _c2 (org-verify-change-for-undo
16574 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
16575 (when (or _c1 _c2)
16576 ;; make sure there are undo boundaries
16577 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
16578 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
16579 ;; remember which buffer to undo
16580 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
16581 org-agenda-undo-list)))))
16583 (defun org-agenda-undo ()
16584 "Undo a remote editing step in the agenda.
16585 This undoes changes both in the agenda buffer and in the remote buffer
16586 that have been changed along."
16587 (interactive)
16588 (or org-agenda-allow-remote-undo
16589 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
16590 (if (not (eq this-command last-command))
16591 (setq org-agenda-undo-has-started-in nil
16592 org-agenda-pending-undo-list org-agenda-undo-list))
16593 (if (not org-agenda-pending-undo-list)
16594 (error "No further undo information"))
16595 (let* ((entry (pop org-agenda-pending-undo-list))
16596 buf line cmd rembuf)
16597 (setq cmd (pop entry) line (pop entry))
16598 (setq rembuf (nth 2 entry))
16599 (org-with-remote-undo rembuf
16600 (while (bufferp (setq buf (pop entry)))
16601 (if (pop entry)
16602 (with-current-buffer buf
16603 (let ((last-undo-buffer buf)
16604 (inhibit-read-only t))
16605 (unless (memq buf org-agenda-undo-has-started-in)
16606 (push buf org-agenda-undo-has-started-in)
16607 (make-local-variable 'pending-undo-list)
16608 (undo-start))
16609 (while (and pending-undo-list
16610 (listp pending-undo-list)
16611 (not (car pending-undo-list)))
16612 (pop pending-undo-list))
16613 (undo-more 1))))))
16614 (goto-line line)
16615 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
16617 (defun org-verify-change-for-undo (l1 l2)
16618 "Verify that a real change occurred between the undo lists L1 and L2."
16619 (while (and l1 (listp l1) (null (car l1))) (pop l1))
16620 (while (and l2 (listp l2) (null (car l2))) (pop l2))
16621 (not (eq l1 l2)))
16623 ;;; Agenda dispatch
16625 (defvar org-agenda-restrict nil)
16626 (defvar org-agenda-restrict-begin (make-marker))
16627 (defvar org-agenda-restrict-end (make-marker))
16628 (defvar org-agenda-last-dispatch-buffer nil)
16630 ;;;###autoload
16631 (defun org-agenda (arg)
16632 "Dispatch agenda commands to collect entries to the agenda buffer.
16633 Prompts for a character to select a command. Any prefix arg will be passed
16634 on to the selected command. The default selections are:
16636 a Call `org-agenda-list' to display the agenda for current day or week.
16637 t Call `org-todo-list' to display the global todo list.
16638 T Call `org-todo-list' to display the global todo list, select only
16639 entries with a specific TODO keyword (the user gets a prompt).
16640 m Call `org-tags-view' to display headlines with tags matching
16641 a condition (the user is prompted for the condition).
16642 M Like `m', but select only TODO entries, no ordinary headlines.
16643 L Create a timeline for the current buffer.
16644 e Export views to associated files.
16646 More commands can be added by configuring the variable
16647 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
16648 searches can be pre-defined in this way.
16650 If the current buffer is in Org-mode and visiting a file, you can also
16651 first press `1' to indicate that the agenda should be temporarily (until the
16652 next use of \\[org-agenda]) restricted to the current file."
16653 (interactive "P")
16654 (catch 'exit
16655 (let* ((buf (current-buffer))
16656 (bfn (buffer-file-name (buffer-base-buffer)))
16657 (restrict-ok (and bfn (org-mode-p)))
16658 (custom org-agenda-custom-commands)
16659 c entry key type match lprops)
16660 ;; Turn off restriction
16661 (put 'org-agenda-files 'org-restrict nil)
16662 (setq org-agenda-restrict nil)
16663 (move-marker org-agenda-restrict-begin nil)
16664 (move-marker org-agenda-restrict-end nil)
16665 ;; Delete old local properties
16666 (put 'org-agenda-redo-command 'org-lprops nil)
16667 ;; Remember where this call originated
16668 (setq org-agenda-last-dispatch-buffer (current-buffer))
16669 (save-window-excursion
16670 (delete-other-windows)
16671 (org-switch-to-buffer-other-window " *Agenda Commands*")
16672 (erase-buffer)
16673 (insert (eval-when-compile
16674 (let ((header
16675 "Press key for an agenda command:
16676 -------------------------------- C Configure custom agenda commands
16677 a Agenda for current week or day e Export agenda views
16678 t List of all TODO entries T Entries with special TODO kwd
16679 m Match a TAGS query M Like m, but only TODO entries
16680 L Timeline for current buffer # List stuck projects (!=configure)
16682 (start 0))
16683 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
16684 (setq start (match-end 0))
16685 (add-text-properties (match-beginning 2) (match-end 2)
16686 '(face bold) header))
16687 header)))
16688 (while (setq entry (pop custom))
16689 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
16690 (insert (format "\n%-4s%-14s: %s"
16691 (org-add-props (copy-sequence key)
16692 '(face bold))
16693 (cond
16694 ((stringp type) type)
16695 ((eq type 'agenda) "Agenda for current week or day")
16696 ((eq type 'alltodo) "List of all TODO entries")
16697 ((eq type 'stuck) "List of stuck projects")
16698 ((eq type 'todo) "TODO keyword")
16699 ((eq type 'tags) "Tags query")
16700 ((eq type 'tags-todo) "Tags (TODO)")
16701 ((eq type 'tags-tree) "Tags tree")
16702 ((eq type 'todo-tree) "TODO kwd tree")
16703 ((eq type 'occur-tree) "Occur tree")
16704 ((functionp type) (symbol-name type))
16705 (t "???"))
16706 (if (stringp match)
16707 (org-add-props match nil 'face 'org-warning)
16708 (format "set of %d commands" (length match))))))
16709 (if restrict-ok
16710 (insert "\n"
16711 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
16712 (goto-char (point-min))
16713 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
16714 (message "Press key for agenda command%s"
16715 (if restrict-ok ", or [1] or [0] to restrict" ""))
16716 (setq c (read-char-exclusive))
16717 (message "")
16718 (when (memq c '(?L ?1 ?0))
16719 (if restrict-ok
16720 (put 'org-agenda-files 'org-restrict (list bfn))
16721 (error "Cannot restrict agenda to current buffer"))
16722 (with-current-buffer " *Agenda Commands*"
16723 (goto-char (point-max))
16724 (delete-region (point-at-bol) (point))
16725 (goto-char (point-min)))
16726 (when (eq c ?0)
16727 (setq org-agenda-restrict t)
16728 (with-current-buffer buf
16729 (if (org-region-active-p)
16730 (progn
16731 (move-marker org-agenda-restrict-begin (region-beginning))
16732 (move-marker org-agenda-restrict-end (region-end)))
16733 (save-excursion
16734 (org-back-to-heading t)
16735 (move-marker org-agenda-restrict-begin (point))
16736 (move-marker org-agenda-restrict-end
16737 (progn (org-end-of-subtree t)))))))
16738 (unless (eq c ?L)
16739 (message "Press key for agenda command%s"
16740 (if restrict-ok " (restricted to current file)" ""))
16741 (setq c (read-char-exclusive)))
16742 (message "")))
16743 (require 'calendar) ; FIXME: can we avoid this for some commands?
16744 ;; For example the todo list should not need it (but does...)
16745 (cond
16746 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
16747 (if (symbolp (nth 1 entry))
16748 (progn
16749 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
16750 lprops (nth 3 entry))
16751 (put 'org-agenda-redo-command 'org-lprops lprops)
16752 (cond
16753 ((eq type 'agenda)
16754 (org-let lprops '(org-agenda-list current-prefix-arg)))
16755 ((eq type 'alltodo)
16756 (org-let lprops '(org-todo-list current-prefix-arg)))
16757 ((eq type 'stuck)
16758 (org-let lprops '(org-agenda-list-stuck-projects
16759 current-prefix-arg)))
16760 ((eq type 'tags)
16761 (org-let lprops '(org-tags-view current-prefix-arg match)))
16762 ((eq type 'tags-todo)
16763 (org-let lprops '(org-tags-view '(4) match)))
16764 ((eq type 'todo)
16765 (org-let lprops '(org-todo-list match)))
16766 ((eq type 'tags-tree)
16767 (org-check-for-org-mode)
16768 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
16769 ((eq type 'todo-tree)
16770 (org-check-for-org-mode)
16771 (org-let lprops
16772 '(org-occur (concat "^" outline-regexp "[ \t]*"
16773 (regexp-quote match) "\\>"))))
16774 ((eq type 'occur-tree)
16775 (org-check-for-org-mode)
16776 (org-let lprops '(org-occur match)))
16777 ((fboundp type)
16778 (org-let lprops '(funcall type match)))
16779 (t (error "Invalid custom agenda command type %s" type))))
16780 (org-run-agenda-series (nth 1 entry) (cddr entry))))
16781 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
16782 ((equal c ?a) (call-interactively 'org-agenda-list))
16783 ((equal c ?t) (call-interactively 'org-todo-list))
16784 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
16785 ((equal c ?m) (call-interactively 'org-tags-view))
16786 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
16787 ((equal c ?e) (call-interactively 'org-store-agenda-views))
16788 ((equal c ?L)
16789 (unless restrict-ok
16790 (error "This is not an Org-mode file"))
16791 (org-call-with-arg 'org-timeline arg))
16792 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
16793 ((equal c ?!) (customize-variable 'org-stuck-projects))
16794 (t (error "Invalid key"))))))
16796 (defun org-run-agenda-series (name series)
16797 (org-prepare-agenda name)
16798 (let* ((org-agenda-multi t)
16799 (redo (list 'org-run-agenda-series name (list 'quote series)))
16800 (cmds (car series))
16801 (gprops (nth 1 series))
16802 match ;; The byte compiler incorrectly complains about this. Keep it!
16803 cmd type lprops)
16804 (while (setq cmd (pop cmds))
16805 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
16806 (cond
16807 ((eq type 'agenda)
16808 (org-let2 gprops lprops
16809 '(call-interactively 'org-agenda-list)))
16810 ((eq type 'alltodo)
16811 (org-let2 gprops lprops
16812 '(call-interactively 'org-todo-list)))
16813 ((eq type 'stuck)
16814 (org-let2 gprops lprops
16815 '(call-interactively 'org-agenda-list-stuck-projects)))
16816 ((eq type 'tags)
16817 (org-let2 gprops lprops
16818 '(org-tags-view current-prefix-arg match)))
16819 ((eq type 'tags-todo)
16820 (org-let2 gprops lprops
16821 '(org-tags-view '(4) match)))
16822 ((eq type 'todo)
16823 (org-let2 gprops lprops
16824 '(org-todo-list match)))
16825 ((fboundp type)
16826 (org-let2 gprops lprops
16827 '(funcall type match)))
16828 (t (error "Invalid type in command series"))))
16829 (widen)
16830 (setq org-agenda-redo-command redo)
16831 (goto-char (point-min)))
16832 (org-finalize-agenda))
16834 ;;;###autoload
16835 (defmacro org-batch-agenda (cmd-key &rest parameters)
16836 "Run an agenda command in batch mode and send the result to STDOUT.
16837 If CMD-KEY is a string of length 1, it is used as a key in
16838 `org-agenda-custom-commands' and triggers this command. If it is a
16839 longer string is is used as a tags/todo match string.
16840 Paramters are alternating variable names and values that will be bound
16841 before running the agenda command."
16842 (let (pars)
16843 (while parameters
16844 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16845 (if (> (length cmd-key) 1)
16846 (eval (list 'let (nreverse pars)
16847 (list 'org-tags-view nil cmd-key)))
16848 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16849 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16850 (set-buffer org-agenda-buffer-name)
16851 (princ (org-encode-for-stdout (buffer-string)))))
16853 (defun org-encode-for-stdout (string)
16854 (if (fboundp 'encode-coding-string)
16855 (encode-coding-string string buffer-file-coding-system)
16856 string))
16858 (defvar org-agenda-info nil)
16860 ;;;###autoload
16861 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
16862 "Run an agenda command in batch mode and send the result to STDOUT.
16863 If CMD-KEY is a string of length 1, it is used as a key in
16864 `org-agenda-custom-commands' and triggers this command. If it is a
16865 longer string is is used as a tags/todo match string.
16866 Paramters are alternating variable names and values that will be bound
16867 before running the agenda command.
16869 The output gives a line for each selected agenda item. Each
16870 item is a list of comma-separated values, like this:
16872 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
16874 category The category of the item
16875 head The headline, without TODO kwd, TAGS and PRIORITY
16876 type The type of the agenda entry, can be
16877 todo selected in TODO match
16878 tagsmatch selected in tags match
16879 diary imported from diary
16880 deadline a deadline on given date
16881 scheduled scheduled on given date
16882 timestamp entry has timestamp on given date
16883 closed entry was closed on given date
16884 upcoming-deadline warning about deadline
16885 past-scheduled forwarded scheduled item
16886 block entry has date block including g. date
16887 todo The todo keyword, if any
16888 tags All tags including inherited ones, separated by colons
16889 date The relevant date, like 2007-2-14
16890 time The time, like 15:00-16:50
16891 extra Sting with extra planning info
16892 priority-l The priority letter if any was given
16893 priority-n The computed numerical priority
16894 agenda-day The day in the agenda where this is listed"
16896 (let (pars)
16897 (while parameters
16898 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16899 (push (list 'org-agenda-remove-tags t) pars)
16900 (if (> (length cmd-key) 1)
16901 (eval (list 'let (nreverse pars)
16902 (list 'org-tags-view nil cmd-key)))
16903 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16904 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16905 (set-buffer org-agenda-buffer-name)
16906 (let* ((lines (org-split-string (buffer-string) "\n"))
16907 line)
16908 (while (setq line (pop lines))
16909 (catch 'next
16910 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
16911 (setq org-agenda-info
16912 (org-fix-agenda-info (text-properties-at 0 line)))
16913 (princ
16914 (org-encode-for-stdout
16915 (mapconcat 'org-agenda-export-csv-mapper
16916 '(org-category txt type todo tags date time-of-day extra
16917 priority-letter priority agenda-day)
16918 ",")))
16919 (princ "\n"))))))
16921 (defun org-fix-agenda-info (props)
16922 "FIXME"
16923 (let (tmp re)
16924 (when (setq tmp (plist-get props 'tags))
16925 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
16926 (when (setq tmp (plist-get props 'date))
16927 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16928 (let ((calendar-date-display-form '(year "-" month "-" day)))
16929 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
16931 (setq tmp (calendar-date-string tmp)))
16932 (setq props (plist-put props 'date tmp)))
16933 (when (setq tmp (plist-get props 'day))
16934 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16935 (let ((calendar-date-display-form '(year "-" month "-" day)))
16936 (setq tmp (calendar-date-string tmp)))
16937 (setq props (plist-put props 'day tmp))
16938 (setq props (plist-put props 'agenda-day tmp)))
16939 (when (setq tmp (plist-get props 'txt))
16940 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
16941 (plist-put props 'priority-letter (match-string 1 tmp))
16942 (setq tmp (replace-match "" t t tmp)))
16943 (when (and (setq re (plist-get props 'org-todo-regexp))
16944 (setq re (concat "\\`\\.*" re " ?"))
16945 (string-match re tmp))
16946 (plist-put props 'todo (match-string 1 tmp))
16947 (setq tmp (replace-match "" t t tmp)))
16948 (plist-put props 'txt tmp)))
16949 props)
16951 (defun org-agenda-export-csv-mapper (prop)
16952 (let ((res (plist-get org-agenda-info prop)))
16953 (setq res
16954 (cond
16955 ((not res) "")
16956 ((stringp res) res)
16957 (t (prin1-to-string res))))
16958 (while (string-match "," res)
16959 (setq res (replace-match ";" t t res)))
16960 (org-trim res)))
16963 ;;;###autoload
16964 (defun org-store-agenda-views (&rest parameters)
16965 (interactive)
16966 (eval (list 'org-batch-store-agenda-views)))
16968 ;; FIXME, why is this a macro?????
16969 ;;;###autoload
16970 (defmacro org-batch-store-agenda-views (&rest parameters)
16971 "Run all custom agenda commands that have a file argument."
16972 (let ((cmds org-agenda-custom-commands)
16973 (pop-up-frames nil)
16974 (dir default-directory)
16975 pars cmd thiscmdkey files opts)
16976 (while parameters
16977 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16978 (setq pars (reverse pars))
16979 (save-window-excursion
16980 (while cmds
16981 (setq cmd (pop cmds)
16982 thiscmdkey (car cmd)
16983 opts (nth 3 cmd)
16984 files (nth 4 cmd))
16985 (if (stringp files) (setq files (list files)))
16986 (when files
16987 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
16988 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16989 '(org-agenda nil))))
16990 (set-buffer org-agenda-buffer-name)
16991 (while files
16992 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16993 (list 'org-write-agenda
16994 (expand-file-name (pop files) dir) t))))
16995 (and (get-buffer org-agenda-buffer-name)
16996 (kill-buffer org-agenda-buffer-name)))))))
16998 (defun org-write-agenda (file &optional nosettings)
16999 "Write the current buffer (an agenda view) as a file.
17000 Depending on the extension of the file name, plain text (.txt),
17001 HTML (.html or .htm) or Postscript (.ps) is produced.
17002 If NOSETTINGS is given, do not scope the settings of
17003 `org-agenda-exporter-settings' into the export commands. This is used when
17004 the settings have already been scoped and we do not wish to overrule other,
17005 higher priority settings."
17006 (interactive "FWrite agenda to file: ")
17007 (if (not (file-writable-p file))
17008 (error "Cannot write agenda to file %s" file))
17009 (cond
17010 ((string-match "\\.html?\\'" file) (require 'htmlize))
17011 ((string-match "\\.ps\\'" file) (require 'ps-print)))
17012 (org-let (if nosettings nil org-agenda-exporter-settings)
17013 '(save-excursion
17014 (save-window-excursion
17015 (cond
17016 ((string-match "\\.html?\\'" file)
17017 (set-buffer (htmlize-buffer (current-buffer)))
17019 (when (and org-agenda-export-html-style
17020 (string-match "<style>" org-agenda-export-html-style))
17021 ;; replace <style> section with org-agenda-export-html-style
17022 (goto-char (point-min))
17023 (kill-region (- (search-forward "<style") 6)
17024 (search-forward "</style>"))
17025 (insert org-agenda-export-html-style))
17026 (write-file file)
17027 (kill-buffer (current-buffer))
17028 (message "HTML written to %s" file))
17029 ((string-match "\\.ps\\'" file)
17030 (ps-print-buffer-with-faces file)
17031 (message "Postscript written to %s" file))
17033 (let ((bs (buffer-string)))
17034 (find-file file)
17035 (insert bs)
17036 (save-buffer 0)
17037 (kill-buffer (current-buffer))
17038 (message "Plain text written to %s" file))))))
17039 (set-buffer org-agenda-buffer-name)))
17041 (defmacro org-no-read-only (&rest body)
17042 "Inhibit read-only for BODY."
17043 `(let ((inhibit-read-only t)) ,@body))
17045 (defun org-check-for-org-mode ()
17046 "Make sure current buffer is in org-mode. Error if not."
17047 (or (org-mode-p)
17048 (error "Cannot execute org-mode agenda command on buffer in %s."
17049 major-mode)))
17051 (defun org-fit-agenda-window ()
17052 "Fit the window to the buffer size."
17053 (and (memq org-agenda-window-setup '(reorganize-frame))
17054 (fboundp 'fit-window-to-buffer)
17055 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
17056 (/ (frame-height) 2))))
17058 ;;; Agenda file list
17060 (defun org-agenda-files (&optional unrestricted)
17061 "Get the list of agenda files.
17062 Optional UNRESTRICTED means return the full list even if a restriction
17063 is currently in place."
17064 (let ((files
17065 (cond
17066 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
17067 ((stringp org-agenda-files) (org-read-agenda-file-list))
17068 ((listp org-agenda-files) org-agenda-files)
17069 (t (error "Invalid value of `org-agenda-files'")))))
17070 (if org-agenda-skip-unavailable-files
17071 (delq nil
17072 (mapcar (function
17073 (lambda (file)
17074 (and (file-readable-p file) file)))
17075 files))
17076 files))) ; `org-check-agenda-file' will remove them from the list
17078 (defun org-edit-agenda-file-list ()
17079 "Edit the list of agenda files.
17080 Depending on setup, this either uses customize to edit the variable
17081 `org-agenda-files', or it visits the file that is holding the list. In the
17082 latter case, the buffer is set up in a way that saving it automatically kills
17083 the buffer and restores the previous window configuration."
17084 (interactive)
17085 (if (stringp org-agenda-files)
17086 (let ((cw (current-window-configuration)))
17087 (find-file org-agenda-files)
17088 (org-set-local 'org-window-configuration cw)
17089 (org-add-hook 'after-save-hook
17090 (lambda ()
17091 (set-window-configuration
17092 (prog1 org-window-configuration
17093 (kill-buffer (current-buffer))))
17094 (org-install-agenda-files-menu)
17095 (message "New agenda file list installed"))
17096 nil 'local)
17097 (message (substitute-command-keys
17098 "Edit list and finish with \\[save-buffer]")))
17099 (customize-variable 'org-agenda-files)))
17101 (defun org-store-new-agenda-file-list (list)
17102 "Set new value for the agenda file list and save it correcly."
17103 (if (stringp org-agenda-files)
17104 (let ((f org-agenda-files) b)
17105 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
17106 (with-temp-file f
17107 (insert (mapconcat 'identity list "\n") "\n")))
17108 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
17109 (setq org-agenda-files list)
17110 (customize-save-variable 'org-agenda-files org-agenda-files))))
17112 (defun org-read-agenda-file-list ()
17113 "Read the list of agenda files from a file."
17114 (when (stringp org-agenda-files)
17115 (with-temp-buffer
17116 (insert-file-contents org-agenda-files)
17117 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
17120 ;;;###autoload
17121 (defun org-cycle-agenda-files ()
17122 "Cycle through the files in `org-agenda-files'.
17123 If the current buffer visits an agenda file, find the next one in the list.
17124 If the current buffer does not, find the first agenda file."
17125 (interactive)
17126 (let* ((fs (org-agenda-files t))
17127 (files (append fs (list (car fs))))
17128 (tcf (if buffer-file-name (file-truename buffer-file-name)))
17129 file)
17130 (unless files (error "No agenda files"))
17131 (catch 'exit
17132 (while (setq file (pop files))
17133 (if (equal (file-truename file) tcf)
17134 (when (car files)
17135 (find-file (car files))
17136 (throw 'exit t))))
17137 (find-file (car fs)))
17138 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
17140 (defun org-agenda-file-to-front (&optional to-end)
17141 "Move/add the current file to the top of the agenda file list.
17142 If the file is not present in the list, it is added to the front. If it is
17143 present, it is moved there. With optional argument TO-END, add/move to the
17144 end of the list."
17145 (interactive "P")
17146 (let ((org-agenda-skip-unavailable-files nil)
17147 (file-alist (mapcar (lambda (x)
17148 (cons (file-truename x) x))
17149 (org-agenda-files t)))
17150 (ctf (file-truename buffer-file-name))
17151 x had)
17152 (setq x (assoc ctf file-alist) had x)
17154 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
17155 (if to-end
17156 (setq file-alist (append (delq x file-alist) (list x)))
17157 (setq file-alist (cons x (delq x file-alist))))
17158 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
17159 (org-install-agenda-files-menu)
17160 (message "File %s to %s of agenda file list"
17161 (if had "moved" "added") (if to-end "end" "front"))))
17163 (defun org-remove-file (&optional file)
17164 "Remove current file from the list of files in variable `org-agenda-files'.
17165 These are the files which are being checked for agenda entries.
17166 Optional argument FILE means, use this file instead of the current."
17167 (interactive)
17168 (let* ((org-agenda-skip-unavailable-files nil)
17169 (file (or file buffer-file-name))
17170 (true-file (file-truename file))
17171 (afile (abbreviate-file-name file))
17172 (files (delq nil (mapcar
17173 (lambda (x)
17174 (if (equal true-file
17175 (file-truename x))
17176 nil x))
17177 (org-agenda-files t)))))
17178 (if (not (= (length files) (length (org-agenda-files t))))
17179 (progn
17180 (org-store-new-agenda-file-list files)
17181 (org-install-agenda-files-menu)
17182 (message "Removed file: %s" afile))
17183 (message "File was not in list: %s" afile))))
17185 (defun org-file-menu-entry (file)
17186 (vector file (list 'find-file file) t))
17188 (defun org-check-agenda-file (file)
17189 "Make sure FILE exists. If not, ask user what to do."
17190 (when (not (file-exists-p file))
17191 (message "non-existent file %s. [R]emove from list or [A]bort?"
17192 (abbreviate-file-name file))
17193 (let ((r (downcase (read-char-exclusive))))
17194 (cond
17195 ((equal r ?r)
17196 (org-remove-file file)
17197 (throw 'nextfile t))
17198 (t (error "Abort"))))))
17200 ;;; Agenda prepare and finalize
17202 (defvar org-agenda-multi nil) ; dynammically scoped
17203 (defvar org-agenda-buffer-name "*Org Agenda*")
17204 (defvar org-pre-agenda-window-conf nil)
17205 (defvar org-agenda-name nil)
17206 (defun org-prepare-agenda (&optional name)
17207 (setq org-todo-keywords-for-agenda nil)
17208 (setq org-done-keywords-for-agenda nil)
17209 (if org-agenda-multi
17210 (progn
17211 (setq buffer-read-only nil)
17212 (goto-char (point-max))
17213 (unless (bobp)
17214 (insert "\n" (make-string (window-width) ?=) "\n"))
17215 (narrow-to-region (point) (point-max)))
17216 (org-agenda-maybe-reset-markers 'force)
17217 (org-prepare-agenda-buffers (org-agenda-files))
17218 (setq org-todo-keywords-for-agenda
17219 (org-uniquify org-todo-keywords-for-agenda))
17220 (setq org-done-keywords-for-agenda
17221 (org-uniquify org-done-keywords-for-agenda))
17222 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
17223 (awin (get-buffer-window abuf)))
17224 (cond
17225 ((equal (current-buffer) abuf) nil)
17226 (awin (select-window awin))
17227 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
17228 ((equal org-agenda-window-setup 'current-window)
17229 (switch-to-buffer abuf))
17230 ((equal org-agenda-window-setup 'other-window)
17231 (org-switch-to-buffer-other-window abuf))
17232 ((equal org-agenda-window-setup 'other-frame)
17233 (switch-to-buffer-other-frame abuf))
17234 ((equal org-agenda-window-setup 'reorganize-frame)
17235 (delete-other-windows)
17236 (org-switch-to-buffer-other-window abuf))))
17237 (setq buffer-read-only nil)
17238 (erase-buffer)
17239 (org-agenda-mode)
17240 (and name (not org-agenda-name)
17241 (org-set-local 'org-agenda-name name)))
17242 (setq buffer-read-only nil))
17244 (defun org-finalize-agenda ()
17245 "Finishing touch for the agenda buffer, called just before displaying it."
17246 (unless org-agenda-multi
17247 (save-excursion
17248 (let ((inhibit-read-only t))
17249 (goto-char (point-min))
17250 (while (org-activate-bracket-links (point-max))
17251 (add-text-properties (match-beginning 0) (match-end 0)
17252 '(face org-link)))
17253 (org-agenda-align-tags)
17254 (unless org-agenda-with-colors
17255 (remove-text-properties (point-min) (point-max) '(face nil))))
17256 (if (and (boundp 'org-overriding-columns-format)
17257 org-overriding-columns-format)
17258 (org-set-local 'org-overriding-columns-format
17259 org-overriding-columns-format))
17260 (if (and (boundp 'org-agenda-view-columns-initially)
17261 org-agenda-view-columns-initially)
17262 (org-agenda-columns))
17263 (run-hooks 'org-finalize-agenda-hook))))
17265 (defun org-prepare-agenda-buffers (files)
17266 "Create buffers for all agenda files, protect archived trees and comments."
17267 (interactive)
17268 (let ((pa '(:org-archived t))
17269 (pc '(:org-comment t))
17270 (pall '(:org-archived t :org-comment t))
17271 (inhibit-read-only t)
17272 (rea (concat ":" org-archive-tag ":"))
17273 bmp file re)
17274 (save-excursion
17275 (save-restriction
17276 (while (setq file (pop files))
17277 (org-check-agenda-file file)
17278 (set-buffer (org-get-agenda-file-buffer file))
17279 (widen)
17280 (setq bmp (buffer-modified-p))
17281 (setq org-todo-keywords-for-agenda
17282 (append org-todo-keywords-for-agenda org-todo-keywords-1))
17283 (setq org-done-keywords-for-agenda
17284 (append org-done-keywords-for-agenda org-done-keywords))
17285 (save-excursion
17286 (remove-text-properties (point-min) (point-max) pall)
17287 (when org-agenda-skip-archived-trees
17288 (goto-char (point-min))
17289 (while (re-search-forward rea nil t)
17290 (if (org-on-heading-p t)
17291 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
17292 (goto-char (point-min))
17293 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
17294 (while (re-search-forward re nil t)
17295 (add-text-properties
17296 (match-beginning 0) (org-end-of-subtree t) pc)))
17297 (set-buffer-modified-p bmp))))))
17299 (defvar org-agenda-skip-function nil
17300 "Function to be called at each match during agenda construction.
17301 If this function returns nil, the current match should not be skipped.
17302 Otherwise, the function must return a position from where the search
17303 should be continued.
17304 This may also be a Lisp form, it will be evaluated.
17305 Never set this variable using `setq' or so, because then it will apply
17306 to all future agenda commands. Instead, bind it with `let' to scope
17307 it dynamically into the agenda-constructing command. A good way to set
17308 it is through options in org-agenda-custom-commands.")
17310 (defun org-agenda-skip ()
17311 "Throw to `:skip' in places that should be skipped.
17312 Also moves point to the end of the skipped region, so that search can
17313 continue from there."
17314 (let ((p (point-at-bol)) to fp)
17315 (and org-agenda-skip-archived-trees
17316 (get-text-property p :org-archived)
17317 (org-end-of-subtree t)
17318 (throw :skip t))
17319 (and (get-text-property p :org-comment)
17320 (org-end-of-subtree t)
17321 (throw :skip t))
17322 (if (equal (char-after p) ?#) (throw :skip t))
17323 (when (and (or (setq fp (functionp org-agenda-skip-function))
17324 (consp org-agenda-skip-function))
17325 (setq to (save-excursion
17326 (save-match-data
17327 (if fp
17328 (funcall org-agenda-skip-function)
17329 (eval org-agenda-skip-function))))))
17330 (goto-char to)
17331 (throw :skip t))))
17333 (defvar org-agenda-markers nil
17334 "List of all currently active markers created by `org-agenda'.")
17335 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
17336 "Creation time of the last agenda marker.")
17338 (defun org-agenda-new-marker (&optional pos)
17339 "Return a new agenda marker.
17340 Org-mode keeps a list of these markers and resets them when they are
17341 no longer in use."
17342 (let ((m (copy-marker (or pos (point)))))
17343 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
17344 (push m org-agenda-markers)
17347 (defun org-agenda-maybe-reset-markers (&optional force)
17348 "Reset markers created by `org-agenda'. But only if they are old enough."
17349 (if (or (and force (not org-agenda-multi))
17350 (> (- (time-to-seconds (current-time))
17351 org-agenda-last-marker-time)
17353 (while org-agenda-markers
17354 (move-marker (pop org-agenda-markers) nil))))
17356 (defvar org-agenda-new-buffers nil
17357 "Buffers created to visit agenda files.")
17359 (defun org-get-agenda-file-buffer (file)
17360 "Get a buffer visiting FILE. If the buffer needs to be created, add
17361 it to the list of buffers which might be released later."
17362 (let ((buf (org-find-base-buffer-visiting file)))
17363 (if buf
17364 buf ; just return it
17365 ;; Make a new buffer and remember it
17366 (setq buf (find-file-noselect file))
17367 (if buf (push buf org-agenda-new-buffers))
17368 buf)))
17370 (defun org-release-buffers (blist)
17371 "Release all buffers in list, asking the user for confirmation when needed.
17372 When a buffer is unmodified, it is just killed. When modified, it is saved
17373 \(if the user agrees) and then killed."
17374 (let (buf file)
17375 (while (setq buf (pop blist))
17376 (setq file (buffer-file-name buf))
17377 (when (and (buffer-modified-p buf)
17378 file
17379 (y-or-n-p (format "Save file %s? " file)))
17380 (with-current-buffer buf (save-buffer)))
17381 (kill-buffer buf))))
17383 (defvar org-category-table nil)
17384 (defun org-get-category-table ()
17385 "Get the table of categories and positions in current buffer."
17386 (let (tbl)
17387 (save-excursion
17388 (save-restriction
17389 (widen)
17390 (goto-char (point-min))
17391 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
17392 nil t)
17393 (push (cons (match-beginning 1)
17394 (org-trim (match-string 1))) tbl))))
17395 tbl))
17397 (defun org-get-category (&optional pos)
17398 "Get the category applying to position POS."
17399 (if (not org-category-table)
17400 (cond
17401 ((null org-category)
17402 (setq org-category
17403 (if buffer-file-name
17404 (file-name-sans-extension
17405 (file-name-nondirectory buffer-file-name))
17406 "???")))
17407 ((symbolp org-category) (symbol-name org-category))
17408 (t org-category))
17409 (let ((tbl org-category-table)
17410 (pos (or pos (point))))
17411 (while (and tbl (> (caar tbl) pos))
17412 (pop tbl))
17413 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
17414 org-category-table))))))
17415 ;;; Agenda timeline
17417 (defun org-timeline (&optional include-all)
17418 "Show a time-sorted view of the entries in the current org file.
17419 Only entries with a time stamp of today or later will be listed. With
17420 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
17421 under the current date.
17422 If the buffer contains an active region, only check the region for
17423 dates."
17424 (interactive "P")
17425 (require 'calendar)
17426 (org-compile-prefix-format 'timeline)
17427 (org-set-sorting-strategy 'timeline)
17428 (let* ((dopast t)
17429 (dotodo include-all)
17430 (doclosed org-agenda-show-log)
17431 (entry buffer-file-name)
17432 (date (calendar-current-date))
17433 (beg (if (org-region-active-p) (region-beginning) (point-min)))
17434 (end (if (org-region-active-p) (region-end) (point-max)))
17435 (day-numbers (org-get-all-dates beg end 'no-ranges
17436 t doclosed ; always include today
17437 org-timeline-show-empty-dates))
17438 (today (time-to-days (current-time)))
17439 (past t)
17440 args
17441 s e rtn d emptyp)
17442 (setq org-agenda-redo-command
17443 (list 'progn
17444 (list 'org-switch-to-buffer-other-window (current-buffer))
17445 (list 'org-timeline (list 'quote include-all))))
17446 (if (not dopast)
17447 ;; Remove past dates from the list of dates.
17448 (setq day-numbers (delq nil (mapcar (lambda(x)
17449 (if (>= x today) x nil))
17450 day-numbers))))
17451 (org-prepare-agenda (concat "Timeline "
17452 (file-name-nondirectory buffer-file-name)))
17453 (if doclosed (push :closed args))
17454 (push :timestamp args)
17455 (push :sexp args)
17456 (if dotodo (push :todo args))
17457 (while (setq d (pop day-numbers))
17458 (if (and (listp d) (eq (car d) :omitted))
17459 (progn
17460 (setq s (point))
17461 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
17462 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
17463 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
17464 (if (and (>= d today)
17465 dopast
17466 past)
17467 (progn
17468 (setq past nil)
17469 (insert (make-string 79 ?-) "\n")))
17470 (setq date (calendar-gregorian-from-absolute d))
17471 (setq s (point))
17472 (setq rtn (and (not emptyp)
17473 (apply 'org-agenda-get-day-entries
17474 entry date args)))
17475 (if (or rtn (equal d today) org-timeline-show-empty-dates)
17476 (progn
17477 (insert (calendar-day-name date) " "
17478 (number-to-string (extract-calendar-day date)) " "
17479 (calendar-month-name (extract-calendar-month date)) " "
17480 (number-to-string (extract-calendar-year date)) "\n")
17481 ; FIXME: this gives a timezone problem
17482 ; (insert (format-time-string org-agenda-date-format
17483 ; (calendar-time-from-absolute d 0))
17484 ; "\n")
17485 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17486 (put-text-property s (1- (point)) 'org-date-line t)
17487 (if (equal d today)
17488 (put-text-property s (1- (point)) 'org-today t))
17489 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
17490 (put-text-property s (1- (point)) 'day d)))))
17491 (goto-char (point-min))
17492 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
17493 (point-min)))
17494 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
17495 (org-finalize-agenda)
17496 (setq buffer-read-only t)))
17498 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
17499 "Return a list of all relevant day numbers from BEG to END buffer positions.
17500 If NO-RANGES is non-nil, include only the start and end dates of a range,
17501 not every single day in the range. If FORCE-TODAY is non-nil, make
17502 sure that TODAY is included in the list. If INACTIVE is non-nil, also
17503 inactive time stamps (those in square brackets) are included.
17504 When EMPTY is non-nil, also include days without any entries."
17505 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
17506 dates dates1 date day day1 day2 ts1 ts2)
17507 (if force-today
17508 (setq dates (list (time-to-days (current-time)))))
17509 (save-excursion
17510 (goto-char beg)
17511 (while (re-search-forward re end t)
17512 (setq day (time-to-days (org-time-string-to-time
17513 (substring (match-string 1) 0 10))))
17514 (or (memq day dates) (push day dates)))
17515 (unless no-ranges
17516 (goto-char beg)
17517 (while (re-search-forward org-tr-regexp end t)
17518 (setq ts1 (substring (match-string 1) 0 10)
17519 ts2 (substring (match-string 2) 0 10)
17520 day1 (time-to-days (org-time-string-to-time ts1))
17521 day2 (time-to-days (org-time-string-to-time ts2)))
17522 (while (< (setq day1 (1+ day1)) day2)
17523 (or (memq day1 dates) (push day1 dates)))))
17524 (setq dates (sort dates '<))
17525 (when empty
17526 (while (setq day (pop dates))
17527 (setq day2 (car dates))
17528 (push day dates1)
17529 (when (and day2 empty)
17530 (if (or (eq empty t)
17531 (and (numberp empty) (<= (- day2 day) empty)))
17532 (while (< (setq day (1+ day)) day2)
17533 (push (list day) dates1))
17534 (push (cons :omitted (- day2 day)) dates1))))
17535 (setq dates (nreverse dates1)))
17536 dates)))
17538 ;;; Agenda Daily/Weekly
17540 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
17541 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
17542 (defvar org-agenda-last-arguments nil
17543 "The arguments of the previous call to org-agenda")
17544 (defvar org-starting-day nil) ; local variable in the agenda buffer
17545 (defvar org-agenda-span nil) ; local variable in the agenda buffer
17546 (defvar org-include-all-loc nil) ; local variable
17549 ;;;###autoload
17550 (defun org-agenda-list (&optional include-all start-day ndays)
17551 "Produce a weekly view from all files in variable `org-agenda-files'.
17552 The view will be for the current week, but from the overview buffer you
17553 will be able to go to other weeks.
17554 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
17555 also be shown, under the current date.
17556 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
17557 on the days are also shown. See the variable `org-log-done' for how
17558 to turn on logging.
17559 START-DAY defaults to TODAY, or to the most recent match for the weekday
17560 given in `org-agenda-start-on-weekday'.
17561 NDAYS defaults to `org-agenda-ndays'."
17562 (interactive "P")
17563 (setq ndays (or ndays org-agenda-ndays)
17564 start-day (or start-day org-agenda-start-day))
17565 (if org-agenda-overriding-arguments
17566 (setq include-all (car org-agenda-overriding-arguments)
17567 start-day (nth 1 org-agenda-overriding-arguments)
17568 ndays (nth 2 org-agenda-overriding-arguments)))
17569 (if (stringp start-day)
17570 ;; Convert to an absolute day number
17571 (setq start-day (time-to-days (org-read-date nil t start-day))))
17572 (setq org-agenda-last-arguments (list include-all start-day ndays))
17573 (org-compile-prefix-format 'agenda)
17574 (org-set-sorting-strategy 'agenda)
17575 (require 'calendar)
17576 (let* ((org-agenda-start-on-weekday
17577 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
17578 org-agenda-start-on-weekday nil))
17579 (thefiles (org-agenda-files))
17580 (files thefiles)
17581 (today (time-to-days (current-time)))
17582 (sd (or start-day today))
17583 (start (if (or (null org-agenda-start-on-weekday)
17584 (< org-agenda-ndays 7))
17586 (let* ((nt (calendar-day-of-week
17587 (calendar-gregorian-from-absolute sd)))
17588 (n1 org-agenda-start-on-weekday)
17589 (d (- nt n1)))
17590 (- sd (+ (if (< d 0) 7 0) d)))))
17591 (day-numbers (list start))
17592 (inhibit-redisplay (not debug-on-error))
17593 s e rtn rtnall file date d start-pos end-pos todayp nd)
17594 (setq org-agenda-redo-command
17595 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
17596 ;; Make the list of days
17597 (setq ndays (or ndays org-agenda-ndays)
17598 nd ndays)
17599 (while (> ndays 1)
17600 (push (1+ (car day-numbers)) day-numbers)
17601 (setq ndays (1- ndays)))
17602 (setq day-numbers (nreverse day-numbers))
17603 (org-prepare-agenda "Day/Week")
17604 (org-set-local 'org-starting-day (car day-numbers))
17605 (org-set-local 'org-include-all-loc include-all)
17606 (org-set-local 'org-agenda-span
17607 (org-agenda-ndays-to-span nd))
17608 (when (and (or include-all org-agenda-include-all-todo)
17609 (member today day-numbers))
17610 (setq files thefiles
17611 rtnall nil)
17612 (while (setq file (pop files))
17613 (catch 'nextfile
17614 (org-check-agenda-file file)
17615 (setq date (calendar-gregorian-from-absolute today)
17616 rtn (org-agenda-get-day-entries
17617 file date :todo))
17618 (setq rtnall (append rtnall rtn))))
17619 (when rtnall
17620 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
17621 (add-text-properties (point-min) (1- (point))
17622 (list 'face 'org-agenda-structure))
17623 (insert (org-finalize-agenda-entries rtnall) "\n")))
17624 (setq s (point))
17625 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
17626 "-agenda:\n")
17627 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
17628 'org-date-line t))
17629 (while (setq d (pop day-numbers))
17630 (setq date (calendar-gregorian-from-absolute d)
17631 s (point))
17632 (if (or (setq todayp (= d today))
17633 (and (not start-pos) (= d sd)))
17634 (setq start-pos (point))
17635 (if (and start-pos (not end-pos))
17636 (setq end-pos (point))))
17637 (setq files thefiles
17638 rtnall nil)
17639 (while (setq file (pop files))
17640 (catch 'nextfile
17641 (org-check-agenda-file file)
17642 (if org-agenda-show-log
17643 (setq rtn (org-agenda-get-day-entries
17644 file date
17645 :deadline :scheduled :timestamp :sexp :closed))
17646 (setq rtn (org-agenda-get-day-entries
17647 file date
17648 :deadline :scheduled :sexp :timestamp)))
17649 (setq rtnall (append rtnall rtn))))
17650 (if org-agenda-include-diary
17651 (progn
17652 (require 'diary-lib)
17653 (setq rtn (org-get-entries-from-diary date))
17654 (setq rtnall (append rtnall rtn))))
17655 (if (or rtnall org-agenda-show-all-dates)
17656 (progn
17657 (insert (format "%-9s %2d %s %4d\n"
17658 (calendar-day-name date)
17659 (extract-calendar-day date)
17660 (calendar-month-name (extract-calendar-month date))
17661 (extract-calendar-year date)))
17662 ; FIXME: this gives a timezone problem
17663 ; (insert (format-time-string org-agenda-date-format
17664 ; (calendar-time-from-absolute d 0)) "\n")
17665 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17666 (put-text-property s (1- (point)) 'org-date-line t)
17667 (if todayp (put-text-property s (1- (point)) 'org-today t))
17668 (if rtnall (insert
17669 (org-finalize-agenda-entries
17670 (org-agenda-add-time-grid-maybe
17671 rtnall nd todayp))
17672 "\n"))
17673 (put-text-property s (1- (point)) 'day d))))
17674 (goto-char (point-min))
17675 (org-fit-agenda-window)
17676 (unless (and (pos-visible-in-window-p (point-min))
17677 (pos-visible-in-window-p (point-max)))
17678 (goto-char (1- (point-max)))
17679 (recenter -1)
17680 (if (not (pos-visible-in-window-p (or start-pos 1)))
17681 (progn
17682 (goto-char (or start-pos 1))
17683 (recenter 1))))
17684 (goto-char (or start-pos 1))
17685 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
17686 (org-finalize-agenda)
17687 (setq buffer-read-only t)
17688 (message "")))
17690 (defun org-agenda-ndays-to-span (n)
17691 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
17693 ;;; Agenda TODO list
17695 (defvar org-select-this-todo-keyword nil)
17696 (defvar org-last-arg nil)
17698 ;;;###autoload
17699 (defun org-todo-list (arg)
17700 "Show all TODO entries from all agenda file in a single list.
17701 The prefix arg can be used to select a specific TODO keyword and limit
17702 the list to these. When using \\[universal-argument], you will be prompted
17703 for a keyword. A numeric prefix directly selects the Nth keyword in
17704 `org-todo-keywords-1'."
17705 (interactive "P")
17706 (require 'calendar)
17707 (org-compile-prefix-format 'todo)
17708 (org-set-sorting-strategy 'todo)
17709 (org-prepare-agenda "TODO")
17710 (let* ((today (time-to-days (current-time)))
17711 (date (calendar-gregorian-from-absolute today))
17712 (kwds org-todo-keywords-for-agenda)
17713 (completion-ignore-case t)
17714 (org-select-this-todo-keyword
17715 (if (stringp arg) arg
17716 (and arg (integerp arg) (> arg 0)
17717 (nth (1- arg) kwds))))
17718 rtn rtnall files file pos)
17719 (when (equal arg '(4))
17720 (setq org-select-this-todo-keyword
17721 (completing-read "Keyword (or KWD1|K2D2|...): "
17722 (mapcar 'list kwds) nil nil)))
17723 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
17724 (org-set-local 'org-last-arg arg)
17725 (setq org-agenda-redo-command
17726 '(org-todo-list (or current-prefix-arg org-last-arg)))
17727 (setq files (org-agenda-files)
17728 rtnall nil)
17729 (while (setq file (pop files))
17730 (catch 'nextfile
17731 (org-check-agenda-file file)
17732 (setq rtn (org-agenda-get-day-entries file date :todo))
17733 (setq rtnall (append rtnall rtn))))
17734 (if org-agenda-overriding-header
17735 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17736 nil 'face 'org-agenda-structure) "\n")
17737 (insert "Global list of TODO items of type: ")
17738 (add-text-properties (point-min) (1- (point))
17739 (list 'face 'org-agenda-structure))
17740 (setq pos (point))
17741 (insert (or org-select-this-todo-keyword "ALL") "\n")
17742 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17743 (setq pos (point))
17744 (unless org-agenda-multi
17745 (insert "Available with `N r': (0)ALL")
17746 (let ((n 0) s)
17747 (mapc (lambda (x)
17748 (setq s (format "(%d)%s" (setq n (1+ n)) x))
17749 (if (> (+ (current-column) (string-width s) 1) (frame-width))
17750 (insert "\n "))
17751 (insert " " s))
17752 kwds))
17753 (insert "\n"))
17754 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17755 (when rtnall
17756 (insert (org-finalize-agenda-entries rtnall) "\n"))
17757 (goto-char (point-min))
17758 (org-fit-agenda-window)
17759 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
17760 (org-finalize-agenda)
17761 (setq buffer-read-only t)))
17763 ;;; Agenda tags match
17765 ;;;###autoload
17766 (defun org-tags-view (&optional todo-only match)
17767 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
17768 The prefix arg TODO-ONLY limits the search to TODO entries."
17769 (interactive "P")
17770 (org-compile-prefix-format 'tags)
17771 (org-set-sorting-strategy 'tags)
17772 (let* ((org-tags-match-list-sublevels
17773 (if todo-only t org-tags-match-list-sublevels))
17774 (completion-ignore-case t)
17775 rtn rtnall files file pos matcher
17776 buffer)
17777 (setq matcher (org-make-tags-matcher match)
17778 match (car matcher) matcher (cdr matcher))
17779 (org-prepare-agenda (concat "TAGS " match))
17780 (setq org-agenda-redo-command
17781 (list 'org-tags-view (list 'quote todo-only)
17782 (list 'if 'current-prefix-arg nil match)))
17783 (setq files (org-agenda-files)
17784 rtnall nil)
17785 (while (setq file (pop files))
17786 (catch 'nextfile
17787 (org-check-agenda-file file)
17788 (setq buffer (if (file-exists-p file)
17789 (org-get-agenda-file-buffer file)
17790 (error "No such file %s" file)))
17791 (if (not buffer)
17792 ;; If file does not exist, merror message to agenda
17793 (setq rtn (list
17794 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17795 rtnall (append rtnall rtn))
17796 (with-current-buffer buffer
17797 (unless (org-mode-p)
17798 (error "Agenda file %s is not in `org-mode'" file))
17799 (setq org-category-table (org-get-category-table))
17800 (save-excursion
17801 (save-restriction
17802 (if org-agenda-restrict
17803 (narrow-to-region org-agenda-restrict-begin
17804 org-agenda-restrict-end)
17805 (widen))
17806 (setq rtn (org-scan-tags 'agenda matcher todo-only))
17807 (setq rtnall (append rtnall rtn))))))))
17808 (if org-agenda-overriding-header
17809 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17810 nil 'face 'org-agenda-structure) "\n")
17811 (insert "Headlines with TAGS match: ")
17812 (add-text-properties (point-min) (1- (point))
17813 (list 'face 'org-agenda-structure))
17814 (setq pos (point))
17815 (insert match "\n")
17816 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17817 (setq pos (point))
17818 (unless org-agenda-multi
17819 (insert "Press `C-u r' to search again with new search string\n"))
17820 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17821 (when rtnall
17822 (insert (org-finalize-agenda-entries rtnall) "\n"))
17823 (goto-char (point-min))
17824 (org-fit-agenda-window)
17825 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
17826 (org-finalize-agenda)
17827 (setq buffer-read-only t)))
17829 ;;; Agenda Finding stuck projects
17831 (defvar org-agenda-skip-regexp nil
17832 "Regular expression used in skipping subtrees for the agenda.
17833 This is basically a temporary global variable that can be set and then
17834 used by user-defined selections using `org-agenda-skip-function'.")
17836 (defvar org-agenda-overriding-header nil
17837 "When this is set during todo and tags searches, will replace header.")
17839 (defun org-agenda-skip-subtree-when-regexp-matches ()
17840 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
17841 If yes, it returns the end position of this tree, causing agenda commands
17842 to skip this subtree. This is a function that can be put into
17843 `org-agenda-skip-function' for the duration of a command."
17844 (let ((end (save-excursion (org-end-of-subtree t)))
17845 skip)
17846 (save-excursion
17847 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
17848 (and skip end)))
17850 (defun org-agenda-skip-entry-if (&rest conditions)
17851 "Skip entry is any of CONDITIONS is true.
17852 See `org-agenda-skip-if for details."
17853 (org-agenda-skip-if nil conditions))
17854 (defun org-agenda-skip-subtree-if (&rest conditions)
17855 "Skip entry is any of CONDITIONS is true.
17856 See `org-agenda-skip-if for details."
17857 (org-agenda-skip-if t conditions))
17859 (defun org-agenda-skip-if (subtree conditions)
17860 "Checks current entity for CONDITIONS.
17861 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
17862 the entry, i.e. the text before the next heading is checked.
17864 CONDITIONS is a list of symbols, boolean OR is used to combine the results
17865 from different tests. Valid conditions are:
17867 scheduled Check if there is a scheduled cookie
17868 notscheduled Check if there is no scheduled cookie
17869 deadline Check if there is a deadline
17870 notdeadline Check if there is no deadline
17871 regexp Check if regexp matches
17872 notregexp Check if regexp does not match.
17874 The regexp is taken from the conditions list, it must com right after the
17875 `regexp' of `notregexp' element.
17877 If any of these conditions is met, this function returns the end point of
17878 the entity, causing the search to continue from there. This is a function
17879 that can be put into `org-agenda-skip-function' for the duration of a command."
17880 (let (beg end m r)
17881 (org-back-to-heading t)
17882 (setq beg (point)
17883 end (if subtree
17884 (progn (org-end-of-subtree t) (point))
17885 (progn (outline-next-heading) (1- (point)))))
17886 (goto-char beg)
17887 (and
17889 (and (memq 'scheduled conditions)
17890 (re-search-forward org-scheduled-time-regexp end t))
17891 (and (memq 'notscheduled conditions)
17892 (not (re-search-forward org-scheduled-time-regexp end t)))
17893 (and (memq 'deadline conditions)
17894 (re-search-forward org-deadline-time-regexp end t))
17895 (and (memq 'notdeadline conditions)
17896 (not (re-search-forward org-deadline-time-regexp end t)))
17897 (and (setq m (memq 'regexp conditions))
17898 (stringp (setq r (nth 1 m)))
17899 (re-search-forward (nth 1 m) end t))
17900 (and (setq m (memq 'notregexp conditions))
17901 (stringp (setq r (nth 1 m)))
17902 (not (re-search-forward (nth 1 m) end t))))
17903 end)))
17905 (defun org-agenda-list-stuck-projects (&rest ignore)
17906 "Create agenda view for projects that are stuck.
17907 Stuck projects are project that have no next actions. For the definitions
17908 of what a project is and how to check if it stuck, customize the variable
17909 `org-stuck-projects'.
17910 MATCH is being ignored."
17911 (interactive)
17912 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
17913 ;; FIXME: we could have used org-agenda-skip-if here.
17914 (org-agenda-overriding-header "List of stuck projects: ")
17915 (matcher (nth 0 org-stuck-projects))
17916 (todo (nth 1 org-stuck-projects))
17917 (todo-wds (if (member "*" todo)
17918 (progn
17919 (org-prepare-agenda-buffers (org-agenda-files))
17920 (org-delete-all
17921 org-done-keywords-for-agenda
17922 (copy-sequence org-todo-keywords-for-agenda)))
17923 todo))
17924 (todo-re (concat "^\\*+[ \t]+\\("
17925 (mapconcat 'identity todo-wds "\\|")
17926 "\\)\\>"))
17927 (tags (nth 2 org-stuck-projects))
17928 (tags-re (if (member "*" tags)
17929 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
17930 (concat "^\\*+ .*:\\("
17931 (mapconcat 'identity tags "\\|")
17932 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
17933 (gen-re (nth 3 org-stuck-projects))
17934 (re-list
17935 (delq nil
17936 (list
17937 (if todo todo-re)
17938 (if tags tags-re)
17939 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
17940 gen-re)))))
17941 (setq org-agenda-skip-regexp
17942 (if re-list
17943 (mapconcat 'identity re-list "\\|")
17944 (error "No information how to identify unstuck projects")))
17945 (org-tags-view nil matcher)
17946 (with-current-buffer org-agenda-buffer-name
17947 (setq org-agenda-redo-command
17948 '(org-agenda-list-stuck-projects
17949 (or current-prefix-arg org-last-arg))))))
17951 ;;; Diary integration
17953 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
17955 (defun org-get-entries-from-diary (date)
17956 "Get the (Emacs Calendar) diary entries for DATE."
17957 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
17958 (diary-display-hook '(fancy-diary-display))
17959 (pop-up-frames nil)
17960 (list-diary-entries-hook
17961 (cons 'org-diary-default-entry list-diary-entries-hook))
17962 (diary-file-name-prefix-function nil) ; turn this feature off
17963 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
17964 entries
17965 (org-disable-agenda-to-diary t))
17966 (save-excursion
17967 (save-window-excursion
17968 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
17969 (if (not (get-buffer fancy-diary-buffer))
17970 (setq entries nil)
17971 (with-current-buffer fancy-diary-buffer
17972 (setq buffer-read-only nil)
17973 (if (zerop (buffer-size))
17974 ;; No entries
17975 (setq entries nil)
17976 ;; Omit the date and other unnecessary stuff
17977 (org-agenda-cleanup-fancy-diary)
17978 ;; Add prefix to each line and extend the text properties
17979 (if (zerop (buffer-size))
17980 (setq entries nil)
17981 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
17982 (set-buffer-modified-p nil)
17983 (kill-buffer fancy-diary-buffer)))
17984 (when entries
17985 (setq entries (org-split-string entries "\n"))
17986 (setq entries
17987 (mapcar
17988 (lambda (x)
17989 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
17990 ;; Extend the text properties to the beginning of the line
17991 (org-add-props x (text-properties-at (1- (length x)) x)
17992 'type "diary" 'date date))
17993 entries)))))
17995 (defun org-agenda-cleanup-fancy-diary ()
17996 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
17997 This gets rid of the date, the underline under the date, and
17998 the dummy entry installed by `org-mode' to ensure non-empty diary for each
17999 date. It also removes lines that contain only whitespace."
18000 (goto-char (point-min))
18001 (if (looking-at ".*?:[ \t]*")
18002 (progn
18003 (replace-match "")
18004 (re-search-forward "\n=+$" nil t)
18005 (replace-match "")
18006 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
18007 (re-search-forward "\n=+$" nil t)
18008 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
18009 (goto-char (point-min))
18010 (while (re-search-forward "^ +\n" nil t)
18011 (replace-match ""))
18012 (goto-char (point-min))
18013 (if (re-search-forward "^Org-mode dummy\n?" nil t)
18014 (replace-match "")))
18016 ;; Make sure entries from the diary have the right text properties.
18017 (eval-after-load "diary-lib"
18018 '(if (boundp 'diary-modify-entry-list-string-function)
18019 ;; We can rely on the hook, nothing to do
18021 ;; Hook not avaiable, must use advice to make this work
18022 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
18023 "Make the position visible."
18024 (if (and org-disable-agenda-to-diary ;; called from org-agenda
18025 (stringp string)
18026 buffer-file-name)
18027 (setq string (org-modify-diary-entry-string string))))))
18029 (defun org-modify-diary-entry-string (string)
18030 "Add text properties to string, allowing org-mode to act on it."
18031 (org-add-props string nil
18032 'mouse-face 'highlight
18033 'keymap org-agenda-keymap
18034 'help-echo (if buffer-file-name
18035 (format "mouse-2 or RET jump to diary file %s"
18036 (abbreviate-file-name buffer-file-name))
18038 'org-agenda-diary-link t
18039 'org-marker (org-agenda-new-marker (point-at-bol))))
18041 (defun org-diary-default-entry ()
18042 "Add a dummy entry to the diary.
18043 Needed to avoid empty dates which mess up holiday display."
18044 ;; Catch the error if dealing with the new add-to-diary-alist
18045 (when org-disable-agenda-to-diary
18046 (condition-case nil
18047 (add-to-diary-list original-date "Org-mode dummy" "")
18048 (error
18049 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
18051 ;;;###autoload
18052 (defun org-diary (&rest args)
18053 "Return diary information from org-files.
18054 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
18055 It accesses org files and extracts information from those files to be
18056 listed in the diary. The function accepts arguments specifying what
18057 items should be listed. The following arguments are allowed:
18059 :timestamp List the headlines of items containing a date stamp or
18060 date range matching the selected date. Deadlines will
18061 also be listed, on the expiration day.
18063 :sexp FIXME
18065 :deadline List any deadlines past due, or due within
18066 `org-deadline-warning-days'. The listing occurs only
18067 in the diary for *today*, not at any other date. If
18068 an entry is marked DONE, it is no longer listed.
18070 :scheduled List all items which are scheduled for the given date.
18071 The diary for *today* also contains items which were
18072 scheduled earlier and are not yet marked DONE.
18074 :todo List all TODO items from the org-file. This may be a
18075 long list - so this is not turned on by default.
18076 Like deadlines, these entries only show up in the
18077 diary for *today*, not at any other date.
18079 The call in the diary file should look like this:
18081 &%%(org-diary) ~/path/to/some/orgfile.org
18083 Use a separate line for each org file to check. Or, if you omit the file name,
18084 all files listed in `org-agenda-files' will be checked automatically:
18086 &%%(org-diary)
18088 If you don't give any arguments (as in the example above), the default
18089 arguments (:deadline :scheduled :timestamp :sexp) are used.
18090 So the example above may also be written as
18092 &%%(org-diary :deadline :timestamp :sexp :scheduled)
18094 The function expects the lisp variables `entry' and `date' to be provided
18095 by the caller, because this is how the calendar works. Don't use this
18096 function from a program - use `org-agenda-get-day-entries' instead."
18097 (org-agenda-maybe-reset-markers)
18098 (org-compile-prefix-format 'agenda)
18099 (org-set-sorting-strategy 'agenda)
18100 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18101 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
18102 (list entry)
18103 (org-agenda-files t)))
18104 file rtn results)
18105 (org-prepare-agenda-buffers files)
18106 ;; If this is called during org-agenda, don't return any entries to
18107 ;; the calendar. Org Agenda will list these entries itself.
18108 (if org-disable-agenda-to-diary (setq files nil))
18109 (while (setq file (pop files))
18110 (setq rtn (apply 'org-agenda-get-day-entries file date args))
18111 (setq results (append results rtn)))
18112 (if results
18113 (concat (org-finalize-agenda-entries results) "\n"))))
18115 ;;; Agenda entry finders
18117 (defun org-agenda-get-day-entries (file date &rest args)
18118 "Does the work for `org-diary' and `org-agenda'.
18119 FILE is the path to a file to be checked for entries. DATE is date like
18120 the one returned by `calendar-current-date'. ARGS are symbols indicating
18121 which kind of entries should be extracted. For details about these, see
18122 the documentation of `org-diary'."
18123 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
18124 (let* ((org-startup-folded nil)
18125 (org-startup-align-all-tables nil)
18126 (buffer (if (file-exists-p file)
18127 (org-get-agenda-file-buffer file)
18128 (error "No such file %s" file)))
18129 arg results rtn)
18130 (if (not buffer)
18131 ;; If file does not exist, make sure an error message ends up in diary
18132 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
18133 (with-current-buffer buffer
18134 (unless (org-mode-p)
18135 (error "Agenda file %s is not in `org-mode'" file))
18136 (setq org-category-table (org-get-category-table))
18137 (let ((case-fold-search nil))
18138 (save-excursion
18139 (save-restriction
18140 (if org-agenda-restrict
18141 (narrow-to-region org-agenda-restrict-begin
18142 org-agenda-restrict-end)
18143 (widen))
18144 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
18145 (while (setq arg (pop args))
18146 (cond
18147 ((and (eq arg :todo)
18148 (equal date (calendar-current-date)))
18149 (setq rtn (org-agenda-get-todos))
18150 (setq results (append results rtn)))
18151 ((eq arg :timestamp)
18152 (setq rtn (org-agenda-get-blocks))
18153 (setq results (append results rtn))
18154 (setq rtn (org-agenda-get-timestamps))
18155 (setq results (append results rtn)))
18156 ((eq arg :sexp)
18157 (setq rtn (org-agenda-get-sexps))
18158 (setq results (append results rtn)))
18159 ((eq arg :scheduled)
18160 (setq rtn (org-agenda-get-scheduled))
18161 (setq results (append results rtn)))
18162 ((eq arg :closed)
18163 (setq rtn (org-agenda-get-closed))
18164 (setq results (append results rtn)))
18165 ((eq arg :deadline)
18166 (setq rtn (org-agenda-get-deadlines))
18167 (setq results (append results rtn))))))))
18168 results))))
18170 ;; FIXME: this works only if the cursor is not at the
18171 ;; beginning of the entry
18172 (defun org-entry-is-done-p ()
18173 "Is the current entry marked DONE?"
18174 (save-excursion
18175 (and (re-search-backward "[\r\n]\\*+ " nil t)
18176 (looking-at org-nl-done-regexp))))
18178 (defun org-at-date-range-p (&optional inactive-ok)
18179 "Is the cursor inside a date range?"
18180 (interactive)
18181 (save-excursion
18182 (catch 'exit
18183 (let ((pos (point)))
18184 (skip-chars-backward "^[<\r\n")
18185 (skip-chars-backward "<[")
18186 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18187 (>= (match-end 0) pos)
18188 (throw 'exit t))
18189 (skip-chars-backward "^<[\r\n")
18190 (skip-chars-backward "<[")
18191 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
18192 (>= (match-end 0) pos)
18193 (throw 'exit t)))
18194 nil)))
18196 (defun org-agenda-get-todos ()
18197 "Return the TODO information for agenda display."
18198 (let* ((props (list 'face nil
18199 'done-face 'org-done
18200 'org-not-done-regexp org-not-done-regexp
18201 'org-todo-regexp org-todo-regexp
18202 'mouse-face 'highlight
18203 'keymap org-agenda-keymap
18204 'help-echo
18205 (format "mouse-2 or RET jump to org file %s"
18206 (abbreviate-file-name buffer-file-name))))
18207 ;; FIXME: get rid of the \n at some point but watch out
18208 (regexp (concat "^\\*+[ \t]+\\("
18209 (if org-select-this-todo-keyword
18210 (if (equal org-select-this-todo-keyword "*")
18211 org-todo-regexp
18212 (concat "\\<\\("
18213 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
18214 "\\)\\>"))
18215 org-not-done-regexp)
18216 "[^\n\r]*\\)"))
18217 marker priority category tags
18218 ee txt beg end)
18219 (goto-char (point-min))
18220 (while (re-search-forward regexp nil t)
18221 (catch :skip
18222 (save-match-data
18223 (beginning-of-line)
18224 (setq beg (point) end (progn (outline-next-heading) (point)))
18225 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
18226 (re-search-forward org-scheduled-time-regexp end t))
18227 (and org-agenda-todo-ignore-deadlines (goto-char beg)
18228 (re-search-forward org-deadline-time-regexp end t)
18229 (org-deadline-close (match-string 1))))
18230 (goto-char (1+ beg))
18231 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
18232 (throw :skip nil)))
18233 (goto-char beg)
18234 (org-agenda-skip)
18235 (goto-char (match-beginning 1))
18236 (setq marker (org-agenda-new-marker (match-beginning 0))
18237 category (org-get-category)
18238 tags (org-get-tags-at (point))
18239 txt (org-format-agenda-item "" (match-string 1) category tags)
18240 priority (1+ (org-get-priority txt)))
18241 (org-add-props txt props
18242 'org-marker marker 'org-hd-marker marker
18243 'priority priority 'org-category category
18244 'type "todo")
18245 (push txt ee)
18246 (if org-agenda-todo-list-sublevels
18247 (goto-char (match-end 1))
18248 (org-end-of-subtree 'invisible))))
18249 (nreverse ee)))
18251 (defconst org-agenda-no-heading-message
18252 "No heading for this item in buffer or region.")
18254 (defun org-agenda-get-timestamps ()
18255 "Return the date stamp information for agenda display."
18256 (let* ((props (list 'face nil
18257 'org-not-done-regexp org-not-done-regexp
18258 'org-todo-regexp org-todo-regexp
18259 'mouse-face 'highlight
18260 'keymap org-agenda-keymap
18261 'help-echo
18262 (format "mouse-2 or RET jump to org file %s"
18263 (abbreviate-file-name buffer-file-name))))
18264 (d1 (calendar-absolute-from-gregorian date))
18265 (regexp
18266 (concat
18267 (regexp-quote
18268 (substring
18269 (format-time-string
18270 (car org-time-stamp-formats)
18271 (apply 'encode-time ; DATE bound by calendar
18272 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18273 0 11))
18274 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
18275 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
18276 marker hdmarker deadlinep scheduledp donep tmp priority category
18277 ee txt timestr tags b0 b3 e3)
18278 (goto-char (point-min))
18279 (while (re-search-forward regexp nil t)
18280 (setq b0 (match-beginning 0)
18281 b3 (match-beginning 3) e3 (match-end 3))
18282 (catch :skip
18283 (and (org-at-date-range-p) (throw :skip nil))
18284 (org-agenda-skip)
18285 (if (and (match-end 1)
18286 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
18287 (throw :skip nil))
18288 (if (and e3
18289 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
18290 (throw :skip nil))
18291 (setq marker (org-agenda-new-marker b0)
18292 category (org-get-category b0)
18293 tmp (buffer-substring (max (point-min)
18294 (- b0 org-ds-keyword-length))
18296 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
18297 deadlinep (string-match org-deadline-regexp tmp)
18298 scheduledp (string-match org-scheduled-regexp tmp)
18299 donep (org-entry-is-done-p))
18300 (if (or scheduledp deadlinep) (throw :skip t))
18301 (if (string-match ">" timestr)
18302 ;; substring should only run to end of time stamp
18303 (setq timestr (substring timestr 0 (match-end 0))))
18304 (save-excursion
18305 (if (re-search-backward "^\\*+ " nil t)
18306 (progn
18307 (goto-char (match-beginning 0))
18308 (setq hdmarker (org-agenda-new-marker)
18309 tags (org-get-tags-at))
18310 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18311 (setq txt (org-format-agenda-item
18312 nil (match-string 1) category tags timestr)))
18313 (setq txt org-agenda-no-heading-message))
18314 (setq priority (org-get-priority txt))
18315 (org-add-props txt props
18316 'org-marker marker 'org-hd-marker hdmarker)
18317 (org-add-props txt nil 'priority priority
18318 'org-category category 'date date
18319 'type "timestamp")
18320 (push txt ee))
18321 (outline-next-heading)))
18322 (nreverse ee)))
18324 (defun org-agenda-get-sexps ()
18325 "Return the sexp information for agenda display."
18326 (require 'diary-lib)
18327 (let* ((props (list 'face nil
18328 'mouse-face 'highlight
18329 'keymap org-agenda-keymap
18330 'help-echo
18331 (format "mouse-2 or RET jump to org file %s"
18332 (abbreviate-file-name buffer-file-name))))
18333 (regexp "^&?%%(")
18334 marker category ee txt tags entry result beg b sexp sexp-entry)
18335 (goto-char (point-min))
18336 (while (re-search-forward regexp nil t)
18337 (catch :skip
18338 (org-agenda-skip)
18339 (setq beg (match-beginning 0))
18340 (goto-char (1- (match-end 0)))
18341 (setq b (point))
18342 (forward-sexp 1)
18343 (setq sexp (buffer-substring b (point)))
18344 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
18345 (org-trim (match-string 1))
18346 ""))
18347 (setq result (org-diary-sexp-entry sexp sexp-entry date))
18348 (when result
18349 (setq marker (org-agenda-new-marker beg)
18350 category (org-get-category beg))
18352 (if (string-match "\\S-" result)
18353 (setq txt result)
18354 (setq txt "SEXP entry returned empty string"))
18356 (setq txt (org-format-agenda-item
18357 "" txt category tags 'time))
18358 (org-add-props txt props 'org-marker marker)
18359 (org-add-props txt nil
18360 'org-category category 'date date
18361 'type "sexp")
18362 (push txt ee))))
18363 (nreverse ee)))
18365 (defun org-agenda-get-closed ()
18366 "Return the logged TODO entries for agenda display."
18367 (let* ((props (list 'mouse-face 'highlight
18368 'org-not-done-regexp org-not-done-regexp
18369 'org-todo-regexp org-todo-regexp
18370 'keymap org-agenda-keymap
18371 'help-echo
18372 (format "mouse-2 or RET jump to org file %s"
18373 (abbreviate-file-name buffer-file-name))))
18374 (regexp (concat
18375 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
18376 (regexp-quote
18377 (substring
18378 (format-time-string
18379 (car org-time-stamp-formats)
18380 (apply 'encode-time ; DATE bound by calendar
18381 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
18382 1 11))))
18383 marker hdmarker priority category tags closedp
18384 ee txt timestr)
18385 (goto-char (point-min))
18386 (while (re-search-forward regexp nil t)
18387 (catch :skip
18388 (org-agenda-skip)
18389 (setq marker (org-agenda-new-marker (match-beginning 0))
18390 closedp (equal (match-string 1) org-closed-string)
18391 category (org-get-category (match-beginning 0))
18392 timestr (buffer-substring (match-beginning 0) (point-at-eol))
18393 ;; donep (org-entry-is-done-p)
18395 (if (string-match "\\]" timestr)
18396 ;; substring should only run to end of time stamp
18397 (setq timestr (substring timestr 0 (match-end 0))))
18398 (save-excursion
18399 (if (re-search-backward "^\\*+ " nil t)
18400 (progn
18401 (goto-char (match-beginning 0))
18402 (setq hdmarker (org-agenda-new-marker)
18403 tags (org-get-tags-at))
18404 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18405 (setq txt (org-format-agenda-item
18406 (if closedp "Closed: " "Clocked: ")
18407 (match-string 1) category tags timestr)))
18408 (setq txt org-agenda-no-heading-message))
18409 (setq priority 100000)
18410 (org-add-props txt props
18411 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
18412 'priority priority 'org-category category
18413 'type "closed" 'date date
18414 'undone-face 'org-warning 'done-face 'org-done)
18415 (push txt ee))
18416 (outline-next-heading)))
18417 (nreverse ee)))
18419 (defun org-agenda-get-deadlines ()
18420 "Return the deadline information for agenda display."
18421 (let* ((props (list 'mouse-face 'highlight
18422 'org-not-done-regexp org-not-done-regexp
18423 'org-todo-regexp org-todo-regexp
18424 'keymap org-agenda-keymap
18425 'help-echo
18426 (format "mouse-2 or RET jump to org file %s"
18427 (abbreviate-file-name buffer-file-name))))
18428 (regexp org-deadline-time-regexp)
18429 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18430 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18431 d2 diff dfrac wdays pos pos1 category tags
18432 ee txt head face s upcomingp donep timestr)
18433 (goto-char (point-min))
18434 (while (re-search-forward regexp nil t)
18435 (catch :skip
18436 (org-agenda-skip)
18437 (setq s (match-string 1)
18438 pos (1- (match-beginning 1))
18439 d2 (org-time-string-to-absolute (match-string 1) d1)
18440 diff (- d2 d1))
18441 (if (string-match "-\\([0-9]+\\)\\([dwmy]\\)\\'" s)
18442 (setq wdays
18443 (floor
18444 (* (string-to-number (match-string 1 s))
18445 (cdr (assoc (match-string 2 s)
18446 '(("d" . 1) ("w" . 7)
18447 ("m" . 30.4) ("y" . 365.25)))))))
18448 (setq wdays org-deadline-warning-days))
18449 (setq dfrac (/ (* 1.0 (- wdays diff)) wdays))
18450 (setq upcomingp (and todayp (> diff 0)))
18451 ;; When to show a deadline in the calendar:
18452 ;; If the expiration is within wdays warning time.
18453 ;; Past-due deadlines are only shown on the current date
18454 (if (or (and (<= diff wdays) todayp)
18455 (= diff 0))
18456 (save-excursion
18457 (setq category (org-get-category))
18458 (if (re-search-backward "^\\*+[ \t]+" nil t)
18459 (progn
18460 (goto-char (match-end 0))
18461 (setq pos1 (match-beginning 0))
18462 (setq tags (org-get-tags-at pos1))
18463 (setq head (buffer-substring-no-properties
18464 (point)
18465 (progn (skip-chars-forward "^\r\n")
18466 (point))))
18467 (setq donep (string-match org-looking-at-done-regexp head))
18468 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18469 (setq timestr
18470 (concat (substring s (match-beginning 1)) " "))
18471 (setq timestr 'time))
18472 (if (and donep
18473 (or org-agenda-skip-deadline-if-done
18474 (not (= diff 0))))
18475 (setq txt nil)
18476 (setq txt (org-format-agenda-item
18477 (if (= diff 0)
18478 "Deadline: "
18479 (format "In %3d d.: " diff))
18480 head category tags timestr))))
18481 (setq txt org-agenda-no-heading-message))
18482 (when txt
18483 (setq face (org-agenda-deadline-face dfrac))
18484 (org-add-props txt props
18485 'org-marker (org-agenda-new-marker pos)
18486 'org-hd-marker (org-agenda-new-marker pos1)
18487 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
18488 (org-get-priority txt))
18489 'org-category category
18490 'type (if upcomingp "upcoming-deadline" "deadline")
18491 'date (if upcomingp date d2)
18492 'face (if donep 'org-done face)
18493 'undone-face face 'done-face 'org-done)
18494 (push txt ee))))))
18495 ee))
18497 (defun org-agenda-deadline-face (fraction)
18498 "Return the face to displaying a deadline item.
18499 FRACTION is what fraction of the head-warning time has passed."
18500 (let ((faces org-agenda-deadline-faces) f)
18501 (catch 'exit
18502 (while (setq f (pop faces))
18503 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
18505 (defun org-agenda-get-scheduled ()
18506 "Return the scheduled information for agenda display."
18507 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
18508 'org-todo-regexp org-todo-regexp
18509 'done-face 'org-done
18510 'mouse-face 'highlight
18511 'keymap org-agenda-keymap
18512 'help-echo
18513 (format "mouse-2 or RET jump to org file %s"
18514 (abbreviate-file-name buffer-file-name))))
18515 (regexp org-scheduled-time-regexp)
18516 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
18517 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
18518 d2 diff pos pos1 category tags
18519 ee txt head pastschedp donep face timestr s)
18520 (goto-char (point-min))
18521 (while (re-search-forward regexp nil t)
18522 (catch :skip
18523 (org-agenda-skip)
18524 (setq s (match-string 1)
18525 pos (1- (match-beginning 1))
18526 d2 (org-time-string-to-absolute (match-string 1) d1)
18527 diff (- d2 d1))
18528 (setq pastschedp (and todayp (< diff 0)))
18529 ;; When to show a scheduled item in the calendar:
18530 ;; If it is on or past the date.
18531 (if (or (and (< diff 0) todayp)
18532 (= diff 0))
18533 (save-excursion
18534 (setq category (org-get-category))
18535 (if (re-search-backward "^\\*+[ \t]+" nil t)
18536 (progn
18537 (goto-char (match-end 0))
18538 (setq pos1 (match-beginning 0))
18539 (setq tags (org-get-tags-at))
18540 (setq head (buffer-substring-no-properties
18541 (point)
18542 (progn (skip-chars-forward "^\r\n") (point))))
18543 (setq donep (string-match org-looking-at-done-regexp head))
18544 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
18545 (setq timestr
18546 (concat (substring s (match-beginning 1)) " "))
18547 (setq timestr 'time))
18548 (if (and donep
18549 (or org-agenda-skip-scheduled-if-done
18550 (not (= diff 0))))
18551 (setq txt nil)
18552 (setq txt (org-format-agenda-item
18553 (if (= diff 0)
18554 "Scheduled: "
18555 (format "Sched.%2dx: " (- 1 diff)))
18556 head category tags timestr))))
18557 (setq txt org-agenda-no-heading-message))
18558 (when txt
18559 (setq face (if pastschedp
18560 'org-scheduled-previously
18561 'org-scheduled-today))
18562 (org-add-props txt props
18563 'undone-face face
18564 'face (if donep 'org-done face)
18565 'org-marker (org-agenda-new-marker pos)
18566 'org-hd-marker (org-agenda-new-marker pos1)
18567 'type (if pastschedp "past-scheduled" "scheduled")
18568 'date (if pastschedp d2 date)
18569 'priority (+ (- 5 diff) (org-get-priority txt))
18570 'org-category category)
18571 (push txt ee))))))
18572 ee))
18574 (defun org-agenda-get-blocks ()
18575 "Return the date-range information for agenda display."
18576 (let* ((props (list 'face nil
18577 'org-not-done-regexp org-not-done-regexp
18578 'org-todo-regexp org-todo-regexp
18579 'mouse-face 'highlight
18580 'keymap org-agenda-keymap
18581 'help-echo
18582 (format "mouse-2 or RET jump to org file %s"
18583 (abbreviate-file-name buffer-file-name))))
18584 (regexp org-tr-regexp)
18585 (d0 (calendar-absolute-from-gregorian date))
18586 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
18587 (goto-char (point-min))
18588 (while (re-search-forward regexp nil t)
18589 (catch :skip
18590 (org-agenda-skip)
18591 (setq pos (point))
18592 (setq timestr (match-string 0)
18593 s1 (match-string 1)
18594 s2 (match-string 2)
18595 d1 (time-to-days (org-time-string-to-time s1))
18596 d2 (time-to-days (org-time-string-to-time s2)))
18597 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
18598 ;; Only allow days between the limits, because the normal
18599 ;; date stamps will catch the limits.
18600 (save-excursion
18601 (setq marker (org-agenda-new-marker (point)))
18602 (setq category (org-get-category))
18603 (if (re-search-backward "^\\*+ " nil t)
18604 (progn
18605 (goto-char (match-beginning 0))
18606 (setq hdmarker (org-agenda-new-marker (point)))
18607 (setq tags (org-get-tags-at))
18608 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
18609 (setq txt (org-format-agenda-item
18610 (format (if (= d1 d2) "" "(%d/%d): ")
18611 (1+ (- d0 d1)) (1+ (- d2 d1)))
18612 (match-string 1) category tags
18613 (if (= d0 d1) timestr))))
18614 (setq txt org-agenda-no-heading-message))
18615 (org-add-props txt props
18616 'org-marker marker 'org-hd-marker hdmarker
18617 'type "block" 'date date
18618 'priority (org-get-priority txt) 'org-category category)
18619 (push txt ee)))
18620 (goto-char pos)))
18621 ;; Sort the entries by expiration date.
18622 (nreverse ee)))
18624 ;;; Agenda presentation and sorting
18626 (defconst org-plain-time-of-day-regexp
18627 (concat
18628 "\\(\\<[012]?[0-9]"
18629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18630 "\\(--?"
18631 "\\(\\<[012]?[0-9]"
18632 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18633 "\\)?")
18634 "Regular expression to match a plain time or time range.
18635 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
18636 groups carry important information:
18637 0 the full match
18638 1 the first time, range or not
18639 8 the second time, if it is a range.")
18641 (defconst org-stamp-time-of-day-regexp
18642 (concat
18643 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
18644 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
18645 "\\(--?"
18646 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
18647 "Regular expression to match a timestamp time or time range.
18648 After a match, the following groups carry important information:
18649 0 the full match
18650 1 date plus weekday, for backreferencing to make sure both times on same day
18651 2 the first time, range or not
18652 4 the second time, if it is a range.")
18654 (defvar org-prefix-has-time nil
18655 "A flag, set by `org-compile-prefix-format'.
18656 The flag is set if the currently compiled format contains a `%t'.")
18657 (defvar org-prefix-has-tag nil
18658 "A flag, set by `org-compile-prefix-format'.
18659 The flag is set if the currently compiled format contains a `%T'.")
18661 (defun org-format-agenda-item (extra txt &optional category tags dotime
18662 noprefix)
18663 "Format TXT to be inserted into the agenda buffer.
18664 In particular, it adds the prefix and corresponding text properties. EXTRA
18665 must be a string and replaces the `%s' specifier in the prefix format.
18666 CATEGORY (string, symbol or nil) may be used to overrule the default
18667 category taken from local variable or file name. It will replace the `%c'
18668 specifier in the format. DOTIME, when non-nil, indicates that a
18669 time-of-day should be extracted from TXT for sorting of this entry, and for
18670 the `%t' specifier in the format. When DOTIME is a string, this string is
18671 searched for a time before TXT is. NOPREFIX is a flag and indicates that
18672 only the correctly processes TXT should be returned - this is used by
18673 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
18674 (save-match-data
18675 ;; Diary entries sometimes have extra whitespace at the beginning
18676 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
18677 (let* ((category (or category
18678 org-category
18679 (if buffer-file-name
18680 (file-name-sans-extension
18681 (file-name-nondirectory buffer-file-name))
18682 "")))
18683 (tag (if tags (nth (1- (length tags)) tags) ""))
18684 time ; time and tag are needed for the eval of the prefix format
18685 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
18686 (time-of-day (and dotime (org-get-time-of-day ts)))
18687 stamp plain s0 s1 s2 rtn srp)
18688 (when (and dotime time-of-day org-prefix-has-time)
18689 ;; Extract starting and ending time and move them to prefix
18690 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
18691 (setq plain (string-match org-plain-time-of-day-regexp ts)))
18692 (setq s0 (match-string 0 ts)
18693 srp (and stamp (match-end 3))
18694 s1 (match-string (if plain 1 2) ts)
18695 s2 (match-string (if plain 8 (if srp 4 6)) ts))
18697 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
18698 ;; them, we might want to remove them there to avoid duplication.
18699 ;; The user can turn this off with a variable.
18700 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
18701 (string-match (concat (regexp-quote s0) " *") txt)
18702 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
18703 (= (match-beginning 0) 0)
18705 (setq txt (replace-match "" nil nil txt))))
18706 ;; Normalize the time(s) to 24 hour
18707 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
18708 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
18710 (when (and s1 (not s2) org-agenda-default-appointment-duration
18711 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
18712 (let ((m (+ (string-to-number (match-string 2 s1))
18713 (* 60 (string-to-number (match-string 1 s1)))
18714 org-agenda-default-appointment-duration))
18716 (setq h (/ m 60) m (- m (* h 60)))
18717 (setq s2 (format "%02d:%02d" h m))))
18719 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
18720 txt)
18721 ;; Tags are in the string
18722 (if (or (eq org-agenda-remove-tags t)
18723 (and org-agenda-remove-tags
18724 org-prefix-has-tag))
18725 (setq txt (replace-match "" t t txt))
18726 (setq txt (replace-match
18727 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
18728 (match-string 2 txt))
18729 t t txt))))
18731 ;; Create the final string
18732 (if noprefix
18733 (setq rtn txt)
18734 ;; Prepare the variables needed in the eval of the compiled format
18735 (setq time (cond (s2 (concat s1 "-" s2))
18736 (s1 (concat s1 "......"))
18737 (t ""))
18738 extra (or extra "")
18739 category (if (symbolp category) (symbol-name category) category))
18740 ;; Evaluate the compiled format
18741 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
18743 ;; And finally add the text properties
18744 (org-add-props rtn nil
18745 'org-category (downcase category) 'tags tags
18746 'prefix-length (- (length rtn) (length txt))
18747 'time-of-day time-of-day
18748 'txt txt
18749 'time time
18750 'extra extra
18751 'dotime dotime))))
18753 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
18754 (defvar org-agenda-sorting-strategy-selected nil)
18756 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
18757 (catch 'exit
18758 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
18759 ((and todayp (member 'today (car org-agenda-time-grid))))
18760 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
18761 ((member 'weekly (car org-agenda-time-grid)))
18762 (t (throw 'exit list)))
18763 (let* ((have (delq nil (mapcar
18764 (lambda (x) (get-text-property 1 'time-of-day x))
18765 list)))
18766 (string (nth 1 org-agenda-time-grid))
18767 (gridtimes (nth 2 org-agenda-time-grid))
18768 (req (car org-agenda-time-grid))
18769 (remove (member 'remove-match req))
18770 new time)
18771 (if (and (member 'require-timed req) (not have))
18772 ;; don't show empty grid
18773 (throw 'exit list))
18774 (while (setq time (pop gridtimes))
18775 (unless (and remove (member time have))
18776 (setq time (int-to-string time))
18777 (push (org-format-agenda-item
18778 nil string "" nil
18779 (concat (substring time 0 -2) ":" (substring time -2)))
18780 new)
18781 (put-text-property
18782 1 (length (car new)) 'face 'org-time-grid (car new))))
18783 (if (member 'time-up org-agenda-sorting-strategy-selected)
18784 (append new list)
18785 (append list new)))))
18787 (defun org-compile-prefix-format (key)
18788 "Compile the prefix format into a Lisp form that can be evaluated.
18789 The resulting form is returned and stored in the variable
18790 `org-prefix-format-compiled'."
18791 (setq org-prefix-has-time nil org-prefix-has-tag nil)
18792 (let ((s (cond
18793 ((stringp org-agenda-prefix-format)
18794 org-agenda-prefix-format)
18795 ((assq key org-agenda-prefix-format)
18796 (cdr (assq key org-agenda-prefix-format)))
18797 (t " %-12:c%?-12t% s")))
18798 (start 0)
18799 varform vars var e c f opt)
18800 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
18801 s start)
18802 (setq var (cdr (assoc (match-string 4 s)
18803 '(("c" . category) ("t" . time) ("s" . extra)
18804 ("T" . tag))))
18805 c (or (match-string 3 s) "")
18806 opt (match-beginning 1)
18807 start (1+ (match-beginning 0)))
18808 (if (equal var 'time) (setq org-prefix-has-time t))
18809 (if (equal var 'tag) (setq org-prefix-has-tag t))
18810 (setq f (concat "%" (match-string 2 s) "s"))
18811 (if opt
18812 (setq varform
18813 `(if (equal "" ,var)
18815 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
18816 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
18817 (setq s (replace-match "%s" t nil s))
18818 (push varform vars))
18819 (setq vars (nreverse vars))
18820 (setq org-prefix-format-compiled `(format ,s ,@vars))))
18822 (defun org-set-sorting-strategy (key)
18823 (if (symbolp (car org-agenda-sorting-strategy))
18824 ;; the old format
18825 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
18826 (setq org-agenda-sorting-strategy-selected
18827 (or (cdr (assq key org-agenda-sorting-strategy))
18828 (cdr (assq 'agenda org-agenda-sorting-strategy))
18829 '(time-up category-keep priority-down)))))
18831 (defun org-get-time-of-day (s &optional string mod24)
18832 "Check string S for a time of day.
18833 If found, return it as a military time number between 0 and 2400.
18834 If not found, return nil.
18835 The optional STRING argument forces conversion into a 5 character wide string
18836 HH:MM."
18837 (save-match-data
18838 (when
18840 (string-match
18841 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
18842 (string-match
18843 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
18844 (let* ((h (string-to-number (match-string 1 s)))
18845 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
18846 (ampm (if (match-end 4) (downcase (match-string 4 s))))
18847 (am-p (equal ampm "am"))
18848 (h1 (cond ((not ampm) h)
18849 ((= h 12) (if am-p 0 12))
18850 (t (+ h (if am-p 0 12)))))
18851 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
18852 (mod h1 24) h1))
18853 (t0 (+ (* 100 h2) m))
18854 (t1 (concat (if (>= h1 24) "+" " ")
18855 (if (< t0 100) "0" "")
18856 (if (< t0 10) "0" "")
18857 (int-to-string t0))))
18858 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
18860 (defun org-finalize-agenda-entries (list &optional nosort)
18861 "Sort and concatenate the agenda items."
18862 (setq list (mapcar 'org-agenda-highlight-todo list))
18863 (if nosort
18864 list
18865 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
18867 (defun org-agenda-highlight-todo (x)
18868 (let (re pl)
18869 (if (eq x 'line)
18870 (save-excursion
18871 (beginning-of-line 1)
18872 (setq re (get-text-property (point) 'org-todo-regexp))
18873 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
18874 (and (looking-at (concat "[ \t]*\\.*" re))
18875 (add-text-properties (match-beginning 0) (match-end 0)
18876 (list 'face (org-get-todo-face 0)))))
18877 (setq re (concat (get-text-property 0 'org-todo-regexp x))
18878 pl (get-text-property 0 'prefix-length x))
18879 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
18880 (add-text-properties
18881 (or (match-end 1) (match-end 0)) (match-end 0)
18882 (list 'face (org-get-todo-face (match-string 2 x)))
18884 x)))
18886 (defsubst org-cmp-priority (a b)
18887 "Compare the priorities of string A and B."
18888 (let ((pa (or (get-text-property 1 'priority a) 0))
18889 (pb (or (get-text-property 1 'priority b) 0)))
18890 (cond ((> pa pb) +1)
18891 ((< pa pb) -1)
18892 (t nil))))
18894 (defsubst org-cmp-category (a b)
18895 "Compare the string values of categories of strings A and B."
18896 (let ((ca (or (get-text-property 1 'org-category a) ""))
18897 (cb (or (get-text-property 1 'org-category b) "")))
18898 (cond ((string-lessp ca cb) -1)
18899 ((string-lessp cb ca) +1)
18900 (t nil))))
18902 (defsubst org-cmp-tag (a b)
18903 "Compare the string values of categories of strings A and B."
18904 (let ((ta (car (last (get-text-property 1 'tags a))))
18905 (tb (car (last (get-text-property 1 'tags b)))))
18906 (cond ((not ta) +1)
18907 ((not tb) -1)
18908 ((string-lessp ta tb) -1)
18909 ((string-lessp tb ta) +1)
18910 (t nil))))
18912 (defsubst org-cmp-time (a b)
18913 "Compare the time-of-day values of strings A and B."
18914 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
18915 (ta (or (get-text-property 1 'time-of-day a) def))
18916 (tb (or (get-text-property 1 'time-of-day b) def)))
18917 (cond ((< ta tb) -1)
18918 ((< tb ta) +1)
18919 (t nil))))
18921 (defun org-entries-lessp (a b)
18922 "Predicate for sorting agenda entries."
18923 ;; The following variables will be used when the form is evaluated.
18924 ;; So even though the compiler complains, keep them.
18925 (let* ((time-up (org-cmp-time a b))
18926 (time-down (if time-up (- time-up) nil))
18927 (priority-up (org-cmp-priority a b))
18928 (priority-down (if priority-up (- priority-up) nil))
18929 (category-up (org-cmp-category a b))
18930 (category-down (if category-up (- category-up) nil))
18931 (category-keep (if category-up +1 nil))
18932 (tag-up (org-cmp-tag a b))
18933 (tag-down (if tag-up (- tag-up) nil)))
18934 (cdr (assoc
18935 (eval (cons 'or org-agenda-sorting-strategy-selected))
18936 '((-1 . t) (1 . nil) (nil . nil))))))
18938 ;;; Agenda commands
18940 (defun org-agenda-check-type (error &rest types)
18941 "Check if agenda buffer is of allowed type.
18942 If ERROR is non-nil, throw an error, otherwise just return nil."
18943 (if (memq org-agenda-type types)
18945 (if error
18946 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
18947 nil)))
18949 (defun org-agenda-quit ()
18950 "Exit agenda by removing the window or the buffer."
18951 (interactive)
18952 (let ((buf (current-buffer)))
18953 (if (not (one-window-p)) (delete-window))
18954 (kill-buffer buf)
18955 (org-agenda-maybe-reset-markers 'force)
18956 (org-columns-remove-overlays))
18957 ;; Maybe restore the pre-agenda window configuration.
18958 (and org-agenda-restore-windows-after-quit
18959 (not (eq org-agenda-window-setup 'other-frame))
18960 org-pre-agenda-window-conf
18961 (set-window-configuration org-pre-agenda-window-conf)))
18963 (defun org-agenda-exit ()
18964 "Exit agenda by removing the window or the buffer.
18965 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
18966 Org-mode buffers visited directly by the user will not be touched."
18967 (interactive)
18968 (org-release-buffers org-agenda-new-buffers)
18969 (setq org-agenda-new-buffers nil)
18970 (org-agenda-quit))
18972 (defun org-save-all-org-buffers ()
18973 "Save all Org-mode buffers without user confirmation."
18974 (interactive)
18975 (message "Saving all Org-mode buffers...")
18976 (save-some-buffers t 'org-mode-p)
18977 (message "Saving all Org-mode buffers... done"))
18979 (defun org-agenda-redo ()
18980 "Rebuild Agenda.
18981 When this is the global TODO list, a prefix argument will be interpreted."
18982 (interactive)
18983 (let* ((org-agenda-keep-modes t)
18984 (line (org-current-line))
18985 (window-line (- line (org-current-line (window-start))))
18986 (lprops (get 'org-agenda-redo-command 'org-lprops)))
18987 (message "Rebuilding agenda buffer...")
18988 (org-let lprops '(eval org-agenda-redo-command))
18989 (setq org-agenda-undo-list nil
18990 org-agenda-pending-undo-list nil)
18991 (message "Rebuilding agenda buffer...done")
18992 (goto-line line)
18993 (recenter window-line)))
18995 (defun org-agenda-goto-date (date)
18996 "Jump to DATE in agenda."
18997 (interactive (list (org-read-date)))
18998 (org-agenda-list nil date))
19000 (defun org-agenda-goto-today ()
19001 "Go to today."
19002 (interactive)
19003 (org-agenda-check-type t 'timeline 'agenda)
19004 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
19005 (cond
19006 (tdpos (goto-char tdpos))
19007 ((eq org-agenda-type 'agenda)
19008 (let* ((sd (time-to-days (current-time)))
19009 (comp (org-agenda-compute-time-span sd org-agenda-span))
19010 (org-agenda-overriding-arguments org-agenda-last-arguments))
19011 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
19012 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
19013 (org-agenda-redo)
19014 (org-agenda-find-today-or-agenda)))
19015 (t (error "Cannot find today")))))
19017 (defun org-agenda-find-today-or-agenda ()
19018 (goto-char
19019 (or (text-property-any (point-min) (point-max) 'org-today t)
19020 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
19021 (point-min))))
19023 (defun org-agenda-later (arg)
19024 "Go forward in time by thee current span.
19025 With prefix ARG, go forward that many times the current span."
19026 (interactive "p")
19027 (org-agenda-check-type t 'agenda)
19028 (let* ((span org-agenda-span)
19029 (sd org-starting-day)
19030 (greg (calendar-gregorian-from-absolute sd))
19031 greg2 nd)
19032 (cond
19033 ((eq span 'day)
19034 (setq sd (+ arg sd) nd 1))
19035 ((eq span 'week)
19036 (setq sd (+ (* 7 arg) sd) nd 7))
19037 ((eq span 'month)
19038 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
19039 sd (calendar-absolute-from-gregorian greg2))
19040 (setcar greg2 (1+ (car greg2)))
19041 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
19042 ((eq span 'year)
19043 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
19044 sd (calendar-absolute-from-gregorian greg2))
19045 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
19046 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
19047 (let ((org-agenda-overriding-arguments
19048 (list (car org-agenda-last-arguments) sd nd t)))
19049 (org-agenda-redo)
19050 (org-agenda-find-today-or-agenda))))
19052 (defun org-agenda-earlier (arg)
19053 "Go backward in time by the current span.
19054 With prefix ARG, go backward that many times the current span."
19055 (interactive "p")
19056 (org-agenda-later (- arg)))
19058 (defun org-agenda-day-view ()
19059 "Switch to daily view for agenda."
19060 (interactive)
19061 (setq org-agenda-ndays 1)
19062 (org-agenda-change-time-span 'day))
19063 (defun org-agenda-week-view ()
19064 "Switch to daily view for agenda."
19065 (interactive)
19066 (setq org-agenda-ndays 7)
19067 (org-agenda-change-time-span 'week))
19068 (defun org-agenda-month-view ()
19069 "Switch to daily view for agenda."
19070 (interactive)
19071 (org-agenda-change-time-span 'month))
19072 (defun org-agenda-year-view ()
19073 "Switch to daily view for agenda."
19074 (interactive)
19075 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
19076 (org-agenda-change-time-span 'year)
19077 (error "Abort")))
19079 (defun org-agenda-change-time-span (span)
19080 "Change the agenda view to SPAN.
19081 SPAN may be `day', `week', `month', `year'."
19082 (org-agenda-check-type t 'agenda)
19083 (if (equal org-agenda-span span)
19084 (error "Viewing span is already \"%s\"" span))
19085 (let* ((sd (or (get-text-property (point) 'day)
19086 org-starting-day))
19087 (computed (org-agenda-compute-time-span sd span))
19088 (org-agenda-overriding-arguments
19089 (list (car org-agenda-last-arguments)
19090 (car computed) (cdr computed) t)))
19091 (org-agenda-redo)
19092 (org-agenda-find-today-or-agenda))
19093 (org-agenda-set-mode-name)
19094 (message "Switched to %s view" span))
19096 (defun org-agenda-compute-time-span (sd span)
19097 "Compute starting date and number of days for agenda.
19098 SPAN may be `day', `week', `month', `year'. The return value
19099 is a cons cell with the starting date and the number of days,
19100 so that the date SD will be in that range."
19101 (let* ((greg (calendar-gregorian-from-absolute sd))
19103 (cond
19104 ((eq span 'day)
19105 (setq nd 1))
19106 ((eq span 'week)
19107 (let* ((nt (calendar-day-of-week
19108 (calendar-gregorian-from-absolute sd)))
19109 (d (if org-agenda-start-on-weekday
19110 (- nt org-agenda-start-on-weekday)
19111 0)))
19112 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
19113 (setq nd 7)))
19114 ((eq span 'month)
19115 (setq sd (calendar-absolute-from-gregorian
19116 (list (car greg) 1 (nth 2 greg)))
19117 nd (- (calendar-absolute-from-gregorian
19118 (list (1+ (car greg)) 1 (nth 2 greg)))
19119 sd)))
19120 ((eq span 'year)
19121 (setq sd (calendar-absolute-from-gregorian
19122 (list 1 1 (nth 2 greg)))
19123 nd (- (calendar-absolute-from-gregorian
19124 (list 1 1 (1+ (nth 2 greg))))
19125 sd))))
19126 (cons sd nd)))
19128 ;; FIXME: this no longer works if user make date format that starts with a blank
19129 (defun org-agenda-next-date-line (&optional arg)
19130 "Jump to the next line indicating a date in agenda buffer."
19131 (interactive "p")
19132 (org-agenda-check-type t 'agenda 'timeline)
19133 (beginning-of-line 1)
19134 (if (looking-at "^\\S-") (forward-char 1))
19135 (if (not (re-search-forward "^\\S-" nil t arg))
19136 (progn
19137 (backward-char 1)
19138 (error "No next date after this line in this buffer")))
19139 (goto-char (match-beginning 0)))
19141 (defun org-agenda-previous-date-line (&optional arg)
19142 "Jump to the previous line indicating a date in agenda buffer."
19143 (interactive "p")
19144 (org-agenda-check-type t 'agenda 'timeline)
19145 (beginning-of-line 1)
19146 (if (not (re-search-backward "^\\S-" nil t arg))
19147 (error "No previous date before this line in this buffer")))
19149 ;; Initialize the highlight
19150 (defvar org-hl (org-make-overlay 1 1))
19151 (org-overlay-put org-hl 'face 'highlight)
19153 (defun org-highlight (begin end &optional buffer)
19154 "Highlight a region with overlay."
19155 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
19156 org-hl begin end (or buffer (current-buffer))))
19158 (defun org-unhighlight ()
19159 "Detach overlay INDEX."
19160 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
19162 ;; FIXME this is currently not used.
19163 (defun org-highlight-until-next-command (beg end &optional buffer)
19164 (org-highlight beg end buffer)
19165 (add-hook 'pre-command-hook 'org-unhighlight-once))
19167 (defun org-unhighlight-once ()
19168 (remove-hook 'pre-command-hook 'org-unhighlight-once)
19169 (org-unhighlight))
19171 (defun org-agenda-follow-mode ()
19172 "Toggle follow mode in an agenda buffer."
19173 (interactive)
19174 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
19175 (org-agenda-set-mode-name)
19176 (message "Follow mode is %s"
19177 (if org-agenda-follow-mode "on" "off")))
19179 (defun org-agenda-log-mode ()
19180 "Toggle log mode in an agenda buffer."
19181 (interactive)
19182 (org-agenda-check-type t 'agenda 'timeline)
19183 (setq org-agenda-show-log (not org-agenda-show-log))
19184 (org-agenda-set-mode-name)
19185 (org-agenda-redo)
19186 (message "Log mode is %s"
19187 (if org-agenda-show-log "on" "off")))
19189 (defun org-agenda-toggle-diary ()
19190 "Toggle diary inclusion in an agenda buffer."
19191 (interactive)
19192 (org-agenda-check-type t 'agenda)
19193 (setq org-agenda-include-diary (not org-agenda-include-diary))
19194 (org-agenda-redo)
19195 (org-agenda-set-mode-name)
19196 (message "Diary inclusion turned %s"
19197 (if org-agenda-include-diary "on" "off")))
19199 (defun org-agenda-toggle-time-grid ()
19200 "Toggle time grid in an agenda buffer."
19201 (interactive)
19202 (org-agenda-check-type t 'agenda)
19203 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
19204 (org-agenda-redo)
19205 (org-agenda-set-mode-name)
19206 (message "Time-grid turned %s"
19207 (if org-agenda-use-time-grid "on" "off")))
19209 (defun org-agenda-set-mode-name ()
19210 "Set the mode name to indicate all the small mode settings."
19211 (setq mode-name
19212 (concat "Org-Agenda"
19213 (if (equal org-agenda-ndays 1) " Day" "")
19214 (if (equal org-agenda-ndays 7) " Week" "")
19215 (if org-agenda-follow-mode " Follow" "")
19216 (if org-agenda-include-diary " Diary" "")
19217 (if org-agenda-use-time-grid " Grid" "")
19218 (if org-agenda-show-log " Log" "")))
19219 (force-mode-line-update))
19221 (defun org-agenda-post-command-hook ()
19222 (and (eolp) (not (bolp)) (backward-char 1))
19223 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
19224 (if (and org-agenda-follow-mode
19225 (get-text-property (point) 'org-marker))
19226 (org-agenda-show)))
19228 (defun org-agenda-show-priority ()
19229 "Show the priority of the current item.
19230 This priority is composed of the main priority given with the [#A] cookies,
19231 and by additional input from the age of a schedules or deadline entry."
19232 (interactive)
19233 (let* ((pri (get-text-property (point-at-bol) 'priority)))
19234 (message "Priority is %d" (if pri pri -1000))))
19236 (defun org-agenda-show-tags ()
19237 "Show the tags applicable to the current item."
19238 (interactive)
19239 (let* ((tags (get-text-property (point-at-bol) 'tags)))
19240 (if tags
19241 (message "Tags are :%s:"
19242 (org-no-properties (mapconcat 'identity tags ":")))
19243 (message "No tags associated with this line"))))
19245 (defun org-agenda-goto (&optional highlight)
19246 "Go to the Org-mode file which contains the item at point."
19247 (interactive)
19248 (let* ((marker (or (get-text-property (point) 'org-marker)
19249 (org-agenda-error)))
19250 (buffer (marker-buffer marker))
19251 (pos (marker-position marker)))
19252 (switch-to-buffer-other-window buffer)
19253 (widen)
19254 (goto-char pos)
19255 (when (org-mode-p)
19256 (org-show-context 'agenda)
19257 (save-excursion
19258 (and (outline-next-heading)
19259 (org-flag-heading nil)))) ; show the next heading
19260 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
19262 (defun org-agenda-kill ()
19263 "Kill the entry or subtree belonging to the current agenda entry."
19264 (interactive)
19265 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19266 (let* ((marker (or (get-text-property (point) 'org-marker)
19267 (org-agenda-error)))
19268 (buffer (marker-buffer marker))
19269 (pos (marker-position marker))
19270 (type (get-text-property (point) 'type))
19271 dbeg dend (n 0) conf)
19272 (org-with-remote-undo buffer
19273 (with-current-buffer buffer
19274 (save-excursion
19275 (goto-char pos)
19276 (if (and (org-mode-p) (not (member type '("sexp"))))
19277 (setq dbeg (progn (org-back-to-heading t) (point))
19278 dend (org-end-of-subtree t t))
19279 (setq dbeg (point-at-bol)
19280 dend (min (point-max) (1+ (point-at-eol)))))
19281 (goto-char dbeg)
19282 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
19283 (setq conf (or (eq t org-agenda-confirm-kill)
19284 (and (numberp org-agenda-confirm-kill)
19285 (> n org-agenda-confirm-kill))))
19286 (and conf
19287 (not (y-or-n-p
19288 (format "Delete entry with %d lines in buffer \"%s\"? "
19289 n (buffer-name buffer))))
19290 (error "Abort"))
19291 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
19292 (with-current-buffer buffer (delete-region dbeg dend))
19293 (message "Agenda item and source killed"))))
19295 (defun org-agenda-archive ()
19296 "Kill the entry or subtree belonging to the current agenda entry."
19297 (interactive)
19298 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
19299 (let* ((marker (or (get-text-property (point) 'org-marker)
19300 (org-agenda-error)))
19301 (buffer (marker-buffer marker))
19302 (pos (marker-position marker)))
19303 (org-with-remote-undo buffer
19304 (with-current-buffer buffer
19305 (if (org-mode-p)
19306 (save-excursion
19307 (goto-char pos)
19308 (org-remove-subtree-entries-from-agenda)
19309 (org-back-to-heading t)
19310 (org-archive-subtree))
19311 (error "Archiving works only in Org-mode files"))))))
19313 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
19314 "Remove all lines in the agenda that correspond to a given subtree.
19315 The subtree is the one in buffer BUF, starting at BEG and ending at END.
19316 If this information is not given, the function uses the tree at point."
19317 (let ((buf (or buf (current-buffer))) m p)
19318 (save-excursion
19319 (unless (and beg end)
19320 (org-back-to-heading t)
19321 (setq beg (point))
19322 (org-end-of-subtree t)
19323 (setq end (point)))
19324 (set-buffer (get-buffer org-agenda-buffer-name))
19325 (save-excursion
19326 (goto-char (point-max))
19327 (beginning-of-line 1)
19328 (while (not (bobp))
19329 (when (and (setq m (get-text-property (point) 'org-marker))
19330 (equal buf (marker-buffer m))
19331 (setq p (marker-position m))
19332 (>= p beg)
19333 (<= p end))
19334 (let ((inhibit-read-only t))
19335 (delete-region (point-at-bol) (1+ (point-at-eol)))))
19336 (beginning-of-line 0))))))
19338 (defun org-agenda-open-link ()
19339 "Follow the link in the current line, if any."
19340 (interactive)
19341 (let ((eol (point-at-eol)))
19342 (save-excursion
19343 (if (or (re-search-forward org-bracket-link-regexp eol t)
19344 (re-search-forward org-angle-link-re eol t)
19345 (re-search-forward org-plain-link-re eol t))
19346 (call-interactively 'org-open-at-point)
19347 (error "No link in current line")))))
19349 (defun org-agenda-switch-to (&optional delete-other-windows)
19350 "Go to the Org-mode file which contains the item at point."
19351 (interactive)
19352 (let* ((marker (or (get-text-property (point) 'org-marker)
19353 (org-agenda-error)))
19354 (buffer (marker-buffer marker))
19355 (pos (marker-position marker)))
19356 (switch-to-buffer buffer)
19357 (and delete-other-windows (delete-other-windows))
19358 (widen)
19359 (goto-char pos)
19360 (when (org-mode-p)
19361 (org-show-context 'agenda)
19362 (save-excursion
19363 (and (outline-next-heading)
19364 (org-flag-heading nil)))))) ; show the next heading
19366 (defun org-agenda-goto-mouse (ev)
19367 "Go to the Org-mode file which contains the item at the mouse click."
19368 (interactive "e")
19369 (mouse-set-point ev)
19370 (org-agenda-goto))
19372 (defun org-agenda-show ()
19373 "Display the Org-mode file which contains the item at point."
19374 (interactive)
19375 (let ((win (selected-window)))
19376 (org-agenda-goto t)
19377 (select-window win)))
19379 (defun org-agenda-recenter (arg)
19380 "Display the Org-mode file which contains the item at point and recenter."
19381 (interactive "P")
19382 (let ((win (selected-window)))
19383 (org-agenda-goto t)
19384 (recenter arg)
19385 (select-window win)))
19387 (defun org-agenda-show-mouse (ev)
19388 "Display the Org-mode file which contains the item at the mouse click."
19389 (interactive "e")
19390 (mouse-set-point ev)
19391 (org-agenda-show))
19393 (defun org-agenda-check-no-diary ()
19394 "Check if the entry is a diary link and abort if yes."
19395 (if (get-text-property (point) 'org-agenda-diary-link)
19396 (org-agenda-error)))
19398 (defun org-agenda-error ()
19399 (error "Command not allowed in this line"))
19401 (defun org-agenda-tree-to-indirect-buffer ()
19402 "Show the subtree corresponding to the current entry in an indirect buffer.
19403 This calls the command `org-tree-to-indirect-buffer' from the original
19404 Org-mode buffer.
19405 With numerical prefix arg ARG, go up to this level and then take that tree.
19406 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
19407 dedicated frame)."
19408 (interactive)
19409 (org-agenda-check-no-diary)
19410 (let* ((marker (or (get-text-property (point) 'org-marker)
19411 (org-agenda-error)))
19412 (buffer (marker-buffer marker))
19413 (pos (marker-position marker)))
19414 (with-current-buffer buffer
19415 (save-excursion
19416 (goto-char pos)
19417 (call-interactively 'org-tree-to-indirect-buffer)))))
19419 (defvar org-last-heading-marker (make-marker)
19420 "Marker pointing to the headline that last changed its TODO state
19421 by a remote command from the agenda.")
19423 (defun org-agenda-todo-nextset ()
19424 "Switch TODO entry to next sequence."
19425 (interactive)
19426 (org-agenda-todo 'nextset))
19428 (defun org-agenda-todo-previousset ()
19429 "Switch TODO entry to previous sequence."
19430 (interactive)
19431 (org-agenda-todo 'previousset))
19433 (defun org-agenda-todo (&optional arg)
19434 "Cycle TODO state of line at point, also in Org-mode file.
19435 This changes the line at point, all other lines in the agenda referring to
19436 the same tree node, and the headline of the tree node in the Org-mode file."
19437 (interactive "P")
19438 (org-agenda-check-no-diary)
19439 (let* ((col (current-column))
19440 (marker (or (get-text-property (point) 'org-marker)
19441 (org-agenda-error)))
19442 (buffer (marker-buffer marker))
19443 (pos (marker-position marker))
19444 (hdmarker (get-text-property (point) 'org-hd-marker))
19445 (inhibit-read-only t)
19446 newhead)
19447 (org-with-remote-undo buffer
19448 (with-current-buffer buffer
19449 (widen)
19450 (goto-char pos)
19451 (org-show-context 'agenda)
19452 (save-excursion
19453 (and (outline-next-heading)
19454 (org-flag-heading nil))) ; show the next heading
19455 (org-todo arg)
19456 (and (bolp) (forward-char 1))
19457 (setq newhead (org-get-heading))
19458 (save-excursion
19459 (org-back-to-heading)
19460 (move-marker org-last-heading-marker (point))))
19461 (beginning-of-line 1)
19462 (save-excursion
19463 (org-agenda-change-all-lines newhead hdmarker 'fixface))
19464 (move-to-column col))))
19466 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
19467 "Change all lines in the agenda buffer which match HDMARKER.
19468 The new content of the line will be NEWHEAD (as modified by
19469 `org-format-agenda-item'). HDMARKER is checked with
19470 `equal' against all `org-hd-marker' text properties in the file.
19471 If FIXFACE is non-nil, the face of each item is modified acording to
19472 the new TODO state."
19473 (let* ((inhibit-read-only t)
19474 props m pl undone-face done-face finish new dotime cat tags)
19475 (save-excursion
19476 (goto-char (point-max))
19477 (beginning-of-line 1)
19478 (while (not finish)
19479 (setq finish (bobp))
19480 (when (and (setq m (get-text-property (point) 'org-hd-marker))
19481 (equal m hdmarker))
19482 (setq props (text-properties-at (point))
19483 dotime (get-text-property (point) 'dotime)
19484 cat (get-text-property (point) 'org-category)
19485 tags (get-text-property (point) 'tags)
19486 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
19487 pl (get-text-property (point) 'prefix-length)
19488 undone-face (get-text-property (point) 'undone-face)
19489 done-face (get-text-property (point) 'done-face))
19490 (move-to-column pl)
19491 (cond
19492 ((equal new "")
19493 (beginning-of-line 1)
19494 (and (looking-at ".*\n?") (replace-match "")))
19495 ((looking-at ".*")
19496 (replace-match new t t)
19497 (beginning-of-line 1)
19498 (add-text-properties (point-at-bol) (point-at-eol) props)
19499 (when fixface
19500 (add-text-properties
19501 (point-at-bol) (point-at-eol)
19502 (list 'face
19503 (if org-last-todo-state-is-todo
19504 undone-face done-face))))
19505 (org-agenda-highlight-todo 'line)
19506 (beginning-of-line 1))
19507 (t (error "Line update did not work"))))
19508 (beginning-of-line 0)))
19509 (org-finalize-agenda)))
19511 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
19512 ;; See the code in set-tags for the way to do this.
19513 (defun org-agenda-align-tags (&optional line)
19514 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
19515 (let ((inhibit-read-only t))
19516 (save-excursion
19517 (goto-char (if line (point-at-bol) (point-min)))
19518 (while (re-search-forward (org-re "\\([ \t]+\\):[[:alnum:]_@:]+:[ \t]*$")
19519 (if line (point-at-eol) nil) t)
19520 (delete-region (match-beginning 1) (match-end 1))
19521 (goto-char (match-beginning 1))
19522 (insert (org-add-props
19523 (make-string (max 1 (- org-agenda-align-tags-to-column
19524 (current-column))) ?\ )
19525 (text-properties-at (point))))))))
19527 (defun org-agenda-priority-up ()
19528 "Increase the priority of line at point, also in Org-mode file."
19529 (interactive)
19530 (org-agenda-priority 'up))
19532 (defun org-agenda-priority-down ()
19533 "Decrease the priority of line at point, also in Org-mode file."
19534 (interactive)
19535 (org-agenda-priority 'down))
19537 (defun org-agenda-priority (&optional force-direction)
19538 "Set the priority of line at point, also in Org-mode file.
19539 This changes the line at point, all other lines in the agenda referring to
19540 the same tree node, and the headline of the tree node in the Org-mode file."
19541 (interactive)
19542 (org-agenda-check-no-diary)
19543 (let* ((marker (or (get-text-property (point) 'org-marker)
19544 (org-agenda-error)))
19545 (hdmarker (get-text-property (point) 'org-hd-marker))
19546 (buffer (marker-buffer hdmarker))
19547 (pos (marker-position hdmarker))
19548 (inhibit-read-only t)
19549 newhead)
19550 (org-with-remote-undo buffer
19551 (with-current-buffer buffer
19552 (widen)
19553 (goto-char pos)
19554 (org-show-context 'agenda)
19555 (save-excursion
19556 (and (outline-next-heading)
19557 (org-flag-heading nil))) ; show the next heading
19558 (funcall 'org-priority force-direction)
19559 (end-of-line 1)
19560 (setq newhead (org-get-heading)))
19561 (org-agenda-change-all-lines newhead hdmarker)
19562 (beginning-of-line 1))))
19564 (defun org-get-tags-at (&optional pos)
19565 "Get a list of all headline tags applicable at POS.
19566 POS defaults to point. If tags are inherited, the list contains
19567 the targets in the same sequence as the headlines appear, i.e.
19568 the tags of the current headline come last."
19569 (interactive)
19570 (let (tags lastpos)
19571 (save-excursion
19572 (save-restriction
19573 (widen)
19574 (goto-char (or pos (point)))
19575 (save-match-data
19576 (org-back-to-heading t)
19577 (condition-case nil
19578 (while (not (equal lastpos (point)))
19579 (setq lastpos (point))
19580 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
19581 (setq tags (append (org-split-string
19582 (org-match-string-no-properties 1) ":")
19583 tags)))
19584 (or org-use-tag-inheritance (error ""))
19585 (org-up-heading-all 1))
19586 (error nil))))
19587 tags)))
19589 ;; FIXME: should fix the tags property of the agenda line.
19590 (defun org-agenda-set-tags ()
19591 "Set tags for the current headline."
19592 (interactive)
19593 (org-agenda-check-no-diary)
19594 (if (and (org-region-active-p) (interactive-p))
19595 (call-interactively 'org-change-tag-in-region)
19596 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19597 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19598 (org-agenda-error)))
19599 (buffer (marker-buffer hdmarker))
19600 (pos (marker-position hdmarker))
19601 (inhibit-read-only t)
19602 newhead)
19603 (org-with-remote-undo buffer
19604 (with-current-buffer buffer
19605 (widen)
19606 (goto-char pos)
19607 (save-excursion
19608 (org-show-context 'agenda))
19609 (save-excursion
19610 (and (outline-next-heading)
19611 (org-flag-heading nil))) ; show the next heading
19612 (goto-char pos)
19613 (call-interactively 'org-set-tags)
19614 (end-of-line 1)
19615 (setq newhead (org-get-heading)))
19616 (org-agenda-change-all-lines newhead hdmarker)
19617 (beginning-of-line 1)))))
19619 (defun org-agenda-toggle-archive-tag ()
19620 "Toggle the archive tag for the current entry."
19621 (interactive)
19622 (org-agenda-check-no-diary)
19623 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
19624 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
19625 (org-agenda-error)))
19626 (buffer (marker-buffer hdmarker))
19627 (pos (marker-position hdmarker))
19628 (inhibit-read-only t)
19629 newhead)
19630 (org-with-remote-undo buffer
19631 (with-current-buffer buffer
19632 (widen)
19633 (goto-char pos)
19634 (org-show-context 'agenda)
19635 (save-excursion
19636 (and (outline-next-heading)
19637 (org-flag-heading nil))) ; show the next heading
19638 (call-interactively 'org-toggle-archive-tag)
19639 (end-of-line 1)
19640 (setq newhead (org-get-heading)))
19641 (org-agenda-change-all-lines newhead hdmarker)
19642 (beginning-of-line 1))))
19644 (defun org-agenda-date-later (arg &optional what)
19645 "Change the date of this item to one day later."
19646 (interactive "p")
19647 (org-agenda-check-type t 'agenda 'timeline)
19648 (org-agenda-check-no-diary)
19649 (let* ((marker (or (get-text-property (point) 'org-marker)
19650 (org-agenda-error)))
19651 (buffer (marker-buffer marker))
19652 (pos (marker-position marker)))
19653 (org-with-remote-undo buffer
19654 (with-current-buffer buffer
19655 (widen)
19656 (goto-char pos)
19657 (if (not (org-at-timestamp-p))
19658 (error "Cannot find time stamp"))
19659 (org-timestamp-change arg (or what 'day)))
19660 (org-agenda-show-new-time marker org-last-changed-timestamp))
19661 (message "Time stamp changed to %s" org-last-changed-timestamp)))
19663 (defun org-agenda-date-earlier (arg &optional what)
19664 "Change the date of this item to one day earlier."
19665 (interactive "p")
19666 (org-agenda-date-later (- arg) what))
19668 (defun org-agenda-show-new-time (marker stamp)
19669 "Show new date stamp via text properties."
19670 ;; We use text properties to make this undoable
19671 (let ((inhibit-read-only t))
19672 (setq stamp (concat " => " stamp))
19673 (save-excursion
19674 (goto-char (point-max))
19675 (while (not (bobp))
19676 (when (equal marker (get-text-property (point) 'org-marker))
19677 (move-to-column (- (window-width) (length stamp)) t)
19678 (if (featurep 'xemacs)
19679 ;; Use `duplicable' property to trigger undo recording
19680 (let ((ex (make-extent nil nil))
19681 (gl (make-glyph stamp)))
19682 (set-glyph-face gl 'secondary-selection)
19683 (set-extent-properties
19684 ex (list 'invisible t 'end-glyph gl 'duplicable t))
19685 (insert-extent ex (1- (point)) (point-at-eol)))
19686 (add-text-properties
19687 (1- (point)) (point-at-eol)
19688 (list 'display (org-add-props stamp nil
19689 'face 'secondary-selection))))
19690 (beginning-of-line 1))
19691 (beginning-of-line 0)))))
19693 (defun org-agenda-date-prompt (arg)
19694 "Change the date of this item. Date is prompted for, with default today.
19695 The prefix ARG is passed to the `org-time-stamp' command and can therefore
19696 be used to request time specification in the time stamp."
19697 (interactive "P")
19698 (org-agenda-check-type t 'agenda 'timeline)
19699 (org-agenda-check-no-diary)
19700 (let* ((marker (or (get-text-property (point) 'org-marker)
19701 (org-agenda-error)))
19702 (buffer (marker-buffer marker))
19703 (pos (marker-position marker)))
19704 (org-with-remote-undo buffer
19705 (with-current-buffer buffer
19706 (widen)
19707 (goto-char pos)
19708 (if (not (org-at-timestamp-p))
19709 (error "Cannot find time stamp"))
19710 (org-time-stamp arg)
19711 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
19713 (defun org-agenda-schedule (arg)
19714 "Schedule the item at point."
19715 (interactive "P")
19716 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19717 (org-agenda-check-no-diary)
19718 (let* ((marker (or (get-text-property (point) 'org-marker)
19719 (org-agenda-error)))
19720 (buffer (marker-buffer marker))
19721 (pos (marker-position marker))
19722 (org-insert-labeled-timestamps-at-point nil)
19724 (org-with-remote-undo buffer
19725 (with-current-buffer buffer
19726 (widen)
19727 (goto-char pos)
19728 (setq ts (org-schedule))
19729 (message "Item scheduled for %s" ts)))))
19731 (defun org-agenda-deadline (arg)
19732 "Schedule the item at point."
19733 (interactive "P")
19734 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19735 (org-agenda-check-no-diary)
19736 (let* ((marker (or (get-text-property (point) 'org-marker)
19737 (org-agenda-error)))
19738 (buffer (marker-buffer marker))
19739 (pos (marker-position marker))
19740 (org-insert-labeled-timestamps-at-point nil)
19742 (org-with-remote-undo buffer
19743 (with-current-buffer buffer
19744 (widen)
19745 (goto-char pos)
19746 (setq ts (org-deadline))
19747 (message "Deadline for this item set to %s" ts)))))
19749 (defun org-get-heading ()
19750 "Return the heading of the current entry, without the stars."
19751 (save-excursion
19752 (org-back-to-heading t)
19753 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
19755 (defun org-agenda-clock-in (&optional arg)
19756 "Start the clock on the currently selected item."
19757 (interactive "P")
19758 (org-agenda-check-no-diary)
19759 (let* ((marker (or (get-text-property (point) 'org-marker)
19760 (org-agenda-error)))
19761 (pos (marker-position marker)))
19762 (org-with-remote-undo (marker-buffer marker)
19763 (with-current-buffer (marker-buffer marker)
19764 (widen)
19765 (goto-char pos)
19766 (org-clock-in)))))
19768 (defun org-agenda-clock-out (&optional arg)
19769 "Stop the currently running clock."
19770 (interactive "P")
19771 (unless (marker-buffer org-clock-marker)
19772 (error "No running clock"))
19773 (org-with-remote-undo (marker-buffer org-clock-marker)
19774 (org-clock-out)))
19776 (defun org-agenda-clock-cancel (&optional arg)
19777 "Cancel the currently running clock."
19778 (interactive "P")
19779 (unless (marker-buffer org-clock-marker)
19780 (error "No running clock"))
19781 (org-with-remote-undo (marker-buffer org-clock-marker)
19782 (org-clock-cancel)))
19784 (defun org-agenda-diary-entry ()
19785 "Make a diary entry, like the `i' command from the calendar.
19786 All the standard commands work: block, weekly etc."
19787 (interactive)
19788 (org-agenda-check-type t 'agenda 'timeline)
19789 (require 'diary-lib)
19790 (let* ((char (progn
19791 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
19792 (read-char-exclusive)))
19793 (cmd (cdr (assoc char
19794 '((?d . insert-diary-entry)
19795 (?w . insert-weekly-diary-entry)
19796 (?m . insert-monthly-diary-entry)
19797 (?y . insert-yearly-diary-entry)
19798 (?a . insert-anniversary-diary-entry)
19799 (?b . insert-block-diary-entry)
19800 (?c . insert-cyclic-diary-entry)))))
19801 (oldf (symbol-function 'calendar-cursor-to-date))
19802 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
19803 (point (point))
19804 (mark (or (mark t) (point))))
19805 (unless cmd
19806 (error "No command associated with <%c>" char))
19807 (unless (and (get-text-property point 'day)
19808 (or (not (equal ?b char))
19809 (get-text-property mark 'day)))
19810 (error "Don't know which date to use for diary entry"))
19811 ;; We implement this by hacking the `calendar-cursor-to-date' function
19812 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
19813 (let ((calendar-mark-ring
19814 (list (calendar-gregorian-from-absolute
19815 (or (get-text-property mark 'day)
19816 (get-text-property point 'day))))))
19817 (unwind-protect
19818 (progn
19819 (fset 'calendar-cursor-to-date
19820 (lambda (&optional error)
19821 (calendar-gregorian-from-absolute
19822 (get-text-property point 'day))))
19823 (call-interactively cmd))
19824 (fset 'calendar-cursor-to-date oldf)))))
19827 (defun org-agenda-execute-calendar-command (cmd)
19828 "Execute a calendar command from the agenda, with the date associated to
19829 the cursor position."
19830 (org-agenda-check-type t 'agenda 'timeline)
19831 (require 'diary-lib)
19832 (unless (get-text-property (point) 'day)
19833 (error "Don't know which date to use for calendar command"))
19834 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
19835 (point (point))
19836 (date (calendar-gregorian-from-absolute
19837 (get-text-property point 'day)))
19838 ;; the following 3 vars are needed in the calendar
19839 (displayed-day (extract-calendar-day date))
19840 (displayed-month (extract-calendar-month date))
19841 (displayed-year (extract-calendar-year date)))
19842 (unwind-protect
19843 (progn
19844 (fset 'calendar-cursor-to-date
19845 (lambda (&optional error)
19846 (calendar-gregorian-from-absolute
19847 (get-text-property point 'day))))
19848 (call-interactively cmd))
19849 (fset 'calendar-cursor-to-date oldf))))
19851 (defun org-agenda-phases-of-moon ()
19852 "Display the phases of the moon for the 3 months around the cursor date."
19853 (interactive)
19854 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
19856 (defun org-agenda-holidays ()
19857 "Display the holidays for the 3 months around the cursor date."
19858 (interactive)
19859 (org-agenda-execute-calendar-command 'list-calendar-holidays))
19861 (defun org-agenda-sunrise-sunset (arg)
19862 "Display sunrise and sunset for the cursor date.
19863 Latitude and longitude can be specified with the variables
19864 `calendar-latitude' and `calendar-longitude'. When called with prefix
19865 argument, latitude and longitude will be prompted for."
19866 (interactive "P")
19867 (let ((calendar-longitude (if arg nil calendar-longitude))
19868 (calendar-latitude (if arg nil calendar-latitude))
19869 (calendar-location-name
19870 (if arg "the given coordinates" calendar-location-name)))
19871 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
19873 (defun org-agenda-goto-calendar ()
19874 "Open the Emacs calendar with the date at the cursor."
19875 (interactive)
19876 (org-agenda-check-type t 'agenda 'timeline)
19877 (let* ((day (or (get-text-property (point) 'day)
19878 (error "Don't know which date to open in calendar")))
19879 (date (calendar-gregorian-from-absolute day))
19880 (calendar-move-hook nil)
19881 (view-calendar-holidays-initially nil)
19882 (view-diary-entries-initially nil))
19883 (calendar)
19884 (calendar-goto-date date)))
19886 (defun org-calendar-goto-agenda ()
19887 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
19888 This is a command that has to be installed in `calendar-mode-map'."
19889 (interactive)
19890 (org-agenda-list nil (calendar-absolute-from-gregorian
19891 (calendar-cursor-to-date))
19892 nil))
19894 (defun org-agenda-convert-date ()
19895 (interactive)
19896 (org-agenda-check-type t 'agenda 'timeline)
19897 (let ((day (get-text-property (point) 'day))
19898 date s)
19899 (unless day
19900 (error "Don't know which date to convert"))
19901 (setq date (calendar-gregorian-from-absolute day))
19902 (setq s (concat
19903 "Gregorian: " (calendar-date-string date) "\n"
19904 "ISO: " (calendar-iso-date-string date) "\n"
19905 "Day of Yr: " (calendar-day-of-year-string date) "\n"
19906 "Julian: " (calendar-julian-date-string date) "\n"
19907 "Astron. JD: " (calendar-astro-date-string date)
19908 " (Julian date number at noon UTC)\n"
19909 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
19910 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
19911 "French: " (calendar-french-date-string date) "\n"
19912 "Bahai: " (calendar-bahai-date-string date) " (until sunset)\n"
19913 "Mayan: " (calendar-mayan-date-string date) "\n"
19914 "Coptic: " (calendar-coptic-date-string date) "\n"
19915 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
19916 "Persian: " (calendar-persian-date-string date) "\n"
19917 "Chinese: " (calendar-chinese-date-string date) "\n"))
19918 (with-output-to-temp-buffer "*Dates*"
19919 (princ s))
19920 (if (fboundp 'fit-window-to-buffer)
19921 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
19924 ;;;; Embedded LaTeX
19926 (defvar org-cdlatex-mode-map (make-sparse-keymap)
19927 "Keymap for the minor `org-cdlatex-mode'.")
19929 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
19930 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
19931 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
19932 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
19933 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
19935 (defvar org-cdlatex-texmathp-advice-is-done nil
19936 "Flag remembering if we have applied the advice to texmathp already.")
19938 (define-minor-mode org-cdlatex-mode
19939 "Toggle the minor `org-cdlatex-mode'.
19940 This mode supports entering LaTeX environment and math in LaTeX fragments
19941 in Org-mode.
19942 \\{org-cdlatex-mode-map}"
19943 nil " OCDL" nil
19944 (when org-cdlatex-mode (require 'cdlatex))
19945 (unless org-cdlatex-texmathp-advice-is-done
19946 (setq org-cdlatex-texmathp-advice-is-done t)
19947 (defadvice texmathp (around org-math-always-on activate)
19948 "Always return t in org-mode buffers.
19949 This is because we want to insert math symbols without dollars even outside
19950 the LaTeX math segments. If Orgmode thinks that point is actually inside
19951 en embedded LaTeX fragement, let texmathp do its job.
19952 \\[org-cdlatex-mode-map]"
19953 (interactive)
19954 (let (p)
19955 (cond
19956 ((not (org-mode-p)) ad-do-it)
19957 ((eq this-command 'cdlatex-math-symbol)
19958 (setq ad-return-value t
19959 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
19961 (let ((p (org-inside-LaTeX-fragment-p)))
19962 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
19963 (setq ad-return-value t
19964 texmathp-why '("Org-mode embedded math" . 0))
19965 (if p ad-do-it)))))))))
19967 (defun turn-on-org-cdlatex ()
19968 "Unconditionally turn on `org-cdlatex-mode'."
19969 (org-cdlatex-mode 1))
19971 (defun org-inside-LaTeX-fragment-p ()
19972 "Test if point is inside a LaTeX fragment.
19973 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19974 sequence appearing also before point.
19975 Even though the matchers for math are configurable, this function assumes
19976 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19977 delimiters are skipped when they have been removed by customization.
19978 The return value is nil, or a cons cell with the delimiter and
19979 and the position of this delimiter.
19981 This function does a reasonably good job, but can locally be fooled by
19982 for example currency specifications. For example it will assume being in
19983 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19984 fragments that are properly closed, but during editing, we have to live
19985 with the uncertainty caused by missing closing delimiters. This function
19986 looks only before point, not after."
19987 (catch 'exit
19988 (let ((pos (point))
19989 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19990 (lim (progn
19991 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19992 (point)))
19993 dd-on str (start 0) m re)
19994 (goto-char pos)
19995 (when dodollar
19996 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19997 re (nth 1 (assoc "$" org-latex-regexps)))
19998 (while (string-match re str start)
19999 (cond
20000 ((= (match-end 0) (length str))
20001 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
20002 ((= (match-end 0) (- (length str) 5))
20003 (throw 'exit nil))
20004 (t (setq start (match-end 0))))))
20005 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
20006 (goto-char pos)
20007 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
20008 (and (match-beginning 2) (throw 'exit nil))
20009 ;; count $$
20010 (while (re-search-backward "\\$\\$" lim t)
20011 (setq dd-on (not dd-on)))
20012 (goto-char pos)
20013 (if dd-on (cons "$$" m))))))
20016 (defun org-try-cdlatex-tab ()
20017 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
20018 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
20019 - inside a LaTeX fragment, or
20020 - after the first word in a line, where an abbreviation expansion could
20021 insert a LaTeX environment."
20022 (when org-cdlatex-mode
20023 (cond
20024 ((save-excursion
20025 (skip-chars-backward "a-zA-Z0-9*")
20026 (skip-chars-backward " \t")
20027 (bolp))
20028 (cdlatex-tab) t)
20029 ((org-inside-LaTeX-fragment-p)
20030 (cdlatex-tab) t)
20031 (t nil))))
20033 (defun org-cdlatex-underscore-caret (&optional arg)
20034 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
20035 Revert to the normal definition outside of these fragments."
20036 (interactive "P")
20037 (if (org-inside-LaTeX-fragment-p)
20038 (call-interactively 'cdlatex-sub-superscript)
20039 (let (org-cdlatex-mode)
20040 (call-interactively (key-binding (vector last-input-event))))))
20042 (defun org-cdlatex-math-modify (&optional arg)
20043 "Execute `cdlatex-math-modify' in LaTeX fragments.
20044 Revert to the normal definition outside of these fragments."
20045 (interactive "P")
20046 (if (org-inside-LaTeX-fragment-p)
20047 (call-interactively 'cdlatex-math-modify)
20048 (let (org-cdlatex-mode)
20049 (call-interactively (key-binding (vector last-input-event))))))
20051 (defvar org-latex-fragment-image-overlays nil
20052 "List of overlays carrying the images of latex fragments.")
20053 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
20055 (defun org-remove-latex-fragment-image-overlays ()
20056 "Remove all overlays with LaTeX fragment images in current buffer."
20057 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
20058 (setq org-latex-fragment-image-overlays nil))
20060 (defun org-preview-latex-fragment (&optional subtree)
20061 "Preview the LaTeX fragment at point, or all locally or globally.
20062 If the cursor is in a LaTeX fragment, create the image and overlay
20063 it over the source code. If there is no fragment at point, display
20064 all fragments in the current text, from one headline to the next. With
20065 prefix SUBTREE, display all fragments in the current subtree. With a
20066 double prefix `C-u C-u', or when the cursor is before the first headline,
20067 display all fragments in the buffer.
20068 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
20069 (interactive "P")
20070 (org-remove-latex-fragment-image-overlays)
20071 (save-excursion
20072 (save-restriction
20073 (let (beg end at msg)
20074 (cond
20075 ((or (equal subtree '(16))
20076 (not (save-excursion
20077 (re-search-backward (concat "^" outline-regexp) nil t))))
20078 (setq beg (point-min) end (point-max)
20079 msg "Creating images for buffer...%s"))
20080 ((equal subtree '(4))
20081 (org-back-to-heading)
20082 (setq beg (point) end (org-end-of-subtree t)
20083 msg "Creating images for subtree...%s"))
20085 (if (setq at (org-inside-LaTeX-fragment-p))
20086 (goto-char (max (point-min) (- (cdr at) 2)))
20087 (org-back-to-heading))
20088 (setq beg (point) end (progn (outline-next-heading) (point))
20089 msg (if at "Creating image...%s"
20090 "Creating images for entry...%s"))))
20091 (message msg "")
20092 (narrow-to-region beg end)
20093 (goto-char beg)
20094 (org-format-latex
20095 (concat "ltxpng/" (file-name-sans-extension
20096 (file-name-nondirectory
20097 buffer-file-name)))
20098 default-directory 'overlays msg at 'forbuffer)
20099 (message msg "done. Use `C-c C-c' to remove images.")))))
20101 (defvar org-latex-regexps
20102 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
20103 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
20104 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
20105 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
20106 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
20107 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
20108 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
20109 "Regular expressions for matching embedded LaTeX.")
20111 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
20112 "Replace LaTeX fragments with links to an image, and produce images."
20113 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
20114 (let* ((prefixnodir (file-name-nondirectory prefix))
20115 (absprefix (expand-file-name prefix dir))
20116 (todir (file-name-directory absprefix))
20117 (opt org-format-latex-options)
20118 (matchers (plist-get opt :matchers))
20119 (re-list org-latex-regexps)
20120 (cnt 0) txt link beg end re e checkdir
20121 m n block linkfile movefile ov)
20122 ;; Check if there are old images files with this prefix, and remove them
20123 (when (file-directory-p todir)
20124 (mapc 'delete-file
20125 (directory-files
20126 todir 'full
20127 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
20128 ;; Check the different regular expressions
20129 (while (setq e (pop re-list))
20130 (setq m (car e) re (nth 1 e) n (nth 2 e)
20131 block (if (nth 3 e) "\n\n" ""))
20132 (when (member m matchers)
20133 (goto-char (point-min))
20134 (while (re-search-forward re nil t)
20135 (when (or (not at) (equal (cdr at) (match-beginning n)))
20136 (setq txt (match-string n)
20137 beg (match-beginning n) end (match-end n)
20138 cnt (1+ cnt)
20139 linkfile (format "%s_%04d.png" prefix cnt)
20140 movefile (format "%s_%04d.png" absprefix cnt)
20141 link (concat block "[[file:" linkfile "]]" block))
20142 (if msg (message msg cnt))
20143 (goto-char beg)
20144 (unless checkdir ; make sure the directory exists
20145 (setq checkdir t)
20146 (or (file-directory-p todir) (make-directory todir)))
20147 (org-create-formula-image
20148 txt movefile opt forbuffer)
20149 (if overlays
20150 (progn
20151 (setq ov (org-make-overlay beg end))
20152 (if (featurep 'xemacs)
20153 (progn
20154 (org-overlay-put ov 'invisible t)
20155 (org-overlay-put
20156 ov 'end-glyph
20157 (make-glyph (vector 'png :file movefile))))
20158 (org-overlay-put
20159 ov 'display
20160 (list 'image :type 'png :file movefile :ascent 'center)))
20161 (push ov org-latex-fragment-image-overlays)
20162 (goto-char end))
20163 (delete-region beg end)
20164 (insert link))))))))
20166 ;; This function borrows from Ganesh Swami's latex2png.el
20167 (defun org-create-formula-image (string tofile options buffer)
20168 (let* ((tmpdir (if (featurep 'xemacs)
20169 (temp-directory)
20170 temporary-file-directory))
20171 (texfilebase (make-temp-name
20172 (expand-file-name "orgtex" tmpdir)))
20173 (texfile (concat texfilebase ".tex"))
20174 (dvifile (concat texfilebase ".dvi"))
20175 (pngfile (concat texfilebase ".png"))
20176 (fnh (face-attribute 'default :height nil))
20177 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
20178 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
20179 (fg (or (plist-get options (if buffer :foreground :html-foreground))
20180 "Black"))
20181 (bg (or (plist-get options (if buffer :background :html-background))
20182 "Transparent")))
20183 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
20184 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
20185 (with-temp-file texfile
20186 (insert org-format-latex-header
20187 "\n\\begin{document}\n" string "\n\\end{document}\n"))
20188 (let ((dir default-directory))
20189 (condition-case nil
20190 (progn
20191 (cd tmpdir)
20192 (call-process "latex" nil nil nil texfile))
20193 (error nil))
20194 (cd dir))
20195 (if (not (file-exists-p dvifile))
20196 (progn (message "Failed to create dvi file from %s" texfile) nil)
20197 (call-process "dvipng" nil nil nil
20198 "-E" "-fg" fg "-bg" bg
20199 "-D" dpi
20200 ;;"-x" scale "-y" scale
20201 "-T" "tight"
20202 "-o" pngfile
20203 dvifile)
20204 (if (not (file-exists-p pngfile))
20205 (progn (message "Failed to create png file from %s" texfile) nil)
20206 ;; Use the requested file name and clean up
20207 (copy-file pngfile tofile 'replace)
20208 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
20209 (delete-file (concat texfilebase e)))
20210 pngfile))))
20212 (defun org-dvipng-color (attr)
20213 "Return an rgb color specification for dvipng."
20214 (apply 'format "rgb %s %s %s"
20215 (mapcar 'org-normalize-color
20216 (color-values (face-attribute 'default attr nil)))))
20218 (defun org-normalize-color (value)
20219 "Return string to be used as color value for an RGB component."
20220 (format "%g" (/ value 65535.0)))
20222 ;;;; Exporting
20224 ;;; Variables, constants, and parameter plists
20226 (defconst org-level-max 20)
20228 (defvar org-export-html-preamble nil
20229 "Preamble, to be inserted just after <body>. Set by publishing functions.")
20230 (defvar org-export-html-postamble nil
20231 "Preamble, to be inserted just before </body>. Set by publishing functions.")
20232 (defvar org-export-html-auto-preamble t
20233 "Should default preamble be inserted? Set by publishing functions.")
20234 (defvar org-export-html-auto-postamble t
20235 "Should default postamble be inserted? Set by publishing functions.")
20236 (defvar org-current-export-file nil) ; dynamically scoped parameter
20237 (defvar org-current-export-dir nil) ; dynamically scoped parameter
20240 (defconst org-export-plist-vars
20241 '((:language . org-export-default-language)
20242 (:customtime . org-display-custom-times)
20243 (:headline-levels . org-export-headline-levels)
20244 (:section-numbers . org-export-with-section-numbers)
20245 (:table-of-contents . org-export-with-toc)
20246 (:preserve-breaks . org-export-preserve-breaks)
20247 (:archived-trees . org-export-with-archived-trees)
20248 (:emphasize . org-export-with-emphasize)
20249 (:sub-superscript . org-export-with-sub-superscripts)
20250 (:footnotes . org-export-with-footnotes)
20251 (:property-drawer . org-export-with-property-drawer)
20252 (:TeX-macros . org-export-with-TeX-macros)
20253 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
20254 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
20255 (:fixed-width . org-export-with-fixed-width)
20256 (:timestamps . org-export-with-timestamps)
20257 (:author-info . org-export-author-info)
20258 (:time-stamp-file . org-export-time-stamp-file)
20259 (:tables . org-export-with-tables)
20260 (:table-auto-headline . org-export-highlight-first-table-line)
20261 (:style . org-export-html-style)
20262 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
20263 (:convert-org-links . org-export-html-link-org-files-as-html)
20264 (:inline-images . org-export-html-inline-images)
20265 (:expand-quoted-html . org-export-html-expand)
20266 (:timestamp . org-export-html-with-timestamp)
20267 (:publishing-directory . org-export-publishing-directory)
20268 (:preamble . org-export-html-preamble)
20269 (:postamble . org-export-html-postamble)
20270 (:auto-preamble . org-export-html-auto-preamble)
20271 (:auto-postamble . org-export-html-auto-postamble)
20272 (:author . user-full-name)
20273 (:email . user-mail-address)))
20275 (defun org-default-export-plist ()
20276 "Return the property list with default settings for the export variables."
20277 (let ((l org-export-plist-vars) rtn e)
20278 (while (setq e (pop l))
20279 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
20280 rtn))
20282 (defun org-infile-export-plist ()
20283 "Return the property list with file-local settings for export."
20284 (save-excursion
20285 (goto-char 0)
20286 (let ((re (org-make-options-regexp
20287 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
20288 p key val text options)
20289 (while (re-search-forward re nil t)
20290 (setq key (org-match-string-no-properties 1)
20291 val (org-match-string-no-properties 2))
20292 (cond
20293 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
20294 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
20295 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
20296 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
20297 ((string-equal key "TEXT")
20298 (setq text (if text (concat text "\n" val) val)))
20299 ((string-equal key "OPTIONS") (setq options val))))
20300 (setq p (plist-put p :text text))
20301 (when options
20302 (let ((op '(("H" . :headline-levels)
20303 ("num" . :section-numbers)
20304 ("toc" . :table-of-contents)
20305 ("\\n" . :preserve-breaks)
20306 ("@" . :expand-quoted-html)
20307 (":" . :fixed-width)
20308 ("|" . :tables)
20309 ("^" . :sub-superscript)
20310 ("f" . :footnotes)
20311 ("p" . :property-drawer)
20312 ("*" . :emphasize)
20313 ("TeX" . :TeX-macros)
20314 ("LaTeX" . :LaTeX-fragments)
20315 ("skip" . :skip-before-1st-heading)
20316 ("author" . :author-info)
20317 ("timestamp" . :time-stamp-file)))
20319 (while (setq o (pop op))
20320 (if (string-match (concat (regexp-quote (car o))
20321 ":\\([^ \t\n\r;,.]*\\)")
20322 options)
20323 (setq p (plist-put p (cdr o)
20324 (car (read-from-string
20325 (match-string 1 options)))))))))
20326 p)))
20328 (defun org-export-directory (type plist)
20329 (let* ((val (plist-get plist :publishing-directory))
20330 (dir (if (listp val)
20331 (or (cdr (assoc type val)) ".")
20332 val)))
20333 dir))
20335 (defun org-skip-comments (lines)
20336 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
20337 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
20338 (re2 "^\\(\\*+\\)[ \t\n\r]")
20339 (case-fold-search nil)
20340 rtn line level)
20341 (while (setq line (pop lines))
20342 (cond
20343 ((and (string-match re1 line)
20344 (setq level (- (match-end 1) (match-beginning 1))))
20345 ;; Beginning of a COMMENT subtree. Skip it.
20346 (while (and (setq line (pop lines))
20347 (or (not (string-match re2 line))
20348 (> (- (match-end 1) (match-beginning 1)) level))))
20349 (setq lines (cons line lines)))
20350 ((string-match "^#" line)
20351 ;; an ordinary comment line
20353 ((and org-export-table-remove-special-lines
20354 (string-match "^[ \t]*|" line)
20355 (or (string-match "^[ \t]*| *[!_^] *|" line)
20356 (and (string-match "| *<[0-9]+> *|" line)
20357 (not (string-match "| *[^ <|]" line)))))
20358 ;; a special table line that should be removed
20360 (t (setq rtn (cons line rtn)))))
20361 (nreverse rtn)))
20363 (defun org-export (&optional arg)
20364 (interactive)
20365 (let ((help "[t] insert the export option template
20366 \[v] limit export to visible part of outline tree
20368 \[a] export as ASCII
20370 \[h] export as HTML
20371 \[H] export as HTML to temporary buffer
20372 \[R] export region as HTML
20373 \[b] export as HTML and browse immediately
20374 \[x] export as XOXO
20376 \[l] export as LaTeX
20377 \[L] export as LaTeX to temporary buffer
20379 \[i] export current file as iCalendar file
20380 \[I] export all agenda files as iCalendar files
20381 \[c] export agenda files into combined iCalendar file
20383 \[F] publish current file
20384 \[P] publish current project
20385 \[X] publish... (project will be prompted for)
20386 \[A] publish all projects")
20387 (cmds
20388 '((?t . org-insert-export-options-template)
20389 (?v . org-export-visible)
20390 (?a . org-export-as-ascii)
20391 (?h . org-export-as-html)
20392 (?b . org-export-as-html-and-open)
20393 (?H . org-export-as-html-to-buffer)
20394 (?R . org-export-region-as-html)
20395 (?x . org-export-as-xoxo)
20396 (?l . org-export-as-latex)
20397 (?L . org-export-as-latex-to-buffer)
20398 (?i . org-export-icalendar-this-file)
20399 (?I . org-export-icalendar-all-agenda-files)
20400 (?c . org-export-icalendar-combine-agenda-files)
20401 (?F . org-publish-current-file)
20402 (?P . org-publish-current-project)
20403 (?X . org-publish)
20404 (?A . org-publish-all)))
20405 r1 r2 ass)
20406 (save-window-excursion
20407 (delete-other-windows)
20408 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
20409 (princ help))
20410 (message "Select command: ")
20411 (setq r1 (read-char-exclusive)))
20412 (setq r2 (if (< r1 27) (+ r1 96) r1))
20413 (if (setq ass (assq r2 cmds))
20414 (call-interactively (cdr ass))
20415 (error "No command associated with key %c" r1))))
20417 (defconst org-html-entities
20418 '(("nbsp")
20419 ("iexcl")
20420 ("cent")
20421 ("pound")
20422 ("curren")
20423 ("yen")
20424 ("brvbar")
20425 ("vert" . "&#124;")
20426 ("sect")
20427 ("uml")
20428 ("copy")
20429 ("ordf")
20430 ("laquo")
20431 ("not")
20432 ("shy")
20433 ("reg")
20434 ("macr")
20435 ("deg")
20436 ("plusmn")
20437 ("sup2")
20438 ("sup3")
20439 ("acute")
20440 ("micro")
20441 ("para")
20442 ("middot")
20443 ("odot"."o")
20444 ("star"."*")
20445 ("cedil")
20446 ("sup1")
20447 ("ordm")
20448 ("raquo")
20449 ("frac14")
20450 ("frac12")
20451 ("frac34")
20452 ("iquest")
20453 ("Agrave")
20454 ("Aacute")
20455 ("Acirc")
20456 ("Atilde")
20457 ("Auml")
20458 ("Aring") ("AA"."&Aring;")
20459 ("AElig")
20460 ("Ccedil")
20461 ("Egrave")
20462 ("Eacute")
20463 ("Ecirc")
20464 ("Euml")
20465 ("Igrave")
20466 ("Iacute")
20467 ("Icirc")
20468 ("Iuml")
20469 ("ETH")
20470 ("Ntilde")
20471 ("Ograve")
20472 ("Oacute")
20473 ("Ocirc")
20474 ("Otilde")
20475 ("Ouml")
20476 ("times")
20477 ("Oslash")
20478 ("Ugrave")
20479 ("Uacute")
20480 ("Ucirc")
20481 ("Uuml")
20482 ("Yacute")
20483 ("THORN")
20484 ("szlig")
20485 ("agrave")
20486 ("aacute")
20487 ("acirc")
20488 ("atilde")
20489 ("auml")
20490 ("aring")
20491 ("aelig")
20492 ("ccedil")
20493 ("egrave")
20494 ("eacute")
20495 ("ecirc")
20496 ("euml")
20497 ("igrave")
20498 ("iacute")
20499 ("icirc")
20500 ("iuml")
20501 ("eth")
20502 ("ntilde")
20503 ("ograve")
20504 ("oacute")
20505 ("ocirc")
20506 ("otilde")
20507 ("ouml")
20508 ("divide")
20509 ("oslash")
20510 ("ugrave")
20511 ("uacute")
20512 ("ucirc")
20513 ("uuml")
20514 ("yacute")
20515 ("thorn")
20516 ("yuml")
20517 ("fnof")
20518 ("Alpha")
20519 ("Beta")
20520 ("Gamma")
20521 ("Delta")
20522 ("Epsilon")
20523 ("Zeta")
20524 ("Eta")
20525 ("Theta")
20526 ("Iota")
20527 ("Kappa")
20528 ("Lambda")
20529 ("Mu")
20530 ("Nu")
20531 ("Xi")
20532 ("Omicron")
20533 ("Pi")
20534 ("Rho")
20535 ("Sigma")
20536 ("Tau")
20537 ("Upsilon")
20538 ("Phi")
20539 ("Chi")
20540 ("Psi")
20541 ("Omega")
20542 ("alpha")
20543 ("beta")
20544 ("gamma")
20545 ("delta")
20546 ("epsilon")
20547 ("varepsilon"."&epsilon;")
20548 ("zeta")
20549 ("eta")
20550 ("theta")
20551 ("iota")
20552 ("kappa")
20553 ("lambda")
20554 ("mu")
20555 ("nu")
20556 ("xi")
20557 ("omicron")
20558 ("pi")
20559 ("rho")
20560 ("sigmaf") ("varsigma"."&sigmaf;")
20561 ("sigma")
20562 ("tau")
20563 ("upsilon")
20564 ("phi")
20565 ("chi")
20566 ("psi")
20567 ("omega")
20568 ("thetasym") ("vartheta"."&thetasym;")
20569 ("upsih")
20570 ("piv")
20571 ("bull") ("bullet"."&bull;")
20572 ("hellip") ("dots"."&hellip;")
20573 ("prime")
20574 ("Prime")
20575 ("oline")
20576 ("frasl")
20577 ("weierp")
20578 ("image")
20579 ("real")
20580 ("trade")
20581 ("alefsym")
20582 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
20583 ("uarr") ("uparrow"."&uarr;")
20584 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
20585 ("darr")("downarrow"."&darr;")
20586 ("harr") ("leftrightarrow"."&harr;")
20587 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
20588 ("lArr") ("Leftarrow"."&lArr;")
20589 ("uArr") ("Uparrow"."&uArr;")
20590 ("rArr") ("Rightarrow"."&rArr;")
20591 ("dArr") ("Downarrow"."&dArr;")
20592 ("hArr") ("Leftrightarrow"."&hArr;")
20593 ("forall")
20594 ("part") ("partial"."&part;")
20595 ("exist") ("exists"."&exist;")
20596 ("empty") ("emptyset"."&empty;")
20597 ("nabla")
20598 ("isin") ("in"."&isin;")
20599 ("notin")
20600 ("ni")
20601 ("prod")
20602 ("sum")
20603 ("minus")
20604 ("lowast") ("ast"."&lowast;")
20605 ("radic")
20606 ("prop") ("proptp"."&prop;")
20607 ("infin") ("infty"."&infin;")
20608 ("ang") ("angle"."&ang;")
20609 ("and") ("vee"."&and;")
20610 ("or") ("wedge"."&or;")
20611 ("cap")
20612 ("cup")
20613 ("int")
20614 ("there4")
20615 ("sim")
20616 ("cong") ("simeq"."&cong;")
20617 ("asymp")("approx"."&asymp;")
20618 ("ne") ("neq"."&ne;")
20619 ("equiv")
20620 ("le")
20621 ("ge")
20622 ("sub") ("subset"."&sub;")
20623 ("sup") ("supset"."&sup;")
20624 ("nsub")
20625 ("sube")
20626 ("supe")
20627 ("oplus")
20628 ("otimes")
20629 ("perp")
20630 ("sdot") ("cdot"."&sdot;")
20631 ("lceil")
20632 ("rceil")
20633 ("lfloor")
20634 ("rfloor")
20635 ("lang")
20636 ("rang")
20637 ("loz") ("Diamond"."&loz;")
20638 ("spades") ("spadesuit"."&spades;")
20639 ("clubs") ("clubsuit"."&clubs;")
20640 ("hearts") ("diamondsuit"."&hearts;")
20641 ("diams") ("diamondsuit"."&diams;")
20642 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
20643 ("quot")
20644 ("amp")
20645 ("lt")
20646 ("gt")
20647 ("OElig")
20648 ("oelig")
20649 ("Scaron")
20650 ("scaron")
20651 ("Yuml")
20652 ("circ")
20653 ("tilde")
20654 ("ensp")
20655 ("emsp")
20656 ("thinsp")
20657 ("zwnj")
20658 ("zwj")
20659 ("lrm")
20660 ("rlm")
20661 ("ndash")
20662 ("mdash")
20663 ("lsquo")
20664 ("rsquo")
20665 ("sbquo")
20666 ("ldquo")
20667 ("rdquo")
20668 ("bdquo")
20669 ("dagger")
20670 ("Dagger")
20671 ("permil")
20672 ("lsaquo")
20673 ("rsaquo")
20674 ("euro")
20676 ("arccos"."arccos")
20677 ("arcsin"."arcsin")
20678 ("arctan"."arctan")
20679 ("arg"."arg")
20680 ("cos"."cos")
20681 ("cosh"."cosh")
20682 ("cot"."cot")
20683 ("coth"."coth")
20684 ("csc"."csc")
20685 ("deg"."deg")
20686 ("det"."det")
20687 ("dim"."dim")
20688 ("exp"."exp")
20689 ("gcd"."gcd")
20690 ("hom"."hom")
20691 ("inf"."inf")
20692 ("ker"."ker")
20693 ("lg"."lg")
20694 ("lim"."lim")
20695 ("liminf"."liminf")
20696 ("limsup"."limsup")
20697 ("ln"."ln")
20698 ("log"."log")
20699 ("max"."max")
20700 ("min"."min")
20701 ("Pr"."Pr")
20702 ("sec"."sec")
20703 ("sin"."sin")
20704 ("sinh"."sinh")
20705 ("sup"."sup")
20706 ("tan"."tan")
20707 ("tanh"."tanh")
20709 "Entities for TeX->HTML translation.
20710 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
20711 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
20712 In that case, \"\\ent\" will be translated to \"&other;\".
20713 The list contains HTML entities for Latin-1, Greek and other symbols.
20714 It is supplemented by a number of commonly used TeX macros with appropriate
20715 translations. There is currently no way for users to extend this.")
20717 ;;; General functions for all backends
20719 (defun org-cleaned-string-for-export (string &rest parameters)
20720 "Cleanup a buffer STRING so that links can be created safely."
20721 (interactive)
20722 (let* ((re-radio (and org-target-link-regexp
20723 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
20724 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
20725 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
20726 (re-archive (concat ":" org-archive-tag ":"))
20727 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
20728 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
20729 (htmlp (plist-get parameters :for-html))
20730 (asciip (plist-get parameters :for-ascii))
20731 (latexp (plist-get parameters :for-LaTeX))
20732 (commentsp (plist-get parameters :comments))
20733 (archived-trees (plist-get parameters :archived-trees))
20734 (inhibit-read-only t)
20735 (outline-regexp "\\*+ ")
20736 a b xx
20737 rtn p)
20738 (with-current-buffer (get-buffer-create " org-mode-tmp")
20739 (erase-buffer)
20740 (insert string)
20741 ;; Remove license-to-kill stuff
20742 (while (setq p (text-property-any (point-min) (point-max)
20743 :org-license-to-kill t))
20744 (delete-region p (next-single-property-change p :org-license-to-kill)))
20746 (let ((org-inhibit-startup t)) (org-mode))
20747 (untabify (point-min) (point-max))
20749 ;; Get the correct stuff before the first headline
20750 (when (plist-get parameters :skip-before-1st-heading)
20751 (goto-char (point-min))
20752 (when (re-search-forward "^\\*+[ \t]" nil t)
20753 (delete-region (point-min) (match-beginning 0))
20754 (goto-char (point-min))
20755 (insert "\n")))
20756 (when (plist-get parameters :add-text)
20757 (goto-char (point-min))
20758 (insert (plist-get parameters :add-text) "\n"))
20760 ;; Get rid of archived trees
20761 (when (not (eq archived-trees t))
20762 (goto-char (point-min))
20763 (while (re-search-forward re-archive nil t)
20764 (if (not (org-on-heading-p t))
20765 (org-end-of-subtree t)
20766 (beginning-of-line 1)
20767 (setq a (if archived-trees
20768 (1+ (point-at-eol)) (point))
20769 b (org-end-of-subtree t))
20770 (if (> b a) (delete-region a b)))))
20772 ;; Get rid of property drawers
20773 (unless org-export-with-property-drawer
20774 (goto-char (point-min))
20775 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
20776 (replace-match "")))
20778 ;; Find targets in comments and move them out of comments,
20779 ;; but mark them as targets that should be invisible
20780 (goto-char (point-min))
20781 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
20782 (replace-match "\\1(INVISIBLE)"))
20784 ;; Protect backend specific stuff, throw away the others.
20785 (goto-char (point-min))
20786 (let ((formatters
20787 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
20788 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
20789 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
20790 fmt)
20791 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
20792 (add-text-properties (match-beginning 0) (match-end 0)
20793 '(org-protected t)))
20794 (while formatters
20795 (setq fmt (pop formatters))
20796 (when (car fmt)
20797 (goto-char (point-min))
20798 (while (re-search-forward (concat "^#\\+" (cadr fmt)
20799 ":[ \t]*\\(.*\\)") nil t)
20800 (replace-match "\\1" t)
20801 (add-text-properties
20802 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
20803 '(org-protected t))))
20804 (goto-char (point-min))
20805 (while (re-search-forward
20806 (concat "^#\\+"
20807 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
20808 (cadddr fmt) "\\>.*\n?") nil t)
20809 (if (car fmt)
20810 (add-text-properties (match-beginning 1) (1+ (match-end 1))
20811 '(org-protected t))
20812 (delete-region (match-beginning 0) (match-end 0))))))
20814 ;; Protect quoted subtrees
20815 (goto-char (point-min))
20816 (while (re-search-forward re-quote nil t)
20817 (goto-char (match-beginning 0))
20818 (end-of-line 1)
20819 (add-text-properties (point) (org-end-of-subtree t)
20820 '(org-protected t)))
20822 ;; Remove subtrees that are commented
20823 (goto-char (point-min))
20824 (while (re-search-forward re-commented nil t)
20825 (goto-char (match-beginning 0))
20826 (delete-region (point) (org-end-of-subtree t)))
20828 ;; Remove special table lines
20829 (when org-export-table-remove-special-lines
20830 (goto-char (point-min))
20831 (while (re-search-forward "^[ \t]*|" nil t)
20832 (beginning-of-line 1)
20833 (if (or (looking-at "[ \t]*| *[!_^] *|")
20834 (and (looking-at ".*?| *<[0-9]+> *|")
20835 (not (looking-at ".*?| *[^ <|]"))))
20836 (delete-region (max (point-min) (1- (point-at-bol)))
20837 (point-at-eol))
20838 (end-of-line 1))))
20840 ;; Specific LaTeX stuff
20841 (when latexp
20842 (require 'org-export-latex nil t)
20843 (org-export-latex-cleaned-string))
20845 ;; Specific HTML stuff
20846 (when htmlp
20847 ;; Convert LaTeX fragments to images
20848 (when (plist-get parameters :LaTeX-fragments)
20849 (org-format-latex
20850 (concat "ltxpng/" (file-name-sans-extension
20851 (file-name-nondirectory
20852 org-current-export-file)))
20853 org-current-export-dir nil "Creating LaTeX image %s"))
20854 (message "Exporting..."))
20856 ;; Remove or replace comments
20857 ;; FIXME: Does LaTeX export take care of its own comments?
20858 ;; If :comments is set, use this char for commenting out comments and
20859 ;; protect them. otherwise delete them
20860 (goto-char (point-min))
20861 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
20862 (if commentsp
20863 (progn (add-text-properties
20864 (match-beginning 0) (match-end 0) '(org-protected t))
20865 (replace-match (format commentsp (match-string 1)) t t))
20866 (replace-match "")))
20868 ;; Find matches for radio targets and turn them into internal links
20869 (goto-char (point-min))
20870 (when re-radio
20871 (while (re-search-forward re-radio nil t)
20872 (org-if-unprotected
20873 (replace-match "\\1[[\\2]]"))))
20875 ;; Find all links that contain a newline and put them into a single line
20876 (goto-char (point-min))
20877 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
20878 (org-if-unprotected
20879 (replace-match "\\1 \\3")
20880 (goto-char (match-beginning 0))))
20883 ;; Normalize links: Convert angle and plain links into bracket links
20884 ;; Expand link abbreviations
20885 (goto-char (point-min))
20886 (while (re-search-forward re-plain-link nil t)
20887 (goto-char (1- (match-end 0)))
20888 (org-if-unprotected
20889 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20890 ":" (match-string 3) "]]")))
20891 ;; added 'org-link face to links
20892 (put-text-property 0 (length s) 'face 'org-link s)
20893 (replace-match s t t))))
20894 (goto-char (point-min))
20895 (while (re-search-forward re-angle-link nil t)
20896 (goto-char (1- (match-end 0)))
20897 (org-if-unprotected
20898 (let* ((s (concat (match-string 1) "[[" (match-string 2)
20899 ":" (match-string 3) "]]")))
20900 (put-text-property 0 (length s) 'face 'org-link s)
20901 (replace-match s t t))))
20902 (goto-char (point-min))
20903 (while (re-search-forward org-bracket-link-regexp nil t)
20904 (org-if-unprotected
20905 (let* ((s (concat "[[" (setq xx (save-match-data
20906 (org-link-expand-abbrev (match-string 1))))
20908 (if (match-end 3)
20909 (match-string 2)
20910 (concat "[" xx "]"))
20911 "]")))
20912 (put-text-property 0 (length s) 'face 'org-link s)
20913 (replace-match s t t))))
20915 ;; Find multiline emphasis and put them into single line
20916 (when (plist-get parameters :emph-multiline)
20917 (goto-char (point-min))
20918 (while (re-search-forward org-emph-re nil t)
20919 (if (not (= (char-after (match-beginning 3))
20920 (char-after (match-beginning 4))))
20921 (org-if-unprotected
20922 (subst-char-in-region (match-beginning 0) (match-end 0)
20923 ?\n ?\ t)
20924 (goto-char (1- (match-end 0))))
20925 (goto-char (1+ (match-beginning 0))))))
20927 (setq rtn (buffer-string)))
20928 (kill-buffer " org-mode-tmp")
20929 rtn))
20931 (defun org-export-grab-title-from-buffer ()
20932 "Get a title for the current document, from looking at the buffer."
20933 (let ((inhibit-read-only t))
20934 (save-excursion
20935 (goto-char (point-min))
20936 (let ((end (save-excursion (outline-next-heading) (point))))
20937 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
20938 ;; Mark the line so that it will not be exported as normal text.
20939 (org-unmodified
20940 (add-text-properties (match-beginning 0) (match-end 0)
20941 (list :org-license-to-kill t)))
20942 ;; Return the title string
20943 (org-trim (match-string 0)))))))
20945 (defun org-export-get-title-from-subtree ()
20946 "Return subtree title and exclude it from export."
20947 (let (title (m (mark)))
20948 (save-excursion
20949 (goto-char (region-beginning))
20950 (when (and (org-at-heading-p)
20951 (>= (org-end-of-subtree t t) (region-end)))
20952 ;; This is a subtree, we take the title from the first heading
20953 (goto-char (region-beginning))
20954 (looking-at org-todo-line-regexp)
20955 (setq title (match-string 3))
20956 (org-unmodified
20957 (add-text-properties (point) (1+ (point-at-eol))
20958 (list :org-license-to-kill t)))))
20959 title))
20961 (defun org-solidify-link-text (s &optional alist)
20962 "Take link text and make a safe target out of it."
20963 (save-match-data
20964 (let* ((rtn
20965 (mapconcat
20966 'identity
20967 (org-split-string s "[ \t\r\n]+") "--"))
20968 (a (assoc rtn alist)))
20969 (or (cdr a) rtn))))
20971 ;; Variable holding the vector with section numbers
20972 (defvar org-section-numbers (make-vector org-level-max 0))
20974 (defun org-init-section-numbers ()
20975 "Initialize the vector for the section numbers."
20976 (let* ((level -1)
20977 (numbers (nreverse (org-split-string "" "\\.")))
20978 (depth (1- (length org-section-numbers)))
20979 (i depth) number-string)
20980 (while (>= i 0)
20981 (if (> i level)
20982 (aset org-section-numbers i 0)
20983 (setq number-string (or (car numbers) "0"))
20984 (if (string-match "\\`[A-Z]\\'" number-string)
20985 (aset org-section-numbers i
20986 (- (string-to-char number-string) ?A -1))
20987 (aset org-section-numbers i (string-to-number number-string)))
20988 (pop numbers))
20989 (setq i (1- i)))))
20991 (defun org-section-number (&optional level)
20992 "Return a string with the current section number.
20993 When LEVEL is non-nil, increase section numbers on that level."
20994 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
20995 (when level
20996 (when (> level -1)
20997 (aset org-section-numbers
20998 level (1+ (aref org-section-numbers level))))
20999 (setq idx (1+ level))
21000 (while (<= idx depth)
21001 (if (not (= idx 1))
21002 (aset org-section-numbers idx 0))
21003 (setq idx (1+ idx))))
21004 (setq idx 0)
21005 (while (<= idx depth)
21006 (setq n (aref org-section-numbers idx))
21007 (setq string (concat string (if (not (string= string "")) "." "")
21008 (int-to-string n)))
21009 (setq idx (1+ idx)))
21010 (save-match-data
21011 (if (string-match "\\`\\([@0]\\.\\)+" string)
21012 (setq string (replace-match "" t nil string)))
21013 (if (string-match "\\(\\.0\\)+\\'" string)
21014 (setq string (replace-match "" t nil string))))
21015 string))
21017 ;;; ASCII export
21019 (defvar org-last-level nil) ; dynamically scoped variable
21020 (defvar org-min-level nil) ; dynamically scoped variable
21021 (defvar org-levels-open nil) ; dynamically scoped parameter
21022 (defvar org-ascii-current-indentation nil) ; For communication
21024 (defun org-export-as-ascii (arg)
21025 "Export the outline as a pretty ASCII file.
21026 If there is an active region, export only the region.
21027 The prefix ARG specifies how many levels of the outline should become
21028 underlined headlines. The default is 3."
21029 (interactive "P")
21030 (setq-default org-todo-line-regexp org-todo-line-regexp)
21031 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21032 (org-infile-export-plist)))
21033 (region-p (org-region-active-p))
21034 (subtree-p
21035 (when region-p
21036 (save-excursion
21037 (goto-char (region-beginning))
21038 (and (org-at-heading-p)
21039 (>= (org-end-of-subtree t t) (region-end))))))
21040 (custom-times org-display-custom-times)
21041 (org-ascii-current-indentation '(0 . 0))
21042 (level 0) line txt
21043 (umax nil)
21044 (umax-toc nil)
21045 (case-fold-search nil)
21046 (filename (concat (file-name-as-directory
21047 (org-export-directory :ascii opt-plist))
21048 (file-name-sans-extension
21049 (or (and subtree-p
21050 (org-entry-get (region-beginning)
21051 "EXPORT_FILE_NAME" t))
21052 (file-name-nondirectory buffer-file-name)))
21053 ".txt"))
21054 (filename (if (equal (file-truename filename)
21055 (file-truename buffer-file-name))
21056 (concat filename ".txt")
21057 filename))
21058 (buffer (find-file-noselect filename))
21059 (org-levels-open (make-vector org-level-max nil))
21060 (odd org-odd-levels-only)
21061 (date (format-time-string "%Y/%m/%d" (current-time)))
21062 (time (format-time-string "%X" (org-current-time)))
21063 (author (plist-get opt-plist :author))
21064 (title (or (and subtree-p (org-export-get-title-from-subtree))
21065 (plist-get opt-plist :title)
21066 (and (not
21067 (plist-get opt-plist :skip-before-1st-heading))
21068 (org-export-grab-title-from-buffer))
21069 (file-name-sans-extension
21070 (file-name-nondirectory buffer-file-name))))
21071 (email (plist-get opt-plist :email))
21072 (language (plist-get opt-plist :language))
21073 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21074 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
21075 (todo nil)
21076 (lang-words nil)
21077 (region
21078 (buffer-substring
21079 (if (org-region-active-p) (region-beginning) (point-min))
21080 (if (org-region-active-p) (region-end) (point-max))))
21081 (lines (org-split-string
21082 (org-cleaned-string-for-export
21083 region
21084 :for-ascii t
21085 :skip-before-1st-heading
21086 (plist-get opt-plist :skip-before-1st-heading)
21087 :archived-trees
21088 (plist-get opt-plist :archived-trees)
21089 :add-text (plist-get opt-plist :text))
21090 "[\r\n]")) ;; FIXME: why \r here???/
21091 thetoc have-headings first-heading-pos
21092 table-open table-buffer)
21094 (let ((inhibit-read-only t))
21095 (org-unmodified
21096 (remove-text-properties (point-min) (point-max)
21097 '(:org-license-to-kill t))))
21099 (setq org-min-level (org-get-min-level lines))
21100 (setq org-last-level org-min-level)
21101 (org-init-section-numbers)
21103 (find-file-noselect filename)
21105 (setq lang-words (or (assoc language org-export-language-setup)
21106 (assoc "en" org-export-language-setup)))
21107 (switch-to-buffer-other-window buffer)
21108 (erase-buffer)
21109 (fundamental-mode)
21110 ;; create local variables for all options, to make sure all called
21111 ;; functions get the correct information
21112 (mapcar (lambda (x)
21113 (set (make-local-variable (cdr x))
21114 (plist-get opt-plist (car x))))
21115 org-export-plist-vars)
21116 (org-set-local 'org-odd-levels-only odd)
21117 (setq umax (if arg (prefix-numeric-value arg)
21118 org-export-headline-levels))
21119 (setq umax-toc (if (integerp org-export-with-toc)
21120 (min org-export-with-toc umax)
21121 umax))
21123 ;; File header
21124 (if title (org-insert-centered title ?=))
21125 (insert "\n")
21126 (if (and (or author email)
21127 org-export-author-info)
21128 (insert (concat (nth 1 lang-words) ": " (or author "")
21129 (if email (concat " <" email ">") "")
21130 "\n")))
21131 (if (and date time org-export-time-stamp-file)
21132 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
21134 (insert "\n\n")
21136 (if org-export-with-toc
21137 (progn
21138 (push (concat (nth 3 lang-words) "\n") thetoc)
21139 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
21140 (mapcar '(lambda (line)
21141 (if (string-match org-todo-line-regexp
21142 line)
21143 ;; This is a headline
21144 (progn
21145 (setq have-headings t)
21146 (setq level (- (match-end 1) (match-beginning 1))
21147 level (org-tr-level level)
21148 txt (match-string 3 line)
21149 todo
21150 (or (and org-export-mark-todo-in-toc
21151 (match-beginning 2)
21152 (not (member (match-string 2 line)
21153 org-done-keywords)))
21154 ; TODO, not DONE
21155 (and org-export-mark-todo-in-toc
21156 (= level umax-toc)
21157 (org-search-todo-below
21158 line lines level))))
21159 (setq txt (org-html-expand-for-ascii txt))
21161 (if (and (memq org-export-with-tags '(not-in-toc nil))
21162 (string-match
21163 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21164 txt))
21165 (setq txt (replace-match "" t t txt)))
21166 (if (string-match quote-re0 txt)
21167 (setq txt (replace-match "" t t txt)))
21169 (if org-export-with-section-numbers
21170 (setq txt (concat (org-section-number level)
21171 " " txt)))
21172 (if (<= level umax-toc)
21173 (progn
21174 (push
21175 (concat
21176 (make-string
21177 (* (max 0 (- level org-min-level)) 4) ?\ )
21178 (format (if todo "%s (*)\n" "%s\n") txt))
21179 thetoc)
21180 (setq org-last-level level))
21181 ))))
21182 lines)
21183 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21185 (org-init-section-numbers)
21186 (while (setq line (pop lines))
21187 ;; Remove the quoted HTML tags.
21188 (setq line (org-html-expand-for-ascii line))
21189 ;; Remove targets
21190 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
21191 (setq line (replace-match "" t t line)))
21192 ;; Replace internal links
21193 (while (string-match org-bracket-link-regexp line)
21194 (setq line (replace-match
21195 (if (match-end 3) "[\\3]" "[\\1]")
21196 t nil line)))
21197 (when custom-times
21198 (setq line (org-translate-time line)))
21199 (cond
21200 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21201 ;; a Headline
21202 (setq first-heading-pos (or first-heading-pos (point)))
21203 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21204 txt (match-string 2 line))
21205 (org-ascii-level-start level txt umax lines))
21207 ((and org-export-with-tables
21208 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21209 (if (not table-open)
21210 ;; New table starts
21211 (setq table-open t table-buffer nil))
21212 ;; Accumulate lines
21213 (setq table-buffer (cons line table-buffer))
21214 (when (or (not lines)
21215 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21216 (car lines))))
21217 (setq table-open nil
21218 table-buffer (nreverse table-buffer))
21219 (insert (mapconcat
21220 (lambda (x)
21221 (org-fix-indentation x org-ascii-current-indentation))
21222 (org-format-table-ascii table-buffer)
21223 "\n") "\n")))
21225 (setq line (org-fix-indentation line org-ascii-current-indentation))
21226 (if (and org-export-with-fixed-width
21227 (string-match "^\\([ \t]*\\)\\(:\\)" line))
21228 (setq line (replace-match "\\1" nil nil line)))
21229 (insert line "\n"))))
21231 (normal-mode)
21233 ;; insert the table of contents
21234 (when thetoc
21235 (goto-char (point-min))
21236 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
21237 (progn
21238 (goto-char (match-beginning 0))
21239 (replace-match ""))
21240 (goto-char first-heading-pos))
21241 (mapc 'insert thetoc)
21242 (or (looking-at "[ \t]*\n[ \t]*\n")
21243 (insert "\n\n")))
21245 (save-buffer)
21246 ;; remove display and invisible chars
21247 (let (beg end)
21248 (goto-char (point-min))
21249 (while (setq beg (next-single-property-change (point) 'display))
21250 (setq end (next-single-property-change beg 'display))
21251 (delete-region beg end)
21252 (goto-char beg)
21253 (insert "=>"))
21254 (goto-char (point-min))
21255 (while (setq beg (next-single-property-change (point) 'org-cwidth))
21256 (setq end (next-single-property-change beg 'org-cwidth))
21257 (delete-region beg end)
21258 (goto-char beg)))
21259 (goto-char (point-min))))
21261 (defun org-search-todo-below (line lines level)
21262 "Search the subtree below LINE for any TODO entries."
21263 (let ((rest (cdr (memq line lines)))
21264 (re org-todo-line-regexp)
21265 line lv todo)
21266 (catch 'exit
21267 (while (setq line (pop rest))
21268 (if (string-match re line)
21269 (progn
21270 (setq lv (- (match-end 1) (match-beginning 1))
21271 todo (and (match-beginning 2)
21272 (not (member (match-string 2 line)
21273 org-done-keywords))))
21274 ; TODO, not DONE
21275 (if (<= lv level) (throw 'exit nil))
21276 (if todo (throw 'exit t))))))))
21278 (defun org-html-expand-for-ascii (line)
21279 "Handle quoted HTML for ASCII export."
21280 (if org-export-html-expand
21281 (while (string-match "@<[^<>\n]*>" line)
21282 ;; We just remove the tags for now.
21283 (setq line (replace-match "" nil nil line))))
21284 line)
21286 (defun org-insert-centered (s &optional underline)
21287 "Insert the string S centered and underline it with character UNDERLINE."
21288 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
21289 (insert (make-string ind ?\ ) s "\n")
21290 (if underline
21291 (insert (make-string ind ?\ )
21292 (make-string (string-width s) underline)
21293 "\n"))))
21295 (defun org-ascii-level-start (level title umax &optional lines)
21296 "Insert a new level in ASCII export."
21297 (let (char (n (- level umax 1)) (ind 0))
21298 (if (> level umax)
21299 (progn
21300 (insert (make-string (* 2 n) ?\ )
21301 (char-to-string (nth (% n (length org-export-ascii-bullets))
21302 org-export-ascii-bullets))
21303 " " title "\n")
21304 ;; find the indentation of the next non-empty line
21305 (catch 'stop
21306 (while lines
21307 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
21308 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
21309 (throw 'stop (setq ind (org-get-indentation (car lines)))))
21310 (pop lines)))
21311 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
21312 (if (or (not (equal (char-before) ?\n))
21313 (not (equal (char-before (1- (point))) ?\n)))
21314 (insert "\n"))
21315 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
21316 (unless org-export-with-tags
21317 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
21318 (setq title (replace-match "" t t title))))
21319 (if org-export-with-section-numbers
21320 (setq title (concat (org-section-number level) " " title)))
21321 (insert title "\n" (make-string (string-width title) char) "\n")
21322 (setq org-ascii-current-indentation '(0 . 0)))))
21324 (defun org-export-visible (type arg)
21325 "Create a copy of the visible part of the current buffer, and export it.
21326 The copy is created in a temporary buffer and removed after use.
21327 TYPE is the final key (as a string) that also select the export command in
21328 the `C-c C-e' export dispatcher.
21329 As a special case, if the you type SPC at the prompt, the temporary
21330 org-mode file will not be removed but presented to you so that you can
21331 continue to use it. The prefix arg ARG is passed through to the exporting
21332 command."
21333 (interactive
21334 (list (progn
21335 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
21336 (read-char-exclusive))
21337 current-prefix-arg))
21338 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
21339 (error "Invalid export key"))
21340 (let* ((binding (cdr (assoc type
21341 '((?a . org-export-as-ascii)
21342 (?\C-a . org-export-as-ascii)
21343 (?b . org-export-as-html-and-open)
21344 (?\C-b . org-export-as-html-and-open)
21345 (?h . org-export-as-html)
21346 (?H . org-export-as-html-to-buffer)
21347 (?R . org-export-region-as-html)
21348 (?x . org-export-as-xoxo)))))
21349 (keepp (equal type ?\ ))
21350 (file buffer-file-name)
21351 (buffer (get-buffer-create "*Org Export Visible*"))
21352 s e)
21353 ;; Need to hack the drawers here.
21354 (save-excursion
21355 (goto-char (point-min))
21356 (while (re-search-forward org-drawer-regexp nil t)
21357 (goto-char (match-beginning 1))
21358 (or (org-invisible-p) (org-flag-drawer nil))))
21359 (with-current-buffer buffer (erase-buffer))
21360 (save-excursion
21361 (setq s (goto-char (point-min)))
21362 (while (not (= (point) (point-max)))
21363 (goto-char (org-find-invisible))
21364 (append-to-buffer buffer s (point))
21365 (setq s (goto-char (org-find-visible))))
21366 (org-cycle-hide-drawers 'all)
21367 (goto-char (point-min))
21368 (unless keepp
21369 ;; Copy all comment lines to the end, to make sure #+ settings are
21370 ;; still available for the second export step. Kind of a hack, but
21371 ;; does do the trick.
21372 (if (looking-at "#[^\r\n]*")
21373 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
21374 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
21375 (append-to-buffer buffer (1+ (match-beginning 0))
21376 (min (point-max) (1+ (match-end 0))))))
21377 (set-buffer buffer)
21378 (let ((buffer-file-name file)
21379 (org-inhibit-startup t))
21380 (org-mode)
21381 (show-all)
21382 (unless keepp (funcall binding arg))))
21383 (if (not keepp)
21384 (kill-buffer buffer)
21385 (switch-to-buffer-other-window buffer)
21386 (goto-char (point-min)))))
21388 (defun org-find-visible ()
21389 (let ((s (point)))
21390 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21391 (get-char-property s 'invisible)))
21393 (defun org-find-invisible ()
21394 (let ((s (point)))
21395 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
21396 (not (get-char-property s 'invisible))))
21399 ;;; HTML export
21401 (defun org-get-current-options ()
21402 "Return a string with current options as keyword options.
21403 Does include HTML export options as well as TODO and CATEGORY stuff."
21404 (format
21405 "#+TITLE: %s
21406 #+AUTHOR: %s
21407 #+EMAIL: %s
21408 #+LANGUAGE: %s
21409 #+TEXT: Some descriptive text to be emitted. Several lines OK.
21410 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
21411 #+CATEGORY: %s
21412 #+SEQ_TODO: %s
21413 #+TYP_TODO: %s
21414 #+PRIORITIES: %c %c %c
21415 #+STARTUP: %s %s %s %s %s
21416 #+TAGS: %s
21417 #+ARCHIVE: %s
21418 #+LINK: %s
21420 (buffer-name) (user-full-name) user-mail-address org-export-default-language
21421 org-export-headline-levels
21422 org-export-with-section-numbers
21423 org-export-with-toc
21424 org-export-preserve-breaks
21425 org-export-html-expand
21426 org-export-with-fixed-width
21427 org-export-with-tables
21428 org-export-with-sub-superscripts
21429 org-export-with-footnotes
21430 org-export-with-emphasize
21431 org-export-with-TeX-macros
21432 org-export-with-LaTeX-fragments
21433 org-export-skip-text-before-1st-heading
21434 org-export-with-property-drawer
21435 (file-name-nondirectory buffer-file-name)
21436 "TODO FEEDBACK VERIFY DONE"
21437 "Me Jason Marie DONE"
21438 org-highest-priority org-lowest-priority org-default-priority
21439 (cdr (assoc org-startup-folded
21440 '((nil . "showall") (t . "overview") (content . "content"))))
21441 (if org-odd-levels-only "odd" "oddeven")
21442 (if org-hide-leading-stars "hidestars" "showstars")
21443 (if org-startup-align-all-tables "align" "noalign")
21444 (cond ((eq t org-log-done) "logdone")
21445 ((not org-log-done) "nologging")
21446 ((listp org-log-done)
21447 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
21448 org-log-done " ")))
21449 (or (mapconcat (lambda (x)
21450 (cond
21451 ((equal '(:startgroup) x) "{")
21452 ((equal '(:endgroup) x) "}")
21453 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
21454 (t (car x))))
21455 (or org-tag-alist (org-get-buffer-tags)) " ") "")
21456 org-archive-location
21457 "org file:~/org/%s.org"
21460 (defun org-insert-export-options-template ()
21461 "Insert into the buffer a template with information for exporting."
21462 (interactive)
21463 (if (not (bolp)) (newline))
21464 (let ((s (org-get-current-options)))
21465 (and (string-match "#\\+CATEGORY" s)
21466 (setq s (substring s 0 (match-beginning 0))))
21467 (insert s)))
21469 (defun org-toggle-fixed-width-section (arg)
21470 "Toggle the fixed-width export.
21471 If there is no active region, the QUOTE keyword at the current headline is
21472 inserted or removed. When present, it causes the text between this headline
21473 and the next to be exported as fixed-width text, and unmodified.
21474 If there is an active region, this command adds or removes a colon as the
21475 first character of this line. If the first character of a line is a colon,
21476 this line is also exported in fixed-width font."
21477 (interactive "P")
21478 (let* ((cc 0)
21479 (regionp (org-region-active-p))
21480 (beg (if regionp (region-beginning) (point)))
21481 (end (if regionp (region-end)))
21482 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
21483 (re "[ \t]*\\(:\\)")
21484 off)
21485 (if regionp
21486 (save-excursion
21487 (goto-char beg)
21488 (setq cc (current-column))
21489 (beginning-of-line 1)
21490 (setq off (looking-at re))
21491 (while (> nlines 0)
21492 (setq nlines (1- nlines))
21493 (beginning-of-line 1)
21494 (cond
21495 (arg
21496 (move-to-column cc t)
21497 (insert ":\n")
21498 (forward-line -1))
21499 ((and off (looking-at re))
21500 (replace-match "" t t nil 1))
21501 ((not off) (move-to-column cc t) (insert ":")))
21502 (forward-line 1)))
21503 (save-excursion
21504 (org-back-to-heading)
21505 (if (looking-at (concat outline-regexp
21506 "\\( *\\<" org-quote-string "\\>\\)"))
21507 (replace-match "" t t nil 1)
21508 (if (looking-at outline-regexp)
21509 (progn
21510 (goto-char (match-end 0))
21511 (insert org-quote-string " "))))))))
21513 (defun org-export-as-html-and-open (arg)
21514 "Export the outline as HTML and immediately open it with a browser.
21515 If there is an active region, export only the region.
21516 The prefix ARG specifies how many levels of the outline should become
21517 headlines. The default is 3. Lower levels will become bulleted lists."
21518 (interactive "P")
21519 (org-export-as-html arg 'hidden)
21520 (org-open-file buffer-file-name))
21522 (defun org-export-as-html-batch ()
21523 "Call `org-export-as-html', may be used in batch processing as
21524 emacs --batch
21525 --load=$HOME/lib/emacs/org.el
21526 --eval \"(setq org-export-headline-levels 2)\"
21527 --visit=MyFile --funcall org-export-as-html-batch"
21528 (org-export-as-html org-export-headline-levels 'hidden))
21530 (defun org-export-as-html-to-buffer (arg)
21531 "Call `org-exort-as-html` with output to a temporary buffer.
21532 No file is created. The prefix ARG is passed through to `org-export-as-html'."
21533 (interactive "P")
21534 (org-export-as-html arg nil nil "*Org HTML Export*")
21535 (switch-to-buffer-other-window "*Org HTML Export*"))
21537 (defun org-replace-region-by-html (beg end)
21538 "Assume the current region has org-mode syntax, and convert it to HTML.
21539 This can be used in any buffer. For example, you could write an
21540 itemized list in org-mode syntax in an HTML buffer and then use this
21541 command to convert it."
21542 (interactive "r")
21543 (let (reg html buf pop-up-frames)
21544 (save-window-excursion
21545 (if (org-mode-p)
21546 (setq html (org-export-region-as-html
21547 beg end t 'string))
21548 (setq reg (buffer-substring beg end)
21549 buf (get-buffer-create "*Org tmp*"))
21550 (with-current-buffer buf
21551 (erase-buffer)
21552 (insert reg)
21553 (org-mode)
21554 (setq html (org-export-region-as-html
21555 (point-min) (point-max) t 'string)))
21556 (kill-buffer buf)))
21557 (delete-region beg end)
21558 (insert html)))
21560 (defun org-export-region-as-html (beg end &optional body-only buffer)
21561 "Convert region from BEG to END in org-mode buffer to HTML.
21562 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
21563 contents, and only produce the region of converted text, useful for
21564 cut-and-paste operations.
21565 If BUFFER is a buffer or a string, use/create that buffer as a target
21566 of the converted HTML. If BUFFER is the symbol `string', return the
21567 produced HTML as a string and leave not buffer behind. For example,
21568 a Lisp program could call this function in the following way:
21570 (setq html (org-export-region-as-html beg end t 'string))
21572 When called interactively, the output buffer is selected, and shown
21573 in a window. A non-interactive call will only retunr the buffer."
21574 (interactive "r\nP")
21575 (when (interactive-p)
21576 (setq buffer "*Org HTML Export*"))
21577 (let ((transient-mark-mode t) (zmacs-regions t)
21578 rtn)
21579 (goto-char end)
21580 (set-mark (point)) ;; to activate the region
21581 (goto-char beg)
21582 (setq rtn (org-export-as-html
21583 nil nil nil
21584 buffer body-only))
21585 (if (fboundp 'deactivate-mark) (deactivate-mark))
21586 (if (and (interactive-p) (bufferp rtn))
21587 (switch-to-buffer-other-window rtn)
21588 rtn)))
21590 (defun org-export-as-html (arg &optional hidden ext-plist
21591 to-buffer body-only)
21592 "Export the outline as a pretty HTML file.
21593 If there is an active region, export only the region. The prefix
21594 ARG specifies how many levels of the outline should become
21595 headlines. The default is 3. Lower levels will become bulleted
21596 lists. When HIDDEN is non-nil, don't display the HTML buffer.
21597 EXT-PLIST is a property list with external parameters overriding
21598 org-mode's default settings, but still inferior to file-local
21599 settings. When TO-BUFFER is non-nil, create a buffer with that
21600 name and export to that buffer. If TO-BUFFER is the symbol `string',
21601 don't leave any buffer behind but just return the resulting HTML as
21602 a string. When BODY-ONLY is set, don't produce the file header and footer,
21603 simply return the content of <body>...</body>, without even
21604 the body tags themselves."
21605 (interactive "P")
21607 ;; Make sure we have a file name when we need it.
21608 (when (and (not (or to-buffer body-only))
21609 (not buffer-file-name))
21610 (if (buffer-base-buffer)
21611 (org-set-local 'buffer-file-name
21612 (with-current-buffer (buffer-base-buffer)
21613 buffer-file-name))
21614 (error "Need a file name to be able to export.")))
21616 (message "Exporting...")
21617 (setq-default org-todo-line-regexp org-todo-line-regexp)
21618 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
21619 (setq-default org-done-keywords org-done-keywords)
21620 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
21621 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
21622 ext-plist
21623 (org-infile-export-plist)))
21625 (style (plist-get opt-plist :style))
21626 (link-validate (plist-get opt-plist :link-validation-function))
21627 valid thetoc have-headings first-heading-pos
21628 (odd org-odd-levels-only)
21629 (region-p (org-region-active-p))
21630 (subtree-p
21631 (when region-p
21632 (save-excursion
21633 (goto-char (region-beginning))
21634 (and (org-at-heading-p)
21635 (>= (org-end-of-subtree t t) (region-end))))))
21636 ;; The following two are dynamically scoped into other
21637 ;; routines below.
21638 (org-current-export-dir (org-export-directory :html opt-plist))
21639 (org-current-export-file buffer-file-name)
21640 (level 0) (line "") (origline "") txt todo
21641 (umax nil)
21642 (umax-toc nil)
21643 (filename (if to-buffer nil
21644 (concat (file-name-as-directory
21645 (org-export-directory :html opt-plist))
21646 (file-name-sans-extension
21647 (or (and subtree-p
21648 (org-entry-get (region-beginning)
21649 "EXPORT_FILE_NAME" t))
21650 (file-name-nondirectory buffer-file-name)))
21651 ".html")))
21652 (current-dir (if buffer-file-name
21653 (file-name-directory buffer-file-name)
21654 default-directory))
21655 (buffer (if to-buffer
21656 (cond
21657 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
21658 (t (get-buffer-create to-buffer)))
21659 (find-file-noselect filename)))
21660 (org-levels-open (make-vector org-level-max nil))
21661 (date (format-time-string "%Y/%m/%d" (current-time)))
21662 (time (format-time-string "%X" (org-current-time)))
21663 (author (plist-get opt-plist :author))
21664 (title (or (and subtree-p (org-export-get-title-from-subtree))
21665 (plist-get opt-plist :title)
21666 (and (not
21667 (plist-get opt-plist :skip-before-1st-heading))
21668 (org-export-grab-title-from-buffer))
21669 (and buffer-file-name
21670 (file-name-sans-extension
21671 (file-name-nondirectory buffer-file-name)))
21672 "UNTITLED"))
21673 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
21674 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
21675 (inquote nil)
21676 (infixed nil)
21677 (in-local-list nil)
21678 (local-list-num nil)
21679 (local-list-indent nil)
21680 (llt org-plain-list-ordered-item-terminator)
21681 (email (plist-get opt-plist :email))
21682 (language (plist-get opt-plist :language))
21683 (lang-words nil)
21684 (target-alist nil) tg
21685 (head-count 0) cnt
21686 (start 0)
21687 (coding-system (and (boundp 'buffer-file-coding-system)
21688 buffer-file-coding-system))
21689 (coding-system-for-write (or org-export-html-coding-system
21690 coding-system))
21691 (save-buffer-coding-system (or org-export-html-coding-system
21692 coding-system))
21693 (charset (and coding-system-for-write
21694 (fboundp 'coding-system-get)
21695 (coding-system-get coding-system-for-write
21696 'mime-charset)))
21697 (region
21698 (buffer-substring
21699 (if region-p (region-beginning) (point-min))
21700 (if region-p (region-end) (point-max))))
21701 (lines
21702 (org-split-string
21703 (org-cleaned-string-for-export
21704 region
21705 :emph-multiline t
21706 :for-html t
21707 :skip-before-1st-heading
21708 (plist-get opt-plist :skip-before-1st-heading)
21709 :archived-trees
21710 (plist-get opt-plist :archived-trees)
21711 :add-text
21712 (plist-get opt-plist :text)
21713 :LaTeX-fragments
21714 (plist-get opt-plist :LaTeX-fragments))
21715 "[\r\n]"))
21716 table-open type
21717 table-buffer table-orig-buffer
21718 ind start-is-num starter didclose
21719 rpl path desc descp desc1 desc2 link
21722 (let ((inhibit-read-only t))
21723 (org-unmodified
21724 (remove-text-properties (point-min) (point-max)
21725 '(:org-license-to-kill t))))
21727 (message "Exporting...")
21729 (setq org-min-level (org-get-min-level lines))
21730 (setq org-last-level org-min-level)
21731 (org-init-section-numbers)
21733 ;; Get the language-dependent settings
21734 (setq lang-words (or (assoc language org-export-language-setup)
21735 (assoc "en" org-export-language-setup)))
21737 ;; Switch to the output buffer
21738 (set-buffer buffer)
21739 (erase-buffer)
21740 (fundamental-mode)
21742 (and (fboundp 'set-buffer-file-coding-system)
21743 (set-buffer-file-coding-system coding-system-for-write))
21745 (let ((case-fold-search nil)
21746 (org-odd-levels-only odd))
21747 ;; create local variables for all options, to make sure all called
21748 ;; functions get the correct information
21749 (mapcar (lambda (x)
21750 (set (make-local-variable (cdr x))
21751 (plist-get opt-plist (car x))))
21752 org-export-plist-vars)
21753 (setq umax (if arg (prefix-numeric-value arg)
21754 org-export-headline-levels))
21755 (setq umax-toc (if (integerp org-export-with-toc)
21756 (min org-export-with-toc umax)
21757 umax))
21758 (unless body-only
21759 ;; File header
21760 (insert (format
21761 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
21762 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
21763 <html xmlns=\"http://www.w3.org/1999/xhtml\"
21764 lang=\"%s\" xml:lang=\"%s\">
21765 <head>
21766 <title>%s</title>
21767 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
21768 <meta name=\"generator\" content=\"Org-mode\"/>
21769 <meta name=\"generated\" content=\"%s %s\"/>
21770 <meta name=\"author\" content=\"%s\"/>
21772 </head><body>
21774 language language (org-html-expand title)
21775 (or charset "iso-8859-1") date time author style))
21777 (insert (or (plist-get opt-plist :preamble) ""))
21779 (when (plist-get opt-plist :auto-preamble)
21780 (if title (insert (format org-export-html-title-format
21781 (org-html-expand title))))))
21783 (if (and org-export-with-toc (not body-only))
21784 (progn
21785 (push (format "<h%d>%s</h%d>\n"
21786 org-export-html-toplevel-hlevel
21787 (nth 3 lang-words)
21788 org-export-html-toplevel-hlevel)
21789 thetoc)
21790 (push "<ul>\n<li>" thetoc)
21791 (setq lines
21792 (mapcar '(lambda (line)
21793 (if (string-match org-todo-line-regexp line)
21794 ;; This is a headline
21795 (progn
21796 (setq have-headings t)
21797 (setq level (- (match-end 1) (match-beginning 1))
21798 level (org-tr-level level)
21799 txt (save-match-data
21800 (org-html-expand
21801 (org-export-cleanup-toc-line
21802 (match-string 3 line))))
21803 todo
21804 (or (and org-export-mark-todo-in-toc
21805 (match-beginning 2)
21806 (not (member (match-string 2 line)
21807 org-done-keywords)))
21808 ; TODO, not DONE
21809 (and org-export-mark-todo-in-toc
21810 (= level umax-toc)
21811 (org-search-todo-below
21812 line lines level))))
21813 (if (and (memq org-export-with-tags '(not-in-toc nil))
21814 (string-match
21815 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21816 txt))
21817 (setq txt (replace-match "" t t txt)))
21818 (if (string-match quote-re0 txt)
21819 (setq txt (replace-match "" t t txt)))
21820 (if org-export-with-section-numbers
21821 (setq txt (concat (org-section-number level)
21822 " " txt)))
21823 (if (<= level (max umax umax-toc))
21824 (setq head-count (+ head-count 1)))
21825 (if (<= level umax-toc)
21826 (progn
21827 (if (> level org-last-level)
21828 (progn
21829 (setq cnt (- level org-last-level))
21830 (while (>= (setq cnt (1- cnt)) 0)
21831 (push "\n<ul>\n<li>" thetoc))
21832 (push "\n" thetoc)))
21833 (if (< level org-last-level)
21834 (progn
21835 (setq cnt (- org-last-level level))
21836 (while (>= (setq cnt (1- cnt)) 0)
21837 (push "</li>\n</ul>" thetoc))
21838 (push "\n" thetoc)))
21839 ;; Check for targets
21840 (while (string-match org-target-regexp line)
21841 (setq tg (match-string 1 line)
21842 line (replace-match
21843 (concat "@<span class=\"target\">" tg "@</span> ")
21844 t t line))
21845 (push (cons (org-solidify-link-text tg)
21846 (format "sec-%d" head-count))
21847 target-alist))
21848 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
21849 (setq txt (replace-match "" t t txt)))
21850 (push
21851 (format
21852 (if todo
21853 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
21854 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
21855 head-count txt) thetoc)
21857 (setq org-last-level level))
21859 line)
21860 lines))
21861 (while (> org-last-level (1- org-min-level))
21862 (setq org-last-level (1- org-last-level))
21863 (push "</li>\n</ul>\n" thetoc))
21864 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21866 (setq head-count 0)
21867 (org-init-section-numbers)
21869 (while (setq line (pop lines) origline line)
21870 (catch 'nextline
21872 ;; end of quote section?
21873 (when (and inquote (string-match "^\\*+ " line))
21874 (insert "</pre>\n")
21875 (setq inquote nil))
21876 ;; inside a quote section?
21877 (when inquote
21878 (insert (org-html-protect line) "\n")
21879 (throw 'nextline nil))
21881 ;; verbatim lines
21882 (when (and org-export-with-fixed-width
21883 (string-match "^[ \t]*:\\(.*\\)" line))
21884 (when (not infixed)
21885 (setq infixed t)
21886 (insert "<pre>\n"))
21887 (insert (org-html-protect (match-string 1 line)) "\n")
21888 (when (and lines
21889 (not (string-match "^[ \t]*\\(:.*\\)"
21890 (car lines))))
21891 (setq infixed nil)
21892 (insert "</pre>\n"))
21893 (throw 'nextline nil))
21895 ;; Protected HTML
21896 (when (get-text-property 0 'org-protected line)
21897 (let (par)
21898 (when (re-search-backward
21899 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
21900 (setq par (match-string 1))
21901 (replace-match "\\2\n"))
21902 (insert line "\n")
21903 (while (and lines
21904 (get-text-property 0 'org-protected (car lines)))
21905 (insert (pop lines) "\n"))
21906 (and par (insert "<p>\n")))
21907 (throw 'nextline nil))
21909 ;; Horizontal line
21910 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
21911 (insert "\n<hr/>\n")
21912 (throw 'nextline nil))
21914 ;; make targets to anchors
21915 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
21916 (cond
21917 ((match-end 2)
21918 (setq line (replace-match
21919 (concat "@<a name=\""
21920 (org-solidify-link-text (match-string 1 line))
21921 "\">\\nbsp@</a>")
21922 t t line)))
21923 ((and org-export-with-toc (equal (string-to-char line) ?*))
21924 (setq line (replace-match
21925 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
21926 ; (concat "@<i>" (match-string 1 line) "@</i> ")
21927 t t line)))
21929 (setq line (replace-match
21930 (concat "@<a name=\""
21931 (org-solidify-link-text (match-string 1 line))
21932 "\" class=\"target\">" (match-string 1 line) "@</a> ")
21933 t t line)))))
21935 (setq line (org-html-handle-time-stamps line))
21937 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
21938 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
21939 ;; Also handle sub_superscripts and checkboxes
21940 (setq line (org-html-expand line))
21942 ;; Format the links
21943 (setq start 0)
21944 (while (string-match org-bracket-link-analytic-regexp line start)
21945 (setq start (match-beginning 0))
21946 (setq type (if (match-end 2) (match-string 2 line) "internal"))
21947 (setq path (match-string 3 line))
21948 (setq desc1 (if (match-end 5) (match-string 5 line))
21949 desc2 (if (match-end 2) (concat type ":" path) path)
21950 descp (and desc1 (not (equal desc1 desc2)))
21951 desc (or desc1 desc2))
21952 ;; Make an image out of the description if that is so wanted
21953 (when (and descp (org-file-image-p desc))
21954 (save-match-data
21955 (if (string-match "^file:" desc)
21956 (setq desc (substring desc (match-end 0)))))
21957 (setq desc (concat "<img src=\"" desc "\"/>")))
21958 ;; FIXME: do we need to unescape here somewhere?
21959 (cond
21960 ((equal type "internal")
21961 (setq rpl
21962 (concat
21963 "<a href=\"#"
21964 (org-solidify-link-text
21965 (save-match-data (org-link-unescape path)) target-alist)
21966 "\">" desc "</a>")))
21967 ((member type '("http" "https")) ; FIXME: need to test this.
21968 ;; standard URL, just check if we need to inline an image
21969 (if (and (or (eq t org-export-html-inline-images)
21970 (and org-export-html-inline-images (not descp)))
21971 (org-file-image-p path))
21972 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
21973 (setq link (concat type ":" path))
21974 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
21975 ((member type '("ftp" "mailto" "news"))
21976 ;; standard URL
21977 (setq link (concat type ":" path))
21978 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
21979 ((string= type "file")
21980 ;; FILE link
21981 (let* ((filename path)
21982 (abs-p (file-name-absolute-p filename))
21983 thefile file-is-image-p search)
21984 (save-match-data
21985 (if (string-match "::\\(.*\\)" filename)
21986 (setq search (match-string 1 filename)
21987 filename (replace-match "" t nil filename)))
21988 (setq valid
21989 (if (functionp link-validate)
21990 (funcall link-validate filename current-dir)
21992 (setq file-is-image-p (org-file-image-p filename))
21993 (setq thefile (if abs-p (expand-file-name filename) filename))
21994 (when (and org-export-html-link-org-files-as-html
21995 (string-match "\\.org$" thefile))
21996 (setq thefile (concat (substring thefile 0
21997 (match-beginning 0))
21998 ".html"))
21999 (if (and search
22000 ;; make sure this is can be used as target search
22001 (not (string-match "^[0-9]*$" search))
22002 (not (string-match "^\\*" search))
22003 (not (string-match "^/.*/$" search)))
22004 (setq thefile (concat thefile "#"
22005 (org-solidify-link-text
22006 (org-link-unescape search)))))
22007 (when (string-match "^file:" desc)
22008 (setq desc (replace-match "" t t desc))
22009 (if (string-match "\\.org$" desc)
22010 (setq desc (replace-match "" t t desc))))))
22011 (setq rpl (if (and file-is-image-p
22012 (or (eq t org-export-html-inline-images)
22013 (and org-export-html-inline-images
22014 (not descp))))
22015 (concat "<img src=\"" thefile "\"/>")
22016 (concat "<a href=\"" thefile "\">" desc "</a>")))
22017 (if (not valid) (setq rpl desc))))
22018 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
22019 (setq rpl (concat "<i>&lt;" type ":"
22020 (save-match-data (org-link-unescape path))
22021 "&gt;</i>"))))
22022 (setq line (replace-match rpl t t line)
22023 start (+ start (length rpl))))
22025 ;; TODO items
22026 (if (and (string-match org-todo-line-regexp line)
22027 (match-beginning 2))
22029 (setq line
22030 (concat (substring line 0 (match-beginning 2))
22031 "<span class=\""
22032 (if (member (match-string 2 line)
22033 org-done-keywords)
22034 "done" "todo")
22035 "\">" (match-string 2 line)
22036 "</span>" (substring line (match-end 2)))))
22038 ;; Does this contain a reference to a footnote?
22039 (when org-export-with-footnotes
22040 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
22041 (let ((n (match-string 2 line)))
22042 (setq line
22043 (replace-match
22044 (format
22045 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
22046 (match-string 1 line) n n n)
22047 t t line)))))
22049 (cond
22050 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22051 ;; This is a headline
22052 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22053 txt (match-string 2 line))
22054 (if (string-match quote-re0 txt)
22055 (setq txt (replace-match "" t t txt)))
22056 (if (<= level (max umax umax-toc))
22057 (setq head-count (+ head-count 1)))
22058 (when in-local-list
22059 ;; Close any local lists before inserting a new header line
22060 (while local-list-num
22061 (org-close-li)
22062 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
22063 (pop local-list-num))
22064 (setq local-list-indent nil
22065 in-local-list nil))
22066 (setq first-heading-pos (or first-heading-pos (point)))
22067 (org-html-level-start level txt umax
22068 (and org-export-with-toc (<= level umax))
22069 head-count)
22070 ;; QUOTES
22071 (when (string-match quote-re line)
22072 (insert "<pre>")
22073 (setq inquote t)))
22075 ((and org-export-with-tables
22076 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22077 (if (not table-open)
22078 ;; New table starts
22079 (setq table-open t table-buffer nil table-orig-buffer nil))
22080 ;; Accumulate lines
22081 (setq table-buffer (cons line table-buffer)
22082 table-orig-buffer (cons origline table-orig-buffer))
22083 (when (or (not lines)
22084 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22085 (car lines))))
22086 (setq table-open nil
22087 table-buffer (nreverse table-buffer)
22088 table-orig-buffer (nreverse table-orig-buffer))
22089 (org-close-par-maybe)
22090 (insert (org-format-table-html table-buffer table-orig-buffer))))
22092 ;; Normal lines
22093 (when (string-match
22094 (cond
22095 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22096 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22097 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
22098 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
22099 line)
22100 (setq ind (org-get-string-indentation line)
22101 start-is-num (match-beginning 4)
22102 starter (if (match-beginning 2)
22103 (substring (match-string 2 line) 0 -1))
22104 line (substring line (match-beginning 5)))
22105 (unless (string-match "[^ \t]" line)
22106 ;; empty line. Pretend indentation is large.
22107 (setq ind (if org-empty-line-terminates-plain-lists
22109 (1+ (or (car local-list-indent) 1)))))
22110 (setq didclose nil)
22111 (while (and in-local-list
22112 (or (and (= ind (car local-list-indent))
22113 (not starter))
22114 (< ind (car local-list-indent))))
22115 (setq didclose t)
22116 (org-close-li)
22117 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
22118 (pop local-list-num) (pop local-list-indent)
22119 (setq in-local-list local-list-indent))
22120 (cond
22121 ((and starter
22122 (or (not in-local-list)
22123 (> ind (car local-list-indent))))
22124 ;; Start new (level of) list
22125 (org-close-par-maybe)
22126 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
22127 (push start-is-num local-list-num)
22128 (push ind local-list-indent)
22129 (setq in-local-list t))
22130 (starter
22131 ;; continue current list
22132 (org-close-li)
22133 (insert "<li>\n"))
22134 (didclose
22135 ;; we did close a list, normal text follows: need <p>
22136 (org-open-par)))
22137 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
22138 (setq line
22139 (replace-match
22140 (if (equal (match-string 1 line) "X")
22141 "<b>[X]</b>"
22142 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
22143 t t line))))
22145 ;; Empty lines start a new paragraph. If hand-formatted lists
22146 ;; are not fully interpreted, lines starting with "-", "+", "*"
22147 ;; also start a new paragraph.
22148 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
22150 ;; Is this the start of a footnote?
22151 (when org-export-with-footnotes
22152 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
22153 (org-close-par-maybe)
22154 (let ((n (match-string 1 line)))
22155 (setq line (replace-match
22156 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
22158 ;; Check if the line break needs to be conserved
22159 (cond
22160 ((string-match "\\\\\\\\[ \t]*$" line)
22161 (setq line (replace-match "<br/>" t t line)))
22162 (org-export-preserve-breaks
22163 (setq line (concat line "<br/>"))))
22165 (insert line "\n")))))
22167 ;; Properly close all local lists and other lists
22168 (when inquote (insert "</pre>\n"))
22169 (when in-local-list
22170 ;; Close any local lists before inserting a new header line
22171 (while local-list-num
22172 (org-close-li)
22173 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
22174 (pop local-list-num))
22175 (setq local-list-indent nil
22176 in-local-list nil))
22177 (org-html-level-start 1 nil umax
22178 (and org-export-with-toc (<= level umax))
22179 head-count)
22181 (unless body-only
22182 (when (plist-get opt-plist :auto-postamble)
22183 (when (and org-export-author-info author)
22184 (insert "<p class=\"author\"> "
22185 (nth 1 lang-words) ": " author "\n")
22186 (when email
22187 (insert "<a href=\"mailto:" email "\">&lt;"
22188 email "&gt;</a>\n"))
22189 (insert "</p>\n"))
22190 (when (and date time org-export-time-stamp-file)
22191 (insert "<p class=\"date\"> "
22192 (nth 2 lang-words) ": "
22193 date " " time "</p>\n")))
22195 (if org-export-html-with-timestamp
22196 (insert org-export-html-html-helper-timestamp))
22197 (insert (or (plist-get opt-plist :postamble) ""))
22198 (insert "</body>\n</html>\n"))
22200 (normal-mode)
22201 (if (eq major-mode default-major-mode) (html-mode))
22203 ;; insert the table of contents
22204 (goto-char (point-min))
22205 (when thetoc
22206 (if (or (re-search-forward
22207 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
22208 (re-search-forward
22209 "\\[TABLE-OF-CONTENTS\\]" nil t))
22210 (progn
22211 (goto-char (match-beginning 0))
22212 (replace-match ""))
22213 (goto-char first-heading-pos)
22214 (when (looking-at "\\s-*</p>")
22215 (goto-char (match-end 0))
22216 (insert "\n")))
22217 (mapc 'insert thetoc))
22218 ;; remove empty paragraphs and lists
22219 (goto-char (point-min))
22220 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
22221 (replace-match ""))
22222 (goto-char (point-min))
22223 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
22224 (replace-match ""))
22225 (or to-buffer (save-buffer))
22226 (goto-char (point-min))
22227 (message "Exporting... done")
22228 (if (eq to-buffer 'string)
22229 (prog1 (buffer-substring (point-min) (point-max))
22230 (kill-buffer (current-buffer)))
22231 (current-buffer)))))
22233 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
22234 (defun org-format-table-ascii (lines)
22235 "Format a table for ascii export."
22236 (if (stringp lines)
22237 (setq lines (org-split-string lines "\n")))
22238 (if (not (string-match "^[ \t]*|" (car lines)))
22239 ;; Table made by table.el - test for spanning
22240 lines
22242 ;; A normal org table
22243 ;; Get rid of hlines at beginning and end
22244 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22245 (setq lines (nreverse lines))
22246 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22247 (setq lines (nreverse lines))
22248 (when org-export-table-remove-special-lines
22249 ;; Check if the table has a marking column. If yes remove the
22250 ;; column and the special lines
22251 (setq lines (org-table-clean-before-export lines)))
22252 ;; Get rid of the vertical lines except for grouping
22253 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
22254 rtn line vl1 start)
22255 (while (setq line (pop lines))
22256 (if (string-match org-table-hline-regexp line)
22257 (and (string-match "|\\(.*\\)|" line)
22258 (setq line (replace-match " \\1" t nil line)))
22259 (setq start 0 vl1 vl)
22260 (while (string-match "|" line start)
22261 (setq start (match-end 0))
22262 (or (pop vl1) (setq line (replace-match " " t t line)))))
22263 (push line rtn))
22264 (nreverse rtn))))
22266 (defun org-colgroup-info-to-vline-list (info)
22267 (let (vl new last)
22268 (while info
22269 (setq last new new (pop info))
22270 (if (or (memq last '(:end :startend))
22271 (memq new '(:start :startend)))
22272 (push t vl)
22273 (push nil vl)))
22274 (setq vl (cons nil (nreverse vl)))))
22277 (defun org-format-table-html (lines olines)
22278 "Find out which HTML converter to use and return the HTML code."
22279 (if (stringp lines)
22280 (setq lines (org-split-string lines "\n")))
22281 (if (string-match "^[ \t]*|" (car lines))
22282 ;; A normal org table
22283 (org-format-org-table-html lines)
22284 ;; Table made by table.el - test for spanning
22285 (let* ((hlines (delq nil (mapcar
22286 (lambda (x)
22287 (if (string-match "^[ \t]*\\+-" x) x
22288 nil))
22289 lines)))
22290 (first (car hlines))
22291 (ll (and (string-match "\\S-+" first)
22292 (match-string 0 first)))
22293 (re (concat "^[ \t]*" (regexp-quote ll)))
22294 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
22295 hlines))))
22296 (if (and (not spanning)
22297 (not org-export-prefer-native-exporter-for-tables))
22298 ;; We can use my own converter with HTML conversions
22299 (org-format-table-table-html lines)
22300 ;; Need to use the code generator in table.el, with the original text.
22301 (org-format-table-table-html-using-table-generate-source olines)))))
22303 (defun org-format-org-table-html (lines &optional splice)
22304 "Format a table into HTML."
22305 ;; Get rid of hlines at beginning and end
22306 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22307 (setq lines (nreverse lines))
22308 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
22309 (setq lines (nreverse lines))
22310 (when org-export-table-remove-special-lines
22311 ;; Check if the table has a marking column. If yes remove the
22312 ;; column and the special lines
22313 (setq lines (org-table-clean-before-export lines)))
22315 (let ((head (and org-export-highlight-first-table-line
22316 (delq nil (mapcar
22317 (lambda (x) (string-match "^[ \t]*|-" x))
22318 (cdr lines)))))
22319 (nlines 0) fnum i
22320 tbopen line fields html gr colgropen)
22321 (if splice (setq head nil))
22322 (unless splice (push (if head "<thead>" "<tbody>") html))
22323 (setq tbopen t)
22324 (while (setq line (pop lines))
22325 (catch 'next-line
22326 (if (string-match "^[ \t]*|-" line)
22327 (progn
22328 (unless splice
22329 (push (if head "</thead>" "</tbody>") html)
22330 (if lines (push "<tbody>" html) (setq tbopen nil)))
22331 (setq head nil) ;; head ends here, first time around
22332 ;; ignore this line
22333 (throw 'next-line t)))
22334 ;; Break the line into fields
22335 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22336 (unless fnum (setq fnum (make-vector (length fields) 0)))
22337 (setq nlines (1+ nlines) i -1)
22338 (push (concat "<tr>"
22339 (mapconcat
22340 (lambda (x)
22341 (setq i (1+ i))
22342 (if (and (< i nlines)
22343 (string-match org-table-number-regexp x))
22344 (incf (aref fnum i)))
22345 (if head
22346 (concat (car org-export-table-header-tags) x
22347 (cdr org-export-table-header-tags))
22348 (concat (car org-export-table-data-tags) x
22349 (cdr org-export-table-data-tags))))
22350 fields "")
22351 "</tr>")
22352 html)))
22353 (unless splice (if tbopen (push "</tbody>" html)))
22354 (unless splice (push "</table>\n" html))
22355 (setq html (nreverse html))
22356 (unless splice
22357 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
22358 (push (mapconcat
22359 (lambda (x)
22360 (setq gr (pop org-table-colgroup-info))
22361 (format "%s<COL align=\"%s\"></COL>%s"
22362 (if (memq gr '(:start :startend))
22363 (prog1
22364 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
22365 (setq colgropen t))
22367 (if (> (/ (float x) nlines) org-table-number-fraction)
22368 "right" "left")
22369 (if (memq gr '(:end :startend))
22370 (progn (setq colgropen nil) "</colgroup>")
22371 "")))
22372 fnum "")
22373 html)
22374 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
22375 (push org-export-html-table-tag html))
22376 (concat (mapconcat 'identity html "\n") "\n")))
22378 (defun org-table-clean-before-export (lines)
22379 "Check if the table has a marking column.
22380 If yes remove the column and the special lines."
22381 (setq org-table-colgroup-info nil)
22382 (if (memq nil
22383 (mapcar
22384 (lambda (x) (or (string-match "^[ \t]*|-" x)
22385 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
22386 lines))
22387 (progn
22388 (setq org-table-clean-did-remove-column nil)
22389 (delq nil
22390 (mapcar
22391 (lambda (x)
22392 (cond
22393 ((string-match "^[ \t]*| */ *|" x)
22394 (setq org-table-colgroup-info
22395 (mapcar (lambda (x)
22396 (cond ((member x '("<" "&lt;")) :start)
22397 ((member x '(">" "&gt;")) :end)
22398 ((member x '("<>" "&lt;&gt;")) :startend)
22399 (t nil)))
22400 (org-split-string x "[ \t]*|[ \t]*")))
22401 nil)
22402 (t x)))
22403 lines)))
22404 (setq org-table-clean-did-remove-column t)
22405 (delq nil
22406 (mapcar
22407 (lambda (x)
22408 (cond
22409 ((string-match "^[ \t]*| */ *|" x)
22410 (setq org-table-colgroup-info
22411 (mapcar (lambda (x)
22412 (cond ((member x '("<" "&lt;")) :start)
22413 ((member x '(">" "&gt;")) :end)
22414 ((member x '("<>" "&lt;&gt;")) :startend)
22415 (t nil)))
22416 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
22417 nil)
22418 ((string-match "^[ \t]*| *[!_^/] *|" x)
22419 nil) ; ignore this line
22420 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
22421 (string-match "^\\([ \t]*\\)|[^|]*|" x))
22422 ;; remove the first column
22423 (replace-match "\\1|" t nil x))
22424 (t (error "This should not happen"))))
22425 lines))))
22427 (defun org-format-table-table-html (lines)
22428 "Format a table generated by table.el into HTML.
22429 This conversion does *not* use `table-generate-source' from table.el.
22430 This has the advantage that Org-mode's HTML conversions can be used.
22431 But it has the disadvantage, that no cell- or row-spanning is allowed."
22432 (let (line field-buffer
22433 (head org-export-highlight-first-table-line)
22434 fields html empty)
22435 (setq html (concat org-export-html-table-tag "\n"))
22436 (while (setq line (pop lines))
22437 (setq empty "&nbsp;")
22438 (catch 'next-line
22439 (if (string-match "^[ \t]*\\+-" line)
22440 (progn
22441 (if field-buffer
22442 (progn
22443 (setq
22444 html
22445 (concat
22446 html
22447 "<tr>"
22448 (mapconcat
22449 (lambda (x)
22450 (if (equal x "") (setq x empty))
22451 (if head
22452 (concat (car org-export-table-header-tags) x
22453 (cdr org-export-table-header-tags))
22454 (concat (car org-export-table-data-tags) x
22455 (cdr org-export-table-data-tags))))
22456 field-buffer "\n")
22457 "</tr>\n"))
22458 (setq head nil)
22459 (setq field-buffer nil)))
22460 ;; Ignore this line
22461 (throw 'next-line t)))
22462 ;; Break the line into fields and store the fields
22463 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
22464 (if field-buffer
22465 (setq field-buffer (mapcar
22466 (lambda (x)
22467 (concat x "<br/>" (pop fields)))
22468 field-buffer))
22469 (setq field-buffer fields))))
22470 (setq html (concat html "</table>\n"))
22471 html))
22473 (defun org-format-table-table-html-using-table-generate-source (lines)
22474 "Format a table into html, using `table-generate-source' from table.el.
22475 This has the advantage that cell- or row-spanning is allowed.
22476 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
22477 (require 'table)
22478 (with-current-buffer (get-buffer-create " org-tmp1 ")
22479 (erase-buffer)
22480 (insert (mapconcat 'identity lines "\n"))
22481 (goto-char (point-min))
22482 (if (not (re-search-forward "|[^+]" nil t))
22483 (error "Error processing table"))
22484 (table-recognize-table)
22485 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
22486 (table-generate-source 'html " org-tmp2 ")
22487 (set-buffer " org-tmp2 ")
22488 (buffer-substring (point-min) (point-max))))
22490 (defun org-html-handle-time-stamps (s)
22491 "Format time stamps in string S, or remove them."
22492 (catch 'exit
22493 (let (r b)
22494 (while (string-match org-maybe-keyword-time-regexp s)
22495 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
22496 ;; never export CLOCK
22497 (throw 'exit ""))
22498 (or b (setq b (substring s 0 (match-beginning 0))))
22499 (if (not org-export-with-timestamps)
22500 (setq r (concat r (substring s 0 (match-beginning 0)))
22501 s (substring s (match-end 0)))
22502 (setq r (concat
22503 r (substring s 0 (match-beginning 0))
22504 (if (match-end 1)
22505 (format "@<span class=\"timestamp-kwd\">%s @</span>"
22506 (match-string 1 s)))
22507 (format " @<span class=\"timestamp\">%s@</span>"
22508 (substring
22509 (org-translate-time (match-string 3 s)) 1 -1)))
22510 s (substring s (match-end 0)))))
22511 ;; Line break if line started and ended with time stamp stuff
22512 (if (not r)
22514 (setq r (concat r s))
22515 (unless (string-match "\\S-" (concat b s))
22516 (setq r (concat r "@<br/>")))
22517 r))))
22519 (defun org-html-protect (s)
22520 ;; convert & to &amp;, < to &lt; and > to &gt;
22521 (let ((start 0))
22522 (while (string-match "&" s start)
22523 (setq s (replace-match "&amp;" t t s)
22524 start (1+ (match-beginning 0))))
22525 (while (string-match "<" s)
22526 (setq s (replace-match "&lt;" t t s)))
22527 (while (string-match ">" s)
22528 (setq s (replace-match "&gt;" t t s))))
22531 (defun org-export-cleanup-toc-line (s)
22532 "Remove tags and time staps from lines going into the toc."
22533 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
22534 (setq s (replace-match "" t t s)))
22535 (when org-export-remove-timestamps-from-toc
22536 (while (string-match org-maybe-keyword-time-regexp s)
22537 (setq s (replace-match "" t t s))))
22538 (while (string-match org-bracket-link-regexp s)
22539 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
22540 t t s)))
22543 (defun org-html-expand (string)
22544 "Prepare STRING for HTML export. Applies all active conversions.
22545 If there are links in the string, don't modify these."
22546 (let* (m s l res)
22547 (while (setq m (string-match org-bracket-link-regexp string))
22548 (setq s (substring string 0 m)
22549 l (match-string 0 string)
22550 string (substring string (match-end 0)))
22551 (push (org-html-do-expand s) res)
22552 (push l res))
22553 (push (org-html-do-expand string) res)
22554 (apply 'concat (nreverse res))))
22556 (defun org-html-do-expand (s)
22557 "Apply all active conversions to translate special ASCII to HTML."
22558 (setq s (org-html-protect s))
22559 (if org-export-html-expand
22560 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
22561 (setq s (replace-match "<\\1>" t nil s))))
22562 (if org-export-with-emphasize
22563 (setq s (org-export-html-convert-emphasize s)))
22564 (if org-export-with-sub-superscripts
22565 (setq s (org-export-html-convert-sub-super s)))
22566 (if org-export-with-TeX-macros
22567 (let ((start 0) wd ass)
22568 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
22569 (setq wd (match-string 1 s))
22570 (if (setq ass (assoc wd org-html-entities))
22571 (setq s (replace-match (or (cdr ass)
22572 (concat "&" (car ass) ";"))
22573 t t s))
22574 (setq start (+ start (length wd)))))))
22577 (defun org-create-multibrace-regexp (left right n)
22578 "Create a regular expression which will match a balanced sexp.
22579 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
22580 as single character strings.
22581 The regexp returned will match the entire expression including the
22582 delimiters. It will also define a single group which contains the
22583 match except for the outermost delimiters. The maximum depth of
22584 stacked delimiters is N. Escaping delimiters is not possible."
22585 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
22586 (or "\\|")
22587 (re nothing)
22588 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
22589 (while (> n 1)
22590 (setq n (1- n)
22591 re (concat re or next)
22592 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
22593 (concat left "\\(" re "\\)" right)))
22595 (defvar org-match-substring-regexp
22596 (concat
22597 "\\([^\\]\\)\\([_^]\\)\\("
22598 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
22599 "\\|"
22600 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
22601 "\\|"
22602 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
22603 "The regular expression matching a sub- or superscript.")
22605 ;(let ((s "a\\_b"))
22606 ; (and (string-match org-match-substring-regexp s)
22607 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
22609 (defun org-export-html-convert-sub-super (string)
22610 "Convert sub- and superscripts in STRING to HTML."
22611 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
22612 (while (string-match org-match-substring-regexp string s)
22613 (if (and requireb (match-end 8))
22614 (setq s (match-end 2))
22615 (setq s (match-end 1)
22616 key (if (string= (match-string 2 string) "_") "sub" "sup")
22617 c (or (match-string 8 string)
22618 (match-string 6 string)
22619 (match-string 5 string))
22620 string (replace-match
22621 (concat (match-string 1 string)
22622 "<" key ">" c "</" key ">")
22623 t t string))))
22624 (while (string-match "\\\\\\([_^]\\)" string)
22625 (setq string (replace-match (match-string 1 string) t t string)))
22626 string))
22628 (defun org-export-html-convert-emphasize (string)
22629 "Apply emphasis."
22630 (let ((s 0))
22631 (while (string-match org-emph-re string s)
22632 (if (not (equal
22633 (substring string (match-beginning 3) (1+ (match-beginning 3)))
22634 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
22635 (setq string (replace-match
22636 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
22637 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
22638 "\\5") t nil string))
22639 (setq s (1+ s))))
22640 string))
22642 (defvar org-par-open nil)
22643 (defun org-open-par ()
22644 "Insert <p>, but first close previous paragraph if any."
22645 (org-close-par-maybe)
22646 (insert "\n<p>")
22647 (setq org-par-open t))
22648 (defun org-close-par-maybe ()
22649 "Close paragraph if there is one open."
22650 (when org-par-open
22651 (insert "</p>")
22652 (setq org-par-open nil)))
22653 (defun org-close-li ()
22654 "Close <li> if necessary."
22655 (org-close-par-maybe)
22656 (insert "</li>\n"))
22658 (defvar body-only) ; dynamically scoped into this.
22659 (defun org-html-level-start (level title umax with-toc head-count)
22660 "Insert a new level in HTML export.
22661 When TITLE is nil, just close all open levels."
22662 (org-close-par-maybe)
22663 (let ((l (1+ (max level umax))))
22664 (while (<= l org-level-max)
22665 (if (aref org-levels-open (1- l))
22666 (progn
22667 (org-html-level-close l)
22668 (aset org-levels-open (1- l) nil)))
22669 (setq l (1+ l)))
22670 (when title
22671 ;; If title is nil, this means this function is called to close
22672 ;; all levels, so the rest is done only if title is given
22673 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22674 (setq title (replace-match
22675 (if org-export-with-tags
22676 (save-match-data
22677 (concat
22678 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
22679 (mapconcat 'identity (org-split-string
22680 (match-string 1 title) ":")
22681 "&nbsp;")
22682 "</span>"))
22684 t t title)))
22685 (if (> level umax)
22686 (progn
22687 (if (aref org-levels-open (1- level))
22688 (progn
22689 (org-close-li)
22690 (insert "<li>" title "<br/>\n"))
22691 (aset org-levels-open (1- level) t)
22692 (org-close-par-maybe)
22693 (insert "<ul>\n<li>" title "<br/>\n")))
22694 (if (and org-export-with-section-numbers (not body-only))
22695 (setq title (concat (org-section-number level) " " title)))
22696 (setq level (+ level org-export-html-toplevel-hlevel -1))
22697 (if with-toc
22698 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
22699 level head-count title level))
22700 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
22701 (org-open-par)))))
22703 (defun org-html-level-close (&rest args)
22704 "Terminate one level in HTML export."
22705 (org-close-li)
22706 (insert "</ul>\n"))
22708 ;;; iCalendar export
22710 ;;;###autoload
22711 (defun org-export-icalendar-this-file ()
22712 "Export current file as an iCalendar file.
22713 The iCalendar file will be located in the same directory as the Org-mode
22714 file, but with extension `.ics'."
22715 (interactive)
22716 (org-export-icalendar nil buffer-file-name))
22718 ;;;###autoload
22719 (defun org-export-icalendar-all-agenda-files ()
22720 "Export all files in `org-agenda-files' to iCalendar .ics files.
22721 Each iCalendar file will be located in the same directory as the Org-mode
22722 file, but with extension `.ics'."
22723 (interactive)
22724 (apply 'org-export-icalendar nil (org-agenda-files t)))
22726 ;;;###autoload
22727 (defun org-export-icalendar-combine-agenda-files ()
22728 "Export all files in `org-agenda-files' to a single combined iCalendar file.
22729 The file is stored under the name `org-combined-agenda-icalendar-file'."
22730 (interactive)
22731 (apply 'org-export-icalendar t (org-agenda-files t)))
22733 (defun org-export-icalendar (combine &rest files)
22734 "Create iCalendar files for all elements of FILES.
22735 If COMBINE is non-nil, combine all calendar entries into a single large
22736 file and store it under the name `org-combined-agenda-icalendar-file'."
22737 (save-excursion
22738 (org-prepare-agenda-buffers files)
22739 (let* ((dir (org-export-directory
22740 :ical (list :publishing-directory
22741 org-export-publishing-directory)))
22742 file ical-file ical-buffer category started org-agenda-new-buffers)
22744 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
22745 (when combine
22746 (setq ical-file
22747 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
22748 org-combined-agenda-icalendar-file
22749 (expand-file-name org-combined-agenda-icalendar-file dir))
22750 ical-buffer (org-get-agenda-file-buffer ical-file))
22751 (set-buffer ical-buffer) (erase-buffer))
22752 (while (setq file (pop files))
22753 (catch 'nextfile
22754 (org-check-agenda-file file)
22755 (set-buffer (org-get-agenda-file-buffer file))
22756 (unless combine
22757 (setq ical-file (concat (file-name-as-directory dir)
22758 (file-name-sans-extension
22759 (file-name-nondirectory buffer-file-name))
22760 ".ics"))
22761 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
22762 (with-current-buffer ical-buffer (erase-buffer)))
22763 (setq category (or org-category
22764 (file-name-sans-extension
22765 (file-name-nondirectory buffer-file-name))))
22766 (if (symbolp category) (setq category (symbol-name category)))
22767 (let ((standard-output ical-buffer))
22768 (if combine
22769 (and (not started) (setq started t)
22770 (org-start-icalendar-file org-icalendar-combined-name))
22771 (org-start-icalendar-file category))
22772 (org-print-icalendar-entries combine)
22773 (when (or (and combine (not files)) (not combine))
22774 (org-finish-icalendar-file)
22775 (set-buffer ical-buffer)
22776 (save-buffer)
22777 (run-hooks 'org-after-save-iCalendar-file-hook)))))
22778 (org-release-buffers org-agenda-new-buffers))))
22780 (defvar org-after-save-iCalendar-file-hook nil
22781 "Hook run after an iCalendar file has been saved.
22782 The iCalendar buffer is still current when this hook is run.
22783 A good way to use this is to tell a desktop calenndar application to re-read
22784 the iCalendar file.")
22786 (defun org-print-icalendar-entries (&optional combine)
22787 "Print iCalendar entries for the current Org-mode file to `standard-output'.
22788 When COMBINE is non nil, add the category to each line."
22789 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
22790 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
22791 (org-category-table (org-get-category-table))
22792 (dts (org-ical-ts-to-string
22793 (format-time-string (cdr org-time-stamp-formats) (current-time))
22794 "DTSTART"))
22795 hd ts ts2 state status (inc t) pos b sexp rrule
22796 scheduledp deadlinep tmp pri category
22797 (sexp-buffer (get-buffer-create "*ical-tmp*")))
22798 (save-excursion
22799 (goto-char (point-min))
22800 (while (re-search-forward re1 nil t)
22801 (catch :skip
22802 (org-agenda-skip)
22803 (setq pos (match-beginning 0)
22804 ts (match-string 0)
22805 inc t
22806 hd (org-get-heading)
22807 category (org-get-category))
22808 (if (looking-at re2)
22809 (progn
22810 (goto-char (match-end 0))
22811 (setq ts2 (match-string 1) inc nil))
22812 (setq tmp (buffer-substring (max (point-min)
22813 (- pos org-ds-keyword-length))
22814 pos)
22815 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
22816 (progn
22817 (setq inc nil)
22818 (replace-match "\\1" t nil ts))
22820 deadlinep (string-match org-deadline-regexp tmp)
22821 scheduledp (string-match org-scheduled-regexp tmp)
22822 ;; donep (org-entry-is-done-p)
22824 (if (or (string-match org-tr-regexp hd)
22825 (string-match org-ts-regexp hd))
22826 (setq hd (replace-match "" t t hd)))
22827 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
22828 (setq rrule
22829 (concat "\nRRULE:FREQ="
22830 (cdr (assoc
22831 (match-string 2 ts)
22832 '(("d" . "DAILY")("w" . "WEEKLY")
22833 ("m" . "MONTHLY")("y" . "YEARLY"))))
22834 ";INTERVAL=" (match-string 1 ts)))
22835 (setq rrule ""))
22836 (if (string-match org-bracket-link-regexp hd)
22837 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22838 (match-string 1 hd))
22839 t t hd)))
22840 (if deadlinep (setq hd (concat "DL: " hd)))
22841 (if scheduledp (setq hd (concat "S: " hd)))
22842 (if (string-match "\\`<%%" ts)
22843 (with-current-buffer sexp-buffer
22844 (insert (substring ts 1 -1) " " hd "\n"))
22845 (princ (format "BEGIN:VEVENT
22847 %s%s
22848 SUMMARY:%s
22849 CATEGORIES:%s
22850 END:VEVENT\n"
22851 (org-ical-ts-to-string ts "DTSTART")
22852 (org-ical-ts-to-string ts2 "DTEND" inc)
22853 rrule hd category)))))
22855 (when (and org-icalendar-include-sexps
22856 (condition-case nil (require 'icalendar) (error nil))
22857 (fboundp 'icalendar-export-region))
22858 ;; Get all the literal sexps
22859 (goto-char (point-min))
22860 (while (re-search-forward "^&?%%(" nil t)
22861 (catch :skip
22862 (org-agenda-skip)
22863 (setq b (match-beginning 0))
22864 (goto-char (1- (match-end 0)))
22865 (forward-sexp 1)
22866 (end-of-line 1)
22867 (setq sexp (buffer-substring b (point)))
22868 (with-current-buffer sexp-buffer
22869 (insert sexp "\n"))
22870 (princ (org-diary-to-ical-string sexp-buffer)))))
22872 (when org-icalendar-include-todo
22873 (goto-char (point-min))
22874 (while (re-search-forward org-todo-line-regexp nil t)
22875 (catch :skip
22876 (org-agenda-skip)
22877 (setq state (match-string 2))
22878 (setq status (if (member state org-done-keywords)
22879 "COMPLETED" "NEEDS-ACTION"))
22880 (when (and state
22881 (or (not (member state org-done-keywords))
22882 (eq org-icalendar-include-todo 'all))
22883 (not (member org-archive-tag (org-get-tags-at)))
22885 (setq hd (match-string 3))
22886 (if (string-match org-bracket-link-regexp hd)
22887 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22888 (match-string 1 hd))
22889 t t hd)))
22890 (if (string-match org-priority-regexp hd)
22891 (setq pri (string-to-char (match-string 2 hd))
22892 hd (concat (substring hd 0 (match-beginning 1))
22893 (substring hd (match-end 1))))
22894 (setq pri org-default-priority))
22895 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
22896 (- org-lowest-priority org-highest-priority))))))
22898 (princ (format "BEGIN:VTODO
22900 SUMMARY:%s
22901 CATEGORIES:%s
22902 SEQUENCE:1
22903 PRIORITY:%d
22904 STATUS:%s
22905 END:VTODO\n"
22906 dts hd category pri status)))))))))
22908 (defun org-start-icalendar-file (name)
22909 "Start an iCalendar file by inserting the header."
22910 (let ((user user-full-name)
22911 (name (or name "unknown"))
22912 (timezone (cadr (current-time-zone))))
22913 (princ
22914 (format "BEGIN:VCALENDAR
22915 VERSION:2.0
22916 X-WR-CALNAME:%s
22917 PRODID:-//%s//Emacs with Org-mode//EN
22918 X-WR-TIMEZONE:%s
22919 CALSCALE:GREGORIAN\n" name user timezone))))
22921 (defun org-finish-icalendar-file ()
22922 "Finish an iCalendar file by inserting the END statement."
22923 (princ "END:VCALENDAR\n"))
22925 (defun org-ical-ts-to-string (s keyword &optional inc)
22926 "Take a time string S and convert it to iCalendar format.
22927 KEYWORD is added in front, to make a complete line like DTSTART....
22928 When INC is non-nil, increase the hour by two (if time string contains
22929 a time), or the day by one (if it does not contain a time)."
22930 (let ((t1 (org-parse-time-string s 'nodefault))
22931 t2 fmt have-time time)
22932 (if (and (car t1) (nth 1 t1) (nth 2 t1))
22933 (setq t2 t1 have-time t)
22934 (setq t2 (org-parse-time-string s)))
22935 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
22936 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
22937 (when inc
22938 (if have-time
22939 (if org-agenda-default-appointment-duration
22940 (setq mi (+ org-agenda-default-appointment-duration mi))
22941 (setq h (+ 2 h)))
22942 (setq d (1+ d))))
22943 (setq time (encode-time s mi h d m y)))
22944 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
22945 (concat keyword (format-time-string fmt time))))
22947 ;;; XOXO export
22949 (defun org-export-as-xoxo-insert-into (buffer &rest output)
22950 (with-current-buffer buffer
22951 (apply 'insert output)))
22952 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
22954 (defun org-export-as-xoxo (&optional buffer)
22955 "Export the org buffer as XOXO.
22956 The XOXO buffer is named *xoxo-<source buffer name>*"
22957 (interactive (list (current-buffer)))
22958 ;; A quickie abstraction
22960 ;; Output everything as XOXO
22961 (with-current-buffer (get-buffer buffer)
22962 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
22963 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22964 (org-infile-export-plist)))
22965 (filename (concat (file-name-as-directory
22966 (org-export-directory :xoxo opt-plist))
22967 (file-name-sans-extension
22968 (file-name-nondirectory buffer-file-name))
22969 ".html"))
22970 (out (find-file-noselect filename))
22971 (last-level 1)
22972 (hanging-li nil))
22973 ;; Check the output buffer is empty.
22974 (with-current-buffer out (erase-buffer))
22975 ;; Kick off the output
22976 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
22977 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
22978 (let* ((hd (match-string-no-properties 1))
22979 (level (length hd))
22980 (text (concat
22981 (match-string-no-properties 2)
22982 (save-excursion
22983 (goto-char (match-end 0))
22984 (let ((str ""))
22985 (catch 'loop
22986 (while 't
22987 (forward-line)
22988 (if (looking-at "^[ \t]\\(.*\\)")
22989 (setq str (concat str (match-string-no-properties 1)))
22990 (throw 'loop str)))))))))
22992 ;; Handle level rendering
22993 (cond
22994 ((> level last-level)
22995 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
22997 ((< level last-level)
22998 (dotimes (- (- last-level level) 1)
22999 (if hanging-li
23000 (org-export-as-xoxo-insert-into out "</li>\n"))
23001 (org-export-as-xoxo-insert-into out "</ol>\n"))
23002 (when hanging-li
23003 (org-export-as-xoxo-insert-into out "</li>\n")
23004 (setq hanging-li nil)))
23006 ((equal level last-level)
23007 (if hanging-li
23008 (org-export-as-xoxo-insert-into out "</li>\n")))
23011 (setq last-level level)
23013 ;; And output the new li
23014 (setq hanging-li 't)
23015 (if (equal ?+ (elt text 0))
23016 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
23017 (org-export-as-xoxo-insert-into out "<li>" text))))
23019 ;; Finally finish off the ol
23020 (dotimes (- last-level 1)
23021 (if hanging-li
23022 (org-export-as-xoxo-insert-into out "</li>\n"))
23023 (org-export-as-xoxo-insert-into out "</ol>\n"))
23025 ;; Finish the buffer off and clean it up.
23026 (switch-to-buffer-other-window out)
23027 (indent-region (point-min) (point-max) nil)
23028 (save-buffer)
23029 (goto-char (point-min))
23033 ;;;; Key bindings
23035 ;; Make `C-c C-x' a prefix key
23036 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
23038 ;; TAB key with modifiers
23039 (org-defkey org-mode-map "\C-i" 'org-cycle)
23040 (org-defkey org-mode-map [(tab)] 'org-cycle)
23041 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
23042 (org-defkey org-mode-map [(meta tab)] 'org-complete)
23043 (org-defkey org-mode-map "\M-\t" 'org-complete)
23044 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
23045 ;; The following line is necessary under Suse GNU/Linux
23046 (unless (featurep 'xemacs)
23047 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
23048 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
23049 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
23051 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
23052 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
23053 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
23055 ;; Cursor keys with modifiers
23056 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
23057 (org-defkey org-mode-map [(meta right)] 'org-metaright)
23058 (org-defkey org-mode-map [(meta up)] 'org-metaup)
23059 (org-defkey org-mode-map [(meta down)] 'org-metadown)
23061 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
23062 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
23063 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
23064 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
23066 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
23067 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
23068 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
23069 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
23071 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
23072 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
23074 ;;; Extra keys for tty access.
23075 ;; We only set them when really needed because otherwise the
23076 ;; menus don't show the simple keys
23078 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
23079 (not window-system))
23080 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
23081 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
23082 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
23083 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
23084 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
23085 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
23086 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
23087 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
23088 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
23089 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
23090 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
23091 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
23092 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
23093 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
23094 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
23095 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
23096 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
23097 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
23098 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
23099 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
23100 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
23101 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
23103 ;; All the other keys
23105 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
23106 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
23107 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
23108 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
23109 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
23110 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
23111 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
23112 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
23113 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
23114 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
23115 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
23116 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
23117 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
23118 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
23119 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
23120 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
23121 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
23122 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
23123 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
23124 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
23125 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
23126 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
23127 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
23128 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
23129 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
23130 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
23131 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
23132 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
23133 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
23134 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
23135 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
23136 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
23137 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
23138 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
23139 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
23140 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
23141 (org-defkey org-mode-map "\C-c^" 'org-sort)
23142 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
23143 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
23144 (org-defkey org-mode-map "\C-m" 'org-return)
23145 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
23146 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
23147 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
23148 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
23149 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
23150 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
23151 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
23152 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
23153 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
23154 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
23155 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
23156 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
23157 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
23158 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
23159 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
23160 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
23162 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
23163 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
23164 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
23165 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
23167 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
23168 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
23169 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
23170 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
23171 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
23172 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
23173 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
23174 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
23175 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
23177 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
23179 (when (featurep 'xemacs)
23180 (org-defkey org-mode-map 'button3 'popup-mode-menu))
23182 (defsubst org-table-p () (org-at-table-p))
23184 (defun org-self-insert-command (N)
23185 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
23186 If the cursor is in a table looking at whitespace, the whitespace is
23187 overwritten, and the table is not marked as requiring realignment."
23188 (interactive "p")
23189 (if (and (org-table-p)
23190 (progn
23191 ;; check if we blank the field, and if that triggers align
23192 (and org-table-auto-blank-field
23193 (member last-command
23194 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
23195 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
23196 ;; got extra space, this field does not determine column width
23197 (let (org-table-may-need-update) (org-table-blank-field))
23198 ;; no extra space, this field may determine column width
23199 (org-table-blank-field)))
23201 (eq N 1)
23202 (looking-at "[^|\n]* |"))
23203 (let (org-table-may-need-update)
23204 (goto-char (1- (match-end 0)))
23205 (delete-backward-char 1)
23206 (goto-char (match-beginning 0))
23207 (self-insert-command N))
23208 (setq org-table-may-need-update t)
23209 (self-insert-command N)
23210 (org-fix-tags-on-the-fly)))
23212 (defun org-fix-tags-on-the-fly ()
23213 (when (and (equal (char-after (point-at-bol)) ?*)
23214 (org-on-heading-p))
23215 (org-align-tags-here org-tags-column)))
23217 (defun org-delete-backward-char (N)
23218 "Like `delete-backward-char', insert whitespace at field end in tables.
23219 When deleting backwards, in tables this function will insert whitespace in
23220 front of the next \"|\" separator, to keep the table aligned. The table will
23221 still be marked for re-alignment if the field did fill the entire column,
23222 because, in this case the deletion might narrow the column."
23223 (interactive "p")
23224 (if (and (org-table-p)
23225 (eq N 1)
23226 (string-match "|" (buffer-substring (point-at-bol) (point)))
23227 (looking-at ".*?|"))
23228 (let ((pos (point))
23229 (noalign (looking-at "[^|\n\r]* |"))
23230 (c org-table-may-need-update))
23231 (backward-delete-char N)
23232 (skip-chars-forward "^|")
23233 (insert " ")
23234 (goto-char (1- pos))
23235 ;; noalign: if there were two spaces at the end, this field
23236 ;; does not determine the width of the column.
23237 (if noalign (setq org-table-may-need-update c)))
23238 (backward-delete-char N)
23239 (org-fix-tags-on-the-fly)))
23241 (defun org-delete-char (N)
23242 "Like `delete-char', but insert whitespace at field end in tables.
23243 When deleting characters, in tables this function will insert whitespace in
23244 front of the next \"|\" separator, to keep the table aligned. The table will
23245 still be marked for re-alignment if the field did fill the entire column,
23246 because, in this case the deletion might narrow the column."
23247 (interactive "p")
23248 (if (and (org-table-p)
23249 (not (bolp))
23250 (not (= (char-after) ?|))
23251 (eq N 1))
23252 (if (looking-at ".*?|")
23253 (let ((pos (point))
23254 (noalign (looking-at "[^|\n\r]* |"))
23255 (c org-table-may-need-update))
23256 (replace-match (concat
23257 (substring (match-string 0) 1 -1)
23258 " |"))
23259 (goto-char pos)
23260 ;; noalign: if there were two spaces at the end, this field
23261 ;; does not determine the width of the column.
23262 (if noalign (setq org-table-may-need-update c)))
23263 (delete-char N))
23264 (delete-char N)
23265 (org-fix-tags-on-the-fly)))
23267 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
23268 (put 'org-self-insert-command 'delete-selection t)
23269 (put 'orgtbl-self-insert-command 'delete-selection t)
23270 (put 'org-delete-char 'delete-selection 'supersede)
23271 (put 'org-delete-backward-char 'delete-selection 'supersede)
23273 ;; Make `flyspell-mode' delay after some commands
23274 (put 'org-self-insert-command 'flyspell-delayed t)
23275 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
23276 (put 'org-delete-char 'flyspell-delayed t)
23277 (put 'org-delete-backward-char 'flyspell-delayed t)
23279 ;; How to do this: Measure non-white length of current string
23280 ;; If equal to column width, we should realign.
23282 (defun org-remap (map &rest commands)
23283 "In MAP, remap the functions given in COMMANDS.
23284 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
23285 (let (new old)
23286 (while commands
23287 (setq old (pop commands) new (pop commands))
23288 (if (fboundp 'command-remapping)
23289 (org-defkey map (vector 'remap old) new)
23290 (substitute-key-definition old new map global-map)))))
23292 (when (eq org-enable-table-editor 'optimized)
23293 ;; If the user wants maximum table support, we need to hijack
23294 ;; some standard editing functions
23295 (org-remap org-mode-map
23296 'self-insert-command 'org-self-insert-command
23297 'delete-char 'org-delete-char
23298 'delete-backward-char 'org-delete-backward-char)
23299 (org-defkey org-mode-map "|" 'org-force-self-insert))
23301 (defun org-shiftcursor-error ()
23302 "Throw an error because Shift-Cursor command was applied in wrong context."
23303 (error "This command is active in special context like tables, headlines or timestamps"))
23305 (defun org-shifttab (&optional arg)
23306 "Global visibility cycling or move to previous table field.
23307 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
23308 on context.
23309 See the individual commands for more information."
23310 (interactive "P")
23311 (cond
23312 ((org-at-table-p) (call-interactively 'org-table-previous-field))
23313 (arg (message "Content view to level: ")
23314 (org-content (prefix-numeric-value arg))
23315 (setq org-cycle-global-status 'overview))
23316 (t (call-interactively 'org-global-cycle))))
23318 (defun org-shiftmetaleft ()
23319 "Promote subtree or delete table column.
23320 Calls `org-promote-subtree', `org-outdent-item',
23321 or `org-table-delete-column', depending on context.
23322 See the individual commands for more information."
23323 (interactive)
23324 (cond
23325 ((org-at-table-p) (call-interactively 'org-table-delete-column))
23326 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
23327 ((org-at-item-p) (call-interactively 'org-outdent-item))
23328 (t (org-shiftcursor-error))))
23330 (defun org-shiftmetaright ()
23331 "Demote subtree or insert table column.
23332 Calls `org-demote-subtree', `org-indent-item',
23333 or `org-table-insert-column', depending on context.
23334 See the individual commands for more information."
23335 (interactive)
23336 (cond
23337 ((org-at-table-p) (call-interactively 'org-table-insert-column))
23338 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
23339 ((org-at-item-p) (call-interactively 'org-indent-item))
23340 (t (org-shiftcursor-error))))
23342 (defun org-shiftmetaup (&optional arg)
23343 "Move subtree up or kill table row.
23344 Calls `org-move-subtree-up' or `org-table-kill-row' or
23345 `org-move-item-up' depending on context. See the individual commands
23346 for more information."
23347 (interactive "P")
23348 (cond
23349 ((org-at-table-p) (call-interactively 'org-table-kill-row))
23350 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23351 ((org-at-item-p) (call-interactively 'org-move-item-up))
23352 (t (org-shiftcursor-error))))
23353 (defun org-shiftmetadown (&optional arg)
23354 "Move subtree down or insert table row.
23355 Calls `org-move-subtree-down' or `org-table-insert-row' or
23356 `org-move-item-down', depending on context. See the individual
23357 commands for more information."
23358 (interactive "P")
23359 (cond
23360 ((org-at-table-p) (call-interactively 'org-table-insert-row))
23361 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23362 ((org-at-item-p) (call-interactively 'org-move-item-down))
23363 (t (org-shiftcursor-error))))
23365 (defun org-metaleft (&optional arg)
23366 "Promote heading or move table column to left.
23367 Calls `org-do-promote' or `org-table-move-column', depending on context.
23368 With no specific context, calls the Emacs default `backward-word'.
23369 See the individual commands for more information."
23370 (interactive "P")
23371 (cond
23372 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
23373 ((or (org-on-heading-p) (org-region-active-p))
23374 (call-interactively 'org-do-promote))
23375 ((org-at-item-p) (call-interactively 'org-outdent-item))
23376 (t (call-interactively 'backward-word))))
23378 (defun org-metaright (&optional arg)
23379 "Demote subtree or move table column to right.
23380 Calls `org-do-demote' or `org-table-move-column', depending on context.
23381 With no specific context, calls the Emacs default `forward-word'.
23382 See the individual commands for more information."
23383 (interactive "P")
23384 (cond
23385 ((org-at-table-p) (call-interactively 'org-table-move-column))
23386 ((or (org-on-heading-p) (org-region-active-p))
23387 (call-interactively 'org-do-demote))
23388 ((org-at-item-p) (call-interactively 'org-indent-item))
23389 (t (call-interactively 'forward-word))))
23391 (defun org-metaup (&optional arg)
23392 "Move subtree up or move table row up.
23393 Calls `org-move-subtree-up' or `org-table-move-row' or
23394 `org-move-item-up', depending on context. See the individual commands
23395 for more information."
23396 (interactive "P")
23397 (cond
23398 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
23399 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
23400 ((org-at-item-p) (call-interactively 'org-move-item-up))
23401 (t (org-shiftcursor-error))))
23403 (defun org-metadown (&optional arg)
23404 "Move subtree down or move table row down.
23405 Calls `org-move-subtree-down' or `org-table-move-row' or
23406 `org-move-item-down', depending on context. See the individual
23407 commands for more information."
23408 (interactive "P")
23409 (cond
23410 ((org-at-table-p) (call-interactively 'org-table-move-row))
23411 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
23412 ((org-at-item-p) (call-interactively 'org-move-item-down))
23413 (t (org-shiftcursor-error))))
23415 (defun org-shiftup (&optional arg)
23416 "Increase item in timestamp or increase priority of current headline.
23417 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
23418 depending on context. See the individual commands for more information."
23419 (interactive "P")
23420 (cond
23421 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
23422 ((org-on-heading-p) (call-interactively 'org-priority-up))
23423 ((org-at-item-p) (call-interactively 'org-previous-item))
23424 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
23426 (defun org-shiftdown (&optional arg)
23427 "Decrease item in timestamp or decrease priority of current headline.
23428 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
23429 depending on context. See the individual commands for more information."
23430 (interactive "P")
23431 (cond
23432 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
23433 ((org-on-heading-p) (call-interactively 'org-priority-down))
23434 (t (call-interactively 'org-next-item))))
23436 (defun org-shiftright ()
23437 "Next TODO keyword or timestamp one day later, depending on context."
23438 (interactive)
23439 (cond
23440 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
23441 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
23442 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
23443 (t (org-shiftcursor-error))))
23445 (defun org-shiftleft ()
23446 "Previous TODO keyword or timestamp one day earlier, depending on context."
23447 (interactive)
23448 (cond
23449 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
23450 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
23451 ((org-at-property-p)
23452 (call-interactively 'org-property-previous-allowed-value))
23453 (t (org-shiftcursor-error))))
23455 (defun org-shiftcontrolright ()
23456 "Switch to next TODO set."
23457 (interactive)
23458 (cond
23459 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
23460 (t (org-shiftcursor-error))))
23462 (defun org-shiftcontrolleft ()
23463 "Switch to previous TODO set."
23464 (interactive)
23465 (cond
23466 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
23467 (t (org-shiftcursor-error))))
23469 (defun org-ctrl-c-ret ()
23470 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
23471 (interactive)
23472 (cond
23473 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
23474 (t (call-interactively 'org-insert-heading))))
23476 (defun org-copy-special ()
23477 "Copy region in table or copy current subtree.
23478 Calls `org-table-copy' or `org-copy-subtree', depending on context.
23479 See the individual commands for more information."
23480 (interactive)
23481 (call-interactively
23482 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
23484 (defun org-cut-special ()
23485 "Cut region in table or cut current subtree.
23486 Calls `org-table-copy' or `org-cut-subtree', depending on context.
23487 See the individual commands for more information."
23488 (interactive)
23489 (call-interactively
23490 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
23492 (defun org-paste-special (arg)
23493 "Paste rectangular region into table, or past subtree relative to level.
23494 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
23495 See the individual commands for more information."
23496 (interactive "P")
23497 (if (org-at-table-p)
23498 (org-table-paste-rectangle)
23499 (org-paste-subtree arg)))
23501 (defun org-ctrl-c-ctrl-c (&optional arg)
23502 "Set tags in headline, or update according to changed information at point.
23504 This command does many different things, depending on context:
23506 - If the cursor is in a headline, prompt for tags and insert them
23507 into the current line, aligned to `org-tags-column'. When called
23508 with prefix arg, realign all tags in the current buffer.
23510 - If the cursor is in one of the special #+KEYWORD lines, this
23511 triggers scanning the buffer for these lines and updating the
23512 information.
23514 - If the cursor is inside a table, realign the table. This command
23515 works even if the automatic table editor has been turned off.
23517 - If the cursor is on a #+TBLFM line, re-apply the formulas to
23518 the entire table.
23520 - If the cursor is inside a table created by the table.el package,
23521 activate that table.
23523 - If the current buffer is a remember buffer, close note and file it.
23524 with a prefix argument, file it without further interaction to the default
23525 location.
23527 - If the cursor is on a <<<target>>>, update radio targets and corresponding
23528 links in this buffer.
23530 - If the cursor is on a numbered item in a plain list, renumber the
23531 ordered list."
23532 (interactive "P")
23533 (let ((org-enable-table-editor t))
23534 (cond
23535 ((or org-clock-overlays
23536 org-occur-highlights
23537 org-latex-fragment-image-overlays)
23538 (org-remove-clock-overlays)
23539 (org-remove-occur-highlights)
23540 (org-remove-latex-fragment-image-overlays)
23541 (message "Temporary highlights/overlays removed from current buffer"))
23542 ((and (local-variable-p 'org-finish-function (current-buffer))
23543 (fboundp org-finish-function))
23544 (funcall org-finish-function))
23545 ((org-at-property-p)
23546 (call-interactively 'org-property-action))
23547 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
23548 ((org-on-heading-p) (call-interactively 'org-set-tags))
23549 ((org-at-table.el-p)
23550 (require 'table)
23551 (beginning-of-line 1)
23552 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
23553 (call-interactively 'table-recognize-table))
23554 ((org-at-table-p)
23555 (org-table-maybe-eval-formula)
23556 (if arg
23557 (call-interactively 'org-table-recalculate)
23558 (org-table-maybe-recalculate-line))
23559 (call-interactively 'org-table-align))
23560 ((org-at-item-checkbox-p)
23561 (call-interactively 'org-toggle-checkbox))
23562 ((org-at-item-p)
23563 (call-interactively 'org-maybe-renumber-ordered-list))
23564 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
23565 (cond
23566 ((equal (match-string 1) "TBLFM")
23567 ;; Recalculate the table before this line
23568 (save-excursion
23569 (beginning-of-line 1)
23570 (skip-chars-backward " \r\n\t")
23571 (if (org-at-table-p)
23572 (org-call-with-arg 'org-table-recalculate t))))
23574 (call-interactively 'org-mode-restart))))
23575 (t (error "C-c C-c can do nothing useful at this location.")))))
23577 (defun org-mode-restart ()
23578 "Restart Org-mode, to scan again for special lines.
23579 Also updates the keyword regular expressions."
23580 (interactive)
23581 (let ((org-inhibit-startup t)) (org-mode))
23582 (message "Org-mode restarted to refresh keyword and special line setup"))
23584 (defun org-return ()
23585 "Goto next table row or insert a newline.
23586 Calls `org-table-next-row' or `newline', depending on context.
23587 See the individual commands for more information."
23588 (interactive)
23589 (cond
23590 ((bobp) (newline))
23591 ((org-at-table-p)
23592 (org-table-justify-field-maybe)
23593 (call-interactively 'org-table-next-row))
23594 (t (newline))))
23596 (defun org-ctrl-c-minus ()
23597 "Insert separator line in table or modify bullet type in list.
23598 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
23599 depending on context."
23600 (interactive)
23601 (cond
23602 ((org-at-table-p)
23603 (call-interactively 'org-table-insert-hline))
23604 ((org-in-item-p)
23605 (call-interactively 'org-cycle-list-bullet))
23606 (t (error "`C-c -' does have no function here."))))
23608 (defun org-meta-return (&optional arg)
23609 "Insert a new heading or wrap a region in a table.
23610 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
23611 See the individual commands for more information."
23612 (interactive "P")
23613 (cond
23614 ((org-at-table-p)
23615 (call-interactively 'org-table-wrap-region))
23616 (t (call-interactively 'org-insert-heading))))
23618 ;;; Menu entries
23620 ;; Define the Org-mode menus
23621 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
23622 '("Tbl"
23623 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
23624 ["Next Field" org-cycle (org-at-table-p)]
23625 ["Previous Field" org-shifttab (org-at-table-p)]
23626 ["Next Row" org-return (org-at-table-p)]
23627 "--"
23628 ["Blank Field" org-table-blank-field (org-at-table-p)]
23629 ["Edit Field" org-table-edit-field (org-at-table-p)]
23630 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
23631 "--"
23632 ("Column"
23633 ["Move Column Left" org-metaleft (org-at-table-p)]
23634 ["Move Column Right" org-metaright (org-at-table-p)]
23635 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
23636 ["Insert Column" org-shiftmetaright (org-at-table-p)])
23637 ("Row"
23638 ["Move Row Up" org-metaup (org-at-table-p)]
23639 ["Move Row Down" org-metadown (org-at-table-p)]
23640 ["Delete Row" org-shiftmetaup (org-at-table-p)]
23641 ["Insert Row" org-shiftmetadown (org-at-table-p)]
23642 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
23643 "--"
23644 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
23645 ("Rectangle"
23646 ["Copy Rectangle" org-copy-special (org-at-table-p)]
23647 ["Cut Rectangle" org-cut-special (org-at-table-p)]
23648 ["Paste Rectangle" org-paste-special (org-at-table-p)]
23649 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
23650 "--"
23651 ("Calculate"
23652 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
23653 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
23654 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
23655 "--"
23656 ["Recalculate line" org-table-recalculate (org-at-table-p)]
23657 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
23658 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
23659 "--"
23660 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
23661 "--"
23662 ["Sum Column/Rectangle" org-table-sum
23663 (or (org-at-table-p) (org-region-active-p))]
23664 ["Which Column?" org-table-current-column (org-at-table-p)])
23665 ["Debug Formulas"
23666 org-table-toggle-formula-debugger
23667 :style toggle :selected org-table-formula-debug]
23668 ["Show Col/Row Numbers"
23669 org-table-toggle-coordinate-overlays
23670 :style toggle :selected org-table-overlay-coordinates]
23671 "--"
23672 ["Create" org-table-create (and (not (org-at-table-p))
23673 org-enable-table-editor)]
23674 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
23675 ["Import from File" org-table-import (not (org-at-table-p))]
23676 ["Export to File" org-table-export (org-at-table-p)]
23677 "--"
23678 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
23680 (easy-menu-define org-org-menu org-mode-map "Org menu"
23681 '("Org"
23682 ("Show/Hide"
23683 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
23684 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
23685 ["Sparse Tree" org-occur t]
23686 ["Reveal Context" org-reveal t]
23687 ["Show All" show-all t]
23688 "--"
23689 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
23690 "--"
23691 ["New Heading" org-insert-heading t]
23692 ("Navigate Headings"
23693 ["Up" outline-up-heading t]
23694 ["Next" outline-next-visible-heading t]
23695 ["Previous" outline-previous-visible-heading t]
23696 ["Next Same Level" outline-forward-same-level t]
23697 ["Previous Same Level" outline-backward-same-level t]
23698 "--"
23699 ["Jump" org-goto t])
23700 ("Edit Structure"
23701 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
23702 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
23703 "--"
23704 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
23705 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
23706 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
23707 "--"
23708 ["Promote Heading" org-metaleft (not (org-at-table-p))]
23709 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
23710 ["Demote Heading" org-metaright (not (org-at-table-p))]
23711 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
23712 "--"
23713 ["Sort Region/Children" org-sort (not (org-at-table-p))]
23714 "--"
23715 ["Convert to odd levels" org-convert-to-odd-levels t]
23716 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
23717 ("Editing"
23718 ["Emphasis..." org-emphasize t])
23719 ("Archive"
23720 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
23721 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
23722 ; :active t :keys "C-u C-c C-x C-a"]
23723 ["Sparse trees open ARCHIVE trees"
23724 (setq org-sparse-tree-open-archived-trees
23725 (not org-sparse-tree-open-archived-trees))
23726 :style toggle :selected org-sparse-tree-open-archived-trees]
23727 ["Cycling opens ARCHIVE trees"
23728 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
23729 :style toggle :selected org-cycle-open-archived-trees]
23730 ["Agenda includes ARCHIVE trees"
23731 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
23732 :style toggle :selected (not org-agenda-skip-archived-trees)]
23733 "--"
23734 ["Move Subtree to Archive" org-advertized-archive-subtree t]
23735 ; ["Check and Move Children" (org-archive-subtree '(4))
23736 ; :active t :keys "C-u C-c C-x C-s"]
23738 "--"
23739 ("TODO Lists"
23740 ["TODO/DONE/-" org-todo t]
23741 ("Select keyword"
23742 ["Next keyword" org-shiftright (org-on-heading-p)]
23743 ["Previous keyword" org-shiftleft (org-on-heading-p)]
23744 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
23745 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
23746 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
23747 ["Show TODO Tree" org-show-todo-tree t]
23748 ["Global TODO list" org-todo-list t]
23749 "--"
23750 ["Set Priority" org-priority t]
23751 ["Priority Up" org-shiftup t]
23752 ["Priority Down" org-shiftdown t])
23753 ("TAGS and Properties"
23754 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
23755 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)] ;FIXME
23756 ["Column view of properties" org-columns t])
23757 ("Dates and Scheduling"
23758 ["Timestamp" org-time-stamp t]
23759 ["Timestamp (inactive)" org-time-stamp-inactive t]
23760 ("Change Date"
23761 ["1 Day Later" org-shiftright t]
23762 ["1 Day Earlier" org-shiftleft t]
23763 ["1 ... Later" org-shiftup t]
23764 ["1 ... Earlier" org-shiftdown t])
23765 ["Compute Time Range" org-evaluate-time-range t]
23766 ["Schedule Item" org-schedule t]
23767 ["Deadline" org-deadline t]
23768 "--"
23769 ["Custom time format" org-toggle-time-stamp-overlays
23770 :style radio :selected org-display-custom-times]
23771 "--"
23772 ["Goto Calendar" org-goto-calendar t]
23773 ["Date from Calendar" org-date-from-calendar t])
23774 ("Logging work"
23775 ["Clock in" org-clock-in t]
23776 ["Clock out" org-clock-out t]
23777 ["Clock cancel" org-clock-cancel t]
23778 ["Display times" org-clock-display t]
23779 ["Create clock table" org-clock-report t]
23780 "--"
23781 ["Record DONE time"
23782 (progn (setq org-log-done (not org-log-done))
23783 (message "Switching to %s will %s record a timestamp"
23784 (car org-done-keywords)
23785 (if org-log-done "automatically" "not")))
23786 :style toggle :selected org-log-done])
23787 "--"
23788 ["Agenda Command..." org-agenda t]
23789 ("File List for Agenda")
23790 ("Special views current file"
23791 ["TODO Tree" org-show-todo-tree t]
23792 ["Check Deadlines" org-check-deadlines t]
23793 ["Timeline" org-timeline t]
23794 ["Tags Tree" org-tags-sparse-tree t])
23795 "--"
23796 ("Hyperlinks"
23797 ["Store Link (Global)" org-store-link t]
23798 ["Insert Link" org-insert-link t]
23799 ["Follow Link" org-open-at-point t]
23800 "--"
23801 ["Next link" org-next-link t]
23802 ["Previous link" org-previous-link t]
23803 "--"
23804 ["Descriptive Links"
23805 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
23806 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
23807 ["Literal Links"
23808 (progn
23809 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
23810 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
23811 "--"
23812 ["Export/Publish..." org-export t]
23813 ("LaTeX"
23814 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
23815 :selected org-cdlatex-mode]
23816 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
23817 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
23818 ["Modify math symbol" org-cdlatex-math-modify
23819 (org-inside-LaTeX-fragment-p)]
23820 ["Export LaTeX fragments as images"
23821 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
23822 :style toggle :selected org-export-with-LaTeX-fragments])
23823 "--"
23824 ("Documentation"
23825 ["Show Version" org-version t]
23826 ["Info Documentation" org-info t])
23827 ("Customize"
23828 ["Browse Org Group" org-customize t]
23829 "--"
23830 ["Expand This Menu" org-create-customize-menu
23831 (fboundp 'customize-menu-create)])
23832 "--"
23833 ["Refresh setup" org-mode-restart t]
23836 (defun org-info (&optional node)
23837 "Read documentation for Org-mode in the info system.
23838 With optional NODE, go directly to that node."
23839 (interactive)
23840 (require 'info)
23841 (Info-goto-node (format "(org)%s" (or node ""))))
23843 (defun org-install-agenda-files-menu ()
23844 (let ((bl (buffer-list)))
23845 (save-excursion
23846 (while bl
23847 (set-buffer (pop bl))
23848 (if (org-mode-p) (setq bl nil)))
23849 (when (org-mode-p)
23850 (easy-menu-change
23851 '("Org") "File List for Agenda"
23852 (append
23853 (list
23854 ["Edit File List" (org-edit-agenda-file-list) t]
23855 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
23856 ["Remove Current File from List" org-remove-file t]
23857 ["Cycle through agenda files" org-cycle-agenda-files t]
23858 "--")
23859 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
23861 ;;;; Documentation
23863 (defun org-customize ()
23864 "Call the customize function with org as argument."
23865 (interactive)
23866 (customize-browse 'org))
23868 (defun org-create-customize-menu ()
23869 "Create a full customization menu for Org-mode, insert it into the menu."
23870 (interactive)
23871 (if (fboundp 'customize-menu-create)
23872 (progn
23873 (easy-menu-change
23874 '("Org") "Customize"
23875 `(["Browse Org group" org-customize t]
23876 "--"
23877 ,(customize-menu-create 'org)
23878 ["Set" Custom-set t]
23879 ["Save" Custom-save t]
23880 ["Reset to Current" Custom-reset-current t]
23881 ["Reset to Saved" Custom-reset-saved t]
23882 ["Reset to Standard Settings" Custom-reset-standard t]))
23883 (message "\"Org\"-menu now contains full customization menu"))
23884 (error "Cannot expand menu (outdated version of cus-edit.el)")))
23886 ;;;; Miscellaneous stuff
23889 ;;; Generally useful functions
23891 (defun org-context ()
23892 "Return a list of contexts of the current cursor position.
23893 If several contexts apply, all are returned.
23894 Each context entry is a list with a symbol naming the context, and
23895 two positions indicating start and end of the context. Possible
23896 contexts are:
23898 :headline anywhere in a headline
23899 :headline-stars on the leading stars in a headline
23900 :todo-keyword on a TODO keyword (including DONE) in a headline
23901 :tags on the TAGS in a headline
23902 :priority on the priority cookie in a headline
23903 :item on the first line of a plain list item
23904 :item-bullet on the bullet/number of a plain list item
23905 :checkbox on the checkbox in a plain list item
23906 :table in an org-mode table
23907 :table-special on a special filed in a table
23908 :table-table in a table.el table
23909 :link on a hyperlink
23910 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
23911 :target on a <<target>>
23912 :radio-target on a <<<radio-target>>>
23913 :latex-fragment on a LaTeX fragment
23914 :latex-preview on a LaTeX fragment with overlayed preview image
23916 This function expects the position to be visible because it uses font-lock
23917 faces as a help to recognize the following contexts: :table-special, :link,
23918 and :keyword."
23919 (let* ((f (get-text-property (point) 'face))
23920 (faces (if (listp f) f (list f)))
23921 (p (point)) clist o)
23922 ;; First the large context
23923 (cond
23924 ((org-on-heading-p t)
23925 (push (list :headline (point-at-bol) (point-at-eol)) clist)
23926 (when (progn
23927 (beginning-of-line 1)
23928 (looking-at org-todo-line-tags-regexp))
23929 (push (org-point-in-group p 1 :headline-stars) clist)
23930 (push (org-point-in-group p 2 :todo-keyword) clist)
23931 (push (org-point-in-group p 4 :tags) clist))
23932 (goto-char p)
23933 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
23934 (if (looking-at "\\[#[A-Z0-9]\\]")
23935 (push (org-point-in-group p 0 :priority) clist)))
23937 ((org-at-item-p)
23938 (push (org-point-in-group p 2 :item-bullet) clist)
23939 (push (list :item (point-at-bol)
23940 (save-excursion (org-end-of-item) (point)))
23941 clist)
23942 (and (org-at-item-checkbox-p)
23943 (push (org-point-in-group p 0 :checkbox) clist)))
23945 ((org-at-table-p)
23946 (push (list :table (org-table-begin) (org-table-end)) clist)
23947 (if (memq 'org-formula faces)
23948 (push (list :table-special
23949 (previous-single-property-change p 'face)
23950 (next-single-property-change p 'face)) clist)))
23951 ((org-at-table-p 'any)
23952 (push (list :table-table) clist)))
23953 (goto-char p)
23955 ;; Now the small context
23956 (cond
23957 ((org-at-timestamp-p)
23958 (push (org-point-in-group p 0 :timestamp) clist))
23959 ((memq 'org-link faces)
23960 (push (list :link
23961 (previous-single-property-change p 'face)
23962 (next-single-property-change p 'face)) clist))
23963 ((memq 'org-special-keyword faces)
23964 (push (list :keyword
23965 (previous-single-property-change p 'face)
23966 (next-single-property-change p 'face)) clist))
23967 ((org-on-target-p)
23968 (push (org-point-in-group p 0 :target) clist)
23969 (goto-char (1- (match-beginning 0)))
23970 (if (looking-at org-radio-target-regexp)
23971 (push (org-point-in-group p 0 :radio-target) clist))
23972 (goto-char p))
23973 ((setq o (car (delq nil
23974 (mapcar
23975 (lambda (x)
23976 (if (memq x org-latex-fragment-image-overlays) x))
23977 (org-overlays-at (point))))))
23978 (push (list :latex-fragment
23979 (org-overlay-start o) (org-overlay-end o)) clist)
23980 (push (list :latex-preview
23981 (org-overlay-start o) (org-overlay-end o)) clist))
23982 ((org-inside-LaTeX-fragment-p)
23983 ;; FIXME: positions wrong.
23984 (push (list :latex-fragment (point) (point)) clist)))
23986 (setq clist (nreverse (delq nil clist)))
23987 clist))
23989 ;; FIXME Compare with at-regexp-p
23990 (defun org-in-regexp (re &optional nlines visually)
23991 "Check if point is inside a match of regexp.
23992 Normally only the current line is checked, but you can include NLINES extra
23993 lines both before and after point into the search.
23994 If VISUALLY is set, require that the cursor is not after the match but
23995 really on, so that the block visually is on the match."
23996 (catch 'exit
23997 (let ((pos (point))
23998 (eol (point-at-eol (+ 1 (or nlines 0))))
23999 (inc (if visually 1 0)))
24000 (save-excursion
24001 (beginning-of-line (- 1 (or nlines 0)))
24002 (while (re-search-forward re eol t)
24003 (if (and (<= (match-beginning 0) pos)
24004 (>= (+ inc (match-end 0)) pos))
24005 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
24007 (defun org-at-regexp-p (regexp)
24008 "Is point inside a match of REGEXP in the current line?"
24009 (catch 'exit
24010 (save-excursion
24011 (let ((pos (point)) (end (point-at-eol)))
24012 (beginning-of-line 1)
24013 (while (re-search-forward regexp end t)
24014 (if (and (<= (match-beginning 0) pos)
24015 (>= (match-end 0) pos))
24016 (throw 'exit t)))
24017 nil))))
24019 (defun org-uniquify (list)
24020 "Remove duplicate elements from LIST."
24021 (let (res)
24022 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
24023 res))
24025 (defun org-delete-all (elts list)
24026 "Remove all elements in ELTS from LIST."
24027 (while elts
24028 (setq list (delete (pop elts) list)))
24029 list)
24031 (defun org-point-in-group (point group &optional context)
24032 "Check if POINT is in match-group GROUP.
24033 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
24034 match. If the match group does ot exist or point is not inside it,
24035 return nil."
24036 (and (match-beginning group)
24037 (>= point (match-beginning group))
24038 (<= point (match-end group))
24039 (if context
24040 (list context (match-beginning group) (match-end group))
24041 t)))
24043 (defun org-switch-to-buffer-other-window (&rest args)
24044 "Switch to buffer in a second window on the current frame.
24045 In particular, do not allow pop-up frames."
24046 (let (pop-up-frames special-display-buffer-names special-display-regexps
24047 special-display-function)
24048 (apply 'switch-to-buffer-other-window args)))
24050 (defun org-combine-plists (&rest plists)
24051 "Create a single property list from all plists in PLISTS.
24052 The process starts by copying the first list, and then setting properties
24053 from the other lists. Settings in the last list are the most significant
24054 ones and overrule settings in the other lists."
24055 (let ((rtn (copy-sequence (pop plists)))
24056 p v ls)
24057 (while plists
24058 (setq ls (pop plists))
24059 (while ls
24060 (setq p (pop ls) v (pop ls))
24061 (setq rtn (plist-put rtn p v))))
24062 rtn))
24064 (defun org-move-line-down (arg)
24065 "Move the current line down. With prefix argument, move it past ARG lines."
24066 (interactive "p")
24067 (let ((col (current-column))
24068 beg end pos)
24069 (beginning-of-line 1) (setq beg (point))
24070 (beginning-of-line 2) (setq end (point))
24071 (beginning-of-line (+ 1 arg))
24072 (setq pos (move-marker (make-marker) (point)))
24073 (insert (delete-and-extract-region beg end))
24074 (goto-char pos)
24075 (move-to-column col)))
24077 (defun org-move-line-up (arg)
24078 "Move the current line up. With prefix argument, move it past ARG lines."
24079 (interactive "p")
24080 (let ((col (current-column))
24081 beg end pos)
24082 (beginning-of-line 1) (setq beg (point))
24083 (beginning-of-line 2) (setq end (point))
24084 (beginning-of-line (- arg))
24085 (setq pos (move-marker (make-marker) (point)))
24086 (insert (delete-and-extract-region beg end))
24087 (goto-char pos)
24088 (move-to-column col)))
24090 (defun org-replace-escapes (string table)
24091 "Replace %-escapes in STRING with values in TABLE.
24092 TABLE is an association list with keys line \"%a\" and string values.
24093 The sequences in STRING may contain normal field width and padding information,
24094 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
24095 so values can contain further %-escapes if they are define later in TABLE."
24096 (let ((case-fold-search nil)
24097 e re rpl)
24098 (while (setq e (pop table))
24099 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
24100 (while (string-match re string)
24101 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
24102 (cdr e)))
24103 (setq string (replace-match rpl t t string))))
24104 string))
24107 (defun org-sublist (list start end)
24108 "Return a section of LIST, from START to END.
24109 Counting starts at 1."
24110 (let (rtn (c start))
24111 (setq list (nthcdr (1- start) list))
24112 (while (and list (<= c end))
24113 (push (pop list) rtn)
24114 (setq c (1+ c)))
24115 (nreverse rtn)))
24117 (defun org-find-base-buffer-visiting (file)
24118 "Like `find-buffer-visiting' but alway return the base buffer and
24119 not an indirect buffer"
24120 (let ((buf (find-buffer-visiting file)))
24121 (or (buffer-base-buffer buf) buf)))
24123 (defun org-image-file-name-regexp ()
24124 "Return regexp matching the file names of images."
24125 (if (fboundp 'image-file-name-regexp)
24126 (image-file-name-regexp)
24127 (let ((image-file-name-extensions
24128 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
24129 "xbm" "xpm" "pbm" "pgm" "ppm")))
24130 (concat "\\."
24131 (regexp-opt (nconc (mapcar 'upcase
24132 image-file-name-extensions)
24133 image-file-name-extensions)
24135 "\\'"))))
24137 (defun org-file-image-p (file)
24138 "Return non-nil if FILE is an image."
24139 (save-match-data
24140 (string-match (org-image-file-name-regexp) file)))
24142 ;;; Paragraph filling stuff.
24143 ;; We want this to be just right, so use the full arsenal.
24145 (defun org-indent-line-function ()
24146 "Indent line like previous, but further if previous was headline or item."
24147 (interactive)
24148 (let* ((pos (point))
24149 (itemp (org-at-item-p))
24150 column bpos bcol tpos tcol bullet btype bullet-type)
24151 ;; Find the previous relevant line
24152 (beginning-of-line 1)
24153 (cond
24154 ((looking-at "#") (setq column 0))
24155 ((looking-at "\\*+ ") (setq column 0))
24157 (beginning-of-line 0)
24158 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
24159 (beginning-of-line 0))
24160 (cond
24161 ((looking-at "\\*+[ \t]+")
24162 (goto-char (match-end 0))
24163 (setq column (current-column)))
24164 ((org-in-item-p)
24165 (org-beginning-of-item)
24166 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24167 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
24168 (setq bpos (match-beginning 1) tpos (match-end 0)
24169 bcol (progn (goto-char bpos) (current-column))
24170 tcol (progn (goto-char tpos) (current-column))
24171 bullet (match-string 1)
24172 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
24173 (if (not itemp)
24174 (setq column tcol)
24175 (goto-char pos)
24176 (beginning-of-line 1)
24177 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
24178 (setq bullet (match-string 1)
24179 btype (if (string-match "[0-9]" bullet) "n" bullet))
24180 (setq column (if (equal btype bullet-type) bcol tcol))))
24181 (t (setq column (org-get-indentation))))))
24182 (goto-char pos)
24183 (if (<= (current-column) (current-indentation))
24184 (indent-line-to column)
24185 (save-excursion (indent-line-to column)))
24186 (setq column (current-column))
24187 (beginning-of-line 1)
24188 (if (looking-at
24189 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
24190 (replace-match (concat "\\1" (format org-property-format
24191 (match-string 2) (match-string 3)))
24192 t nil))
24193 (move-to-column column)))
24195 (defun org-set-autofill-regexps ()
24196 (interactive)
24197 ;; In the paragraph separator we include headlines, because filling
24198 ;; text in a line directly attached to a headline would otherwise
24199 ;; fill the headline as well.
24200 (org-set-local 'comment-start-skip "^#+[ \t]*")
24201 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
24202 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
24203 ;; The paragraph starter includes hand-formatted lists.
24204 (org-set-local 'paragraph-start
24205 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
24206 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
24207 ;; But only if the user has not turned off tables or fixed-width regions
24208 (org-set-local
24209 'auto-fill-inhibit-regexp
24210 (concat "\\*+ \\|#\\+"
24211 "\\|[ \t]*" org-keyword-time-regexp
24212 (if (or org-enable-table-editor org-enable-fixed-width-editor)
24213 (concat
24214 "\\|[ \t]*["
24215 (if org-enable-table-editor "|" "")
24216 (if org-enable-fixed-width-editor ":" "")
24217 "]"))))
24218 ;; We use our own fill-paragraph function, to make sure that tables
24219 ;; and fixed-width regions are not wrapped. That function will pass
24220 ;; through to `fill-paragraph' when appropriate.
24221 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
24222 ; Adaptive filling: To get full control, first make sure that
24223 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
24224 (org-set-local 'adaptive-fill-regexp "\000")
24225 (org-set-local 'adaptive-fill-function
24226 'org-adaptive-fill-function))
24228 (defun org-fill-paragraph (&optional justify)
24229 "Re-align a table, pass through to fill-paragraph if no table."
24230 (let ((table-p (org-at-table-p))
24231 (table.el-p (org-at-table.el-p)))
24232 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24233 (table.el-p t) ; skip table.el tables
24234 (table-p (org-table-align) t) ; align org-mode tables
24235 (t nil)))) ; call paragraph-fill
24237 ;; For reference, this is the default value of adaptive-fill-regexp
24238 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
24240 (defun org-adaptive-fill-function ()
24241 "Return a fill prefix for org-mode files.
24242 In particular, this makes sure hanging paragraphs for hand-formatted lists
24243 work correctly."
24244 (cond ((looking-at "#[ \t]+")
24245 (match-string 0))
24246 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
24247 (save-excursion
24248 (goto-char (match-end 0))
24249 (make-string (current-column) ?\ )))
24250 (t nil)))
24252 ;;;; Functions extending outline functionality
24254 (defun org-beginning-of-line (&optional arg)
24255 "Go to the beginning of the current line. If that is invisible, continue
24256 to a visible line beginning. This makes the function of C-a more intuitive.
24257 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24258 first attempt, and only move to after the tags when the cursor is already
24259 beyond the end of the headline."
24260 (interactive "P")
24261 (let ((pos (point)))
24262 (beginning-of-line 1)
24263 (if (bobp)
24265 (backward-char 1)
24266 (if (org-invisible-p)
24267 (while (and (not (bobp)) (org-invisible-p))
24268 (backward-char 1)
24269 (beginning-of-line 1))
24270 (forward-char 1)))
24271 (when org-special-ctrl-a/e
24272 (cond
24273 ((and (looking-at org-todo-line-regexp)
24274 (= (char-after (match-end 1)) ?\ ))
24275 (goto-char
24276 (if (eq org-special-ctrl-a/e t)
24277 (cond ((> pos (match-beginning 3)) (match-beginning 3))
24278 ((= pos (point)) (match-beginning 3))
24279 (t (point)))
24280 (cond ((> pos (point)) (point))
24281 ((not (eq last-command this-command)) (point))
24282 (t (match-beginning 3))))))
24283 ((org-at-item-p)
24284 (goto-char
24285 (if (eq org-special-ctrl-a/e t)
24286 (cond ((> pos (match-end 4)) (match-end 4))
24287 ((= pos (point)) (match-end 4))
24288 (t (point)))
24289 (cond ((> pos (point)) (point))
24290 ((not (eq last-command this-command)) (point))
24291 (t (match-end 4))))))))))
24293 (defun org-end-of-line (&optional arg)
24294 "Go to the end of the line.
24295 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
24296 first attempt, and only move to after the tags when the cursor is already
24297 beyond the end of the headline."
24298 (interactive "P")
24299 (if (or (not org-special-ctrl-a/e)
24300 (not (org-on-heading-p)))
24301 (end-of-line arg)
24302 (let ((pos (point)))
24303 (beginning-of-line 1)
24304 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
24305 (if (eq org-special-ctrl-a/e t)
24306 (if (or (< pos (match-beginning 1))
24307 (= pos (match-end 0)))
24308 (goto-char (match-beginning 1))
24309 (goto-char (match-end 0)))
24310 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
24311 (goto-char (match-end 0))
24312 (goto-char (match-beginning 1))))
24313 (end-of-line arg)))))
24315 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24316 (define-key org-mode-map "\C-e" 'org-end-of-line)
24318 (defun org-invisible-p ()
24319 "Check if point is at a character currently not visible."
24320 ;; Early versions of noutline don't have `outline-invisible-p'.
24321 (if (fboundp 'outline-invisible-p)
24322 (outline-invisible-p)
24323 (get-char-property (point) 'invisible)))
24325 (defun org-invisible-p2 ()
24326 "Check if point is at a character currently not visible."
24327 (save-excursion
24328 (if (and (eolp) (not (bobp))) (backward-char 1))
24329 ;; Early versions of noutline don't have `outline-invisible-p'.
24330 (if (fboundp 'outline-invisible-p)
24331 (outline-invisible-p)
24332 (get-char-property (point) 'invisible))))
24334 (defalias 'org-back-to-heading 'outline-back-to-heading)
24335 (defalias 'org-on-heading-p 'outline-on-heading-p)
24336 (defalias 'org-at-heading-p 'outline-on-heading-p)
24337 (defun org-at-heading-or-item-p ()
24338 (or (org-on-heading-p) (org-at-item-p)))
24340 (defun org-on-target-p ()
24341 (or (org-in-regexp org-radio-target-regexp)
24342 (org-in-regexp org-target-regexp)))
24344 (defun org-up-heading-all (arg)
24345 "Move to the heading line of which the present line is a subheading.
24346 This function considers both visible and invisible heading lines.
24347 With argument, move up ARG levels."
24348 (if (fboundp 'outline-up-heading-all)
24349 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24350 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24352 (defun org-goto-sibling (&optional previous)
24353 "Goto the next sibling, even if it is invisible.
24354 When PREVIOUS is set, go to the previous sibling instead. Returns t
24355 when a sibling was found. When none is found, return nil and don't
24356 move point."
24357 (let ((fun (if previous 're-search-backward 're-search-forward))
24358 (pos (point))
24359 (re (concat "^" outline-regexp))
24360 level l)
24361 (when (condition-case nil (org-back-to-heading t) (error nil))
24362 (setq level (funcall outline-level))
24363 (catch 'exit
24364 (or previous (forward-char 1))
24365 (while (funcall fun re nil t)
24366 (setq l (funcall outline-level))
24367 (when (< l level) (goto-char pos) (throw 'exit nil))
24368 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24369 (goto-char pos)
24370 nil))))
24372 (defun org-show-siblings ()
24373 "Show all siblings of the current headline."
24374 (save-excursion
24375 (while (org-goto-sibling) (org-flag-heading nil)))
24376 (save-excursion
24377 (while (org-goto-sibling 'previous)
24378 (org-flag-heading nil))))
24380 (defun org-show-hidden-entry ()
24381 "Show an entry where even the heading is hidden."
24382 (save-excursion
24383 (org-show-entry)))
24385 (defun org-flag-heading (flag &optional entry)
24386 "Flag the current heading. FLAG non-nil means make invisible.
24387 When ENTRY is non-nil, show the entire entry."
24388 (save-excursion
24389 (org-back-to-heading t)
24390 ;; Check if we should show the entire entry
24391 (if entry
24392 (progn
24393 (org-show-entry)
24394 (save-excursion
24395 (and (outline-next-heading)
24396 (org-flag-heading nil))))
24397 (outline-flag-region (max (point-min) (1- (point)))
24398 (save-excursion (outline-end-of-heading) (point))
24399 flag))))
24401 (defun org-end-of-subtree (&optional invisible-OK to-heading)
24402 ;; This is an exact copy of the original function, but it uses
24403 ;; `org-back-to-heading', to make it work also in invisible
24404 ;; trees. And is uses an invisible-OK argument.
24405 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24406 (org-back-to-heading invisible-OK)
24407 (let ((first t)
24408 (level (funcall outline-level)))
24409 (while (and (not (eobp))
24410 (or first (> (funcall outline-level) level)))
24411 (setq first nil)
24412 (outline-next-heading))
24413 (unless to-heading
24414 (if (memq (preceding-char) '(?\n ?\^M))
24415 (progn
24416 ;; Go to end of line before heading
24417 (forward-char -1)
24418 (if (memq (preceding-char) '(?\n ?\^M))
24419 ;; leave blank line before heading
24420 (forward-char -1))))))
24421 (point))
24423 (defun org-show-subtree ()
24424 "Show everything after this heading at deeper levels."
24425 (outline-flag-region
24426 (point)
24427 (save-excursion
24428 (outline-end-of-subtree) (outline-next-heading) (point))
24429 nil))
24431 (defun org-show-entry ()
24432 "Show the body directly following this heading.
24433 Show the heading too, if it is currently invisible."
24434 (interactive)
24435 (save-excursion
24436 (org-back-to-heading t)
24437 (outline-flag-region
24438 (max (point-min) (1- (point)))
24439 (save-excursion
24440 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
24441 (or (match-beginning 1) (point-max)))
24442 nil)))
24444 (defun org-make-options-regexp (kwds)
24445 "Make a regular expression for keyword lines."
24446 (concat
24448 "#?[ \t]*\\+\\("
24449 (mapconcat 'regexp-quote kwds "\\|")
24450 "\\):[ \t]*"
24451 "\\(.+\\)"))
24453 ;; Make isearch reveal the necessary context
24454 (defun org-isearch-end ()
24455 "Reveal context after isearch exits."
24456 (when isearch-success ; only if search was successful
24457 (if (featurep 'xemacs)
24458 ;; Under XEmacs, the hook is run in the correct place,
24459 ;; we directly show the context.
24460 (org-show-context 'isearch)
24461 ;; In Emacs the hook runs *before* restoring the overlays.
24462 ;; So we have to use a one-time post-command-hook to do this.
24463 ;; (Emacs 22 has a special variable, see function `org-mode')
24464 (unless (and (boundp 'isearch-mode-end-hook-quit)
24465 isearch-mode-end-hook-quit)
24466 ;; Only when the isearch was not quitted.
24467 (org-add-hook 'post-command-hook 'org-isearch-post-command
24468 'append 'local)))))
24470 (defun org-isearch-post-command ()
24471 "Remove self from hook, and show context."
24472 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
24473 (org-show-context 'isearch))
24476 ;;;; Address problems with some other packages
24478 ;; Make flyspell not check words in links, to not mess up our keymap
24479 (defun org-mode-flyspell-verify ()
24480 "Don't let flyspell put overlays at active buttons."
24481 (not (get-text-property (point) 'keymap)))
24483 ;; Make `bookmark-jump' show the jump location if it was hidden.
24484 (eval-after-load "bookmark"
24485 '(if (boundp 'bookmark-after-jump-hook)
24486 ;; We can use the hook
24487 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24488 ;; Hook not available, use advice
24489 (defadvice bookmark-jump (after org-make-visible activate)
24490 "Make the position visible."
24491 (org-bookmark-jump-unhide))))
24493 (defun org-bookmark-jump-unhide ()
24494 "Unhide the current position, to show the bookmark location."
24495 (and (org-mode-p)
24496 (or (org-invisible-p)
24497 (save-excursion (goto-char (max (point-min) (1- (point))))
24498 (org-invisible-p)))
24499 (org-show-context 'bookmark-jump)))
24501 ;; Make session.el ignore our circular variable
24502 (eval-after-load "session"
24503 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24505 ;;;; Experimental code
24507 ;; Make appt aware of appointments from the agenda
24508 (defun org-agenda-to-appt ()
24509 "Activate appointments found in `org-agenda-files'."
24510 (interactive)
24511 (require 'org)
24512 (let* ((today (org-date-to-gregorian
24513 (time-to-days (current-time))))
24514 (files org-agenda-files) entries file)
24515 (while (setq file (pop files))
24516 (setq entries (append entries (org-agenda-get-day-entries
24517 file today :timestamp))))
24518 (setq entries (delq nil entries))
24519 (mapc (lambda(x)
24520 (let* ((event (org-trim (get-text-property 1 'txt x)))
24521 (time-of-day (get-text-property 1 'time-of-day x)) tod)
24522 (when time-of-day
24523 (setq tod (number-to-string time-of-day)
24524 tod (when (string-match
24525 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
24526 (concat (match-string 1 tod) ":"
24527 (match-string 2 tod))))
24528 (if tod (appt-add tod event))))) entries)))
24530 (defun org-closed-in-range ()
24531 "Sparse tree of items closed in a certain time range.
24532 Still experimental, may disappear in the furture."
24533 (interactive)
24534 ;; Get the time interval from the user.
24535 (let* ((time1 (time-to-seconds
24536 (org-read-date nil 'to-time nil "Starting date: ")))
24537 (time2 (time-to-seconds
24538 (org-read-date nil 'to-time nil "End date:")))
24539 ;; callback function
24540 (callback (lambda ()
24541 (let ((time
24542 (time-to-seconds
24543 (apply 'encode-time
24544 (org-parse-time-string
24545 (match-string 1))))))
24546 ;; check if time in interval
24547 (and (>= time time1) (<= time time2))))))
24548 ;; make tree, check each match with the callback
24549 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
24551 (defun org-fill-paragraph-experimental (&optional justify)
24552 "Re-align a table, pass through to fill-paragraph if no table."
24553 (let ((table-p (org-at-table-p))
24554 (table.el-p (org-at-table.el-p)))
24555 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
24556 (table.el-p t) ; skip table.el tables
24557 (table-p (org-table-align) t) ; align org-mode tables
24558 ((save-excursion
24559 (let ((pos (1+ (point-at-eol))))
24560 (backward-paragraph 1)
24561 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
24562 (save-excursion
24563 (save-restriction
24564 (narrow-to-region (1+ (match-end 0)) (point-max))
24565 (fill-paragraph nil)
24566 t)))
24567 (t nil)))) ; call paragraph-fill
24569 (defun org-get-min-level (lines)
24570 (let ((re "^\\(\\*+\\) ") l min)
24571 (catch 'exit
24572 (while (setq l (pop lines))
24573 (if (string-match re l)
24574 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24575 1)))
24577 ;;;; Finish up
24579 (provide 'org)
24581 (run-hooks 'org-load-hook)
24583 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
24584 ;;; org.el ends here