Merge from emacs--rel--22
[emacs.git] / lisp / textmodes / org.el
bloba7eb10dbb4f5d3782877d41b33e809dff49af6da
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.03b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://www.astro.uva.nl/~dominik/Tools/org/Changes
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.03b"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 (defmacro org-unmodified (&rest body)
101 "Execute body without changing buffer-modified-p."
102 `(set-buffer-modified-p
103 (prog1 (buffer-modified-p) ,@body)))
105 (defmacro org-re (s)
106 "Replace posix classes in regular expression."
107 (if (featurep 'xemacs)
108 (let ((ss s))
109 (save-match-data
110 (while (string-match "\\[:alnum:\\]" ss)
111 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
112 ss))
115 (defmacro org-preserve-lc (&rest body)
116 `(let ((_line (org-current-line))
117 (_col (current-column)))
118 (unwind-protect
119 (progn ,@body)
120 (goto-line _line)
121 (move-to-column _col))))
123 ;;; The custom variables
125 (defgroup org nil
126 "Outline-based notes management and organizer."
127 :tag "Org"
128 :group 'outlines
129 :group 'hypermedia
130 :group 'calendar)
132 (defgroup org-startup nil
133 "Options concerning startup of Org-mode."
134 :tag "Org Startup"
135 :group 'org)
137 (defcustom org-startup-folded t
138 "Non-nil means, entering Org-mode will switch to OVERVIEW.
139 This can also be configured on a per-file basis by adding one of
140 the following lines anywhere in the buffer:
142 #+STARTUP: fold
143 #+STARTUP: nofold
144 #+STARTUP: content"
145 :group 'org-startup
146 :type '(choice
147 (const :tag "nofold: show all" nil)
148 (const :tag "fold: overview" t)
149 (const :tag "content: all headlines" content)))
151 (defcustom org-startup-truncated t
152 "Non-nil means, entering Org-mode will set `truncate-lines'.
153 This is useful since some lines containing links can be very long and
154 uninteresting. Also tables look terrible when wrapped."
155 :group 'org-startup
156 :type 'boolean)
158 (defcustom org-startup-align-all-tables nil
159 "Non-nil means, align all tables when visiting a file.
160 This is useful when the column width in tables is forced with <N> cookies
161 in table fields. Such tables will look correct only after the first re-align.
162 This can also be configured on a per-file basis by adding one of
163 the following lines anywhere in the buffer:
164 #+STARTUP: align
165 #+STARTUP: noalign"
166 :group 'org-startup
167 :type 'boolean)
169 (defcustom org-insert-mode-line-in-empty-file nil
170 "Non-nil means insert the first line setting Org-mode in empty files.
171 When the function `org-mode' is called interactively in an empty file, this
172 normally means that the file name does not automatically trigger Org-mode.
173 To ensure that the file will always be in Org-mode in the future, a
174 line enforcing Org-mode will be inserted into the buffer, if this option
175 has been set."
176 :group 'org-startup
177 :type 'boolean)
179 (defcustom org-replace-disputed-keys nil
180 "Non-nil means use alternative key bindings for some keys.
181 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
182 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
183 If you want to use Org-mode together with one of these other modes,
184 or more generally if you would like to move some Org-mode commands to
185 other keys, set this variable and configure the keys with the variable
186 `org-disputed-keys'.
188 This option is only relevant at load-time of Org-mode, and must be set
189 *before* org.el is loaded. Changing it requires a restart of Emacs to
190 become effective."
191 :group 'org-startup
192 :type 'boolean)
194 (if (fboundp 'defvaralias)
195 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
197 (defcustom org-disputed-keys
198 '(([(shift up)] . [(meta p)])
199 ([(shift down)] . [(meta n)])
200 ([(shift left)] . [(meta -)])
201 ([(shift right)] . [(meta +)])
202 ([(control shift right)] . [(meta shift +)])
203 ([(control shift left)] . [(meta shift -)]))
204 "Keys for which Org-mode and other modes compete.
205 This is an alist, cars are the default keys, second element specifies
206 the alternative to use when `org-replace-disputed-keys' is t.
208 Keys can be specified in any syntax supported by `define-key'.
209 The value of this option takes effect only at Org-mode's startup,
210 therefore you'll have to restart Emacs to apply it after changing."
211 :group 'org-startup
212 :type 'alist)
214 (defun org-key (key)
215 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
216 Or return the original if not disputed."
217 (if org-replace-disputed-keys
218 (let* ((nkey (key-description key))
219 (x (org-find-if (lambda (x)
220 (equal (key-description (car x)) nkey))
221 org-disputed-keys)))
222 (if x (cdr x) key))
223 key))
225 (defun org-find-if (predicate seq)
226 (catch 'exit
227 (while seq
228 (if (funcall predicate (car seq))
229 (throw 'exit (car seq))
230 (pop seq)))))
232 (defun org-defkey (keymap key def)
233 "Define a key, possibly translated, as returned by `org-key'."
234 (define-key keymap (org-key key) def))
236 (defcustom org-ellipsis nil
237 "The ellipsis to use in the Org-mode outline.
238 When nil, just use the standard three dots. When a string, use that instead,
239 and just in Org-mode (which will then use its own display table).
240 Changing this requires executing `M-x org-mode' in a buffer to become
241 effective."
242 :group 'org-startup
243 :type '(choice (const :tag "Default" nil)
244 (string :tag "String" :value "...#")))
246 (defvar org-display-table nil
247 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
249 (defgroup org-keywords nil
250 "Keywords in Org-mode."
251 :tag "Org Keywords"
252 :group 'org)
254 (defcustom org-deadline-string "DEADLINE:"
255 "String to mark deadline entries.
256 A deadline is this string, followed by a time stamp. Should be a word,
257 terminated by a colon. You can insert a schedule keyword and
258 a timestamp with \\[org-deadline].
259 Changes become only effective after restarting Emacs."
260 :group 'org-keywords
261 :type 'string)
263 (defcustom org-scheduled-string "SCHEDULED:"
264 "String to mark scheduled TODO entries.
265 A schedule is this string, followed by a time stamp. Should be a word,
266 terminated by a colon. You can insert a schedule keyword and
267 a timestamp with \\[org-schedule].
268 Changes become only effective after restarting Emacs."
269 :group 'org-keywords
270 :type 'string)
272 (defcustom org-closed-string "CLOSED:"
273 "String used as the prefix for timestamps logging closing a TODO entry."
274 :group 'org-keywords
275 :type 'string)
277 (defcustom org-archived-string "ARCHIVED:"
278 "String used as the prefix for timestamps logging archiving a TODO entry."
279 :group 'org-keywords
280 :type 'string)
282 (defcustom org-clock-string "CLOCK:"
283 "String used as prefix for timestamps clocking work hours on an item."
284 :group 'org-keywords
285 :type 'string)
287 (defcustom org-comment-string "COMMENT"
288 "Entries starting with this keyword will never be exported.
289 An entry can be toggled between COMMENT and normal with
290 \\[org-toggle-comment].
291 Changes become only effective after restarting Emacs."
292 :group 'org-keywords
293 :type 'string)
295 (defcustom org-quote-string "QUOTE"
296 "Entries starting with this keyword will be exported in fixed-width font.
297 Quoting applies only to the text in the entry following the headline, and does
298 not extend beyond the next headline, even if that is lower level.
299 An entry can be toggled between QUOTE and normal with
300 \\[org-toggle-fixed-width-section]."
301 :group 'org-keywords
302 :type 'string)
304 (defconst org-repeat-re
305 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
306 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
307 "Regular expression for specifying repeated events.
308 After a match, group 1 contains the repeat expression.")
310 (defgroup org-structure nil
311 "Options concerning the general structure of Org-mode files."
312 :tag "Org Structure"
313 :group 'org)
315 (defgroup org-reveal-location nil
316 "Options about how to make context of a location visible."
317 :tag "Org Reveal Location"
318 :group 'org-structure)
320 (defcustom org-show-hierarchy-above '((default . t))
321 "Non-nil means, show full hierarchy when revealing a location.
322 Org-mode often shows locations in an org-mode file which might have
323 been invisible before. When this is set, the hierarchy of headings
324 above the exposed location is shown.
325 Turning this off for example for sparse trees makes them very compact.
326 Instead of t, this can also be an alist specifying this option for different
327 contexts. Valid contexts are
328 agenda when exposing an entry from the agenda
329 org-goto when using the command `org-goto' on key C-c C-j
330 occur-tree when using the command `org-occur' on key C-c /
331 tags-tree when constructing a sparse tree based on tags matches
332 link-search when exposing search matches associated with a link
333 mark-goto when exposing the jump goal of a mark
334 bookmark-jump when exposing a bookmark location
335 isearch when exiting from an incremental search
336 default default for all contexts not set explicitly"
337 :group 'org-reveal-location
338 :type '(choice
339 (const :tag "Always" t)
340 (const :tag "Never" nil)
341 (repeat :greedy t :tag "Individual contexts"
342 (cons
343 (choice :tag "Context"
344 (const agenda)
345 (const org-goto)
346 (const occur-tree)
347 (const tags-tree)
348 (const link-search)
349 (const mark-goto)
350 (const bookmark-jump)
351 (const isearch)
352 (const default))
353 (boolean)))))
355 (defcustom org-show-following-heading '((default . nil))
356 "Non-nil means, show following heading when revealing a location.
357 Org-mode often shows locations in an org-mode file which might have
358 been invisible before. When this is set, the heading following the
359 match is shown.
360 Turning this off for example for sparse trees makes them very compact,
361 but makes it harder to edit the location of the match. In such a case,
362 use the command \\[org-reveal] to show more context.
363 Instead of t, this can also be an alist specifying this option for different
364 contexts. See `org-show-hierarchy-above' for valid contexts."
365 :group 'org-reveal-location
366 :type '(choice
367 (const :tag "Always" t)
368 (const :tag "Never" nil)
369 (repeat :greedy t :tag "Individual contexts"
370 (cons
371 (choice :tag "Context"
372 (const agenda)
373 (const org-goto)
374 (const occur-tree)
375 (const tags-tree)
376 (const link-search)
377 (const mark-goto)
378 (const bookmark-jump)
379 (const isearch)
380 (const default))
381 (boolean)))))
383 (defcustom org-show-siblings '((default . nil) (isearch t))
384 "Non-nil means, show all sibling heading when revealing a location.
385 Org-mode often shows locations in an org-mode file which might have
386 been invisible before. When this is set, the sibling of the current entry
387 heading are all made visible. If `org-show-hierarchy-above' is t,
388 the same happens on each level of the hierarchy above the current entry.
390 By default this is on for the isearch context, off for all other contexts.
391 Turning this off for example for sparse trees makes them very compact,
392 but makes it harder to edit the location of the match. In such a case,
393 use the command \\[org-reveal] to show more context.
394 Instead of t, this can also be an alist specifying this option for different
395 contexts. See `org-show-hierarchy-above' for valid contexts."
396 :group 'org-reveal-location
397 :type '(choice
398 (const :tag "Always" t)
399 (const :tag "Never" nil)
400 (repeat :greedy t :tag "Individual contexts"
401 (cons
402 (choice :tag "Context"
403 (const agenda)
404 (const org-goto)
405 (const occur-tree)
406 (const tags-tree)
407 (const link-search)
408 (const mark-goto)
409 (const bookmark-jump)
410 (const isearch)
411 (const default))
412 (boolean)))))
414 (defgroup org-cycle nil
415 "Options concerning visibility cycling in Org-mode."
416 :tag "Org Cycle"
417 :group 'org-structure)
419 (defcustom org-drawers '("PROPERTIES")
420 "Names of drawers. Drawers are not opened by cycling on the headline above.
421 Drawers only open with a TAB on the drawer line itself. A drawer looks like
422 this:
423 :DRAWERNAME:
424 .....
425 :END:
426 The drawer \"PROPERTIES\" is special for capturing properties through
427 the property API."
428 :group 'org-structure
429 :type '(repeat (string :tag "Drawer Name")))
431 (defcustom org-cycle-global-at-bob t
432 "Cycle globally if cursor is at beginning of buffer and not at a headline.
433 This makes it possible to do global cycling without having to use S-TAB or
434 C-u TAB. For this special case to work, the first line of the buffer
435 must not be a headline - it may be empty ot some other text. When used in
436 this way, `org-cycle-hook' is disables temporarily, to make sure the
437 cursor stays at the beginning of the buffer.
438 When this option is nil, don't do anything special at the beginning
439 of the buffer."
440 :group 'org-cycle
441 :type 'boolean)
443 (defcustom org-cycle-emulate-tab t
444 "Where should `org-cycle' emulate TAB.
445 nil Never
446 white Only in completely white lines
447 whitestart Only at the beginning of lines, before the first non-white char.
448 t Everywhere except in headlines
449 exc-hl-bol Everywhere except at the start of a headline
450 If TAB is used in a place where it does not emulate TAB, the current subtree
451 visibility is cycled."
452 :group 'org-cycle
453 :type '(choice (const :tag "Never" nil)
454 (const :tag "Only in completely white lines" white)
455 (const :tag "Before first char in a line" whitestart)
456 (const :tag "Everywhere except in headlines" t)
457 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
460 (defcustom org-cycle-separator-lines 2
461 "Number of empty lines needed to keep an empty line between collapsed trees.
462 If you leave an empty line between the end of a subtree and the following
463 headline, this empty line is hidden when the subtree is folded.
464 Org-mode will leave (exactly) one empty line visible if the number of
465 empty lines is equal or larger to the number given in this variable.
466 So the default 2 means, at least 2 empty lines after the end of a subtree
467 are needed to produce free space between a collapsed subtree and the
468 following headline.
470 Special case: when 0, never leave empty lines in collapsed view."
471 :group 'org-cycle
472 :type 'integer)
474 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
475 org-cycle-hide-drawers
476 org-cycle-show-empty-lines
477 org-optimize-window-after-visibility-change)
478 "Hook that is run after `org-cycle' has changed the buffer visibility.
479 The function(s) in this hook must accept a single argument which indicates
480 the new state that was set by the most recent `org-cycle' command. The
481 argument is a symbol. After a global state change, it can have the values
482 `overview', `content', or `all'. After a local state change, it can have
483 the values `folded', `children', or `subtree'."
484 :group 'org-cycle
485 :type 'hook)
487 (defgroup org-edit-structure nil
488 "Options concerning structure editing in Org-mode."
489 :tag "Org Edit Structure"
490 :group 'org-structure)
493 (defcustom org-special-ctrl-a/e nil
494 "Non-nil means `C-a' and `C-e' behave specially in headlines.
495 When set, `C-a' will bring back the cursor to the beginning of the
496 headline text, i.e. after the stars and after a possible TODO keyword.
497 When the cursor is already at that position, another `C-a' will bring
498 it to the beginning of the line.
499 `C-e' will jump to the end of the headline, ignoring the presence of tags
500 in the headline. A second `C-e' will then jump to the true end of the
501 line, after any tags."
502 :group 'org-edit-structure
503 :type 'boolean)
505 (if (fboundp 'defvaralias)
506 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
508 (defcustom org-odd-levels-only nil
509 "Non-nil means, skip even levels and only use odd levels for the outline.
510 This has the effect that two stars are being added/taken away in
511 promotion/demotion commands. It also influences how levels are
512 handled by the exporters.
513 Changing it requires restart of `font-lock-mode' to become effective
514 for fontification also in regions already fontified.
515 You may also set this on a per-file basis by adding one of the following
516 lines to the buffer:
518 #+STARTUP: odd
519 #+STARTUP: oddeven"
520 :group 'org-edit-structure
521 :group 'org-font-lock
522 :type 'boolean)
524 (defcustom org-adapt-indentation t
525 "Non-nil means, adapt indentation when promoting and demoting.
526 When this is set and the *entire* text in an entry is indented, the
527 indentation is increased by one space in a demotion command, and
528 decreased by one in a promotion command. If any line in the entry
529 body starts at column 0, indentation is not changed at all."
530 :group 'org-edit-structure
531 :type 'boolean)
533 (defcustom org-blank-before-new-entry '((heading . nil)
534 (plain-list-item . nil))
535 "Should `org-insert-heading' leave a blank line before new heading/item?
536 The value is an alist, with `heading' and `plain-list-item' as car,
537 and a boolean flag as cdr."
538 :group 'org-edit-structure
539 :type '(list
540 (cons (const heading) (boolean))
541 (cons (const plain-list-item) (boolean))))
543 (defcustom org-insert-heading-hook nil
544 "Hook being run after inserting a new heading."
545 :group 'org-edit-structure
546 :type 'boolean)
548 (defcustom org-enable-fixed-width-editor t
549 "Non-nil means, lines starting with \":\" are treated as fixed-width.
550 This currently only means, they are never auto-wrapped.
551 When nil, such lines will be treated like ordinary lines.
552 See also the QUOTE keyword."
553 :group 'org-edit-structure
554 :type 'boolean)
556 (defgroup org-sparse-trees nil
557 "Options concerning sparse trees in Org-mode."
558 :tag "Org Sparse Trees"
559 :group 'org-structure)
561 (defcustom org-highlight-sparse-tree-matches t
562 "Non-nil means, highlight all matches that define a sparse tree.
563 The highlights will automatically disappear the next time the buffer is
564 changed by an edit command."
565 :group 'org-sparse-trees
566 :type 'boolean)
568 (defcustom org-remove-highlights-with-change t
569 "Non-nil means, any change to the buffer will remove temporary highlights.
570 Such highlights are created by `org-occur' and `org-clock-display'.
571 When nil, `C-c C-c needs to be used to get rid of the highlights.
572 The highlights created by `org-preview-latex-fragment' always need
573 `C-c C-c' to be removed."
574 :group 'org-sparse-trees
575 :group 'org-time
576 :type 'boolean)
579 (defcustom org-occur-hook '(org-first-headline-recenter)
580 "Hook that is run after `org-occur' has constructed a sparse tree.
581 This can be used to recenter the window to show as much of the structure
582 as possible."
583 :group 'org-sparse-trees
584 :type 'hook)
586 (defgroup org-plain-lists nil
587 "Options concerning plain lists in Org-mode."
588 :tag "Org Plain lists"
589 :group 'org-structure)
591 (defcustom org-cycle-include-plain-lists nil
592 "Non-nil means, include plain lists into visibility cycling.
593 This means that during cycling, plain list items will *temporarily* be
594 interpreted as outline headlines with a level given by 1000+i where i is the
595 indentation of the bullet. In all other operations, plain list items are
596 not seen as headlines. For example, you cannot assign a TODO keyword to
597 such an item."
598 :group 'org-plain-lists
599 :type 'boolean)
601 (defcustom org-plain-list-ordered-item-terminator t
602 "The character that makes a line with leading number an ordered list item.
603 Valid values are ?. and ?\). To get both terminators, use t. While
604 ?. may look nicer, it creates the danger that a line with leading
605 number may be incorrectly interpreted as an item. ?\) therefore is
606 the safe choice."
607 :group 'org-plain-lists
608 :type '(choice (const :tag "dot like in \"2.\"" ?.)
609 (const :tag "paren like in \"2)\"" ?\))
610 (const :tab "both" t)))
612 (defcustom org-auto-renumber-ordered-lists t
613 "Non-nil means, automatically renumber ordered plain lists.
614 Renumbering happens when the sequence have been changed with
615 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
616 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
617 :group 'org-plain-lists
618 :type 'boolean)
620 (defcustom org-provide-checkbox-statistics t
621 "Non-nil means, update checkbox statistics after insert and toggle.
622 When this is set, checkbox statistics is updated each time you either insert
623 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
624 with \\[org-ctrl-c-ctrl-c\\]."
625 :group 'org-plain-lists
626 :type 'boolean)
628 (defgroup org-archive nil
629 "Options concerning archiving in Org-mode."
630 :tag "Org Archive"
631 :group 'org-structure)
633 (defcustom org-archive-tag "ARCHIVE"
634 "The tag that marks a subtree as archived.
635 An archived subtree does not open during visibility cycling, and does
636 not contribute to the agenda listings."
637 :group 'org-archive
638 :group 'org-keywords
639 :type 'string)
641 (defcustom org-agenda-skip-archived-trees t
642 "Non-nil means, the agenda will skip any items located in archived trees.
643 An archived tree is a tree marked with the tag ARCHIVE."
644 :group 'org-archive
645 :group 'org-agenda-skip
646 :type 'boolean)
648 (defcustom org-cycle-open-archived-trees nil
649 "Non-nil means, `org-cycle' will open archived trees.
650 An archived tree is a tree marked with the tag ARCHIVE.
651 When nil, archived trees will stay folded. You can still open them with
652 normal outline commands like `show-all', but not with the cycling commands."
653 :group 'org-archive
654 :group 'org-cycle
655 :type 'boolean)
657 (defcustom org-sparse-tree-open-archived-trees nil
658 "Non-nil means sparse tree construction shows matches in archived trees.
659 When nil, matches in these trees are highlighted, but the trees are kept in
660 collapsed state."
661 :group 'org-archive
662 :group 'org-sparse-trees
663 :type 'boolean)
665 (defcustom org-archive-location "%s_archive::"
666 "The location where subtrees should be archived.
667 This string consists of two parts, separated by a double-colon.
669 The first part is a file name - when omitted, archiving happens in the same
670 file. %s will be replaced by the current file name (without directory part).
671 Archiving to a different file is useful to keep archived entries from
672 contributing to the Org-mode Agenda.
674 The part after the double colon is a headline. The archived entries will be
675 filed under that headline. When omitted, the subtrees are simply filed away
676 at the end of the file, as top-level entries.
678 Here are a few examples:
679 \"%s_archive::\"
680 If the current file is Projects.org, archive in file
681 Projects.org_archive, as top-level trees. This is the default.
683 \"::* Archived Tasks\"
684 Archive in the current file, under the top-level headline
685 \"* Archived Tasks\".
687 \"~/org/archive.org::\"
688 Archive in file ~/org/archive.org (absolute path), as top-level trees.
690 \"basement::** Finished Tasks\"
691 Archive in file ./basement (relative path), as level 3 trees
692 below the level 2 heading \"** Finished Tasks\".
694 You may set this option on a per-file basis by adding to the buffer a
695 line like
697 #+ARCHIVE: basement::** Finished Tasks"
698 :group 'org-archive
699 :type 'string)
701 (defcustom org-archive-mark-done t
702 "Non-nil means, mark entries as DONE when they are moved to the archive file."
703 :group 'org-archive
704 :type 'boolean)
706 (defcustom org-archive-stamp-time t
707 "Non-nil means, add a time stamp to entries moved to an archive file."
708 :group 'org-archive
709 :type 'boolean)
711 (defgroup org-table nil
712 "Options concerning tables in Org-mode."
713 :tag "Org Table"
714 :group 'org)
716 (defcustom org-enable-table-editor 'optimized
717 "Non-nil means, lines starting with \"|\" are handled by the table editor.
718 When nil, such lines will be treated like ordinary lines.
720 When equal to the symbol `optimized', the table editor will be optimized to
721 do the following:
722 - Automatic overwrite mode in front of whitespace in table fields.
723 This makes the structure of the table stay in tact as long as the edited
724 field does not exceed the column width.
725 - Minimize the number of realigns. Normally, the table is aligned each time
726 TAB or RET are pressed to move to another field. With optimization this
727 happens only if changes to a field might have changed the column width.
728 Optimization requires replacing the functions `self-insert-command',
729 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
730 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
731 very good at guessing when a re-align will be necessary, but you can always
732 force one with \\[org-ctrl-c-ctrl-c].
734 If you would like to use the optimized version in Org-mode, but the
735 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
737 This variable can be used to turn on and off the table editor during a session,
738 but in order to toggle optimization, a restart is required.
740 See also the variable `org-table-auto-blank-field'."
741 :group 'org-table
742 :type '(choice
743 (const :tag "off" nil)
744 (const :tag "on" t)
745 (const :tag "on, optimized" optimized)))
747 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
748 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
749 In the optimized version, the table editor takes over all simple keys that
750 normally just insert a character. In tables, the characters are inserted
751 in a way to minimize disturbing the table structure (i.e. in overwrite mode
752 for empty fields). Outside tables, the correct binding of the keys is
753 restored.
755 The default for this option is t if the optimized version is also used in
756 Org-mode. See the variable `org-enable-table-editor' for details. Changing
757 this variable requires a restart of Emacs to become effective."
758 :group 'org-table
759 :type 'boolean)
761 (defcustom orgtbl-radio-table-templates
762 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
763 % END RECEIVE ORGTBL %n
764 \\begin{comment}
765 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
766 | | |
767 \\end{comment}\n")
768 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
769 @c END RECEIVE ORGTBL %n
770 @ignore
771 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
772 | | |
773 @end ignore\n")
774 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
775 <!-- END RECEIVE ORGTBL %n -->
776 <!--
777 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
778 | | |
779 -->\n"))
780 "Templates for radio tables in different major modes.
781 All occurrences of %n in a template will be replaced with the name of the
782 table, obtained by prompting the user."
783 :group 'org-table
784 :type '(repeat
785 (list (symbol :tag "Major mode")
786 (string :tag "Format"))))
788 (defgroup org-table-settings nil
789 "Settings for tables in Org-mode."
790 :tag "Org Table Settings"
791 :group 'org-table)
793 (defcustom org-table-default-size "5x2"
794 "The default size for newly created tables, Columns x Rows."
795 :group 'org-table-settings
796 :type 'string)
798 (defcustom org-table-number-regexp
799 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$"
800 "Regular expression for recognizing numbers in table columns.
801 If a table column contains mostly numbers, it will be aligned to the
802 right. If not, it will be aligned to the left.
804 The default value of this option is a regular expression which allows
805 anything which looks remotely like a number as used in scientific
806 context. For example, all of the following will be considered a
807 number:
808 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
810 Other options offered by the customize interface are more restrictive."
811 :group 'org-table-settings
812 :type '(choice
813 (const :tag "Positive Integers"
814 "^[0-9]+$")
815 (const :tag "Integers"
816 "^[-+]?[0-9]+$")
817 (const :tag "Floating Point Numbers"
818 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
819 (const :tag "Floating Point Number or Integer"
820 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
821 (const :tag "Exponential, Floating point, Integer"
822 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
823 (const :tag "Very General Number-Like, including hex"
824 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\)$")
825 (string :tag "Regexp:")))
827 (defcustom org-table-number-fraction 0.5
828 "Fraction of numbers in a column required to make the column align right.
829 In a column all non-white fields are considered. If at least this
830 fraction of fields is matched by `org-table-number-fraction',
831 alignment to the right border applies."
832 :group 'org-table-settings
833 :type 'number)
835 (defgroup org-table-editing nil
836 "Bahavior of tables during editing in Org-mode."
837 :tag "Org Table Editing"
838 :group 'org-table)
840 (defcustom org-table-automatic-realign t
841 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
842 When nil, aligning is only done with \\[org-table-align], or after column
843 removal/insertion."
844 :group 'org-table-editing
845 :type 'boolean)
847 (defcustom org-table-auto-blank-field t
848 "Non-nil means, automatically blank table field when starting to type into it.
849 This only happens when typing immediately after a field motion
850 command (TAB, S-TAB or RET).
851 Only relevant when `org-enable-table-editor' is equal to `optimized'."
852 :group 'org-table-editing
853 :type 'boolean)
855 (defcustom org-table-tab-jumps-over-hlines t
856 "Non-nil means, tab in the last column of a table with jump over a hline.
857 If a horizontal separator line is following the current line,
858 `org-table-next-field' can either create a new row before that line, or jump
859 over the line. When this option is nil, a new line will be created before
860 this line."
861 :group 'org-table-editing
862 :type 'boolean)
864 (defcustom org-table-tab-recognizes-table.el t
865 "Non-nil means, TAB will automatically notice a table.el table.
866 When it sees such a table, it moves point into it and - if necessary -
867 calls `table-recognize-table'."
868 :group 'org-table-editing
869 :type 'boolean)
871 (defgroup org-table-calculation nil
872 "Options concerning tables in Org-mode."
873 :tag "Org Table Calculation"
874 :group 'org-table)
876 (defcustom org-table-use-standard-references t
877 "Should org-mode work with table refrences like B3 instead of @3$2?
878 Possible values are:
879 nil never use them
880 from accept as input, do not present for editing
881 t: accept as input and present for editing"
882 :group 'org-table-calculation
883 :type '(choice
884 (const :tag "Never, don't even check unser input for them" nil)
885 (const :tag "Always, both as user input, and when editing" t)
886 (const :tag "Convert user input, don't offer during editing" 'from)))
888 (defcustom org-table-copy-increment t
889 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
890 :group 'org-table-calculation
891 :type 'boolean)
893 (defcustom org-calc-default-modes
894 '(calc-internal-prec 12
895 calc-float-format (float 5)
896 calc-angle-mode deg
897 calc-prefer-frac nil
898 calc-symbolic-mode nil
899 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
900 calc-display-working-message t
902 "List with Calc mode settings for use in calc-eval for table formulas.
903 The list must contain alternating symbols (Calc modes variables and values).
904 Don't remove any of the default settings, just change the values. Org-mode
905 relies on the variables to be present in the list."
906 :group 'org-table-calculation
907 :type 'plist)
909 (defcustom org-table-formula-evaluate-inline t
910 "Non-nil means, TAB and RET evaluate a formula in current table field.
911 If the current field starts with an equal sign, it is assumed to be a formula
912 which should be evaluated as described in the manual and in the documentation
913 string of the command `org-table-eval-formula'. This feature requires the
914 Emacs calc package.
915 When this variable is nil, formula calculation is only available through
916 the command \\[org-table-eval-formula]."
917 :group 'org-table-calculation
918 :type 'boolean)
920 (defcustom org-table-formula-use-constants t
921 "Non-nil means, interpret constants in formulas in tables.
922 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
923 by the value given in `org-table-formula-constants', or by a value obtained
924 from the `constants.el' package."
925 :group 'org-table-calculation
926 :type 'boolean)
928 (defcustom org-table-formula-constants nil
929 "Alist with constant names and values, for use in table formulas.
930 The car of each element is a name of a constant, without the `$' before it.
931 The cdr is the value as a string. For example, if you'd like to use the
932 speed of light in a formula, you would configure
934 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
936 and then use it in an equation like `$1*$c'.
938 Constants can also be defined on a per-file basis using a line like
940 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
941 :group 'org-table-calculation
942 :type '(repeat
943 (cons (string :tag "name")
944 (string :tag "value"))))
946 (defvar org-table-formula-constants-local nil
947 "Local version of `org-table-formula-constants'.")
948 (make-variable-buffer-local 'org-table-formula-constants-local)
950 (defcustom org-table-allow-automatic-line-recalculation t
951 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
952 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
953 :group 'org-table-calculation
954 :type 'boolean)
956 (defgroup org-link nil
957 "Options concerning links in Org-mode."
958 :tag "Org Link"
959 :group 'org)
961 (defvar org-link-abbrev-alist-local nil
962 "Buffer-local version of `org-link-abbrev-alist', which see.
963 The value of this is taken from the #+LINK lines.")
964 (make-variable-buffer-local 'org-link-abbrev-alist-local)
966 (defcustom org-link-abbrev-alist nil
967 "Alist of link abbreviations.
968 The car of each element is a string, to be replaced at the start of a link.
969 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
970 links in Org-mode buffers can have an optional tag after a double colon, e.g.
972 [[linkkey:tag][description]]
974 If REPLACE is a string, the tag will simply be appended to create the link.
975 If the string contains \"%s\", the tag will be inserted there. REPLACE may
976 also be a function that will be called with the tag as the only argument to
977 create the link. See the manual for examples."
978 :group 'org-link
979 :type 'alist)
981 (defcustom org-descriptive-links t
982 "Non-nil means, hide link part and only show description of bracket links.
983 Bracket links are like [[link][descritpion]]. This variable sets the initial
984 state in new org-mode buffers. The setting can then be toggled on a
985 per-buffer basis from the Org->Hyperlinks menu."
986 :group 'org-link
987 :type 'boolean)
989 (defcustom org-link-file-path-type 'adaptive
990 "How the path name in file links should be stored.
991 Valid values are:
993 relative relative to the current directory, i.e. the directory of the file
994 into which the link is being inserted.
995 absolute absolute path, if possible with ~ for home directory.
996 noabbrev absolute path, no abbreviation of home directory.
997 adaptive Use relative path for files in the current directory and sub-
998 directories of it. For other files, use an absolute path."
999 :group 'org-link
1000 :type '(choice
1001 (const relative)
1002 (const absolute)
1003 (const noabbrev)
1004 (const adaptive)))
1006 (defcustom org-activate-links '(bracket angle plain radio tag date)
1007 "Types of links that should be activated in Org-mode files.
1008 This is a list of symbols, each leading to the activation of a certain link
1009 type. In principle, it does not hurt to turn on most link types - there may
1010 be a small gain when turning off unused link types. The types are:
1012 bracket The recommended [[link][description]] or [[link]] links with hiding.
1013 angular Links in angular brackes that may contain whitespace like
1014 <bbdb:Carsten Dominik>.
1015 plain Plain links in normal text, no whitespace, like http://google.com.
1016 radio Text that is matched by a radio target, see manual for details.
1017 tag Tag settings in a headline (link to tag search).
1018 date Time stamps (link to calendar).
1020 Changing this variable requires a restart of Emacs to become effective."
1021 :group 'org-link
1022 :type '(set (const :tag "Double bracket links (new style)" bracket)
1023 (const :tag "Angular bracket links (old style)" angular)
1024 (const :tag "plain text links" plain)
1025 (const :tag "Radio target matches" radio)
1026 (const :tag "Tags" tag)
1027 (const :tag "Tags" target)
1028 (const :tag "Timestamps" date)))
1030 (defgroup org-link-store nil
1031 "Options concerning storing links in Org-mode"
1032 :tag "Org Store Link"
1033 :group 'org-link)
1035 (defcustom org-email-link-description-format "Email %c: %.30s"
1036 "Format of the description part of a link to an email or usenet message.
1037 The following %-excapes will be replaced by corresponding information:
1039 %F full \"From\" field
1040 %f name, taken from \"From\" field, address if no name
1041 %T full \"To\" field
1042 %t first name in \"To\" field, address if no name
1043 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1044 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1045 %s subject
1046 %m message-id.
1048 You may use normal field width specification between the % and the letter.
1049 This is for example useful to limit the length of the subject.
1051 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1052 :group 'org-link-store
1053 :type 'string)
1055 (defcustom org-from-is-user-regexp
1056 (let (r1 r2)
1057 (when (and user-mail-address (not (string= user-mail-address "")))
1058 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1059 (when (and user-full-name (not (string= user-full-name "")))
1060 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1061 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1062 "Regexp mached against the \"From:\" header of an email or usenet message.
1063 It should match if the message is from the user him/herself."
1064 :group 'org-link-store
1065 :type 'regexp)
1067 (defcustom org-context-in-file-links t
1068 "Non-nil means, file links from `org-store-link' contain context.
1069 A search string will be added to the file name with :: as separator and
1070 used to find the context when the link is activated by the command
1071 `org-open-at-point'.
1072 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1073 negates this setting for the duration of the command."
1074 :group 'org-link-store
1075 :type 'boolean)
1077 (defcustom org-keep-stored-link-after-insertion nil
1078 "Non-nil means, keep link in list for entire session.
1080 The command `org-store-link' adds a link pointing to the current
1081 location to an internal list. These links accumulate during a session.
1082 The command `org-insert-link' can be used to insert links into any
1083 Org-mode file (offering completion for all stored links). When this
1084 option is nil, every link which has been inserted once using \\[org-insert-link]
1085 will be removed from the list, to make completing the unused links
1086 more efficient."
1087 :group 'org-link-store
1088 :type 'boolean)
1090 (defcustom org-usenet-links-prefer-google nil
1091 "Non-nil means, `org-store-link' will create web links to Google groups.
1092 When nil, Gnus will be used for such links.
1093 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1094 negates this setting for the duration of the command."
1095 :group 'org-link-store
1096 :type 'boolean)
1098 (defgroup org-link-follow nil
1099 "Options concerning following links in Org-mode"
1100 :tag "Org Follow Link"
1101 :group 'org-link)
1103 (defcustom org-tab-follows-link nil
1104 "Non-nil means, on links TAB will follow the link.
1105 Needs to be set before org.el is loaded."
1106 :group 'org-link-follow
1107 :type 'boolean)
1109 (defcustom org-return-follows-link nil
1110 "Non-nil means, on links RET will follow the link.
1111 Needs to be set before org.el is loaded."
1112 :group 'org-link-follow
1113 :type 'boolean)
1115 (defcustom org-mouse-1-follows-link t
1116 "Non-nil means, mouse-1 on a link will follow the link.
1117 A longer mouse click will still set point. Does not wortk on XEmacs.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1122 (defcustom org-mark-ring-length 4
1123 "Number of different positions to be recorded in the ring
1124 Changing this requires a restart of Emacs to work correctly."
1125 :group 'org-link-follow
1126 :type 'interger)
1128 (defcustom org-link-frame-setup
1129 '((vm . vm-visit-folder-other-frame)
1130 (gnus . gnus-other-frame)
1131 (file . find-file-other-window))
1132 "Setup the frame configuration for following links.
1133 When following a link with Emacs, it may often be useful to display
1134 this link in another window or frame. This variable can be used to
1135 set this up for the different types of links.
1136 For VM, use any of
1137 `vm-visit-folder'
1138 `vm-visit-folder-other-frame'
1139 For Gnus, use any of
1140 `gnus'
1141 `gnus-other-frame'
1142 For FILE, use any of
1143 `find-file'
1144 `find-file-other-window'
1145 `find-file-other-frame'
1146 For the calendar, use the variable `calendar-setup'.
1147 For BBDB, it is currently only possible to display the matches in
1148 another window."
1149 :group 'org-link-follow
1150 :type '(list
1151 (cons (const vm)
1152 (choice
1153 (const vm-visit-folder)
1154 (const vm-visit-folder-other-window)
1155 (const vm-visit-folder-other-frame)))
1156 (cons (const gnus)
1157 (choice
1158 (const gnus)
1159 (const gnus-other-frame)))
1160 (cons (const file)
1161 (choice
1162 (const find-file)
1163 (const find-file-other-window)
1164 (const find-file-other-frame)))))
1166 (defcustom org-display-internal-link-with-indirect-buffer nil
1167 "Non-nil means, use indirect buffer to display infile links.
1168 Activating internal links (from one location in a file to another location
1169 in the same file) normally just jumps to the location. When the link is
1170 activated with a C-u prefix (or with mouse-3), the link is displayed in
1171 another window. When this option is set, the other window actually displays
1172 an indirect buffer clone of the current buffer, to avoid any visibility
1173 changes to the current buffer."
1174 :group 'org-link-follow
1175 :type 'boolean)
1177 (defcustom org-open-non-existing-files nil
1178 "Non-nil means, `org-open-file' will open non-existing files.
1179 When nil, an error will be generated."
1180 :group 'org-link-follow
1181 :type 'boolean)
1183 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1184 "Function and arguments to call for following mailto links.
1185 This is a list with the first element being a lisp function, and the
1186 remaining elements being arguments to the function. In string arguments,
1187 %a will be replaced by the address, and %s will be replaced by the subject
1188 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1189 :group 'org-link-follow
1190 :type '(choice
1191 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1192 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1193 (const :tag "message-mail" (message-mail "%a" "%s"))
1194 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1196 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1197 "Non-nil means, ask for confirmation before executing shell links.
1198 Shell links can be dangerous, just thing about a link
1200 [[shell:rm -rf ~/*][Google Search]]
1202 This link would show up in your Org-mode document as \"Google Search\"
1203 but really it would remove your entire home directory.
1204 Therefore I *definitely* advise against setting this variable to nil.
1205 Just change it to `y-or-n-p' of you want to confirm with a single key press
1206 rather than having to type \"yes\"."
1207 :group 'org-link-follow
1208 :type '(choice
1209 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1210 (const :tag "with y-or-n (faster)" y-or-n-p)
1211 (const :tag "no confirmation (dangerous)" nil)))
1213 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing elisp links.
1215 Elisp links can be dangerous, just think about a link
1217 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1219 This link would show up in your Org-mode document as \"Google Search\"
1220 but really it would remove your entire home directory.
1221 Therefore I *definitely* advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a single key press
1223 rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1230 (defconst org-file-apps-defaults-gnu
1231 '((remote . emacs)
1232 (t . mailcap))
1233 "Default file applications on a UNIX or GNU/Linux system.
1234 See `org-file-apps'.")
1236 (defconst org-file-apps-defaults-macosx
1237 '((remote . emacs)
1238 (t . "open %s")
1239 ("ps" . "gv %s")
1240 ("ps.gz" . "gv %s")
1241 ("eps" . "gv %s")
1242 ("eps.gz" . "gv %s")
1243 ("dvi" . "xdvi %s")
1244 ("fig" . "xfig %s"))
1245 "Default file applications on a MacOS X system.
1246 The system \"open\" is known as a default, but we use X11 applications
1247 for some files for which the OS does not have a good default.
1248 See `org-file-apps'.")
1250 (defconst org-file-apps-defaults-windowsnt
1251 (list
1252 '(remote . emacs)
1253 (cons t
1254 (list (if (featurep 'xemacs)
1255 'mswindows-shell-execute
1256 'w32-shell-execute)
1257 "open" 'file)))
1258 "Default file applications on a Windows NT system.
1259 The system \"open\" is used for most files.
1260 See `org-file-apps'.")
1262 (defcustom org-file-apps
1264 ("txt" . emacs)
1265 ("tex" . emacs)
1266 ("ltx" . emacs)
1267 ("org" . emacs)
1268 ("el" . emacs)
1269 ("bib" . emacs)
1271 "External applications for opening `file:path' items in a document.
1272 Org-mode uses system defaults for different file types, but
1273 you can use this variable to set the application for a given file
1274 extension. The entries in this list are cons cells where the car identifies
1275 files and the cdr the corresponding command. Possible values for the
1276 file identifier are
1277 \"ext\" A string identifying an extension
1278 `directory' Matches a directory
1279 `remote' Matches a remote file, accessible through tramp or efs.
1280 Remote files most likely should be visited through Emacs
1281 because external applications cannot handle such paths.
1282 t Default for all remaining files
1284 Possible values for the command are:
1285 `emacs' The file will be visited by the current Emacs process.
1286 `default' Use the default application for this file type.
1287 string A command to be executed by a shell; %s will be replaced
1288 by the path to the file.
1289 sexp A Lisp form which will be evaluated. The file path will
1290 be available in the Lisp variable `file'.
1291 For more examples, see the system specific constants
1292 `org-file-apps-defaults-macosx'
1293 `org-file-apps-defaults-windowsnt'
1294 `org-file-apps-defaults-gnu'."
1295 :group 'org-link-follow
1296 :type '(repeat
1297 (cons (choice :value ""
1298 (string :tag "Extension")
1299 (const :tag "Default for unrecognized files" t)
1300 (const :tag "Remote file" remote)
1301 (const :tag "Links to a directory" directory))
1302 (choice :value ""
1303 (const :tag "Visit with Emacs" emacs)
1304 (const :tag "Use system default" default)
1305 (string :tag "Command")
1306 (sexp :tag "Lisp form")))))
1308 (defcustom org-mhe-search-all-folders nil
1309 "Non-nil means, that the search for the mh-message will be extended to
1310 all folders if the message cannot be found in the folder given in the link.
1311 Searching all folders is very efficient with one of the search engines
1312 supported by MH-E, but will be slow with pick."
1313 :group 'org-link-follow
1314 :type 'boolean)
1316 (defgroup org-remember nil
1317 "Options concerning interaction with remember.el."
1318 :tag "Org Remember"
1319 :group 'org)
1321 (defcustom org-directory "~/org"
1322 "Directory with org files.
1323 This directory will be used as default to prompt for org files.
1324 Used by the hooks for remember.el."
1325 :group 'org-remember
1326 :type 'directory)
1328 (defcustom org-default-notes-file "~/.notes"
1329 "Default target for storing notes.
1330 Used by the hooks for remember.el. This can be a string, or nil to mean
1331 the value of `remember-data-file'.
1332 You can set this on a per-template basis with the variable
1333 `org-remember-templates'."
1334 :group 'org-remember
1335 :type '(choice
1336 (const :tag "Default from remember-data-file" nil)
1337 file))
1339 (defcustom org-remember-default-headline ""
1340 "The headline that should be the default location in the notes file.
1341 When filing remember notes, the cursor will start at that position.
1342 You can set this on a per-template basis with the variable
1343 `org-remember-templates'."
1344 :group 'org-remember
1345 :type 'string)
1347 (defcustom org-remember-templates nil
1348 "Templates for the creation of remember buffers.
1349 When nil, just let remember make the buffer.
1350 When not nil, this is a list of 4-element lists. In each entry, the first
1351 element is a character, a unique key to select this template.
1352 The second element is the template. The third element is optional and can
1353 specify a destination file for remember items created with this template.
1354 The default file is given by `org-default-notes-file'. An optional forth
1355 element can specify the headline in that file that should be offered
1356 first when the user is asked to file the entry. The default headline is
1357 given in the variable `org-remember-default-headline'.
1359 The template specifies the structure of the remember buffer. It should have
1360 a first line starting with a star, to act as the org-mode headline.
1361 Furthermore, the following %-escapes will be replaced with content:
1363 %^{prompt} prompt the user for a string and replace this sequence with it.
1364 %t time stamp, date only
1365 %T time stamp with date and time
1366 %u, %U like the above, but inactive time stamps
1367 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1368 You may define a prompt like %^{Please specify birthday}t
1369 %n user name (taken from `user-full-name')
1370 %a annotation, normally the link created with org-store-link
1371 %i initial content, the region when remember is called with C-u.
1372 If %i is indented, the entire inserted text will be indented
1373 as well.
1375 %? After completing the template, position cursor here.
1377 Apart from these general escapes, you can access information specific to the
1378 link type that is created. For example, calling `remember' in emails or gnus
1379 will record the author and the subject of the message, which you can access
1380 with %:author and %:subject, respectively. Here is a complete list of what
1381 is recorded for each link type.
1383 Link type | Available information
1384 -------------------+------------------------------------------------------
1385 bbdb | %:type %:name %:company
1386 vm, wl, mh, rmail | %:type %:subject %:message-id
1387 | %:from %:fromname %:fromaddress
1388 | %:to %:toname %:toaddress
1389 | %:fromto (either \"to NAME\" or \"from NAME\")
1390 gnus | %:group, for messages also all email fields
1391 w3, w3m | %:type %:url
1392 info | %:type %:file %:node
1393 calendar | %:type %:date"
1394 :group 'org-remember
1395 :get (lambda (var) ; Make sure all entries have 4 elements
1396 (mapcar (lambda (x)
1397 (cond ((= (length x) 3) (append x '("")))
1398 ((= (length x) 2) (append x '("" "")))
1399 (t x)))
1400 (default-value var)))
1401 :type '(repeat
1402 :tag "enabled"
1403 (list :value (?a "\n" nil nil)
1404 (character :tag "Selection Key")
1405 (string :tag "Template")
1406 (file :tag "Destination file (optional)")
1407 (string :tag "Destination headline (optional)"))))
1409 (defcustom org-reverse-note-order nil
1410 "Non-nil means, store new notes at the beginning of a file or entry.
1411 When nil, new notes will be filed to the end of a file or entry."
1412 :group 'org-remember
1413 :type '(choice
1414 (const :tag "Reverse always" t)
1415 (const :tag "Reverse never" nil)
1416 (repeat :tag "By file name regexp"
1417 (cons regexp boolean))))
1419 (defgroup org-todo nil
1420 "Options concerning TODO items in Org-mode."
1421 :tag "Org TODO"
1422 :group 'org)
1424 (defgroup org-progress nil
1425 "Options concerning Progress logging in Org-mode."
1426 :tag "Org Progress"
1427 :group 'org-time)
1429 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1430 "List of TODO entry keyword sequences and their interpretation.
1431 \\<org-mode-map>This is a list of sequences.
1433 Each sequence starts with a symbol, either `sequence' or `type',
1434 indicating if the keywords should be interpreted as a sequence of
1435 action steps, or as different types of TODO items. The first
1436 keywords are states requiring action - these states will select a headline
1437 for inclusion into the global TODO list Org-mode produces. If one of
1438 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1439 signify that no further action is necessary. If \"|\" is not found,
1440 the last keyword is treated as the only DONE state of the sequence.
1442 The command \\[org-todo] cycles an entry through these states, and one
1443 additional state where no keyword is present. For details about this
1444 cycling, see the manual.
1446 TODO keywords and interpretation can also be set on a per-file basis with
1447 the special #+SEQ_TODO and #+TYP_TODO lines.
1449 For backward compatibility, this variable may also be just a list
1450 of keywords - in this case the interptetation (sequence or type) will be
1451 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1452 :group 'org-todo
1453 :group 'org-keywords
1454 :type '(choice
1455 (repeat :tag "Old syntax, just keywords"
1456 (string :tag "Keyword"))
1457 (repeat :tag "New syntax"
1458 (cons
1459 (choice
1460 :tag "Interpretation"
1461 (const :tag "Sequence (cycling hits every state)" sequence)
1462 (const :tag "Type (cycling directly to DONE)" type))
1463 (repeat
1464 (string :tag "Keyword"))))))
1466 (defvar org-todo-keywords-1 nil)
1467 (make-variable-buffer-local 'org-todo-keywords-1)
1468 (defvar org-todo-keywords-for-agenda nil)
1469 (defvar org-done-keywords-for-agenda nil)
1470 (defvar org-not-done-keywords nil)
1471 (make-variable-buffer-local 'org-not-done-keywords)
1472 (defvar org-done-keywords nil)
1473 (make-variable-buffer-local 'org-done-keywords)
1474 (defvar org-todo-heads nil)
1475 (make-variable-buffer-local 'org-todo-heads)
1476 (defvar org-todo-sets nil)
1477 (make-variable-buffer-local 'org-todo-sets)
1478 (defvar org-todo-kwd-alist nil)
1479 (make-variable-buffer-local 'org-todo-kwd-alist)
1481 (defcustom org-todo-interpretation 'sequence
1482 "Controls how TODO keywords are interpreted.
1483 This variable is in principle obsolete and is only used for
1484 backward compatibility, if the interpretation of todo keywords is
1485 not given already in `org-todo-keywords'. See that variable for
1486 more information."
1487 :group 'org-todo
1488 :group 'org-keywords
1489 :type '(choice (const sequence)
1490 (const type)))
1492 (defcustom org-after-todo-state-change-hook nil
1493 "Hook which is run after the state of a TODO item was changed.
1494 The new state (a string with a TODO keyword, or nil) is available in the
1495 Lisp variable `state'."
1496 :group 'org-todo
1497 :type 'hook)
1499 (defcustom org-log-done nil
1500 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1501 When the state of an entry is changed from nothing to TODO, remove a previous
1502 closing date.
1504 This can also be a list of symbols indicating under which conditions
1505 the time stamp recording the action should be annotated with a short note.
1506 Valid members of this list are
1508 done Offer to record a note when marking entries done
1509 state Offer to record a note whenever changing the TODO state
1510 of an item. This is only relevant if TODO keywords are
1511 interpreted as sequence, see variable `org-todo-interpretation'.
1512 When `state' is set, this includes tracking `done'.
1513 clock-out Offer to record a note when clocking out of an item.
1515 A separate window will then pop up and allow you to type a note.
1516 After finishing with C-c C-c, the note will be added directly after the
1517 timestamp, as a plain list item. See also the variable
1518 `org-log-note-headings'.
1520 Logging can also be configured on a per-file basis by adding one of
1521 the following lines anywhere in the buffer:
1523 #+STARTUP: logdone
1524 #+STARTUP: nologging
1525 #+STARTUP: lognotedone
1526 #+STARTUP: lognotestate
1527 #+STARTUP: lognoteclock-out"
1528 :group 'org-todo
1529 :group 'org-progress
1530 :type '(choice
1531 (const :tag "off" nil)
1532 (const :tag "on" t)
1533 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1534 (const :tag "when item is marked DONE" done)
1535 (const :tag "when TODO state changes" state)
1536 (const :tag "when clocking out" clock-out))))
1538 (defcustom org-log-done-with-time t
1539 "Non-nil means, the CLOSED time stamp will contain date and time.
1540 When nil, only the date will be recorded."
1541 :group 'org-progress
1542 :type 'boolean)
1544 (defcustom org-log-note-headings
1545 '((done . "CLOSING NOTE %t")
1546 (state . "State %-12s %t")
1547 (clock-out . ""))
1548 "Headings for notes added when clocking out or closing TODO items.
1549 The value is an alist, with the car being a sympol indicating the note
1550 context, and the cdr is the heading to be used. The heading may also be the
1551 empty string.
1552 %t in the heading will be replaced by a time stamp.
1553 %s will be replaced by the new TODO state, in double quotes.
1554 %u will be replaced by the user name.
1555 %U will be replaced by the full user name."
1556 :group 'org-todo
1557 :group 'org-progress
1558 :type '(list :greedy t
1559 (cons (const :tag "Heading when closing an item" done) string)
1560 (cons (const :tag
1561 "Heading when changing todo state (todo sequence only)"
1562 state) string)
1563 (cons (const :tag "Heading when clocking out" clock-out) string)))
1565 (defcustom org-log-repeat t
1566 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1567 When nil, no note will be taken."
1568 :group 'org-todo
1569 :group 'org-progress
1570 :type 'boolean)
1572 (defgroup org-priorities nil
1573 "Priorities in Org-mode."
1574 :tag "Org Priorities"
1575 :group 'org-todo)
1577 (defcustom org-highest-priority ?A
1578 "The highest priority of TODO items. A character like ?A, ?B etc.
1579 Must have a smaller ASCII number than `org-lowest-priority'."
1580 :group 'org-priorities
1581 :type 'character)
1583 (defcustom org-lowest-priority ?C
1584 "The lowest priority of TODO items. A character like ?A, ?B etc.
1585 Must have a larger ASCII number than `org-highest-priority'."
1586 :group 'org-priorities
1587 :type 'character)
1589 (defcustom org-default-priority ?B
1590 "The default priority of TODO items.
1591 This is the priority an item get if no explicit priority is given."
1592 :group 'org-priorities
1593 :type 'character)
1595 (defgroup org-time nil
1596 "Options concerning time stamps and deadlines in Org-mode."
1597 :tag "Org Time"
1598 :group 'org)
1600 (defcustom org-insert-labeled-timestamps-at-point nil
1601 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1602 When nil, these labeled time stamps are forces into the second line of an
1603 entry, just after the headline. When scheduling from the global TODO list,
1604 the time stamp will always be forced into the second line."
1605 :group 'org-time
1606 :type 'boolean)
1608 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1609 "Formats for `format-time-string' which are used for time stamps.
1610 It is not recommended to change this constant.")
1612 (defcustom org-time-stamp-rounding-minutes 0
1613 "Number of minutes to round time stamps to upon insertion.
1614 When zero, insert the time unmodified. Useful rounding numbers
1615 should be factors of 60, so for example 5, 10, 15.
1616 When this is not zero, you can still force an exact time-stamp by using
1617 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1618 :group 'org-time
1619 :type 'integer)
1621 (defcustom org-display-custom-times nil
1622 "Non-nil means, overlay custom formats over all time stamps.
1623 The formats are defined through the variable `org-time-stamp-custom-formats'.
1624 To turn this on on a per-file basis, insert anywhere in the file:
1625 #+STARTUP: customtime"
1626 :group 'org-time
1627 :set 'set-default
1628 :type 'sexp)
1629 (make-variable-buffer-local 'org-display-custom-times)
1631 (defcustom org-time-stamp-custom-formats
1632 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1633 "Custom formats for time stamps. See `format-time-string' for the syntax.
1634 These are overlayed over the default ISO format if the variable
1635 `org-display-custom-times' is set. Time like %H:%M should be at the
1636 end of the second format."
1637 :group 'org-time
1638 :type 'sexp)
1640 (defun org-time-stamp-format (&optional long inactive)
1641 "Get the right format for a time string."
1642 (let ((f (if long (cdr org-time-stamp-formats)
1643 (car org-time-stamp-formats))))
1644 (if inactive
1645 (concat "[" (substring f 1 -1) "]")
1646 f)))
1648 (defcustom org-deadline-warning-days 30
1649 "No. of days before expiration during which a deadline becomes active.
1650 This variable governs the display in sparse trees and in the agenda."
1651 :group 'org-time
1652 :type 'number)
1654 (defcustom org-popup-calendar-for-date-prompt t
1655 "Non-nil means, pop up a calendar when prompting for a date.
1656 In the calendar, the date can be selected with mouse-1. However, the
1657 minibuffer will also be active, and you can simply enter the date as well.
1658 When nil, only the minibuffer will be available."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defcustom org-calendar-follow-timestamp-change t
1663 "Non-nil means, make the calendar window follow timestamp changes.
1664 When a timestamp is modified and the calendar window is visible, it will be
1665 moved to the new date."
1666 :group 'org-time
1667 :type 'boolean)
1669 (defgroup org-tags nil
1670 "Options concerning tags in Org-mode."
1671 :tag "Org Tags"
1672 :group 'org)
1674 (defcustom org-tag-alist nil
1675 "List of tags allowed in Org-mode files.
1676 When this list is nil, Org-mode will base TAG input on what is already in the
1677 buffer.
1678 The value of this variable is an alist, the car may be (and should) be a
1679 character that is used to select that tag through the fast-tag-selection
1680 interface. See the manual for details."
1681 :group 'org-tags
1682 :type '(repeat
1683 (choice
1684 (cons (string :tag "Tag name")
1685 (character :tag "Access char"))
1686 (const :tag "Start radio group" (:startgroup))
1687 (const :tag "End radio group" (:endgroup)))))
1689 (defcustom org-use-fast-tag-selection 'auto
1690 "Non-nil means, use fast tag selection scheme.
1691 This is a special interface to select and deselect tags with single keys.
1692 When nil, fast selection is never used.
1693 When the symbol `auto', fast selection is used if and only if selection
1694 characters for tags have been configured, either through the variable
1695 `org-tag-alist' or through a #+TAGS line in the buffer.
1696 When t, fast selection is always used and selection keys are assigned
1697 automatically if necessary."
1698 :group 'org-tags
1699 :type '(choice
1700 (const :tag "Always" t)
1701 (const :tag "Never" nil)
1702 (const :tag "When selection characters are configured" 'auto)))
1704 (defcustom org-fast-tag-selection-single-key nil
1705 "Non-nil means, fast tag selection exits after first change.
1706 When nil, you have to press RET to exit it.
1707 During fast tag selection, you can toggle this flag with `C-c'.
1708 This variable can also have the value `expert'. In this case, the window
1709 displaying the tags menu is not even shown, until you press C-c again."
1710 :group 'org-tags
1711 :type '(choice
1712 (const :tag "No" nil)
1713 (const :tag "Yes" t)
1714 (const :tag "Expert" expert)))
1716 (defcustom org-tags-column 48
1717 "The column to which tags should be indented in a headline.
1718 If this number is positive, it specifies the column. If it is negative,
1719 it means that the tags should be flushright to that column. For example,
1720 -79 works well for a normal 80 character screen."
1721 :group 'org-tags
1722 :type 'integer)
1724 (defcustom org-auto-align-tags t
1725 "Non-nil means, realign tags after pro/demotion of TODO state change.
1726 These operations change the length of a headline and therefore shift
1727 the tags around. With this options turned on, after each such operation
1728 the tags are again aligned to `org-tags-column'."
1729 :group 'org-tags
1730 :type 'boolean)
1732 (defcustom org-use-tag-inheritance t
1733 "Non-nil means, tags in levels apply also for sublevels.
1734 When nil, only the tags directly given in a specific line apply there.
1735 If you turn off this option, you very likely want to turn on the
1736 companion option `org-tags-match-list-sublevels'."
1737 :group 'org-tags
1738 :type 'boolean)
1740 (defcustom org-tags-match-list-sublevels nil
1741 "Non-nil means list also sublevels of headlines matching tag search.
1742 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1743 the sublevels of a headline matching a tag search often also match
1744 the same search. Listing all of them can create very long lists.
1745 Setting this variable to nil causes subtrees of a match to be skipped.
1746 This option is off by default, because inheritance in on. If you turn
1747 inheritance off, you very likely want to turn this option on.
1749 As a special case, if the tag search is restricted to TODO items, the
1750 value of this variable is ignored and sublevels are always checked, to
1751 make sure all corresponding TODO items find their way into the list."
1752 :group 'org-tags
1753 :type 'boolean)
1755 (defvar org-tags-history nil
1756 "History of minibuffer reads for tags.")
1757 (defvar org-last-tags-completion-table nil
1758 "The last used completion table for tags.")
1760 (defgroup org-properties nil
1761 "Options concerning properties in Org-mode."
1762 :tag "Org Properties"
1763 :group 'org)
1765 (defcustom org-property-format "%-10s %s"
1766 "How property key/value pairs should be formatted by `indent-line'.
1767 When `indent-line' hits a property definition, it will format the line
1768 according to this format, mainly to make sure that the values are
1769 lined-up with respect to each other."
1770 :group 'org-properties
1771 :type 'string)
1773 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1774 "The default column format, if no other format has been defined.
1775 This variable can be set on the per-file basis by inserting a line
1777 #+COLUMNS: %25ITEM ....."
1778 :group 'org-properties
1779 :type 'string)
1782 (defgroup org-agenda nil
1783 "Options concerning agenda views in Org-mode."
1784 :tag "Org Agenda"
1785 :group 'org)
1787 (defvar org-category nil
1788 "Variable used by org files to set a category for agenda display.
1789 Such files should use a file variable to set it, for example
1791 # -*- mode: org; org-category: \"ELisp\"
1793 or contain a special line
1795 #+CATEGORY: ELisp
1797 If the file does not specify a category, then file's base name
1798 is used instead.")
1799 (make-variable-buffer-local 'org-category)
1801 (defcustom org-agenda-files nil
1802 "The files to be used for agenda display.
1803 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1804 \\[org-remove-file]. You can also use customize to edit the list.
1806 If the value of the variable is not a list but a single file name, then
1807 the list of agenda files is actually stored and maintained in that file, one
1808 agenda file per line."
1809 :group 'org-agenda
1810 :type '(choice
1811 (repeat :tag "List of files" file)
1812 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1815 (defcustom org-agenda-confirm-kill 1
1816 "When set, remote killing from the agenda buffer needs confirmation.
1817 When t, a confirmation is always needed. When a number N, confirmation is
1818 only needed when the text to be killed contains more than N non-white lines."
1819 :group 'org-agenda
1820 :type '(choice
1821 (const :tag "Never" nil)
1822 (const :tag "Always" t)
1823 (number :tag "When more than N lines")))
1825 (defcustom org-calendar-to-agenda-key [?c]
1826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1827 The command `org-calendar-goto-agenda' will be bound to this key. The
1828 default is the character `c' because then `c' can be used to switch back and
1829 forth between agenda and calendar."
1830 :group 'org-agenda
1831 :type 'sexp)
1833 (defgroup org-agenda-export nil
1834 "Options concerning exporting agenda views in Org-mode."
1835 :tag "Org Agenda Export"
1836 :group 'org-agenda)
1838 (defcustom org-agenda-with-colors t
1839 "Non-nil means, use colors in agenda views."
1840 :group 'org-agenda-export
1841 :type 'boolean)
1843 (defcustom org-agenda-exporter-settings nil
1844 "Alist of variable/value pairs that should be active during agenda export.
1845 This is a good place to set uptions for ps-print and for htmlize."
1846 :group 'org-agenda-export
1847 :type '(repeat
1848 (list
1849 (variable)
1850 (sexp :tag "Value"))))
1852 (defcustom org-agenda-export-html-style ""
1853 "The style specification for exported HTML Agenda files.
1854 If this variable contains a string, it will replace the default <style>
1855 section as produced by `htmlize'.
1856 Since there are different ways of setting style information, this variable
1857 needs to contain the full HTML structure to provide a style, including the
1858 surrounding HTML tags. The style specifications should include definitions
1859 the fonts used by the agenda, here is an example:
1861 <style type=\"text/css\">
1862 p { font-weight: normal; color: gray; }
1863 .org-agenda-structure {
1864 font-size: 110%;
1865 color: #003399;
1866 font-weight: 600;
1868 .org-todo {
1869 color: #cc6666;Week-agenda:
1870 font-weight: bold;
1872 .org-done {
1873 color: #339933;
1875 .title { text-align: center; }
1876 .todo, .deadline { color: red; }
1877 .done { color: green; }
1878 </style>
1880 or, if you want to keep the style in a file,
1882 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1884 As the value of this option simply gets inserted into the HTML <head> header,
1885 you can \"misuse\" it to also add other text to the header. However,
1886 <style>...</style> is required, if not present the variable will be ignored."
1887 :group 'org-agenda-export
1888 :group 'org-export-html
1889 :type 'string)
1891 (defgroup org-agenda-custom-commands nil
1892 "Options concerning agenda views in Org-mode."
1893 :tag "Org Agenda Custom Commands"
1894 :group 'org-agenda)
1896 (defcustom org-agenda-custom-commands nil
1897 "Custom commands for the agenda.
1898 These commands will be offered on the splash screen displayed by the
1899 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1901 (key type match options files)
1903 key The key (a single char as a string) to be associated with the command.
1904 type The command type, any of the following symbols:
1905 todo Entries with a specific TODO keyword, in all agenda files.
1906 tags Tags match in all agenda files.
1907 tags-todo Tags match in all agenda files, TODO entries only.
1908 todo-tree Sparse tree of specific TODO keyword in *current* file.
1909 tags-tree Sparse tree with all tags matches in *current* file.
1910 occur-tree Occur sparse tree for *current* file.
1911 match What to search for:
1912 - a single keyword for TODO keyword searches
1913 - a tags match expression for tags searches
1914 - a regular expression for occur searches
1915 options A list of option setttings, similar to that in a let form, so like
1916 this: ((opt1 val1) (opt2 val2) ...)
1917 files A list of files file to write the produced agenda buffer to
1918 with the command `org-store-agenda-views'.
1919 If a file name ends in \".html\", an HTML version of the buffer
1920 is written out. If it ends in \".ps\", a postscript version is
1921 produced. Otherwide, only the plain text is written to the file.
1923 You can also define a set of commands, to create a composite agenda buffer.
1924 In this case, an entry looks like this:
1926 (key desc (cmd1 cmd2 ...) general-options file)
1928 where
1930 desc A description string to be displayed in the dispatcher menu.
1931 cmd An agenda command, similar to the above. However, tree commands
1932 are no allowed, but instead you can get agenda and global todo list.
1933 So valid commands for a set are:
1934 (agenda)
1935 (alltodo)
1936 (stuck)
1937 (todo \"match\" options files)
1938 (tags \"match\" options files)
1939 (tags-todo \"match\" options files)
1941 Each command can carry a list of options, and another set of options can be
1942 given for the whole set of commands. Individual command options take
1943 precedence over the general options."
1944 :group 'org-agenda-custom-commands
1945 :type '(repeat
1946 (choice :value ("a" tags "" nil)
1947 (list :tag "Single command"
1948 (string :tag "Key")
1949 (choice
1950 (const :tag "Agenda" agenda)
1951 (const :tag "TODO list" alltodo)
1952 (const :tag "Stuck projects" stuck)
1953 (const :tag "Tags search (all agenda files)" tags)
1954 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1955 (const :tag "TODO keyword search (all agenda files)" todo)
1956 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1957 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1958 (const :tag "Occur tree (current buffer)" occur-tree)
1959 (symbol :tag "Other, user-defined function"))
1960 (string :tag "Match")
1961 (repeat :tag "Local options"
1962 (list (variable :tag "Option") (sexp :tag "Value")))
1963 (option (repeat :tag "Export" (file :tag "Export to"))))
1964 (list :tag "Command series, all agenda files"
1965 (string :tag "Key")
1966 (string :tag "Description")
1967 (repeat
1968 (choice
1969 (const :tag "Agenda" (agenda))
1970 (const :tag "TODO list" (alltodo))
1971 (const :tag "Stuck projects" (stuck))
1972 (list :tag "Tags search"
1973 (const :format "" tags)
1974 (string :tag "Match")
1975 (repeat :tag "Local options"
1976 (list (variable :tag "Option")
1977 (sexp :tag "Value"))))
1979 (list :tag "Tags search, TODO entries only"
1980 (const :format "" tags-todo)
1981 (string :tag "Match")
1982 (repeat :tag "Local options"
1983 (list (variable :tag "Option")
1984 (sexp :tag "Value"))))
1986 (list :tag "TODO keyword search"
1987 (const :format "" todo)
1988 (string :tag "Match")
1989 (repeat :tag "Local options"
1990 (list (variable :tag "Option")
1991 (sexp :tag "Value"))))
1993 (list :tag "Other, user-defined function"
1994 (symbol :tag "function")
1995 (string :tag "Match")
1996 (repeat :tag "Local options"
1997 (list (variable :tag "Option")
1998 (sexp :tag "Value"))))))
2000 (repeat :tag "General options"
2001 (list (variable :tag "Option")
2002 (sexp :tag "Value")))
2003 (option (repeat :tag "Export" (file :tag "Export to")))))))
2005 (defcustom org-stuck-projects
2006 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2007 "How to identify stuck projects.
2008 This is a list of four items:
2009 1. A tags/todo matcher string that is used to identify a project.
2010 The entire tree below a headline matched by this is considered one project.
2011 2. A list of TODO keywords identifying non-stuck projects.
2012 If the project subtree contains any headline with one of these todo
2013 keywords, the project is considered to be not stuck. If you specify
2014 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2015 3. A list of tags identifying non-stuck projects.
2016 If the project subtree contains any headline with one of these tags,
2017 the project is considered to be not stuck. If you specify \"*\" as
2018 a tag, any tag will mark the project unstuck.
2019 4. An arbitrary regular expression matching non-stuck projects.
2021 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2022 or `C-c a #' to produce the list."
2023 :group 'org-agenda-custom-commands
2024 :type '(list
2025 (string :tag "Tags/TODO match to identify a project")
2026 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2027 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2028 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2031 (defgroup org-agenda-skip nil
2032 "Options concerning skipping parts of agenda files."
2033 :tag "Org Agenda Skip"
2034 :group 'org-agenda)
2036 (defcustom org-agenda-todo-list-sublevels t
2037 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2038 When nil, the sublevels of a TODO entry are not checked, resulting in
2039 potentially much shorter TODO lists."
2040 :group 'org-agenda-skip
2041 :group 'org-todo
2042 :type 'boolean)
2044 (defcustom org-agenda-todo-ignore-scheduled nil
2045 "Non-nil means, don't show scheduled entries in the global todo list.
2046 The idea behind this is that by scheduling it, you have already taken care
2047 of this item."
2048 :group 'org-agenda-skip
2049 :group 'org-todo
2050 :type 'boolean)
2052 (defcustom org-agenda-todo-ignore-deadlines nil
2053 "Non-nil means, don't show near deadline entries in the global todo list.
2054 Near means closer than `org-deadline-warning-days' days.
2055 The idea behind this is that such items will appear in the agenda anyway."
2056 :group 'org-agenda-skip
2057 :group 'org-todo
2058 :type 'boolean)
2060 (defcustom org-agenda-skip-scheduled-if-done nil
2061 "Non-nil means don't show scheduled items in agenda when they are done.
2062 This is relevant for the daily/weekly agenda, not for the TODO list."
2063 :group 'org-agenda-skip
2064 :type 'boolean)
2066 (defcustom org-agenda-skip-deadline-if-done nil
2067 "Non-nil means don't show deadines when the corresponding item is done.
2068 When nil, the deadline is still shown and should give you a happy feeling.
2070 This is relevant for the daily/weekly agenda."
2071 :group 'org-agenda-skip
2072 :type 'boolean)
2074 (defcustom org-timeline-show-empty-dates 3
2075 "Non-nil means, `org-timeline' also shows dates without an entry.
2076 When nil, only the days which actually have entries are shown.
2077 When t, all days between the first and the last date are shown.
2078 When an integer, show also empty dates, but if there is a gap of more than
2079 N days, just insert a special line indicating the size of the gap."
2080 :group 'org-agenda-skip
2081 :type '(choice
2082 (const :tag "None" nil)
2083 (const :tag "All" t)
2084 (number :tag "at most")))
2087 (defgroup org-agenda-startup nil
2088 "Options concerning initial settings in the Agenda in Org Mode."
2089 :tag "Org Agenda Startup"
2090 :group 'org-agenda)
2092 (defcustom org-finalize-agenda-hook nil
2093 "Hook run just before displaying an agenda buffer."
2094 :group 'org-agenda-startup
2095 :type 'hook)
2097 (defcustom org-agenda-mouse-1-follows-link nil
2098 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2099 A longer mouse click will still set point. Does not wortk on XEmacs.
2100 Needs to be set before org.el is loaded."
2101 :group 'org-agenda-startup
2102 :type 'boolean)
2104 (defcustom org-agenda-start-with-follow-mode nil
2105 "The initial value of follow-mode in a newly created agenda window."
2106 :group 'org-agenda-startup
2107 :type 'boolean)
2109 (defgroup org-agenda-windows nil
2110 "Options concerning the windows used by the Agenda in Org Mode."
2111 :tag "Org Agenda Windows"
2112 :group 'org-agenda)
2114 (defcustom org-agenda-window-setup 'reorganize-frame
2115 "How the agenda buffer should be displayed.
2116 Possible values for this option are:
2118 current-window Show agenda in the current window, keeping all other windows.
2119 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2120 other-window Use `switch-to-buffer-other-window' to display agenda.
2121 reorganize-frame Show only two windows on the current frame, the current
2122 window and the agenda.
2123 See also the variable `org-agenda-restore-windows-after-quit'."
2124 :group 'org-agenda-windows
2125 :type '(choice
2126 (const current-window)
2127 (const other-frame)
2128 (const other-window)
2129 (const reorganize-frame)))
2131 (defcustom org-agenda-restore-windows-after-quit nil
2132 "Non-nil means, restore window configuration open exiting agenda.
2133 Before the window configuration is changed for displaying the agenda,
2134 the current status is recorded. When the agenda is exited with
2135 `q' or `x' and this option is set, the old state is restored. If
2136 `org-agenda-window-setup' is `other-frame', the value of this
2137 option will be ignored.."
2138 :group 'org-agenda-windows
2139 :type 'boolean)
2141 (defcustom org-indirect-buffer-display 'other-window
2142 "How should indirect tree buffers be displayed?
2143 This applies to indirect buffers created with the commands
2144 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2145 Valid values are:
2146 current-window Display in the current window
2147 other-window Just display in another window.
2148 dedicated-frame Create one new frame, and re-use it each time.
2149 new-frame Make a new frame each time."
2150 :group 'org-structure
2151 :group 'org-agenda-windows
2152 :type '(choice
2153 (const :tag "In current window" current-window)
2154 (const :tag "In current frame, other window" other-window)
2155 (const :tag "Each time a new frame" new-frame)
2156 (const :tag "One dedicated frame" dedicated-frame)))
2158 (defgroup org-agenda-daily/weekly nil
2159 "Options concerning the daily/weekly agenda."
2160 :tag "Org Agenda Daily/Weekly"
2161 :group 'org-agenda)
2163 (defcustom org-agenda-ndays 7
2164 "Number of days to include in overview display.
2165 Should be 1 or 7."
2166 :group 'org-agenda-daily/weekly
2167 :type 'number)
2169 (defcustom org-agenda-start-on-weekday 1
2170 "Non-nil means, start the overview always on the specified weekday.
2171 0 denotes Sunday, 1 denotes Monday etc.
2172 When nil, always start on the current day."
2173 :group 'org-agenda-daily/weekly
2174 :type '(choice (const :tag "Today" nil)
2175 (number :tag "Weekday No.")))
2177 (defcustom org-agenda-show-all-dates t
2178 "Non-nil means, `org-agenda' shows every day in the selected range.
2179 When nil, only the days which actually have entries are shown."
2180 :group 'org-agenda-daily/weekly
2181 :type 'boolean)
2183 (defcustom org-agenda-date-format "%A %d %B %Y"
2184 "Format string for displaying dates in the agenda.
2185 Used by the daily/weekly agenda and by the timeline. This should be
2186 a format string understood by `format-time-string'.
2187 FIXME: Not used currently, because of timezone problem."
2188 :group 'org-agenda-daily/weekly
2189 :type 'string)
2191 (defcustom org-agenda-include-diary nil
2192 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2193 :group 'org-agenda-daily/weekly
2194 :type 'boolean)
2196 (defcustom org-agenda-include-all-todo nil
2197 "Set means weekly/daily agenda will always contain all TODO entries.
2198 The TODO entries will be listed at the top of the agenda, before
2199 the entries for specific days."
2200 :group 'org-agenda-daily/weekly
2201 :type 'boolean)
2203 (defgroup org-agenda-time-grid nil
2204 "Options concerning the time grid in the Org-mode Agenda."
2205 :tag "Org Agenda Time Grid"
2206 :group 'org-agenda)
2208 (defcustom org-agenda-use-time-grid t
2209 "Non-nil means, show a time grid in the agenda schedule.
2210 A time grid is a set of lines for specific times (like every two hours between
2211 8:00 and 20:00). The items scheduled for a day at specific times are
2212 sorted in between these lines.
2213 For details about when the grid will be shown, and what it will look like, see
2214 the variable `org-agenda-time-grid'."
2215 :group 'org-agenda-time-grid
2216 :type 'boolean)
2218 (defcustom org-agenda-time-grid
2219 '((daily today require-timed)
2220 "----------------"
2221 (800 1000 1200 1400 1600 1800 2000))
2223 "The settings for time grid for agenda display.
2224 This is a list of three items. The first item is again a list. It contains
2225 symbols specifying conditions when the grid should be displayed:
2227 daily if the agenda shows a single day
2228 weekly if the agenda shows an entire week
2229 today show grid on current date, independent of daily/weekly display
2230 require-timed show grid only if at least one item has a time specification
2232 The second item is a string which will be places behing the grid time.
2234 The third item is a list of integers, indicating the times that should have
2235 a grid line."
2236 :group 'org-agenda-time-grid
2237 :type
2238 '(list
2239 (set :greedy t :tag "Grid Display Options"
2240 (const :tag "Show grid in single day agenda display" daily)
2241 (const :tag "Show grid in weekly agenda display" weekly)
2242 (const :tag "Always show grid for today" today)
2243 (const :tag "Show grid only if any timed entries are present"
2244 require-timed)
2245 (const :tag "Skip grid times already present in an entry"
2246 remove-match))
2247 (string :tag "Grid String")
2248 (repeat :tag "Grid Times" (integer :tag "Time"))))
2250 (defgroup org-agenda-sorting nil
2251 "Options concerning sorting in the Org-mode Agenda."
2252 :tag "Org Agenda Sorting"
2253 :group 'org-agenda)
2255 (let ((sorting-choice
2256 '(choice
2257 (const time-up) (const time-down)
2258 (const category-keep) (const category-up) (const category-down)
2259 (const tag-down) (const tag-up)
2260 (const priority-up) (const priority-down))))
2262 (defcustom org-agenda-sorting-strategy
2263 '((agenda time-up category-keep priority-down)
2264 (todo category-keep priority-down)
2265 (tags category-keep priority-down))
2266 "Sorting structure for the agenda items of a single day.
2267 This is a list of symbols which will be used in sequence to determine
2268 if an entry should be listed before another entry. The following
2269 symbols are recognized:
2271 time-up Put entries with time-of-day indications first, early first
2272 time-down Put entries with time-of-day indications first, late first
2273 category-keep Keep the default order of categories, corresponding to the
2274 sequence in `org-agenda-files'.
2275 category-up Sort alphabetically by category, A-Z.
2276 category-down Sort alphabetically by category, Z-A.
2277 tag-up Sort alphabetically by last tag, A-Z.
2278 tag-down Sort alphabetically by last tag, Z-A.
2279 priority-up Sort numerically by priority, high priority last.
2280 priority-down Sort numerically by priority, high priority first.
2282 The different possibilities will be tried in sequence, and testing stops
2283 if one comparison returns a \"not-equal\". For example, the default
2284 '(time-up category-keep priority-down)
2285 means: Pull out all entries having a specified time of day and sort them,
2286 in order to make a time schedule for the current day the first thing in the
2287 agenda listing for the day. Of the entries without a time indication, keep
2288 the grouped in categories, don't sort the categories, but keep them in
2289 the sequence given in `org-agenda-files'. Within each category sort by
2290 priority.
2292 Leaving out `category-keep' would mean that items will be sorted across
2293 categories by priority."
2294 :group 'org-agenda-sorting
2295 :type `(choice
2296 (repeat :tag "General" ,sorting-choice)
2297 (list :tag "Individually"
2298 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2299 (repeat ,sorting-choice))
2300 (cons (const :tag "Strategy for TODO lists" todo)
2301 (repeat ,sorting-choice))
2302 (cons (const :tag "Strategy for Tags matches" tags)
2303 (repeat ,sorting-choice))))))
2305 (defcustom org-sort-agenda-notime-is-late t
2306 "Non-nil means, items without time are considered late.
2307 This is only relevant for sorting. When t, items which have no explicit
2308 time like 15:30 will be considered as 99:01, i.e. later than any items which
2309 do have a time. When nil, the default time is before 0:00. You can use this
2310 option to decide if the schedule for today should come before or after timeless
2311 agenda entries."
2312 :group 'org-agenda-sorting
2313 :type 'boolean)
2315 (defgroup org-agenda-prefix nil
2316 "Options concerning the entry prefix in the Org-mode agenda display."
2317 :tag "Org Agenda Prefix"
2318 :group 'org-agenda)
2320 (defcustom org-agenda-prefix-format
2321 '((agenda . " %-12:c%?-12t% s")
2322 (timeline . " % s")
2323 (todo . " %-12:c")
2324 (tags . " %-12:c"))
2325 "Format specifications for the prefix of items in the agenda views.
2326 An alist with four entries, for the different agenda types. The keys to the
2327 sublists are `agenda', `timeline', `todo', and `tags'. The values
2328 are format strings.
2329 This format works similar to a printf format, with the following meaning:
2331 %c the category of the item, \"Diary\" for entries from the diary, or
2332 as given by the CATEGORY keyword or derived from the file name.
2333 %T the *last* tag of the item. Last because inherited tags come
2334 first in the list.
2335 %t the time-of-day specification if one applies to the entry, in the
2336 format HH:MM
2337 %s Scheduling/Deadline information, a short string
2339 All specifiers work basically like the standard `%s' of printf, but may
2340 contain two additional characters: A question mark just after the `%' and
2341 a whitespace/punctuation character just before the final letter.
2343 If the first character after `%' is a question mark, the entire field
2344 will only be included if the corresponding value applies to the
2345 current entry. This is useful for fields which should have fixed
2346 width when present, but zero width when absent. For example,
2347 \"%?-12t\" will result in a 12 character time field if a time of the
2348 day is specified, but will completely disappear in entries which do
2349 not contain a time.
2351 If there is punctuation or whitespace character just before the final
2352 format letter, this character will be appended to the field value if
2353 the value is not empty. For example, the format \"%-12:c\" leads to
2354 \"Diary: \" if the category is \"Diary\". If the category were be
2355 empty, no additional colon would be interted.
2357 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2358 - Indent the line with two space characters
2359 - Give the category in a 12 chars wide field, padded with whitespace on
2360 the right (because of `-'). Append a colon if there is a category
2361 (because of `:').
2362 - If there is a time-of-day, put it into a 12 chars wide field. If no
2363 time, don't put in an empty field, just skip it (because of '?').
2364 - Finally, put the scheduling information and append a whitespace.
2366 As another example, if you don't want the time-of-day of entries in
2367 the prefix, you could use:
2369 (setq org-agenda-prefix-format \" %-11:c% s\")
2371 See also the variables `org-agenda-remove-times-when-in-prefix' and
2372 `org-agenda-remove-tags'."
2373 :type '(choice
2374 (string :tag "General format")
2375 (list :greedy t :tag "View dependent"
2376 (cons (const agenda) (string :tag "Format"))
2377 (cons (const timeline) (string :tag "Format"))
2378 (cons (const todo) (string :tag "Format"))
2379 (cons (const tags) (string :tag "Format"))))
2380 :group 'org-agenda-prefix)
2382 (defvar org-prefix-format-compiled nil
2383 "The compiled version of the most recently used prefix format.
2384 See the variable `org-agenda-prefix-format'.")
2386 (defcustom org-agenda-remove-times-when-in-prefix t
2387 "Non-nil means, remove duplicate time specifications in agenda items.
2388 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2389 time-of-day specification in a headline or diary entry is extracted and
2390 placed into the prefix. If this option is non-nil, the original specification
2391 \(a timestamp or -range, or just a plain time(range) specification like
2392 11:30-4pm) will be removed for agenda display. This makes the agenda less
2393 cluttered.
2394 The option can be t or nil. It may also be the symbol `beg', indicating
2395 that the time should only be removed what it is located at the beginning of
2396 the headline/diary entry."
2397 :group 'org-agenda-prefix
2398 :type '(choice
2399 (const :tag "Always" t)
2400 (const :tag "Never" nil)
2401 (const :tag "When at beginning of entry" beg)))
2404 (defcustom org-agenda-default-appointment-duration nil
2405 "Default duration for appointments that only have a starting time.
2406 When nil, no duration is specified in such cases.
2407 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2408 :group 'org-agenda-prefix
2409 :type '(choice
2410 (integer :tag "Minutes")
2411 (const :tag "No default duration")))
2414 (defcustom org-agenda-remove-tags nil
2415 "Non-nil means, remove the tags from the headline copy in the agenda.
2416 When this is the symbol `prefix', only remove tags when
2417 `org-agenda-prefix-format' contains a `%T' specifier."
2418 :group 'org-agenda-prefix
2419 :type '(choice
2420 (const :tag "Always" t)
2421 (const :tag "Never" nil)
2422 (const :tag "When prefix format contains %T" prefix)))
2424 (if (fboundp 'defvaralias)
2425 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2426 'org-agenda-remove-tags))
2428 (defcustom org-agenda-align-tags-to-column 65
2429 "Shift tags in agenda items to this column."
2430 :group 'org-agenda-prefix
2431 :type 'integer)
2433 (defgroup org-latex nil
2434 "Options for embedding LaTeX code into Org-mode"
2435 :tag "Org LaTeX"
2436 :group 'org)
2438 (defcustom org-format-latex-options
2439 '(:foreground default :background default :scale 1.0
2440 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2441 :matchers ("begin" "$" "$$" "\\(" "\\["))
2442 "Options for creating images from LaTeX fragments.
2443 This is a property list with the following properties:
2444 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2445 `default' means use the forground of the default face.
2446 :background the background color, or \"Transparent\".
2447 `default' means use the background of the default face.
2448 :scale a scaling factor for the size of the images
2449 :html-foreground, :html-background, :html-scale
2450 The same numbers for HTML export.
2451 :matchers a list indicating which matchers should be used to
2452 find LaTeX fragments. Valid members of this list are:
2453 \"begin\" find environments
2454 \"$\" find math expressions surrounded by $...$
2455 \"$$\" find math expressions surrounded by $$....$$
2456 \"\\(\" find math expressions surrounded by \\(...\\)
2457 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2458 :group 'org-latex
2459 :type 'plist)
2461 (defcustom org-format-latex-header "\\documentclass{article}
2462 \\usepackage{fullpage} % do not remove
2463 \\usepackage{amssymb}
2464 \\usepackage[usenames]{color}
2465 \\usepackage{amsmath}
2466 \\usepackage{latexsym}
2467 \\usepackage[mathscr]{eucal}
2468 \\pagestyle{empty} % do not remove"
2469 "The document header used for processing LaTeX fragments."
2470 :group 'org-latex
2471 :type 'string)
2473 (defgroup org-export nil
2474 "Options for exporting org-listings."
2475 :tag "Org Export"
2476 :group 'org)
2478 (defgroup org-export-general nil
2479 "General options for exporting Org-mode files."
2480 :tag "Org Export General"
2481 :group 'org-export)
2483 (defcustom org-export-publishing-directory "."
2484 "Path to the location where exported files should be located.
2485 This path may be relative to the directory where the Org-mode file lives.
2486 The default is to put them into the same directory as the Org-mode file.
2487 The variable may also be an alist with export types `:html', `:ascii',
2488 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
2489 is relative, it is interpreted relative to the directory where the exported
2490 Org-mode files lives."
2491 :group 'org-export-general
2492 :type '(choice
2493 (directory)
2494 (repeat
2495 (cons
2496 (choice :tag "Type"
2497 (const :html) (const :ascii) (const :ical) (const :xoxo))
2498 (directory)))))
2500 (defcustom org-export-language-setup
2501 '(("en" "Author" "Date" "Table of Contents")
2502 ("cs" "Autor" "Datum" "Obsah")
2503 ("da" "Ophavsmand" "Dato" "Indhold")
2504 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2505 ("es" "Autor" "Fecha" "\xccndice")
2506 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
2507 ("it" "Autore" "Data" "Indice")
2508 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2509 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2510 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2511 "Terms used in export text, translated to different languages.
2512 Use the variable `org-export-default-language' to set the language,
2513 or use the +OPTION lines for a per-file setting."
2514 :group 'org-export-general
2515 :type '(repeat
2516 (list
2517 (string :tag "HTML language tag")
2518 (string :tag "Author")
2519 (string :tag "Date")
2520 (string :tag "Table of Contents"))))
2522 (defcustom org-export-default-language "en"
2523 "The default language of HTML export, as a string.
2524 This should have an association in `org-export-language-setup'."
2525 :group 'org-export-general
2526 :type 'string)
2528 (defcustom org-export-skip-text-before-1st-heading t
2529 "Non-nil means, skip all text before the first headline when exporting.
2530 When nil, that text is exported as well."
2531 :group 'org-export-general
2532 :type 'boolean)
2534 (defcustom org-export-headline-levels 3
2535 "The last level which is still exported as a headline.
2536 Inferior levels will produce itemize lists when exported.
2537 Note that a numeric prefix argument to an exporter function overrides
2538 this setting.
2540 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2541 :group 'org-export-general
2542 :type 'number)
2544 (defcustom org-export-with-section-numbers t
2545 "Non-nil means, add section numbers to headlines when exporting.
2547 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2548 :group 'org-export-general
2549 :type 'boolean)
2551 (defcustom org-export-with-toc t
2552 "Non-nil means, create a table of contents in exported files.
2553 The TOC contains headlines with levels up to`org-export-headline-levels'.
2554 When an integer, include levels up to N in the toc, this may then be
2555 different from `org-export-headline-levels', but it will not be allowed
2556 to be larger than the number of headline levels.
2557 When nil, no table of contents is made.
2559 Headlines which contain any TODO items will be marked with \"(*)\" in
2560 ASCII export, and with red color in HTML output, if the option
2561 `org-export-mark-todo-in-toc' is set.
2563 In HTML output, the TOC will be clickable.
2565 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2566 or \"toc:3\"."
2567 :group 'org-export-general
2568 :type '(choice
2569 (const :tag "No Table of Contents" nil)
2570 (const :tag "Full Table of Contents" t)
2571 (integer :tag "TOC to level")))
2573 (defcustom org-export-mark-todo-in-toc nil
2574 "Non-nil means, mark TOC lines that contain any open TODO items."
2575 :group 'org-export-general
2576 :type 'boolean)
2578 (defcustom org-export-preserve-breaks nil
2579 "Non-nil means, preserve all line breaks when exporting.
2580 Normally, in HTML output paragraphs will be reformatted. In ASCII
2581 export, line breaks will always be preserved, regardless of this variable.
2583 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2584 :group 'org-export-general
2585 :type 'boolean)
2587 (defcustom org-export-with-archived-trees 'headline
2588 "Whether subtrees with the ARCHIVE tag should be exported.
2589 This can have three different values
2590 nil Do not export, pretend this tree is not present
2591 t Do export the entire tree
2592 headline Only export the headline, but skip the tree below it."
2593 :group 'org-export-general
2594 :group 'org-archive
2595 :type '(choice
2596 (const :tag "not at all" nil)
2597 (const :tag "headline only" 'headline)
2598 (const :tag "entirely" t)))
2600 (defcustom org-export-with-timestamps t
2601 "If nil, do not export time stamps and associated keywords."
2602 :group 'org-export-general
2603 :type 'boolean)
2605 (defcustom org-export-remove-timestamps-from-toc t
2606 "If nil, remove timestamps from the table of contents entries."
2607 :group 'org-export-general
2608 :type 'boolean)
2610 (defcustom org-export-with-tags 'not-in-toc
2611 "If nil, do not export tags, just remove them from headlines.
2612 If this is the symbol `not-in-toc', tags will be removed from table of
2613 contents entries, but still be shown in the headlines of the document."
2614 :group 'org-export-general
2615 :type '(choice
2616 (const :tag "Off" nil)
2617 (const :tag "Not in TOC" not-in-toc)
2618 (const :tag "On" t)))
2620 (defcustom org-export-with-property-drawer nil
2621 "Non-nil means, export property drawers.
2622 When nil, these drawers are removed before export.
2624 This option can also be set with the +OPTIONS line, e.g. \"p:t\"."
2625 :group 'org-export-general
2626 :type 'boolean)
2628 (defgroup org-export-translation nil
2629 "Options for translating special ascii sequences for the export backends."
2630 :tag "Org Export Translation"
2631 :group 'org-export)
2633 (defcustom org-export-with-emphasize t
2634 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2635 If the export target supports emphasizing text, the word will be
2636 typeset in bold, italic, or underlined, respectively. Works only for
2637 single words, but you can say: I *really* *mean* *this*.
2638 Not all export backends support this.
2640 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2641 :group 'org-export-translation
2642 :type 'boolean)
2644 (defcustom org-export-with-footnotes t
2645 "If nil, export [1] as a footnote marker.
2646 Lines starting with [1] will be formatted as footnotes.
2648 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2649 :group 'org-export-translation
2650 :type 'boolean)
2652 (defcustom org-export-with-sub-superscripts t
2653 "Non-nil means, interpret \"_\" and \"^\" for export.
2654 When this option is turned on, you can use TeX-like syntax for sub- and
2655 superscripts. Several characters after \"_\" or \"^\" will be
2656 considered as a single item - so grouping with {} is normally not
2657 needed. For example, the following things will be parsed as single
2658 sub- or superscripts.
2660 10^24 or 10^tau several digits will be considered 1 item.
2661 10^-12 or 10^-tau a leading sign with digits or a word
2662 x^2-y^3 will be read as x^2 - y^3, because items are
2663 terminated by almost any nonword/nondigit char.
2664 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
2666 Still, ambiguity is possible - so when in doubt use {} to enclose the
2667 sub/superscript. If you set this variable to the symbol `{}',
2668 the braces are *required* in order to trigger interpretations as
2669 sub/superscript. This can be helpful in documents that need \"_\"
2670 frequently in plain text.
2672 Not all export backends support this, but HTML does.
2674 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
2675 :group 'org-export-translation
2676 :type '(choice
2677 (const :tag "Always interpret" t)
2678 (const :tag "Only with braces" {})
2679 (const :tag "Never interpret" nil)))
2681 (defcustom org-export-with-TeX-macros t
2682 "Non-nil means, interpret simple TeX-like macros when exporting.
2683 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
2684 No only real TeX macros will work here, but the standard HTML entities
2685 for math can be used as macro names as well. For a list of supported
2686 names in HTML export, see the constant `org-html-entities'.
2687 Not all export backends support this.
2689 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
2690 :group 'org-export-translation
2691 :group 'org-latex
2692 :type 'boolean)
2694 (defcustom org-export-with-LaTeX-fragments nil
2695 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
2696 When set, the exporter will find LaTeX environments if the \\begin line is
2697 the first non-white thing on a line. It will also find the math delimiters
2698 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
2699 display math.
2701 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
2702 :group 'org-export-translation
2703 :group 'org-latex
2704 :type 'boolean)
2706 (defcustom org-export-with-fixed-width t
2707 "Non-nil means, lines starting with \":\" will be in fixed width font.
2708 This can be used to have pre-formatted text, fragments of code etc. For
2709 example:
2710 : ;; Some Lisp examples
2711 : (while (defc cnt)
2712 : (ding))
2713 will be looking just like this in also HTML. See also the QUOTE keyword.
2714 Not all export backends support this.
2716 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2717 :group 'org-export-translation
2718 :type 'boolean)
2720 (defcustom org-match-sexp-depth 3
2721 "Number of stacked braces for sub/superscript matching.
2722 This has to be set before loading org.el to be effective."
2723 :group 'org-export-translation
2724 :type 'integer)
2726 (defgroup org-export-tables nil
2727 "Options for exporting tables in Org-mode."
2728 :tag "Org Export Tables"
2729 :group 'org-export)
2731 (defcustom org-export-with-tables t
2732 "If non-nil, lines starting with \"|\" define a table.
2733 For example:
2735 | Name | Address | Birthday |
2736 |-------------+----------+-----------|
2737 | Arthur Dent | England | 29.2.2100 |
2739 Not all export backends support this.
2741 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2742 :group 'org-export-tables
2743 :type 'boolean)
2745 (defcustom org-export-highlight-first-table-line t
2746 "Non-nil means, highlight the first table line.
2747 In HTML export, this means use <th> instead of <td>.
2748 In tables created with table.el, this applies to the first table line.
2749 In Org-mode tables, all lines before the first horizontal separator
2750 line will be formatted with <th> tags."
2751 :group 'org-export-tables
2752 :type 'boolean)
2754 (defcustom org-export-table-remove-special-lines t
2755 "Remove special lines and marking characters in calculating tables.
2756 This removes the special marking character column from tables that are set
2757 up for spreadsheet calculations. It also removes the entire lines
2758 marked with `!', `_', or `^'. The lines with `$' are kept, because
2759 the values of constants may be useful to have."
2760 :group 'org-export-tables
2761 :type 'boolean)
2763 (defcustom org-export-prefer-native-exporter-for-tables nil
2764 "Non-nil means, always export tables created with table.el natively.
2765 Natively means, use the HTML code generator in table.el.
2766 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2767 the table does not use row- or column-spanning). This has the
2768 advantage, that the automatic HTML conversions for math symbols and
2769 sub/superscripts can be applied. Org-mode's HTML generator is also
2770 much faster."
2771 :group 'org-export-tables
2772 :type 'boolean)
2774 (defgroup org-export-ascii nil
2775 "Options specific for ASCII export of Org-mode files."
2776 :tag "Org Export ASCII"
2777 :group 'org-export)
2779 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2780 "Characters for underlining headings in ASCII export.
2781 In the given sequence, these characters will be used for level 1, 2, ..."
2782 :group 'org-export-ascii
2783 :type '(repeat character))
2785 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2786 "Bullet characters for headlines converted to lists in ASCII export.
2787 The first character is is used for the first lest level generated in this
2788 way, and so on. If there are more levels than characters given here,
2789 the list will be repeated.
2790 Note that plain lists will keep the same bullets as the have in the
2791 Org-mode file."
2792 :group 'org-export-ascii
2793 :type '(repeat character))
2795 (defgroup org-export-xml nil
2796 "Options specific for XML export of Org-mode files."
2797 :tag "Org Export XML"
2798 :group 'org-export)
2800 (defgroup org-export-html nil
2801 "Options specific for HTML export of Org-mode files."
2802 :tag "Org Export HTML"
2803 :group 'org-export)
2805 (defcustom org-export-html-coding-system nil
2807 :group 'org-export-html
2808 :type 'coding-system)
2810 (defcustom org-export-html-style
2811 "<style type=\"text/css\">
2812 html {
2813 font-family: Times, serif;
2814 font-size: 12pt;
2816 .title { text-align: center; }
2817 .todo { color: red; }
2818 .done { color: green; }
2819 .timestamp { color: grey }
2820 .timestamp-kwd { color: CadetBlue }
2821 .tag { background-color:lightblue; font-weight:normal }
2822 .target { background-color: lavender; }
2823 pre {
2824 border: 1pt solid #AEBDCC;
2825 background-color: #F3F5F7;
2826 padding: 5pt;
2827 font-family: courier, monospace;
2829 table { border-collapse: collapse; }
2830 td, th {
2831 vertical-align: top;
2832 <!--border: 1pt solid #ADB9CC;-->
2834 </style>"
2835 "The default style specification for exported HTML files.
2836 Since there are different ways of setting style information, this variable
2837 needs to contain the full HTML structure to provide a style, including the
2838 surrounding HTML tags. The style specifications should include definitions
2839 for new classes todo, done, title, and deadline. For example, legal values
2840 would be:
2842 <style type=\"text/css\">
2843 p { font-weight: normal; color: gray; }
2844 h1 { color: black; }
2845 .title { text-align: center; }
2846 .todo, .deadline { color: red; }
2847 .done { color: green; }
2848 </style>
2850 or, if you want to keep the style in a file,
2852 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2854 As the value of this option simply gets inserted into the HTML <head> header,
2855 you can \"misuse\" it to add arbitrary text to the header."
2856 :group 'org-export-html
2857 :type 'string)
2860 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2861 "Format for typesetting the document title in HTML export."
2862 :group 'org-export-html
2863 :type 'string)
2865 (defcustom org-export-html-toplevel-hlevel 2
2866 "The <H> level for level 1 headings in HTML export."
2867 :group 'org-export-html
2868 :type 'string)
2870 (defcustom org-export-html-link-org-files-as-html t
2871 "Non-nil means, make file links to `file.org' point to `file.html'.
2872 When org-mode is exporting an org-mode file to HTML, links to
2873 non-html files are directly put into a href tag in HTML.
2874 However, links to other Org-mode files (recognized by the
2875 extension `.org.) should become links to the corresponding html
2876 file, assuming that the linked org-mode file will also be
2877 converted to HTML.
2878 When nil, the links still point to the plain `.org' file."
2879 :group 'org-export-html
2880 :type 'boolean)
2882 (defcustom org-export-html-inline-images 'maybe
2883 "Non-nil means, inline images into exported HTML pages.
2884 This is done using an <img> tag. When nil, an anchor with href is used to
2885 link to the image. If this option is `maybe', then images in links with
2886 an empty description will be inlined, while images with a description will
2887 be linked only."
2888 :group 'org-export-html
2889 :type '(choice (const :tag "Never" nil)
2890 (const :tag "Always" t)
2891 (const :tag "When there is no description" maybe)))
2893 ;; FIXME: rename
2894 (defcustom org-export-html-expand t
2895 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2896 When nil, these tags will be exported as plain text and therefore
2897 not be interpreted by a browser.
2899 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2900 :group 'org-export-html
2901 :type 'boolean)
2903 (defcustom org-export-html-table-tag
2904 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
2905 "The HTML tag that is used to start a table.
2906 This must be a <table> tag, but you may change the options like
2907 borders and spacing."
2908 :group 'org-export-html
2909 :type 'string)
2911 (defcustom org-export-table-header-tags '("<th>" . "</th>")
2912 "The opening tag for table header fields.
2913 This is customizable so that alignment options can be specified."
2914 :group 'org-export-tables
2915 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2917 (defcustom org-export-table-data-tags '("<td>" . "</td>")
2918 "The opening tag for table data fields.
2919 This is customizable so that alignment options can be specified."
2920 :group 'org-export-tables
2921 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
2923 (defcustom org-export-html-with-timestamp nil
2924 "If non-nil, write `org-export-html-html-helper-timestamp'
2925 into the exported HTML text. Otherwise, the buffer will just be saved
2926 to a file."
2927 :group 'org-export-html
2928 :type 'boolean)
2930 (defcustom org-export-html-html-helper-timestamp
2931 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2932 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2933 :group 'org-export-html
2934 :type 'string)
2936 (defgroup org-export-icalendar nil
2937 "Options specific for iCalendar export of Org-mode files."
2938 :tag "Org Export iCalendar"
2939 :group 'org-export)
2941 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2942 "The file name for the iCalendar file covering all agenda files.
2943 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2944 The file name should be absolute."
2945 :group 'org-export-icalendar
2946 :type 'file)
2948 (defcustom org-icalendar-include-todo nil
2949 "Non-nil means, export to iCalendar files should also cover TODO items."
2950 :group 'org-export-icalendar
2951 :type '(choice
2952 (const :tag "None" nil)
2953 (const :tag "Unfinished" t)
2954 (const :tag "All" all)))
2956 (defcustom org-icalendar-include-sexps t
2957 "Non-nil means, export to iCalendar files should also cover sexp entries.
2958 These are entries like in the diary, but directly in an Org-mode file."
2959 :group 'org-export-icalendar
2960 :type 'boolean)
2962 (defcustom org-icalendar-combined-name "OrgMode"
2963 "Calendar name for the combined iCalendar representing all agenda files."
2964 :group 'org-export-icalendar
2965 :type 'string)
2967 (defgroup org-font-lock nil
2968 "Font-lock settings for highlighting in Org-mode."
2969 :tag "Org Font Lock"
2970 :group 'org)
2972 (defcustom org-level-color-stars-only nil
2973 "Non-nil means fontify only the stars in each headline.
2974 When nil, the entire headline is fontified.
2975 Changing it requires restart of `font-lock-mode' to become effective
2976 also in regions already fontified."
2977 :group 'org-font-lock
2978 :type 'boolean)
2980 (defcustom org-hide-leading-stars nil
2981 "Non-nil means, hide the first N-1 stars in a headline.
2982 This works by using the face `org-hide' for these stars. This
2983 face is white for a light background, and black for a dark
2984 background. You may have to customize the face `org-hide' to
2985 make this work.
2986 Changing it requires restart of `font-lock-mode' to become effective
2987 also in regions already fontified.
2988 You may also set this on a per-file basis by adding one of the following
2989 lines to the buffer:
2991 #+STARTUP: hidestars
2992 #+STARTUP: showstars"
2993 :group 'org-font-lock
2994 :type 'boolean)
2996 (defcustom org-fontify-done-headline nil
2997 "Non-nil means, change the face of a headline if it is marked DONE.
2998 Normally, only the TODO/DONE keyword indicates the state of a headline.
2999 When this is non-nil, the headline after the keyword is set to the
3000 `org-headline-done' as an additional indication."
3001 :group 'org-font-lock
3002 :type 'boolean)
3004 (defcustom org-fontify-emphasized-text t
3005 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3006 Changing this variable requires a restart of Emacs to take effect."
3007 :group 'org-font-lock
3008 :type 'boolean)
3010 (defvar org-emph-re nil
3011 "Regular expression for matching emphasis.")
3012 (defvar org-emphasis-regexp-components) ; defined just below
3013 (defvar org-emphasis-alist) ; defined just below
3014 (defun org-set-emph-re (var val)
3015 "Set variable and compute the emphasis regular expression."
3016 (set var val)
3017 (when (and (boundp 'org-emphasis-alist)
3018 (boundp 'org-emphasis-regexp-components)
3019 org-emphasis-alist org-emphasis-regexp-components)
3020 (let* ((e org-emphasis-regexp-components)
3021 (pre (car e))
3022 (post (nth 1 e))
3023 (border (nth 2 e))
3024 (body (nth 3 e))
3025 (nl (nth 4 e))
3026 (stacked (nth 5 e))
3027 (body1 (concat body "*?"))
3028 (markers (mapconcat 'car org-emphasis-alist "")))
3029 ;; make sure special characters appear at the right position in the class
3030 (if (string-match "\\^" markers)
3031 (setq markers (concat (replace-match "" t t markers) "^")))
3032 (if (string-match "-" markers)
3033 (setq markers (concat (replace-match "" t t markers) "-")))
3034 (if (> nl 0)
3035 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3036 (int-to-string nl) "\\}")))
3037 ;; Make the regexp
3038 (setq org-emph-re
3039 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3040 "\\("
3041 "\\([" markers "]\\)"
3042 "\\("
3043 "[^" border (if (and nil stacked) markers) "]"
3044 body1
3045 "[^" border (if (and nil stacked) markers) "]"
3046 "\\)"
3047 "\\3\\)"
3048 "\\([" post (if stacked markers) "]\\|$\\)")))))
3050 (defcustom org-emphasis-regexp-components
3051 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3052 "Components used to build the reqular expression for emphasis.
3053 This is a list with 6 entries. Terminology: In an emphasis string
3054 like \" *strong word* \", we call the initial space PREMATCH, the final
3055 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3056 and \"trong wor\" is the body. The different components in this variable
3057 specify what is allowed/forbidden in each part:
3059 pre Chars allowed as prematch. Beginning of line will be allowed too.
3060 post Chars allowed as postmatch. End of line will be allowed too.
3061 border The chars *forbidden* as border characters.
3062 body-regexp A regexp like \".\" to match a body character. Don't use
3063 non-shy groups here, and don't allow newline here.
3064 newline The maximum number of newlines allowed in an emphasis exp.
3065 stacked Non-nil means, allow stacked styles. This works only in HTML
3066 export. When this is set, all marker characters (as given in
3067 `org-emphasis-alist') will be allowed as pre/post, aiding
3068 inside-out matching.
3069 Use customize to modify this, or restart Emacs after changing it."
3070 :group 'org-font-lock
3071 :set 'org-set-emph-re
3072 :type '(list
3073 (sexp :tag "Allowed chars in pre ")
3074 (sexp :tag "Allowed chars in post ")
3075 (sexp :tag "Forbidden chars in border ")
3076 (sexp :tag "Regexp for body ")
3077 (integer :tag "number of newlines allowed")
3078 (boolean :tag "Stacking allowed ")))
3080 (defcustom org-emphasis-alist
3081 '(("*" bold "<b>" "</b>")
3082 ("/" italic "<i>" "</i>")
3083 ("_" underline "<u>" "</u>")
3084 ("=" shadow "<code>" "</code>")
3085 ("+" (:strike-through t) "<del>" "</del>")
3087 "Special syntax for emphasized text.
3088 Text starting and ending with a special character will be emphasized, for
3089 example *bold*, _underlined_ and /italic/. This variable sets the marker
3090 characters, the face to be used by font-lock for highlighting in Org-mode
3091 Emacs buffers, and the HTML tags to be used for this.
3092 Use customize to modify this, or restart Emacs after changing it."
3093 :group 'org-font-lock
3094 :set 'org-set-emph-re
3095 :type '(repeat
3096 (list
3097 (string :tag "Marker character")
3098 (choice
3099 (face :tag "Font-lock-face")
3100 (plist :tag "Face property list"))
3101 (string :tag "HTML start tag")
3102 (string :tag "HTML end tag"))))
3104 ;;; The faces
3106 (defgroup org-faces nil
3107 "Faces in Org-mode."
3108 :tag "Org Faces"
3109 :group 'org-font-lock)
3111 ;; FIXME: convert that into a macro? Not critical, because this
3112 ;; is only executed a few times at load time.
3113 (defun org-compatible-face (specs)
3114 "Make a compatible face specification.
3115 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3116 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3117 to the top of the list. The `min-colors' attribute will be removed from
3118 any other entries, and any resulting duplicates will be removed entirely."
3119 (if (or (featurep 'xemacs) (< emacs-major-version 22))
3120 (let (r e a)
3121 (while (setq e (pop specs))
3122 (cond
3123 ((memq (car e) '(t default)) (push e r))
3124 ((setq a (member '(min-colors 8) (car e)))
3125 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3126 (cdr e)))))
3127 ((setq a (assq 'min-colors (car e)))
3128 (setq e (cons (delq a (car e)) (cdr e)))
3129 (or (assoc (car e) r) (push e r)))
3130 (t (or (assoc (car e) r) (push e r)))))
3131 (nreverse r))
3132 specs))
3134 (defface org-hide
3135 '((((background light)) (:foreground "white"))
3136 (((background dark)) (:foreground "black")))
3137 "Face used to hide leading stars in headlines.
3138 The forground color of this face should be equal to the background
3139 color of the frame."
3140 :group 'org-faces)
3142 (defface org-level-1 ;; font-lock-function-name-face
3143 (org-compatible-face
3144 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3145 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3146 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3147 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3148 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3149 (t (:bold t))))
3150 "Face used for level 1 headlines."
3151 :group 'org-faces)
3153 (defface org-level-2 ;; font-lock-variable-name-face
3154 (org-compatible-face
3155 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3156 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3157 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3158 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3159 (t (:bold t))))
3160 "Face used for level 2 headlines."
3161 :group 'org-faces)
3163 (defface org-level-3 ;; font-lock-keyword-face
3164 (org-compatible-face
3165 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3166 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3167 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3168 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3169 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3170 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3171 (t (:bold t))))
3172 "Face used for level 3 headlines."
3173 :group 'org-faces)
3175 (defface org-level-4 ;; font-lock-comment-face
3176 (org-compatible-face
3177 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3178 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3179 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3180 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3181 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3182 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3183 (t (:bold t))))
3184 "Face used for level 4 headlines."
3185 :group 'org-faces)
3187 (defface org-level-5 ;; font-lock-type-face
3188 (org-compatible-face
3189 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3190 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3191 (((class color) (min-colors 8)) (:foreground "green"))))
3192 "Face used for level 5 headlines."
3193 :group 'org-faces)
3195 (defface org-level-6 ;; font-lock-constant-face
3196 (org-compatible-face
3197 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3198 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3199 (((class color) (min-colors 8)) (:foreground "magenta"))))
3200 "Face used for level 6 headlines."
3201 :group 'org-faces)
3203 (defface org-level-7 ;; font-lock-builtin-face
3204 (org-compatible-face
3205 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3206 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3207 (((class color) (min-colors 8)) (:foreground "blue"))))
3208 "Face used for level 7 headlines."
3209 :group 'org-faces)
3211 (defface org-level-8 ;; font-lock-string-face
3212 (org-compatible-face
3213 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3214 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3215 (((class color) (min-colors 8)) (:foreground "green"))))
3216 "Face used for level 8 headlines."
3217 :group 'org-faces)
3219 (defface org-special-keyword ;; font-lock-string-face
3220 (org-compatible-face
3221 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3222 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3223 (t (:italic t))))
3224 "Face used for special keywords."
3225 :group 'org-faces)
3227 (defface org-drawer ;; font-lock-function-name-face
3228 (org-compatible-face
3229 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3230 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3231 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3232 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3233 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3234 (t (:bold t))))
3235 "Face used for drawers."
3236 :group 'org-faces)
3238 (defface org-property-value nil
3239 "Face used for the value of a property."
3240 :group 'org-faces)
3242 (defface org-column
3243 (org-compatible-face
3244 '((((class color) (min-colors 16) (background light))
3245 (:background "grey90"))
3246 (((class color) (min-colors 16) (background dark))
3247 (:background "grey30"))
3248 (((class color) (min-colors 8))
3249 (:background "cyan" :foreground "black"))
3250 (t (:inverse-video t))))
3251 "Face for column display of entry properties."
3252 :group 'org-faces)
3254 (when (fboundp 'set-face-attribute)
3255 ;; Make sure that a fixed-width face is used when we have a column table.
3256 (set-face-attribute 'org-column nil
3257 :height (face-attribute 'default :height)
3258 :family (face-attribute 'default :family)))
3260 (defface org-warning ;; font-lock-warning-face
3261 (org-compatible-face
3262 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3263 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3264 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3265 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3266 (t (:bold t))))
3267 "Face for deadlines and TODO keywords."
3268 :group 'org-faces)
3270 (defface org-archived ; similar to shadow
3271 (org-compatible-face
3272 '((((class color grayscale) (min-colors 88) (background light))
3273 (:foreground "grey50"))
3274 (((class color grayscale) (min-colors 88) (background dark))
3275 (:foreground "grey70"))
3276 (((class color) (min-colors 8) (background light))
3277 (:foreground "green"))
3278 (((class color) (min-colors 8) (background dark))
3279 (:foreground "yellow"))))
3280 "Face for headline with the ARCHIVE tag."
3281 :group 'org-faces)
3283 (defface org-link
3284 '((((class color) (background light)) (:foreground "Purple" :underline t))
3285 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3286 (t (:underline t)))
3287 "Face for links."
3288 :group 'org-faces)
3290 (defface org-target
3291 '((((class color) (background light)) (:underline t))
3292 (((class color) (background dark)) (:underline t))
3293 (t (:underline t)))
3294 "Face for links."
3295 :group 'org-faces)
3297 (defface org-date
3298 '((((class color) (background light)) (:foreground "Purple" :underline t))
3299 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3300 (t (:underline t)))
3301 "Face for links."
3302 :group 'org-faces)
3304 (defface org-sexp-date
3305 '((((class color) (background light)) (:foreground "Purple"))
3306 (((class color) (background dark)) (:foreground "Cyan"))
3307 (t (:underline t)))
3308 "Face for links."
3309 :group 'org-faces)
3311 (defface org-tag
3312 '((t (:bold t)))
3313 "Face for tags."
3314 :group 'org-faces)
3316 (defface org-todo ;; font-lock-warning-face
3317 (org-compatible-face
3318 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3319 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3320 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3321 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3322 (t (:inverse-video t :bold t))))
3323 "Face for TODO keywords."
3324 :group 'org-faces)
3326 (defface org-done ;; font-lock-type-face
3327 (org-compatible-face
3328 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3329 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3330 (((class color) (min-colors 8)) (:foreground "green"))
3331 (t (:bold t))))
3332 "Face used for todo keywords that indicate DONE items."
3333 :group 'org-faces)
3335 (defface org-headline-done ;; 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 (((class color) (min-colors 8) (background light)) (:bold nil))))
3340 "Face used to indicate that a headline is DONE.
3341 This face is only used if `org-fontify-done-headline' is set. If applies
3342 to the part of the headline after the DONE keyword."
3343 :group 'org-faces)
3345 (defface org-table ;; font-lock-function-name-face
3346 (org-compatible-face
3347 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3348 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3349 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3350 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3351 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3352 (((class color) (min-colors 8) (background dark)))))
3353 "Face used for tables."
3354 :group 'org-faces)
3356 (defface org-formula
3357 (org-compatible-face
3358 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3359 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3360 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3361 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3362 (t (:bold t :italic t))))
3363 "Face for formulas."
3364 :group 'org-faces)
3366 (defface org-agenda-structure ;; font-lock-function-name-face
3367 (org-compatible-face
3368 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3369 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3370 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3371 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3372 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3373 (t (:bold t))))
3374 "Face used in agenda for captions and dates."
3375 :group 'org-faces)
3377 (defface org-scheduled-today
3378 (org-compatible-face
3379 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3380 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3381 (((class color) (min-colors 8)) (:foreground "green"))
3382 (t (:bold t :italic t))))
3383 "Face for items scheduled for a certain day."
3384 :group 'org-faces)
3386 (defface org-scheduled-previously
3387 (org-compatible-face
3388 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3389 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3390 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3391 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3392 (t (:bold t))))
3393 "Face for items scheduled previously, and not yet done."
3394 :group 'org-faces)
3396 (defface org-upcoming-deadline
3397 (org-compatible-face
3398 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3399 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3400 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3401 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3402 (t (:bold t))))
3403 "Face for items scheduled previously, and not yet done."
3404 :group 'org-faces)
3406 (defface org-time-grid ;; font-lock-variable-name-face
3407 (org-compatible-face
3408 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3409 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3410 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3411 "Face used for time grids."
3412 :group 'org-faces)
3414 (defconst org-level-faces
3415 '(org-level-1 org-level-2 org-level-3 org-level-4
3416 org-level-5 org-level-6 org-level-7 org-level-8
3419 (defcustom org-n-level-faces (length org-level-faces)
3420 "The number different faces to be used for headlines.
3421 Org-mode defines 8 different headline faces, so this can be at most 8.
3422 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3423 :type 'number
3424 :group 'org-faces)
3426 ;;; Variables for pre-computed regular expressions, all buffer local
3428 (defvar org-drawer-regexp nil
3429 "Matches first line of a hidden block.")
3430 (make-variable-buffer-local 'org-drawer-regexp)
3431 (defvar org-todo-regexp nil
3432 "Matches any of the TODO state keywords.")
3433 (make-variable-buffer-local 'org-todo-regexp)
3434 (defvar org-not-done-regexp nil
3435 "Matches any of the TODO state keywords except the last one.")
3436 (make-variable-buffer-local 'org-not-done-regexp)
3437 (defvar org-todo-line-regexp nil
3438 "Matches a headline and puts TODO state into group 2 if present.")
3439 (make-variable-buffer-local 'org-todo-line-regexp)
3440 (defvar org-todo-line-tags-regexp nil
3441 "Matches a headline and puts TODO state into group 2 if present.
3442 Also put tags into group 4 if tags are present.")
3443 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3444 (defvar org-nl-done-regexp nil
3445 "Matches newline followed by a headline with the DONE keyword.")
3446 (make-variable-buffer-local 'org-nl-done-regexp)
3447 (defvar org-looking-at-done-regexp nil
3448 "Matches the DONE keyword a point.")
3449 (make-variable-buffer-local 'org-looking-at-done-regexp)
3450 (defvar org-ds-keyword-length 12
3451 "Maximum length of the Deadline and SCHEDULED keywords.")
3452 (make-variable-buffer-local 'org-ds-keyword-length)
3453 (defvar org-deadline-regexp nil
3454 "Matches the DEADLINE keyword.")
3455 (make-variable-buffer-local 'org-deadline-regexp)
3456 (defvar org-deadline-time-regexp nil
3457 "Matches the DEADLINE keyword together with a time stamp.")
3458 (make-variable-buffer-local 'org-deadline-time-regexp)
3459 (defvar org-deadline-line-regexp nil
3460 "Matches the DEADLINE keyword and the rest of the line.")
3461 (make-variable-buffer-local 'org-deadline-line-regexp)
3462 (defvar org-scheduled-regexp nil
3463 "Matches the SCHEDULED keyword.")
3464 (make-variable-buffer-local 'org-scheduled-regexp)
3465 (defvar org-scheduled-time-regexp nil
3466 "Matches the SCHEDULED keyword together with a time stamp.")
3467 (make-variable-buffer-local 'org-scheduled-time-regexp)
3468 (defvar org-closed-time-regexp nil
3469 "Matches the CLOSED keyword together with a time stamp.")
3470 (make-variable-buffer-local 'org-closed-time-regexp)
3472 (defvar org-keyword-time-regexp nil
3473 "Matches any of the 4 keywords, together with the time stamp.")
3474 (make-variable-buffer-local 'org-keyword-time-regexp)
3475 (defvar org-keyword-time-not-clock-regexp nil
3476 "Matches any of the 3 keywords, together with the time stamp.")
3477 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3478 (defvar org-maybe-keyword-time-regexp nil
3479 "Matches a timestamp, possibly preceeded by a keyword.")
3480 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3481 (defvar org-planning-or-clock-line-re nil
3482 "Matches a line with planning or clock info.")
3483 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3485 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3486 rear-nonsticky t mouse-map t fontified t)
3487 "Properties to remove when a string without properties is wanted.")
3489 (defsubst org-match-string-no-properties (num &optional string)
3490 (if (featurep 'xemacs)
3491 (let ((s (match-string num string)))
3492 (remove-text-properties 0 (length s) org-rm-props s)
3494 (match-string-no-properties num string)))
3496 (defsubst org-no-properties (s)
3497 (if (fboundp 'set-text-properties)
3498 (set-text-properties 0 (length s) nil s)
3499 (remove-text-properties 0 (length s) org-rm-props s))
3502 (defsubst org-get-alist-option (option key)
3503 (cond ((eq key t) t)
3504 ((eq option t) t)
3505 ((assoc key option) (cdr (assoc key option)))
3506 (t (cdr (assq 'default option)))))
3508 (defsubst org-inhibit-invisibility ()
3509 "Modified `buffer-invisibility-spec' for Emacs 21.
3510 Some ops with invisible text do not work correctly on Emacs 21. For these
3511 we turn off invisibility temporarily. Use this in a `let' form."
3512 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3514 (defsubst org-set-local (var value)
3515 "Make VAR local in current buffer and set it to VALUE."
3516 (set (make-variable-buffer-local var) value))
3518 (defsubst org-mode-p ()
3519 "Check if the current buffer is in Org-mode."
3520 (eq major-mode 'org-mode))
3522 (defsubst org-last (list)
3523 "Return the last element of LIST."
3524 (car (last list)))
3526 (defun org-let (list &rest body)
3527 (eval (cons 'let (cons list body))))
3528 (put 'org-let 'lisp-indent-function 1)
3530 (defun org-let2 (list1 list2 &rest body)
3531 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3532 (put 'org-let2 'lisp-indent-function 2)
3533 (defconst org-startup-options
3534 '(("fold" org-startup-folded t)
3535 ("overview" org-startup-folded t)
3536 ("nofold" org-startup-folded nil)
3537 ("showall" org-startup-folded nil)
3538 ("content" org-startup-folded content)
3539 ("hidestars" org-hide-leading-stars t)
3540 ("showstars" org-hide-leading-stars nil)
3541 ("odd" org-odd-levels-only t)
3542 ("oddeven" org-odd-levels-only nil)
3543 ("align" org-startup-align-all-tables t)
3544 ("noalign" org-startup-align-all-tables nil)
3545 ("customtime" org-display-custom-times t)
3546 ("logging" org-log-done t)
3547 ("logdone" org-log-done t)
3548 ("nologging" org-log-done nil)
3549 ("lognotedone" org-log-done done push)
3550 ("lognotestate" org-log-done state push)
3551 ("lognoteclock-out" org-log-done clock-out push)
3552 ("logrepeat" org-log-repeat t)
3553 ("nologrepeat" org-log-repeat nil)
3554 ("constcgs" constants-unit-system cgs)
3555 ("constSI" constants-unit-system SI))
3556 "Variable associated with STARTUP options for org-mode.
3557 Each element is a list of three items: The startup options as written
3558 in the #+STARTUP line, the corresponding variable, and the value to
3559 set this variable to if the option is found. An optional forth element PUSH
3560 means to push this value onto the list in the variable.")
3562 (defun org-set-regexps-and-options ()
3563 "Precompute regular expressions for current buffer."
3564 (when (org-mode-p)
3565 (org-set-local 'org-todo-kwd-alist nil)
3566 (org-set-local 'org-todo-keywords-1 nil)
3567 (org-set-local 'org-done-keywords nil)
3568 (org-set-local 'org-todo-heads nil)
3569 (org-set-local 'org-todo-sets nil)
3570 (let ((re (org-make-options-regexp
3571 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO" "COLUMNS"
3572 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3573 "CONSTANTS")))
3574 (splitre "[ \t]+")
3575 kwds key value cat arch tags const links hw dws tail sep kws1 prio)
3576 (save-excursion
3577 (save-restriction
3578 (widen)
3579 (goto-char (point-min))
3580 (while (re-search-forward re nil t)
3581 (setq key (match-string 1) value (org-match-string-no-properties 2))
3582 (cond
3583 ((equal key "CATEGORY")
3584 (if (string-match "[ \t]+$" value)
3585 (setq value (replace-match "" t t value)))
3586 (setq cat (intern value)))
3587 ((equal key "SEQ_TODO")
3588 (push (cons 'sequence (org-split-string value splitre)) kwds))
3589 ((equal key "TYP_TODO")
3590 (push (cons 'type (org-split-string value splitre)) kwds))
3591 ((equal key "TAGS")
3592 (setq tags (append tags (org-split-string value splitre))))
3593 ((equal key "COLUMNS")
3594 (org-set-local 'org-columns-default-format value))
3595 ((equal key "LINK")
3596 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3597 (push (cons (match-string 1 value)
3598 (org-trim (match-string 2 value)))
3599 links)))
3600 ((equal key "PRIORITIES")
3601 (setq prio (org-split-string value " +")))
3602 ((equal key "CONSTANTS")
3603 (setq const (append const (org-split-string value splitre))))
3604 ((equal key "STARTUP")
3605 (let ((opts (org-split-string value splitre))
3606 l var val)
3607 (while (setq l (pop opts))
3608 (when (setq l (assoc l org-startup-options))
3609 (setq var (nth 1 l) val (nth 2 l))
3610 (if (not (nth 3 l))
3611 (set (make-local-variable var) val)
3612 (if (not (listp (symbol-value var)))
3613 (set (make-local-variable var) nil))
3614 (set (make-local-variable var) (symbol-value var))
3615 (add-to-list var val))))))
3616 ((equal key "ARCHIVE")
3617 (string-match " *$" value)
3618 (setq arch (replace-match "" t t value))
3619 (remove-text-properties 0 (length arch)
3620 '(face t fontified t) arch)))
3622 (and cat (org-set-local 'org-category cat))
3623 (when prio
3624 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3625 (setq prio (mapcar 'string-to-char prio))
3626 (org-set-local 'org-highest-priority (nth 0 prio))
3627 (org-set-local 'org-lowest-priority (nth 1 prio))
3628 (org-set-local 'org-default-priority (nth 2 prio)))
3629 (and arch (org-set-local 'org-archive-location arch))
3630 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3631 ;; Process the TODO keywords
3632 (unless kwds
3633 ;; Use the global values as if they had been given locally.
3634 (setq kwds (default-value 'org-todo-keywords))
3635 (if (stringp (car kwds))
3636 (setq kwds (list (cons org-todo-interpretation
3637 (default-value 'org-todo-keywords)))))
3638 (setq kwds (reverse kwds)))
3639 (setq kwds (nreverse kwds))
3640 (let (inter kws)
3641 (while (setq kws (pop kwds))
3642 (setq inter (pop kws) sep (member "|" kws)
3643 kws1 (delete "|" (copy-sequence kws))
3644 hw (car kws1)
3645 dws (if sep (cdr sep) (last kws1))
3646 tail (list inter hw (car dws) (org-last dws)))
3647 (add-to-list 'org-todo-heads hw 'append)
3648 (push kws1 org-todo-sets)
3649 (setq org-done-keywords (append org-done-keywords dws nil))
3650 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3651 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3652 (setq org-todo-sets (nreverse org-todo-sets)
3653 org-todo-kwd-alist (nreverse org-todo-kwd-alist)))
3654 ;; Process the constants
3655 (when const
3656 (let (e cst)
3657 (while (setq e (pop const))
3658 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3659 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3660 (setq org-table-formula-constants-local cst)))
3662 ;; Process the tags.
3663 (when tags
3664 (let (e tgs)
3665 (while (setq e (pop tags))
3666 (cond
3667 ((equal e "{") (push '(:startgroup) tgs))
3668 ((equal e "}") (push '(:endgroup) tgs))
3669 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3670 (push (cons (match-string 1 e)
3671 (string-to-char (match-string 2 e)))
3672 tgs))
3673 (t (push (list e) tgs))))
3674 (org-set-local 'org-tag-alist nil)
3675 (while (setq e (pop tgs))
3676 (or (and (stringp (car e))
3677 (assoc (car e) org-tag-alist))
3678 (push e org-tag-alist))))))
3680 ;; Compute the regular expressions and other local variables
3681 (if (not org-done-keywords)
3682 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3683 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3684 (length org-scheduled-string)))
3685 org-drawer-regexp
3686 (concat "^[ \t]*:\\("
3687 (mapconcat 'regexp-quote org-drawers "\\|")
3688 "\\):[ \t]*$")
3689 org-not-done-keywords
3690 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3691 org-todo-regexp
3692 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3693 "\\|") "\\)\\>")
3694 org-not-done-regexp
3695 (concat "\\<\\("
3696 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3697 "\\)\\>")
3698 org-todo-line-regexp
3699 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3700 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3701 "\\)\\>\\)?[ \t]*\\(.*\\)")
3702 org-nl-done-regexp
3703 (concat "\n\\*+[ \t]+"
3704 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3705 "\\)" "\\>")
3706 org-todo-line-tags-regexp
3707 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3708 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3709 (org-re
3710 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3711 org-looking-at-done-regexp
3712 (concat "^" "\\(?:"
3713 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3714 "\\>")
3715 org-deadline-regexp (concat "\\<" org-deadline-string)
3716 org-deadline-time-regexp
3717 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3718 org-deadline-line-regexp
3719 (concat "\\<\\(" org-deadline-string "\\).*")
3720 org-scheduled-regexp
3721 (concat "\\<" org-scheduled-string)
3722 org-scheduled-time-regexp
3723 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3724 org-closed-time-regexp
3725 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3726 org-keyword-time-regexp
3727 (concat "\\<\\(" org-scheduled-string
3728 "\\|" org-deadline-string
3729 "\\|" org-closed-string
3730 "\\|" org-archived-string
3731 "\\|" org-clock-string "\\)"
3732 " *[[<]\\([^]>]+\\)[]>]")
3733 org-keyword-time-not-clock-regexp
3734 (concat "\\<\\(" org-scheduled-string
3735 "\\|" org-deadline-string
3736 "\\|" org-closed-string
3737 "\\|" org-archived-string
3738 "\\)"
3739 " *[[<]\\([^]>]+\\)[]>]")
3740 org-maybe-keyword-time-regexp
3741 (concat "\\(\\<\\(" org-scheduled-string
3742 "\\|" org-deadline-string
3743 "\\|" org-closed-string
3744 "\\|" org-archived-string
3745 "\\|" org-clock-string "\\)\\)?"
3746 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3747 org-planning-or-clock-line-re
3748 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3749 "\\|" org-deadline-string
3750 "\\|" org-closed-string "\\|" org-clock-string
3751 "\\|" org-archived-string "\\)\\>\\)")
3754 (org-set-font-lock-defaults)))
3757 ;;; Some variables ujsed in various places
3759 (defvar org-window-configuration nil
3760 "Used in various places to store a window configuration.")
3761 (defvar org-finish-function nil
3762 "Function to be called when `C-c C-c' is used.
3763 This is for getting out of special buffers like remember.")
3765 ;;; Foreign variables, to inform the compiler
3767 ;; XEmacs only
3768 (defvar outline-mode-menu-heading)
3769 (defvar outline-mode-menu-show)
3770 (defvar outline-mode-menu-hide)
3771 (defvar zmacs-regions) ; XEmacs regions
3772 ;; Emacs only
3773 (defvar mark-active)
3775 ;; Packages that org-mode interacts with
3776 (defvar calc-embedded-close-formula)
3777 (defvar calc-embedded-open-formula)
3778 (defvar font-lock-unfontify-region-function)
3779 (defvar org-goto-start-pos)
3780 (defvar vm-message-pointer)
3781 (defvar vm-folder-directory)
3782 (defvar wl-summary-buffer-elmo-folder)
3783 (defvar wl-summary-buffer-folder-name)
3784 (defvar gnus-other-frame-object)
3785 (defvar gnus-group-name)
3786 (defvar gnus-article-current)
3787 (defvar w3m-current-url)
3788 (defvar w3m-current-title)
3789 (defvar mh-progs)
3790 (defvar mh-current-folder)
3791 (defvar mh-show-folder-buffer)
3792 (defvar mh-index-folder)
3793 (defvar mh-searcher)
3794 (defvar calendar-mode-map)
3795 (defvar Info-current-file)
3796 (defvar Info-current-node)
3797 (defvar texmathp-why)
3798 (defvar remember-save-after-remembering)
3799 (defvar remember-data-file)
3800 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
3801 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
3802 (defvar org-latex-regexps)
3803 (defvar constants-unit-system)
3805 (defvar original-date) ; dynamically scoped in calendar.el does scope this
3807 ;; FIXME: Occasionally check by commenting these, to make sure
3808 ;; no other functions uses these, forgetting to let-bind them.
3809 (defvar entry)
3810 (defvar state)
3811 (defvar last-state)
3812 (defvar date)
3813 (defvar description)
3816 ;; Defined somewhere in this file, but used before definition.
3817 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
3818 (defvar org-agenda-undo-list)
3819 (defvar org-agenda-pending-undo-list)
3820 (defvar org-agenda-overriding-header)
3821 (defvar orgtbl-mode)
3822 (defvar org-html-entities)
3823 (defvar org-struct-menu)
3824 (defvar org-org-menu)
3825 (defvar org-tbl-menu)
3826 (defvar org-agenda-keymap)
3827 (defvar org-category-table)
3829 ;;;; Emacs/XEmacs compatibility
3831 ;; Overlay compatibility functions
3832 (defun org-make-overlay (beg end &optional buffer)
3833 (if (featurep 'xemacs)
3834 (make-extent beg end buffer)
3835 (make-overlay beg end buffer)))
3836 (defun org-delete-overlay (ovl)
3837 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3838 (defun org-detach-overlay (ovl)
3839 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3840 (defun org-move-overlay (ovl beg end &optional buffer)
3841 (if (featurep 'xemacs)
3842 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
3843 (move-overlay ovl beg end buffer)))
3844 (defun org-overlay-put (ovl prop value)
3845 (if (featurep 'xemacs)
3846 (set-extent-property ovl prop value)
3847 (overlay-put ovl prop value)))
3848 (defun org-overlay-display (ovl text &optional face evap)
3849 "Make overlay OVL display TEXT with face FACE."
3850 (if (featurep 'xemacs)
3851 (let ((gl (make-glyph text)))
3852 (and face (set-glyph-face gl face))
3853 (set-extent-property ovl 'invisible t)
3854 (set-extent-property ovl 'end-glyph gl))
3855 (overlay-put ovl 'display text)
3856 (if face (overlay-put ovl 'face face))
3857 (if evap (overlay-put ovl 'evaporate t))))
3858 (defun org-overlay-before-string (ovl text &optional face evap)
3859 "Make overlay OVL display TEXT with face FACE."
3860 (if (featurep 'xemacs)
3861 (let ((gl (make-glyph text)))
3862 (and face (set-glyph-face gl face))
3863 (set-extent-property ovl 'begin-glyph gl))
3864 (if face (org-add-props text nil 'face face))
3865 (overlay-put ovl 'before-string text)
3866 (if evap (overlay-put ovl 'evaporate t))))
3867 (defun org-overlay-get (ovl prop)
3868 (if (featurep 'xemacs)
3869 (extent-property ovl prop)
3870 (overlay-get ovl prop)))
3871 (defun org-overlays-at (pos)
3872 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
3873 ;; FIXME: this is currently not used
3874 (defun org-overlays-in (&optional start end)
3875 (if (featurep 'xemacs)
3876 (extent-list nil start end)
3877 (overlays-in start end)))
3878 (defun org-overlay-start (o)
3879 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
3880 (defun org-overlay-end (o)
3881 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
3882 ;; FIXME: this is currently not used
3883 (defun org-find-overlays (prop &optional pos delete)
3884 "Find all overlays specifying PROP at POS or point.
3885 If DELETE is non-nil, delete all those overlays."
3886 (let ((overlays (org-overlays-at (or pos (point))))
3887 ov found)
3888 (while (setq ov (pop overlays))
3889 (if (org-overlay-get ov prop)
3890 (if delete (org-delete-overlay ov) (push ov found))))
3891 found))
3893 ;; Region compatibility
3895 (defun org-add-hook (hook function &optional append local)
3896 "Add-hook, compatible with both Emacsen."
3897 (if (and local (featurep 'xemacs))
3898 (add-local-hook hook function append)
3899 (add-hook hook function append local)))
3901 (defvar org-ignore-region nil
3902 "To temporarily disable the active region.")
3904 (defun org-region-active-p ()
3905 "Is `transient-mark-mode' on and the region active?
3906 Works on both Emacs and XEmacs."
3907 (if org-ignore-region
3909 (if (featurep 'xemacs)
3910 (and zmacs-regions (region-active-p))
3911 (and transient-mark-mode mark-active))))
3913 ;; Invisibility compatibility
3915 (defun org-add-to-invisibility-spec (arg)
3916 "Add elements to `buffer-invisibility-spec'.
3917 See documentation for `buffer-invisibility-spec' for the kind of elements
3918 that can be added."
3919 (cond
3920 ((fboundp 'add-to-invisibility-spec)
3921 (add-to-invisibility-spec arg))
3922 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
3923 (setq buffer-invisibility-spec (list arg)))
3925 (setq buffer-invisibility-spec
3926 (cons arg buffer-invisibility-spec)))))
3928 (defun org-remove-from-invisibility-spec (arg)
3929 "Remove elements from `buffer-invisibility-spec'."
3930 (if (fboundp 'remove-from-invisibility-spec)
3931 (remove-from-invisibility-spec arg)
3932 (if (consp buffer-invisibility-spec)
3933 (setq buffer-invisibility-spec
3934 (delete arg buffer-invisibility-spec)))))
3936 ;; FIXME: this is currently not used
3937 (defun org-in-invisibility-spec-p (arg)
3938 "Is ARG a member of `buffer-invisibility-spec'?"
3939 (if (consp buffer-invisibility-spec)
3940 (member arg buffer-invisibility-spec)
3941 nil))
3943 ;;;; Define the Org-mode
3945 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3946 (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."))
3949 ;; We use a before-change function to check if a table might need
3950 ;; an update.
3951 (defvar org-table-may-need-update t
3952 "Indicates that a table might need an update.
3953 This variable is set by `org-before-change-function'.
3954 `org-table-align' sets it back to nil.")
3955 (defvar org-mode-map)
3956 (defvar org-mode-hook nil)
3957 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3958 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3959 (defvar org-table-buffer-is-an nil)
3962 ;;;###autoload
3963 (define-derived-mode org-mode outline-mode "Org"
3964 "Outline-based notes management and organizer, alias
3965 \"Carsten's outline-mode for keeping track of everything.\"
3967 Org-mode develops organizational tasks around a NOTES file which
3968 contains information about projects as plain text. Org-mode is
3969 implemented on top of outline-mode, which is ideal to keep the content
3970 of large files well structured. It supports ToDo items, deadlines and
3971 time stamps, which magically appear in the diary listing of the Emacs
3972 calendar. Tables are easily created with a built-in table editor.
3973 Plain text URL-like links connect to websites, emails (VM), Usenet
3974 messages (Gnus), BBDB entries, and any files related to the project.
3975 For printing and sharing of notes, an Org-mode file (or a part of it)
3976 can be exported as a structured ASCII or HTML file.
3978 The following commands are available:
3980 \\{org-mode-map}"
3982 ;; Get rid of Outline menus, they are not needed
3983 ;; Need to do this here because define-derived-mode sets up
3984 ;; the keymap so late. Still, it is a waste to call this each time
3985 ;; we switch another buffer into org-mode.
3986 (if (featurep 'xemacs)
3987 (when (boundp 'outline-mode-menu-heading)
3988 ;; Assume this is Greg's port, it used easymenu
3989 (easy-menu-remove outline-mode-menu-heading)
3990 (easy-menu-remove outline-mode-menu-show)
3991 (easy-menu-remove outline-mode-menu-hide))
3992 (define-key org-mode-map [menu-bar headings] 'undefined)
3993 (define-key org-mode-map [menu-bar hide] 'undefined)
3994 (define-key org-mode-map [menu-bar show] 'undefined))
3996 (easy-menu-add org-org-menu)
3997 (easy-menu-add org-tbl-menu)
3998 (org-install-agenda-files-menu)
3999 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4000 (org-add-to-invisibility-spec '(org-cwidth))
4001 (when (featurep 'xemacs)
4002 (org-set-local 'line-move-ignore-invisible t))
4003 (setq outline-regexp "\\*+ ")
4004 (setq outline-level 'org-outline-level)
4005 (when (and org-ellipsis (stringp org-ellipsis)
4006 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table))
4007 (unless org-display-table
4008 (setq org-display-table (make-display-table)))
4009 (set-display-table-slot org-display-table
4010 4 (string-to-vector org-ellipsis))
4011 (setq buffer-display-table org-display-table))
4012 (org-set-regexps-and-options)
4013 ;; Calc embedded
4014 (org-set-local 'calc-embedded-open-mode "# ")
4015 (modify-syntax-entry ?# "<")
4016 (modify-syntax-entry ?@ "w")
4017 (if org-startup-truncated (setq truncate-lines t))
4018 (org-set-local 'font-lock-unfontify-region-function
4019 'org-unfontify-region)
4020 ;; Activate before-change-function
4021 (org-set-local 'org-table-may-need-update t)
4022 (org-add-hook 'before-change-functions 'org-before-change-function nil
4023 'local)
4024 ;; Check for running clock before killing a buffer
4025 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4026 ;; Paragraphs and auto-filling
4027 (org-set-autofill-regexps)
4028 (setq indent-line-function 'org-indent-line-function)
4029 (org-update-radio-target-regexp)
4031 ;; Comment characters
4032 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4033 (org-set-local 'comment-padding " ")
4035 ;; Make isearch reveal context
4036 (if (or (featurep 'xemacs)
4037 (not (boundp 'outline-isearch-open-invisible-function)))
4038 ;; Emacs 21 and XEmacs make use of the hook
4039 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4040 ;; Emacs 22 deals with this through a special variable
4041 (org-set-local 'outline-isearch-open-invisible-function
4042 (lambda (&rest ignore) (org-show-context 'isearch))))
4044 ;; If empty file that did not turn on org-mode automatically, make it to.
4045 (if (and org-insert-mode-line-in-empty-file
4046 (interactive-p)
4047 (= (point-min) (point-max)))
4048 (insert "# -*- mode: org -*-\n\n"))
4050 (unless org-inhibit-startup
4051 (when org-startup-align-all-tables
4052 (let ((bmp (buffer-modified-p)))
4053 (org-table-map-tables 'org-table-align)
4054 (set-buffer-modified-p bmp)))
4055 (cond
4056 ((eq org-startup-folded t)
4057 (org-cycle '(4)))
4058 ((eq org-startup-folded 'content)
4059 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4060 (org-cycle '(4)) (org-cycle '(4)))))))
4062 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4064 (defsubst org-call-with-arg (command arg)
4065 "Call COMMAND interactively, but pretend prefix are was ARG."
4066 (let ((current-prefix-arg arg)) (call-interactively command)))
4068 (defsubst org-current-line (&optional pos)
4069 (save-excursion
4070 (and pos (goto-char pos))
4071 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4073 (defun org-current-time ()
4074 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4075 (if (> org-time-stamp-rounding-minutes 0)
4076 (let ((r org-time-stamp-rounding-minutes)
4077 (time (decode-time)))
4078 (apply 'encode-time
4079 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4080 (nthcdr 2 time))))
4081 (current-time)))
4083 (defun org-add-props (string plist &rest props)
4084 "Add text properties to entire string, from beginning to end.
4085 PLIST may be a list of properties, PROPS are individual properties and values
4086 that will be added to PLIST. Returns the string that was modified."
4087 (add-text-properties
4088 0 (length string) (if props (append plist props) plist) string)
4089 string)
4090 (put 'org-add-props 'lisp-indent-function 2)
4093 ;;;; Font-Lock stuff, including the activators
4095 (defvar org-mouse-map (make-sparse-keymap))
4096 (org-defkey org-mouse-map
4097 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4098 (org-defkey org-mouse-map
4099 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4100 (when org-mouse-1-follows-link
4101 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4102 (when org-tab-follows-link
4103 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4104 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4105 (when org-return-follows-link
4106 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4107 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4109 (require 'font-lock)
4111 (defconst org-non-link-chars "]\t\n\r<>")
4112 (defconst org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4113 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4114 (defconst org-link-re-with-space
4115 (concat
4116 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4117 "\\([^" org-non-link-chars " ]"
4118 "[^" org-non-link-chars "]*"
4119 "[^" org-non-link-chars " ]\\)>?")
4120 "Matches a link with spaces, optional angular brackets around it.")
4122 (defconst org-link-re-with-space2
4123 (concat
4124 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4125 "\\([^" org-non-link-chars " ]"
4126 "[^]\t\n\r]*"
4127 "[^" org-non-link-chars " ]\\)>?")
4128 "Matches a link with spaces, optional angular brackets around it.")
4130 (defconst org-angle-link-re
4131 (concat
4132 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4133 "\\([^" org-non-link-chars " ]"
4134 "[^" org-non-link-chars "]*"
4135 "\\)>")
4136 "Matches link with angular brackets, spaces are allowed.")
4137 (defconst org-plain-link-re
4138 (concat
4139 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4140 "\\([^]\t\n\r<>,;() ]+\\)")
4141 "Matches plain link, without spaces.")
4143 (defconst org-bracket-link-regexp
4144 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4145 "Matches a link in double brackets.")
4147 (defconst org-bracket-link-analytic-regexp
4148 (concat
4149 "\\[\\["
4150 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4151 "\\([^]]+\\)"
4152 "\\]"
4153 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4154 "\\]"))
4155 ; 1: http:
4156 ; 2: http
4157 ; 3: path
4158 ; 4: [desc]
4159 ; 5: desc
4161 (defconst org-any-link-re
4162 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4163 org-angle-link-re "\\)\\|\\("
4164 org-plain-link-re "\\)")
4165 "Regular expression matching any link.")
4167 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4168 "Regular expression for fast time stamp matching.")
4169 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4170 "Regular expression for fast time stamp matching.")
4171 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4172 "Regular expression matching time strings for analysis.
4173 This one does not require the space after the date.")
4174 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4175 "Regular expression matching time strings for analysis.")
4176 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,11\\}>")
4177 "Regular expression matching time stamps, with groups.")
4178 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,11\\}[]>]")
4179 "Regular expression matching time stamps (also [..]), with groups.")
4180 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4181 "Regular expression matching a time stamp range.")
4182 (defconst org-tr-regexp-both
4183 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4184 "Regular expression matching a time stamp range.")
4185 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4186 org-ts-regexp "\\)?")
4187 "Regular expression matching a time stamp or time stamp range.")
4188 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4189 org-ts-regexp-both "\\)?")
4190 "Regular expression matching a time stamp or time stamp range.
4191 The time stamps may be either active or inactive.")
4193 (defvar org-emph-face nil)
4195 (defun org-do-emphasis-faces (limit)
4196 "Run through the buffer and add overlays to links."
4197 (let (rtn)
4198 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4199 (if (not (= (char-after (match-beginning 3))
4200 (char-after (match-beginning 4))))
4201 (progn
4202 (setq rtn t)
4203 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4204 'face
4205 (nth 1 (assoc (match-string 3)
4206 org-emphasis-alist)))
4207 (add-text-properties (match-beginning 2) (match-end 2)
4208 '(font-lock-multiline t))
4209 (backward-char 1))))
4210 rtn))
4212 (defun org-emphasize (&optional char)
4213 "Insert or change an emphasis, i.e. a font like bold or italic.
4214 If there is an active region, change that region to a new emphasis.
4215 If there is no region, just insert the marker characters and position
4216 the cursor between them.
4217 CHAR should be either the marker character, or the first character of the
4218 HTML tag associated with that emphasis. If CHAR is a space, the means
4219 to remove the emphasis of the selected region.
4220 If char is not given (for example in an interactive call) it
4221 will be prompted for."
4222 (interactive)
4223 (let ((eal org-emphasis-alist) e det
4224 (erc org-emphasis-regexp-components)
4225 (prompt "")
4226 (string "") beg end move tag c s)
4227 (if (org-region-active-p)
4228 (setq beg (region-beginning) end (region-end)
4229 string (buffer-substring beg end))
4230 (setq move t))
4232 (while (setq e (pop eal))
4233 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4234 c (aref tag 0))
4235 (push (cons c (string-to-char (car e))) det)
4236 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4237 (substring tag 1)))))
4238 (unless char
4239 (message "%s" (concat "Emphasis marker or tag:" prompt))
4240 (setq char (read-char-exclusive)))
4241 (setq char (or (cdr (assoc char det)) char))
4242 (if (equal char ?\ )
4243 (setq s "" move nil)
4244 (unless (assoc (char-to-string char) org-emphasis-alist)
4245 (error "No such emphasis marker: \"%c\"" char))
4246 (setq s (char-to-string char)))
4247 (while (and (> (length string) 1)
4248 (equal (substring string 0 1) (substring string -1))
4249 (assoc (substring string 0 1) org-emphasis-alist))
4250 (setq string (substring string 1 -1)))
4251 (setq string (concat s string s))
4252 (if beg (delete-region beg end))
4253 (unless (or (bolp)
4254 (string-match (concat "[" (nth 0 erc) "\n]")
4255 (char-to-string (char-before (point)))))
4256 (insert " "))
4257 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4258 (char-to-string (char-after (point))))
4259 (insert " ") (backward-char 1))
4260 (insert string)
4261 (and move (backward-char 1))))
4263 (defun org-activate-plain-links (limit)
4264 "Run through the buffer and add overlays to links."
4265 (catch 'exit
4266 (let (f)
4267 (while (re-search-forward org-plain-link-re limit t)
4268 (setq f (get-text-property (match-beginning 0) 'face))
4269 (if (or (eq f 'org-tag)
4270 (and (listp f) (memq 'org-tag f)))
4272 (add-text-properties (match-beginning 0) (match-end 0)
4273 (list 'mouse-face 'highlight
4274 'rear-nonsticky t
4275 'keymap org-mouse-map
4277 (throw 'exit t))))))
4279 (defun org-activate-angle-links (limit)
4280 "Run through the buffer and add overlays to links."
4281 (if (re-search-forward org-angle-link-re limit t)
4282 (progn
4283 (add-text-properties (match-beginning 0) (match-end 0)
4284 (list 'mouse-face 'highlight
4285 'rear-nonsticky t
4286 'keymap org-mouse-map
4288 t)))
4290 (defmacro org-maybe-intangible (props)
4291 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4292 In emacs 21, invisible text is not avoided by the command loop, so the
4293 intangible property is needed to make sure point skips this text.
4294 In Emacs 22, this is not necessary. The intangible text property has
4295 led to problems with flyspell. These problems are fixed in flyspell.el,
4296 but we still avoid setting the property in Emacs 22 and later.
4297 We use a macro so that the test can happen at compilation time."
4298 (if (< emacs-major-version 22)
4299 `(append '(intangible t) ,props)
4300 props))
4302 (defun org-activate-bracket-links (limit)
4303 "Run through the buffer and add overlays to bracketed links."
4304 (if (re-search-forward org-bracket-link-regexp limit t)
4305 (let* ((help (concat "LINK: "
4306 (org-match-string-no-properties 1)))
4307 ;; FIXME: above we should remove the escapes.
4308 ;; but that requires another match, protecting match data,
4309 ;; a lot of overhead for font-lock.
4310 (ip (org-maybe-intangible
4311 (list 'invisible 'org-link 'rear-nonsticky t
4312 'keymap org-mouse-map 'mouse-face 'highlight
4313 'help-echo help)))
4314 (vp (list 'rear-nonsticky t
4315 'keymap org-mouse-map 'mouse-face 'highlight
4316 'help-echo help)))
4317 ;; We need to remove the invisible property here. Table narrowing
4318 ;; may have made some of this invisible.
4319 (remove-text-properties (match-beginning 0) (match-end 0)
4320 '(invisible nil))
4321 (if (match-end 3)
4322 (progn
4323 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4324 (add-text-properties (match-beginning 3) (match-end 3) vp)
4325 (add-text-properties (match-end 3) (match-end 0) ip))
4326 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4327 (add-text-properties (match-beginning 1) (match-end 1) vp)
4328 (add-text-properties (match-end 1) (match-end 0) ip))
4329 t)))
4331 (defun org-activate-dates (limit)
4332 "Run through the buffer and add overlays to dates."
4333 (if (re-search-forward org-tsr-regexp-both limit t)
4334 (progn
4335 (add-text-properties (match-beginning 0) (match-end 0)
4336 (list 'mouse-face 'highlight
4337 'rear-nonsticky t
4338 'keymap org-mouse-map))
4339 (when org-display-custom-times
4340 (if (match-end 3)
4341 (org-display-custom-time (match-beginning 3) (match-end 3)))
4342 (org-display-custom-time (match-beginning 1) (match-end 1)))
4343 t)))
4345 (defvar org-target-link-regexp nil
4346 "Regular expression matching radio targets in plain text.")
4347 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4348 "Regular expression matching a link target.")
4349 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4350 "Regular expression matching a radio target.")
4351 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4352 "Regular expression matching any target.")
4354 (defun org-activate-target-links (limit)
4355 "Run through the buffer and add overlays to target matches."
4356 (when org-target-link-regexp
4357 (let ((case-fold-search t))
4358 (if (re-search-forward org-target-link-regexp limit t)
4359 (progn
4360 (add-text-properties (match-beginning 0) (match-end 0)
4361 (list 'mouse-face 'highlight
4362 'rear-nonsticky t
4363 'keymap org-mouse-map
4364 'help-echo "Radio target link"
4365 'org-linked-text t))
4366 t)))))
4368 (defun org-update-radio-target-regexp ()
4369 "Find all radio targets in this file and update the regular expression."
4370 (interactive)
4371 (when (memq 'radio org-activate-links)
4372 (setq org-target-link-regexp
4373 (org-make-target-link-regexp (org-all-targets 'radio)))
4374 (org-restart-font-lock)))
4376 (defun org-hide-wide-columns (limit)
4377 (let (s e)
4378 (setq s (text-property-any (point) (or limit (point-max))
4379 'org-cwidth t))
4380 (when s
4381 (setq e (next-single-property-change s 'org-cwidth))
4382 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4383 (goto-char e)
4384 t)))
4386 (defun org-restart-font-lock ()
4387 "Restart font-lock-mode, to force refontification."
4388 (when (and (boundp 'font-lock-mode) font-lock-mode)
4389 (font-lock-mode -1)
4390 (font-lock-mode 1)))
4392 (defun org-all-targets (&optional radio)
4393 "Return a list of all targets in this file.
4394 With optional argument RADIO, only find radio targets."
4395 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4396 rtn)
4397 (save-excursion
4398 (goto-char (point-min))
4399 (while (re-search-forward re nil t)
4400 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4401 rtn)))
4403 (defun org-make-target-link-regexp (targets)
4404 "Make regular expression matching all strings in TARGETS.
4405 The regular expression finds the targets also if there is a line break
4406 between words."
4407 (and targets
4408 (concat
4409 "\\<\\("
4410 (mapconcat
4411 (lambda (x)
4412 (while (string-match " +" x)
4413 (setq x (replace-match "\\s-+" t t x)))
4415 targets
4416 "\\|")
4417 "\\)\\>")))
4419 (defun org-activate-tags (limit)
4420 (if (re-search-forward (org-re "[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4421 (progn
4422 (add-text-properties (match-beginning 1) (match-end 1)
4423 (list 'mouse-face 'highlight
4424 'rear-nonsticky t
4425 'keymap org-mouse-map))
4426 t)))
4428 (defun org-outline-level ()
4429 (save-excursion
4430 (looking-at outline-regexp)
4431 (if (match-beginning 1)
4432 (+ (org-get-string-indentation (match-string 1)) 1000)
4433 (1- (- (match-end 0) (match-beginning 0))))))
4435 (defvar org-font-lock-keywords nil)
4437 (defconst org-property-re "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(\\S-.*\\)"
4438 "Regular expression matching a property line.")
4440 (defun org-set-font-lock-defaults ()
4441 (let* ((em org-fontify-emphasized-text)
4442 (lk org-activate-links)
4443 (org-font-lock-extra-keywords
4444 ;; Headlines
4445 (list
4446 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4447 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4448 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4449 (1 'org-table))
4450 ;; Links
4451 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4452 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4453 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4454 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4455 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4456 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4457 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4458 '(org-hide-wide-columns (0 nil append))
4459 ;; TODO lines
4460 (list (concat "^\\*+[ \t]+" org-not-done-regexp)
4461 '(1 'org-todo t))
4462 ;; Priorities
4463 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4464 ;; Special keywords
4465 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4466 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4467 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4468 (list (concat "\\<" org-archived-string) '(0 'org-special-keyword t))
4469 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4470 ;; Emphasis
4471 (if em
4472 (if (featurep 'xemacs)
4473 '(org-do-emphasis-faces (0 nil append))
4474 '(org-do-emphasis-faces)))
4475 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
4476 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4477 2 'bold prepend)
4478 (if org-provide-checkbox-statistics
4479 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4480 (0 (org-get-checkbox-statistics-face) t)))
4481 ;; COMMENT
4482 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4483 "\\|" org-quote-string "\\)\\>")
4484 '(1 'org-special-keyword t))
4485 '("^#.*" (0 'font-lock-comment-face t))
4486 ;; DONE
4487 (if org-fontify-done-headline
4488 (list (concat "^[*]+ +\\<\\("
4489 (mapconcat 'regexp-quote org-done-keywords "\\|")
4490 "\\)\\(.*\\)")
4491 '(1 'org-done t) '(2 'org-headline-done t))
4492 (list (concat "^[*]+ +\\<\\("
4493 (mapconcat 'regexp-quote org-done-keywords "\\|")
4494 "\\)\\>")
4495 '(1 'org-done t)))
4496 ;; Table stuff
4497 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
4498 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4499 ; '("^[ \t]*| *\\([#!$*_^/]\\) *|" (1 'org-formula t))
4500 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4501 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4502 ;; Drawers
4503 ; (list org-drawer-regexp '(0 'org-drawer t))
4504 ; (list "^[ \t]*:END:" '(0 'org-drawer t))
4505 (list org-drawer-regexp '(0 'org-special-keyword t))
4506 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4507 ;; Properties
4508 (list org-property-re
4509 '(1 'org-special-keyword t)
4510 '(3 'org-property-value t))
4511 (if org-format-transports-properties-p
4512 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4513 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
4515 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4516 ;; Now set the full font-lock-keywords
4517 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4518 (org-set-local 'font-lock-defaults
4519 '(org-font-lock-keywords t nil nil backward-paragraph))
4520 (kill-local-variable 'font-lock-keywords) nil))
4522 (defvar org-m nil)
4523 (defvar org-l nil)
4524 (defvar org-f nil)
4525 (defun org-get-level-face (n)
4526 "Get the right face for match N in font-lock matching of healdines."
4527 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4528 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4529 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4530 (cond
4531 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4532 ((eq n 2) org-f)
4533 (t (if org-level-color-stars-only nil org-f))))
4535 (defun org-unfontify-region (beg end &optional maybe_loudly)
4536 "Remove fontification and activation overlays from links."
4537 (font-lock-default-unfontify-region beg end)
4538 (let* ((buffer-undo-list t)
4539 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4540 (inhibit-modification-hooks t)
4541 deactivate-mark buffer-file-name buffer-file-truename)
4542 (remove-text-properties beg end
4543 '(mouse-face t keymap t org-linked-text t
4544 rear-nonsticky t
4545 invisible t intangible t))))
4547 ;;;; Visibility cycling, including org-goto and indirect buffer
4549 ;;; Cycling
4551 (defvar org-cycle-global-status nil)
4552 (make-variable-buffer-local 'org-cycle-global-status)
4553 (defvar org-cycle-subtree-status nil)
4554 (make-variable-buffer-local 'org-cycle-subtree-status)
4556 ;;;###autoload
4557 (defun org-cycle (&optional arg)
4558 "Visibility cycling for Org-mode.
4560 - When this function is called with a prefix argument, rotate the entire
4561 buffer through 3 states (global cycling)
4562 1. OVERVIEW: Show only top-level headlines.
4563 2. CONTENTS: Show all headlines of all levels, but no body text.
4564 3. SHOW ALL: Show everything.
4566 - When point is at the beginning of a headline, rotate the subtree started
4567 by this line through 3 different states (local cycling)
4568 1. FOLDED: Only the main headline is shown.
4569 2. CHILDREN: The main headline and the direct children are shown.
4570 From this state, you can move to one of the children
4571 and zoom in further.
4572 3. SUBTREE: Show the entire subtree, including body text.
4574 - When there is a numeric prefix, go up to a heading with level ARG, do
4575 a `show-subtree' and return to the previous cursor position. If ARG
4576 is negative, go up that many levels.
4578 - When point is not at the beginning of a headline, execute
4579 `indent-relative', like TAB normally does. See the option
4580 `org-cycle-emulate-tab' for details.
4582 - Special case: if point is at the beginning of the buffer and there is
4583 no headline in line 1, this function will act as if called with prefix arg."
4584 (interactive "P")
4585 (let* ((outline-regexp
4586 (if (and (org-mode-p) org-cycle-include-plain-lists)
4587 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4588 outline-regexp))
4589 (bob-special (and org-cycle-global-at-bob (bobp)
4590 (not (looking-at outline-regexp))))
4591 (org-cycle-hook
4592 (if bob-special
4593 (delq 'org-optimize-window-after-visibility-change
4594 (copy-sequence org-cycle-hook))
4595 org-cycle-hook))
4596 (pos (point)))
4598 (if (or bob-special (equal arg '(4)))
4599 ;; special case: use global cycling
4600 (setq arg t))
4602 (cond
4604 ((org-at-table-p 'any)
4605 ;; Enter the table or move to the next field in the table
4606 (or (org-table-recognize-table.el)
4607 (progn
4608 (if arg (org-table-edit-field t)
4609 (org-table-justify-field-maybe)
4610 (call-interactively 'org-table-next-field)))))
4612 ((eq arg t) ;; Global cycling
4614 (cond
4615 ((and (eq last-command this-command)
4616 (eq org-cycle-global-status 'overview))
4617 ;; We just created the overview - now do table of contents
4618 ;; This can be slow in very large buffers, so indicate action
4619 (message "CONTENTS...")
4620 (org-content)
4621 (message "CONTENTS...done")
4622 (setq org-cycle-global-status 'contents)
4623 (run-hook-with-args 'org-cycle-hook 'contents))
4625 ((and (eq last-command this-command)
4626 (eq org-cycle-global-status 'contents))
4627 ;; We just showed the table of contents - now show everything
4628 (show-all)
4629 (message "SHOW ALL")
4630 (setq org-cycle-global-status 'all)
4631 (run-hook-with-args 'org-cycle-hook 'all))
4634 ;; Default action: go to overview
4635 (org-overview)
4636 (message "OVERVIEW")
4637 (setq org-cycle-global-status 'overview)
4638 (run-hook-with-args 'org-cycle-hook 'overview))))
4640 ((and org-drawers
4641 (save-excursion
4642 (beginning-of-line 1)
4643 (looking-at org-drawer-regexp)))
4644 ;; Toggle block visibility
4645 (org-flag-drawer
4646 (not (get-char-property (match-end 0) 'invisible))))
4648 ((integerp arg)
4649 ;; Show-subtree, ARG levels up from here.
4650 (save-excursion
4651 (org-back-to-heading)
4652 (outline-up-heading (if (< arg 0) (- arg)
4653 (- (funcall outline-level) arg)))
4654 (org-show-subtree)))
4656 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4657 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4658 ;; At a heading: rotate between three different views
4659 (org-back-to-heading)
4660 (let ((goal-column 0) eoh eol eos)
4661 ;; First, some boundaries
4662 (save-excursion
4663 (org-back-to-heading)
4664 (save-excursion
4665 (beginning-of-line 2)
4666 (while (and (not (eobp)) ;; this is like `next-line'
4667 (get-char-property (1- (point)) 'invisible))
4668 (beginning-of-line 2)) (setq eol (point)))
4669 (outline-end-of-heading) (setq eoh (point))
4670 (org-end-of-subtree t)
4671 (unless (eobp)
4672 (skip-chars-forward " \t\n")
4673 (beginning-of-line 1) ; in case this is an item
4675 (setq eos (1- (point))))
4676 ;; Find out what to do next and set `this-command'
4677 (cond
4678 ((= eos eoh)
4679 ;; Nothing is hidden behind this heading
4680 (message "EMPTY ENTRY")
4681 (setq org-cycle-subtree-status nil)
4682 (save-excursion
4683 (goto-char eos)
4684 (outline-next-heading)
4685 (if (org-invisible-p) (org-flag-heading nil))))
4686 ((>= eol eos)
4687 ;; Entire subtree is hidden in one line: open it
4688 (org-show-entry)
4689 (show-children)
4690 (message "CHILDREN")
4691 (save-excursion
4692 (goto-char eos)
4693 (outline-next-heading)
4694 (if (org-invisible-p) (org-flag-heading nil)))
4695 (setq org-cycle-subtree-status 'children)
4696 (run-hook-with-args 'org-cycle-hook 'children))
4697 ((and (eq last-command this-command)
4698 (eq org-cycle-subtree-status 'children))
4699 ;; We just showed the children, now show everything.
4700 (org-show-subtree)
4701 (message "SUBTREE")
4702 (setq org-cycle-subtree-status 'subtree)
4703 (run-hook-with-args 'org-cycle-hook 'subtree))
4705 ;; Default action: hide the subtree.
4706 (hide-subtree)
4707 (message "FOLDED")
4708 (setq org-cycle-subtree-status 'folded)
4709 (run-hook-with-args 'org-cycle-hook 'folded)))))
4711 ;; TAB emulation
4712 (buffer-read-only (org-back-to-heading))
4714 ((org-try-cdlatex-tab))
4716 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4717 (or (not (bolp))
4718 (not (looking-at outline-regexp))))
4719 (call-interactively (global-key-binding "\t")))
4721 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4722 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4723 (or (and (eq org-cycle-emulate-tab 'white)
4724 (= (match-end 0) (point-at-eol)))
4725 (and (eq org-cycle-emulate-tab 'whitestart)
4726 (>= (match-end 0) pos))))
4728 (eq org-cycle-emulate-tab t))
4729 (if (and (looking-at "[ \n\r\t]")
4730 (string-match "^[ \t]*$" (buffer-substring
4731 (point-at-bol) (point))))
4732 (progn
4733 (beginning-of-line 1)
4734 (and (looking-at "[ \t]+") (replace-match ""))))
4735 (call-interactively (global-key-binding "\t")))
4737 (t (save-excursion
4738 (org-back-to-heading)
4739 (org-cycle))))))
4741 ;;;###autoload
4742 (defun org-global-cycle (&optional arg)
4743 "Cycle the global visibility. For details see `org-cycle'."
4744 (interactive "P")
4745 (let ((org-cycle-include-plain-lists
4746 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4747 (if (integerp arg)
4748 (progn
4749 (show-all)
4750 (hide-sublevels arg)
4751 (setq org-cycle-global-status 'contents))
4752 (org-cycle '(4)))))
4754 (defun org-overview ()
4755 "Switch to overview mode, shoing only top-level headlines.
4756 Really, this shows all headlines with level equal or greater than the level
4757 of the first headline in the buffer. This is important, because if the
4758 first headline is not level one, then (hide-sublevels 1) gives confusing
4759 results."
4760 (interactive)
4761 (let ((level (save-excursion
4762 (goto-char (point-min))
4763 (if (re-search-forward (concat "^" outline-regexp) nil t)
4764 (progn
4765 (goto-char (match-beginning 0))
4766 (funcall outline-level))))))
4767 (and level (hide-sublevels level))))
4769 (defun org-content (&optional arg)
4770 "Show all headlines in the buffer, like a table of contents.
4771 With numerical argument N, show content up to level N."
4772 (interactive "P")
4773 (save-excursion
4774 ;; Visit all headings and show their offspring
4775 (and (integerp arg) (org-overview))
4776 (goto-char (point-max))
4777 (catch 'exit
4778 (while (and (progn (condition-case nil
4779 (outline-previous-visible-heading 1)
4780 (error (goto-char (point-min))))
4782 (looking-at outline-regexp))
4783 (if (integerp arg)
4784 (show-children (1- arg))
4785 (show-branches))
4786 (if (bobp) (throw 'exit nil))))))
4789 (defun org-optimize-window-after-visibility-change (state)
4790 "Adjust the window after a change in outline visibility.
4791 This function is the default value of the hook `org-cycle-hook'."
4792 (when (get-buffer-window (current-buffer))
4793 (cond
4794 ; ((eq state 'overview) (org-first-headline-recenter 1))
4795 ; ((eq state 'overview) (org-beginning-of-line))
4796 ((eq state 'content) nil)
4797 ((eq state 'all) nil)
4798 ((eq state 'folded) nil)
4799 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4800 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4803 (defun org-cycle-show-empty-lines (state)
4804 "Show empty lines above all visible headlines.
4805 The region to be covered depends on STATE when called through
4806 `org-cycle-hook'. Lisp program can use t for STATE to get the
4807 entire buffer covered. Note that an empty line is only shown if there
4808 are at least `org-cycle-separator-lines' empty lines before the headeline."
4809 (when (> org-cycle-separator-lines 0)
4810 (save-excursion
4811 (let* ((n org-cycle-separator-lines)
4812 (re (cond
4813 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4814 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4815 (t (let ((ns (number-to-string (- n 2))))
4816 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4817 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4818 beg end)
4819 (cond
4820 ((memq state '(overview contents t))
4821 (setq beg (point-min) end (point-max)))
4822 ((memq state '(children folded))
4823 (setq beg (point) end (progn (org-end-of-subtree t t)
4824 (beginning-of-line 2)
4825 (point)))))
4826 (when beg
4827 (goto-char beg)
4828 (while (re-search-forward re end t)
4829 (if (not (get-char-property (match-end 1) 'invisible))
4830 (outline-flag-region
4831 (match-beginning 1) (match-end 1) nil)))))))
4832 ;; Never hide empty lines at the end of the file.
4833 (save-excursion
4834 (goto-char (point-max))
4835 (outline-previous-heading)
4836 (outline-end-of-heading)
4837 (if (and (looking-at "[ \t\n]+")
4838 (= (match-end 0) (point-max)))
4839 (outline-flag-region (point) (match-end 0) nil))))
4841 (defun org-subtree-end-visible-p ()
4842 "Is the end of the current subtree visible?"
4843 (pos-visible-in-window-p
4844 (save-excursion (org-end-of-subtree t) (point))))
4846 (defun org-first-headline-recenter (&optional N)
4847 "Move cursor to the first headline and recenter the headline.
4848 Optional argument N means, put the headline into the Nth line of the window."
4849 (goto-char (point-min))
4850 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4851 (beginning-of-line)
4852 (recenter (prefix-numeric-value N))))
4854 ;;; Org-goto
4856 (defvar org-goto-window-configuration nil)
4857 (defvar org-goto-marker nil)
4858 (defvar org-goto-map (make-sparse-keymap))
4859 (let ((cmds '(isearch-forward isearch-backward)) cmd)
4860 (while (setq cmd (pop cmds))
4861 (substitute-key-definition cmd cmd org-goto-map global-map)))
4862 (org-defkey org-goto-map "\C-m" 'org-goto-ret)
4863 (org-defkey org-goto-map [(left)] 'org-goto-left)
4864 (org-defkey org-goto-map [(right)] 'org-goto-right)
4865 (org-defkey org-goto-map [(?q)] 'org-goto-quit)
4866 (org-defkey org-goto-map [(control ?g)] 'org-goto-quit)
4867 (org-defkey org-goto-map "\C-i" 'org-cycle)
4868 (org-defkey org-goto-map [(tab)] 'org-cycle)
4869 (org-defkey org-goto-map [(down)] 'outline-next-visible-heading)
4870 (org-defkey org-goto-map [(up)] 'outline-previous-visible-heading)
4871 (org-defkey org-goto-map "n" 'outline-next-visible-heading)
4872 (org-defkey org-goto-map "p" 'outline-previous-visible-heading)
4873 (org-defkey org-goto-map "f" 'outline-forward-same-level)
4874 (org-defkey org-goto-map "b" 'outline-backward-same-level)
4875 (org-defkey org-goto-map "u" 'outline-up-heading)
4876 (org-defkey org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
4877 (org-defkey org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
4878 (org-defkey org-goto-map "\C-c\C-f" 'outline-forward-same-level)
4879 (org-defkey org-goto-map "\C-c\C-b" 'outline-backward-same-level)
4880 (org-defkey org-goto-map "\C-c\C-u" 'outline-up-heading)
4881 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4882 (while l (org-defkey org-goto-map (int-to-string (pop l)) 'digit-argument)))
4884 (defconst org-goto-help
4885 "Select a location to jump to, press RET
4886 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
4888 (defun org-goto ()
4889 "Go to a different location of the document, keeping current visibility.
4891 When you want to go to a different location in a document, the fastest way
4892 is often to fold the entire buffer and then dive into the tree. This
4893 method has the disadvantage, that the previous location will be folded,
4894 which may not be what you want.
4896 This command works around this by showing a copy of the current buffer in
4897 overview mode. You can dive into the tree in that copy, to find the
4898 location you want to reach. When pressing RET, the command returns to the
4899 original buffer in which the visibility is still unchanged. It then jumps
4900 to the new location, making it and the headline hierarchy above it visible."
4901 (interactive)
4902 (let* ((org-goto-start-pos (point))
4903 (selected-point
4904 (org-get-location (current-buffer) org-goto-help)))
4905 (if selected-point
4906 (progn
4907 (org-mark-ring-push org-goto-start-pos)
4908 (goto-char selected-point)
4909 (if (or (org-invisible-p) (org-invisible-p2))
4910 (org-show-context 'org-goto)))
4911 (error "Quit"))))
4913 (defvar org-selected-point nil) ; dynamically scoped parameter
4915 (defun org-get-location (buf help)
4916 "Let the user select a location in the Org-mode buffer BUF.
4917 This function uses a recursive edit. It returns the selected position
4918 or nil."
4919 (let (org-selected-point)
4920 (save-excursion
4921 (save-window-excursion
4922 (delete-other-windows)
4923 (switch-to-buffer (get-buffer-create "*org-goto*"))
4924 (with-output-to-temp-buffer "*Help*"
4925 (princ help))
4926 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4927 (setq buffer-read-only nil)
4928 (erase-buffer)
4929 (insert-buffer-substring buf)
4930 (let ((org-startup-truncated t)
4931 (org-startup-folded t)
4932 (org-startup-align-all-tables nil))
4933 (org-mode))
4934 (setq buffer-read-only t)
4935 (if (and (boundp 'org-goto-start-pos)
4936 (integer-or-marker-p org-goto-start-pos))
4937 (let ((org-show-hierarchy-above t)
4938 (org-show-siblings t)
4939 (org-show-following-heading t))
4940 (goto-char org-goto-start-pos)
4941 (and (org-invisible-p) (org-show-context)))
4942 (goto-char (point-min)))
4943 (org-beginning-of-line)
4944 (message "Select location and press RET")
4945 ;; now we make sure that during selection, ony very few keys work
4946 ;; and that it is impossible to switch to another window.
4947 (let ((gm (current-global-map))
4948 (overriding-local-map org-goto-map))
4949 (unwind-protect
4950 (progn
4951 (use-global-map org-goto-map)
4952 (recursive-edit))
4953 (use-global-map gm)))))
4954 (kill-buffer "*org-goto*")
4955 org-selected-point))
4957 (defun org-goto-ret (&optional arg)
4958 "Finish `org-goto' by going to the new location."
4959 (interactive "P")
4960 (setq org-selected-point (point)
4961 current-prefix-arg arg)
4962 (throw 'exit nil))
4964 (defun org-goto-left ()
4965 "Finish `org-goto' by going to the new location."
4966 (interactive)
4967 (if (org-on-heading-p)
4968 (progn
4969 (beginning-of-line 1)
4970 (setq org-selected-point (point)
4971 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4972 (throw 'exit nil))
4973 (error "Not on a heading")))
4975 (defun org-goto-right ()
4976 "Finish `org-goto' by going to the new location."
4977 (interactive)
4978 (if (org-on-heading-p)
4979 (progn
4980 (outline-end-of-subtree)
4981 (or (eobp) (forward-char 1))
4982 (setq org-selected-point (point)
4983 current-prefix-arg (- (match-end 0) (match-beginning 0)))
4984 (throw 'exit nil))
4985 (error "Not on a heading")))
4987 (defun org-goto-quit ()
4988 "Finish `org-goto' without cursor motion."
4989 (interactive)
4990 (setq org-selected-point nil)
4991 (throw 'exit nil))
4993 ;;; Indirect buffer display of subtrees
4995 (defvar org-indirect-dedicated-frame nil
4996 "This is the frame being used for indirect tree display.")
4997 (defvar org-last-indirect-buffer nil)
4999 (defun org-tree-to-indirect-buffer (&optional arg)
5000 "Create indirect buffer and narrow it to current subtree.
5001 With numerical prefix ARG, go up to this level and then take that tree.
5002 If ARG is negative, go up that many levels.
5003 Normally this command removes the indirect buffer previously made
5004 with this command. However, when called with a C-u prefix, the last buffer
5005 is kept so that you can work with several indirect buffers at the same time.
5006 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5007 requests that a new frame be made for the new buffer, so that the dedicated
5008 frame is not changed."
5009 (interactive "P")
5010 (let ((cbuf (current-buffer))
5011 (cwin (selected-window))
5012 (pos (point))
5013 beg end level heading ibuf)
5014 (save-excursion
5015 (org-back-to-heading t)
5016 (when (numberp arg)
5017 (setq level (org-outline-level))
5018 (if (< arg 0) (setq arg (+ level arg)))
5019 (while (> (setq level (org-outline-level)) arg)
5020 (outline-up-heading 1 t)))
5021 (setq beg (point)
5022 heading (org-get-heading))
5023 (org-end-of-subtree t) (setq end (point)))
5024 (if (and (not arg)
5025 (buffer-live-p org-last-indirect-buffer))
5026 (kill-buffer org-last-indirect-buffer))
5027 (setq ibuf (org-get-indirect-buffer cbuf)
5028 org-last-indirect-buffer ibuf)
5029 (cond
5030 ((or (eq org-indirect-buffer-display 'new-frame)
5031 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5032 (select-frame (make-frame))
5033 (delete-other-windows)
5034 (switch-to-buffer ibuf)
5035 (org-set-frame-title heading))
5036 ((eq org-indirect-buffer-display 'dedicated-frame)
5037 (raise-frame
5038 (select-frame (or (and org-indirect-dedicated-frame
5039 (frame-live-p org-indirect-dedicated-frame)
5040 org-indirect-dedicated-frame)
5041 (setq org-indirect-dedicated-frame (make-frame)))))
5042 (delete-other-windows)
5043 (switch-to-buffer ibuf)
5044 (org-set-frame-title (concat "Indirect: " heading)))
5045 ((eq org-indirect-buffer-display 'current-window)
5046 (switch-to-buffer ibuf))
5047 ((eq org-indirect-buffer-display 'other-window)
5048 (pop-to-buffer ibuf))
5049 (t (error "Invalid value.")))
5050 (if (featurep 'xemacs)
5051 (save-excursion (org-mode) (turn-on-font-lock)))
5052 (narrow-to-region beg end)
5053 (show-all)
5054 (goto-char pos)
5055 (and (window-live-p cwin) (select-window cwin))))
5057 (defun org-get-indirect-buffer (&optional buffer)
5058 (setq buffer (or buffer (current-buffer)))
5059 (let ((n 1) (base (buffer-name buffer)) bname)
5060 (while (buffer-live-p
5061 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5062 (setq n (1+ n)))
5063 (condition-case nil
5064 (make-indirect-buffer buffer bname 'clone)
5065 (error (make-indirect-buffer buffer bname)))))
5067 (defun org-set-frame-title (title)
5068 "Set the title of the current frame to the string TITLE."
5069 ;; FIXME: how to name a single frame in XEmacs???
5070 (unless (featurep 'xemacs)
5071 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5073 ;;;; Structure editing
5075 ;;; Inserting headlines
5077 (defun org-insert-heading (&optional force-heading)
5078 "Insert a new heading or item with same depth at point.
5079 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5080 If point is at the beginning of a headline, insert a sibling before the
5081 current headline. If point is in the middle of a headline, split the headline
5082 at that position and make the rest of the headline part of the sibling below
5083 the current headline."
5084 (interactive "P")
5085 (if (= (buffer-size) 0)
5086 (insert "\n* ")
5087 (when (or force-heading (not (org-insert-item)))
5088 (let* ((head (save-excursion
5089 (condition-case nil
5090 (progn
5091 (org-back-to-heading)
5092 (match-string 0))
5093 (error "*"))))
5094 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5095 pos)
5096 (cond
5097 ((and (org-on-heading-p) (bolp)
5098 (or (bobp)
5099 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5100 (open-line (if blank 2 1)))
5101 ((and (bolp)
5102 (or (bobp)
5103 (save-excursion
5104 (backward-char 1) (not (org-invisible-p)))))
5105 nil)
5106 (t (newline (if blank 2 1))))
5107 (insert head) (just-one-space)
5108 (setq pos (point))
5109 (end-of-line 1)
5110 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5111 (run-hooks 'org-insert-heading-hook)))))
5114 (defun org-insert-todo-heading (arg)
5115 "Insert a new heading with the same level and TODO state as current heading.
5116 If the heading has no TODO state, or if the state is DONE, use the first
5117 state (TODO by default). Also with prefix arg, force first state."
5118 (interactive "P")
5119 (when (not (org-insert-item 'checkbox))
5120 (org-insert-heading)
5121 (save-excursion
5122 (org-back-to-heading)
5123 (outline-previous-heading)
5124 (looking-at org-todo-line-regexp))
5125 (if (or arg
5126 (not (match-beginning 2))
5127 (member (match-string 2) org-done-keywords))
5128 (insert (car org-todo-keywords-1) " ")
5129 (insert (match-string 2) " "))))
5131 ;;; Promotion and Demotion
5133 (defun org-promote-subtree ()
5134 "Promote the entire subtree.
5135 See also `org-promote'."
5136 (interactive)
5137 (save-excursion
5138 (org-map-tree 'org-promote))
5139 (org-fix-position-after-promote))
5141 (defun org-demote-subtree ()
5142 "Demote the entire subtree. See `org-demote'.
5143 See also `org-promote'."
5144 (interactive)
5145 (save-excursion
5146 (org-map-tree 'org-demote))
5147 (org-fix-position-after-promote))
5150 (defun org-do-promote ()
5151 "Promote the current heading higher up the tree.
5152 If the region is active in `transient-mark-mode', promote all headings
5153 in the region."
5154 (interactive)
5155 (save-excursion
5156 (if (org-region-active-p)
5157 (org-map-region 'org-promote (region-beginning) (region-end))
5158 (org-promote)))
5159 (org-fix-position-after-promote))
5161 (defun org-do-demote ()
5162 "Demote the current heading lower down the tree.
5163 If the region is active in `transient-mark-mode', demote all headings
5164 in the region."
5165 (interactive)
5166 (save-excursion
5167 (if (org-region-active-p)
5168 (org-map-region 'org-demote (region-beginning) (region-end))
5169 (org-demote)))
5170 (org-fix-position-after-promote))
5172 (defun org-fix-position-after-promote ()
5173 "Make sure that after pro/demotion cursor position is right."
5174 (let ((pos (point)))
5175 (when (save-excursion
5176 (beginning-of-line 1)
5177 (looking-at org-todo-line-regexp)
5178 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5179 (cond ((eobp) (insert " "))
5180 ((eolp) (insert " "))
5181 ((equal (char-after) ?\ ) (forward-char 1))))))
5183 (defun org-reduced-level (l)
5184 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5186 (defun org-get-legal-level (level &optional change)
5187 "Rectify a level change under the influence of `org-odd-levels-only'
5188 LEVEL is a current level, CHANGE is by how much the level should be
5189 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5190 even level numbers will become the next higher odd number."
5191 (if org-odd-levels-only
5192 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5193 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5194 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5195 (max 1 (+ level change))))
5197 (defun org-promote ()
5198 "Promote the current heading higher up the tree.
5199 If the region is active in `transient-mark-mode', promote all headings
5200 in the region."
5201 (org-back-to-heading t)
5202 (let* ((level (save-match-data (funcall outline-level)))
5203 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5204 (diff (abs (- level (length up-head) -1))))
5205 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5206 (replace-match up-head nil t)
5207 ;; Fixup tag positioning
5208 (and org-auto-align-tags (org-set-tags nil t))
5209 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5211 (defun org-demote ()
5212 "Demote the current heading lower down the tree.
5213 If the region is active in `transient-mark-mode', demote all headings
5214 in the region."
5215 (org-back-to-heading t)
5216 (let* ((level (save-match-data (funcall outline-level)))
5217 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5218 (diff (abs (- level (length down-head) -1))))
5219 (replace-match down-head nil t)
5220 ;; Fixup tag positioning
5221 (and org-auto-align-tags (org-set-tags nil t))
5222 (if org-adapt-indentation (org-fixup-indentation diff))))
5224 (defun org-map-tree (fun)
5225 "Call FUN for every heading underneath the current one."
5226 (org-back-to-heading)
5227 (let ((level (funcall outline-level)))
5228 (save-excursion
5229 (funcall fun)
5230 (while (and (progn
5231 (outline-next-heading)
5232 (> (funcall outline-level) level))
5233 (not (eobp)))
5234 (funcall fun)))))
5236 (defun org-map-region (fun beg end)
5237 "Call FUN for every heading between BEG and END."
5238 (let ((org-ignore-region t))
5239 (save-excursion
5240 (setq end (copy-marker end))
5241 (goto-char beg)
5242 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5243 (< (point) end))
5244 (funcall fun))
5245 (while (and (progn
5246 (outline-next-heading)
5247 (< (point) end))
5248 (not (eobp)))
5249 (funcall fun)))))
5251 (defun org-fixup-indentation (diff)
5252 "Change the indentation in the current entry by DIFF
5253 However, if any line in the current entry has no indentation, or if it
5254 would end up with no indentation after the change, nothing at all is done."
5255 (save-excursion
5256 (let ((end (save-excursion (outline-next-heading)
5257 (point-marker)))
5258 (prohibit (if (> diff 0)
5259 "^\\S-"
5260 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5261 col)
5262 (unless (save-excursion (re-search-forward prohibit end t))
5263 (while (re-search-forward "^[ \t]+" end t)
5264 (goto-char (match-end 0))
5265 (setq col (current-column))
5266 (if (< diff 0) (replace-match ""))
5267 (indent-to (+ diff col))))
5268 (move-marker end nil))))
5270 (defun org-convert-to-odd-levels ()
5271 "Convert an org-mode file with all levels allowed to one with odd levels.
5272 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5273 level 5 etc."
5274 (interactive)
5275 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5276 (let ((org-odd-levels-only nil) n)
5277 (save-excursion
5278 (goto-char (point-min))
5279 (while (re-search-forward "^\\*\\*+ " nil t)
5280 (setq n (- (length (match-string 0)) 2))
5281 (while (>= (setq n (1- n)) 0)
5282 (org-demote))
5283 (end-of-line 1))))))
5286 (defun org-convert-to-oddeven-levels ()
5287 "Convert an org-mode file with only odd levels to one with odd and even levels.
5288 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5289 section with an even level, conversion would destroy the structure of the file. An error
5290 is signaled in this case."
5291 (interactive)
5292 (goto-char (point-min))
5293 ;; First check if there are no even levels
5294 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5295 (org-show-context t)
5296 (error "Not all levels are odd in this file. Conversion not possible."))
5297 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5298 (let ((org-odd-levels-only nil) n)
5299 (save-excursion
5300 (goto-char (point-min))
5301 (while (re-search-forward "^\\*\\*+ " nil t)
5302 (setq n (/ (length (1- (match-string 0))) 2))
5303 (while (>= (setq n (1- n)) 0)
5304 (org-promote))
5305 (end-of-line 1))))))
5307 (defun org-tr-level (n)
5308 "Make N odd if required."
5309 (if org-odd-levels-only (1+ (/ n 2)) n))
5311 ;;; Vertical tree motion, cutting and pasting of subtrees
5313 (defun org-move-subtree-up (&optional arg)
5314 "Move the current subtree up past ARG headlines of the same level."
5315 (interactive "p")
5316 (org-move-subtree-down (- (prefix-numeric-value arg))))
5318 (defun org-move-subtree-down (&optional arg)
5319 "Move the current subtree down past ARG headlines of the same level."
5320 (interactive "p")
5321 (setq arg (prefix-numeric-value arg))
5322 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5323 'outline-get-last-sibling))
5324 (ins-point (make-marker))
5325 (cnt (abs arg))
5326 beg end txt folded)
5327 ;; Select the tree
5328 (org-back-to-heading)
5329 (setq beg (point))
5330 (save-match-data
5331 (save-excursion (outline-end-of-heading)
5332 (setq folded (org-invisible-p)))
5333 (outline-end-of-subtree))
5334 (outline-next-heading)
5335 (setq end (point))
5336 ;; Find insertion point, with error handling
5337 (goto-char beg)
5338 (while (> cnt 0)
5339 (or (and (funcall movfunc) (looking-at outline-regexp))
5340 (progn (goto-char beg)
5341 (error "Cannot move past superior level or buffer limit")))
5342 (setq cnt (1- cnt)))
5343 (if (> arg 0)
5344 ;; Moving forward - still need to move over subtree
5345 (progn (outline-end-of-subtree)
5346 (outline-next-heading)
5347 (if (not (or (looking-at (concat "^" outline-regexp))
5348 (bolp)))
5349 (newline))))
5350 (move-marker ins-point (point))
5351 (setq txt (buffer-substring beg end))
5352 (delete-region beg end)
5353 (insert txt)
5354 (or (bolp) (insert "\n"))
5355 (goto-char ins-point)
5356 (if folded (hide-subtree))
5357 (move-marker ins-point nil)))
5359 (defvar org-subtree-clip ""
5360 "Clipboard for cut and paste of subtrees.
5361 This is actually only a copy of the kill, because we use the normal kill
5362 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5364 (defvar org-subtree-clip-folded nil
5365 "Was the last copied subtree folded?
5366 This is used to fold the tree back after pasting.")
5368 (defun org-cut-subtree ()
5369 "Cut the current subtree into the clipboard.
5370 This is a short-hand for marking the subtree and then cutting it."
5371 (interactive)
5372 (org-copy-subtree 'cut))
5374 (defun org-copy-subtree (&optional cut)
5375 "Cut the current subtree into the clipboard.
5376 This is a short-hand for marking the subtree and then copying it.
5377 If CUT is non-nil, actually cut the subtree."
5378 (interactive)
5379 (let (beg end folded)
5380 (if (interactive-p)
5381 (org-back-to-heading nil) ; take what looks like a subtree
5382 (org-back-to-heading t)) ; take what is really there
5383 (setq beg (point))
5384 (save-match-data
5385 (save-excursion (outline-end-of-heading)
5386 (setq folded (org-invisible-p)))
5387 (outline-end-of-subtree))
5388 (if (equal (char-after) ?\n) (forward-char 1))
5389 (setq end (point))
5390 (goto-char beg)
5391 (when (> end beg)
5392 (setq org-subtree-clip-folded folded)
5393 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5394 (setq org-subtree-clip (current-kill 0))
5395 (message "%s: Subtree with %d characters"
5396 (if cut "Cut" "Copied")
5397 (length org-subtree-clip)))))
5399 (defun org-paste-subtree (&optional level tree)
5400 "Paste the clipboard as a subtree, with modification of headline level.
5401 The entire subtree is promoted or demoted in order to match a new headline
5402 level. By default, the new level is derived from the visible headings
5403 before and after the insertion point, and taken to be the inferior headline
5404 level of the two. So if the previous visible heading is level 3 and the
5405 next is level 4 (or vice versa), level 4 will be used for insertion.
5406 This makes sure that the subtree remains an independent subtree and does
5407 not swallow low level entries.
5409 You can also force a different level, either by using a numeric prefix
5410 argument, or by inserting the heading marker by hand. For example, if the
5411 cursor is after \"*****\", then the tree will be shifted to level 5.
5413 If you want to insert the tree as is, just use \\[yank].
5415 If optional TREE is given, use this text instead of the kill ring."
5416 (interactive "P")
5417 (unless (org-kill-is-subtree-p tree)
5418 (error
5419 (substitute-command-keys
5420 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5421 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5422 (^re (concat "^\\(" outline-regexp "\\)"))
5423 (re (concat "\\(" outline-regexp "\\)"))
5424 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
5426 (old-level (if (string-match ^re txt)
5427 (- (match-end 0) (match-beginning 0) 1)
5428 -1))
5429 (force-level (cond (level (prefix-numeric-value level))
5430 ((string-match
5431 ^re_ (buffer-substring (point-at-bol) (point)))
5432 (- (match-end 0) (match-beginning 0)))
5433 (t nil)))
5434 (previous-level (save-excursion
5435 (condition-case nil
5436 (progn
5437 (outline-previous-visible-heading 1)
5438 (if (looking-at re)
5439 (- (match-end 0) (match-beginning 0))
5441 (error 1))))
5442 (next-level (save-excursion
5443 (condition-case nil
5444 (progn
5445 (outline-next-visible-heading 1)
5446 (if (looking-at re)
5447 (- (match-end 0) (match-beginning 0))
5449 (error 1))))
5450 (new-level (or force-level (max previous-level next-level)))
5451 (shift (if (or (= old-level -1)
5452 (= new-level -1)
5453 (= old-level new-level))
5455 (- new-level old-level)))
5456 (shift1 shift)
5457 (delta (if (> shift 0) -1 1))
5458 (func (if (> shift 0) 'org-demote 'org-promote))
5459 (org-odd-levels-only nil)
5460 beg end)
5461 ;; Remove the forces level indicator
5462 (if force-level
5463 (delete-region (point-at-bol) (point)))
5464 ;; Make sure we start at the beginning of an empty line
5465 (if (not (bolp)) (insert "\n"))
5466 (if (not (looking-at "[ \t]*$"))
5467 (progn (insert "\n") (backward-char 1)))
5468 ;; Paste
5469 (setq beg (point))
5470 (if (string-match "[ \t\r\n]+\\'" txt)
5471 (setq txt (replace-match "\n" t t txt)))
5472 (insert txt)
5473 (setq end (point))
5474 (if (looking-at "[ \t\r\n]+")
5475 (replace-match "\n"))
5476 (goto-char beg)
5477 ;; Shift if necessary
5478 (if (= shift 0)
5479 (message "Pasted at level %d, without shift" new-level)
5480 (save-restriction
5481 (narrow-to-region beg end)
5482 (while (not (= shift 0))
5483 (org-map-region func (point-min) (point-max))
5484 (setq shift (+ delta shift)))
5485 (goto-char (point-min))
5486 (message "Pasted at level %d, with shift by %d levels"
5487 new-level shift1)))
5488 (if (and kill-ring
5489 (eq org-subtree-clip (current-kill 0))
5490 org-subtree-clip-folded)
5491 ;; The tree was folded before it was killed/copied
5492 (hide-subtree))))
5494 (defun org-kill-is-subtree-p (&optional txt)
5495 "Check if the current kill is an outline subtree, or a set of trees.
5496 Returns nil if kill does not start with a headline, or if the first
5497 headline level is not the largest headline level in the tree.
5498 So this will actually accept several entries of equal levels as well,
5499 which is OK for `org-paste-subtree'.
5500 If optional TXT is given, check this string instead of the current kill."
5501 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5502 (start-level (and kill
5503 (string-match (concat "\\`" outline-regexp) kill)
5504 (- (match-end 0) (match-beginning 0))))
5505 (re (concat "^" outline-regexp))
5506 (start 1))
5507 (if (not start-level)
5508 nil ;; does not even start with a heading
5509 (catch 'exit
5510 (while (setq start (string-match re kill (1+ start)))
5511 (if (< (- (match-end 0) (match-beginning 0)) start-level)
5512 (throw 'exit nil)))
5513 t))))
5515 (defun org-narrow-to-subtree ()
5516 "Narrow buffer to the current subtree."
5517 (interactive)
5518 (save-excursion
5519 (narrow-to-region
5520 (progn (org-back-to-heading) (point))
5521 (progn (org-end-of-subtree t t) (point)))))
5524 ;;; Outline Sorting
5526 (defun org-sort (with-case)
5527 "Call `org-sort-entries' or `org-table-sort-lines', depending on context."
5528 (interactive "P")
5529 (if (org-at-table-p)
5530 (org-call-with-arg 'org-table-sort-lines with-case)
5531 (org-call-with-arg 'org-sort-entries with-case)))
5533 (defun org-sort-entries (&optional with-case sorting-type)
5534 "Sort entries on a certain level of an outline tree.
5535 If there is an active region, the entries in the region are sorted.
5536 Else, if the cursor is before the first entry, sort the top-level items.
5537 Else, the children of the entry at point are sorted.
5539 Sorting can be alphabetically, numerically, and by date/time as given by
5540 the first time stamp in the entry. The command prompts for the sorting
5541 type unless it has been given to the function through the SORTING-TYPE
5542 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T).
5544 Comparing entries ignores case by default. However, with an optional argument
5545 WITH-CASE, the sorting considers case as well. With two prefix arguments
5546 `C-u C-u', sorting is case-sensitive and duplicate entries will be removed."
5547 (interactive "P")
5548 (let ((unique (equal with-case '(16)))
5549 start beg end entries stars re re2 p nentries (nremoved 0)
5550 last txt what)
5551 ;; Find beginning and end of region to sort
5552 (cond
5553 ((org-region-active-p)
5554 ;; we will sort the region
5555 (setq end (region-end)
5556 what "region")
5557 (goto-char (region-beginning))
5558 (if (not (org-on-heading-p)) (outline-next-heading))
5559 (setq start (point)))
5560 ((or (org-on-heading-p)
5561 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5562 ;; we will sort the children of the current headline
5563 (org-back-to-heading)
5564 (setq start (point) end (org-end-of-subtree) what "children")
5565 (goto-char start)
5566 (show-subtree)
5567 (outline-next-heading))
5569 ;; we will sort the top-level entries in this file
5570 (goto-char (point-min))
5571 (or (org-on-heading-p) (outline-next-heading))
5572 (setq start (point) end (point-max) what "top-level")
5573 (goto-char start)
5574 (show-all)))
5575 (setq beg (point))
5576 (if (>= (point) end) (error "Nothing to sort"))
5577 (looking-at "\\(\\*+\\)")
5578 (setq stars (match-string 1)
5579 re (concat "^" (regexp-quote stars) " +")
5580 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5581 txt (buffer-substring beg end))
5582 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5583 (if (and (not (equal stars "*")) (string-match re2 txt))
5584 (error "Region to sort contains a level above the first entry"))
5585 ;; Make a list that can be sorted.
5586 ;; The car is the string for comparison, the cdr is the subtree
5587 (message "Sorting entries...")
5588 (setq entries
5589 (mapcar
5590 (lambda (x)
5591 (string-match "^.*\\(\n.*\\)?" x) ; take two lines
5592 (cons (match-string 0 x) x))
5593 (org-split-string txt re)))
5595 ;; Sort the list
5596 (save-excursion
5597 (goto-char start)
5598 (setq entries (org-do-sort entries what with-case sorting-type)))
5600 ;; Delete the old stuff
5601 (goto-char beg)
5602 (kill-region beg end)
5603 (setq nentries (length entries))
5604 ;; Insert the sorted entries, and remove duplicates if this is required
5605 (while (setq p (pop entries))
5606 (if (and unique (equal last (setq last (org-trim (cdr p)))))
5607 (setq nremoved (1+ nremoved)) ; same entry as before, skip it
5608 (insert stars " " (cdr p))))
5609 (goto-char start)
5610 (message "Sorting entries...done (%d entries%s)"
5611 nentries
5612 (if unique (format ", %d duplicates removed" nremoved) ""))))
5614 (defun org-do-sort (table what &optional with-case sorting-type)
5615 "Sort TABLE of WHAT according to SORTING-TYPE.
5616 The user will be prompted for the SORTING-TYPE if the call to this
5617 function does not specify it. WHAT is only for the prompt, to indicate
5618 what is being sorted. The sorting key will be extracted from
5619 the car of the elements of the table.
5620 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5621 (unless sorting-type
5622 (message
5623 "Sort %s: [a]lphabetically [n]umerically [t]ime. A/N/T means reversed:"
5624 what)
5625 (setq sorting-type (read-char-exclusive)))
5626 (let ((dcst (downcase sorting-type))
5627 extractfun comparefun)
5628 ;; Define the appropriate functions
5629 (cond
5630 ((= dcst ?n)
5631 (setq extractfun 'string-to-number
5632 comparefun (if (= dcst sorting-type) '< '>)))
5633 ((= dcst ?a)
5634 (setq extractfun (if with-case 'identity 'downcase)
5635 comparefun (if (= dcst sorting-type)
5636 'string<
5637 (lambda (a b) (and (not (string< a b))
5638 (not (string= a b)))))))
5639 ((= dcst ?t)
5640 (setq extractfun
5641 (lambda (x)
5642 (if (string-match org-ts-regexp x)
5643 (time-to-seconds
5644 (org-time-string-to-time (match-string 0 x)))
5646 comparefun (if (= dcst sorting-type) '< '>)))
5647 (t (error "Invalid sorting type `%c'" sorting-type)))
5649 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5650 table)
5651 (lambda (a b) (funcall comparefun (car a) (car b))))))
5653 ;;;; Plain list items, including checkboxes
5655 ;;; Plain list items
5657 (defun org-at-item-p ()
5658 "Is point in a line starting a hand-formatted item?"
5659 (let ((llt org-plain-list-ordered-item-terminator))
5660 (save-excursion
5661 (goto-char (point-at-bol))
5662 (looking-at
5663 (cond
5664 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5665 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5666 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5667 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5669 (defun org-in-item-p ()
5670 "It the cursor inside a plain list item.
5671 Does not have to be the first line."
5672 (save-excursion
5673 (condition-case nil
5674 (progn
5675 (org-beginning-of-item)
5676 (org-at-item-p)
5678 (error nil))))
5680 (defun org-insert-item (&optional checkbox)
5681 "Insert a new item at the current level.
5682 Return t when things worked, nil when we are not in an item."
5683 (when (save-excursion
5684 (condition-case nil
5685 (progn
5686 (org-beginning-of-item)
5687 (org-at-item-p)
5688 (if (org-invisible-p) (error "Invisible item"))
5690 (error nil)))
5691 (let* ((bul (match-string 0))
5692 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5693 (match-end 0)))
5694 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5695 pos)
5696 (cond
5697 ((and (org-at-item-p) (<= (point) eow))
5698 ;; before the bullet
5699 (beginning-of-line 1)
5700 (open-line (if blank 2 1)))
5701 ((<= (point) eow)
5702 (beginning-of-line 1))
5703 (t (newline (if blank 2 1))))
5704 (insert bul (if checkbox "[ ]" ""))
5705 (just-one-space)
5706 (setq pos (point))
5707 (end-of-line 1)
5708 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5709 (org-maybe-renumber-ordered-list)
5710 (and checkbox (org-update-checkbox-count-maybe))
5713 ;;; Checkboxes
5715 (defun org-at-item-checkbox-p ()
5716 "Is point at a line starting a plain-list item with a checklet?"
5717 (and (org-at-item-p)
5718 (save-excursion
5719 (goto-char (match-end 0))
5720 (skip-chars-forward " \t")
5721 (looking-at "\\[[- X]\\]"))))
5723 (defun org-toggle-checkbox (&optional arg)
5724 "Toggle the checkbox in the current line."
5725 (interactive "P")
5726 (catch 'exit
5727 (let (beg end status (firstnew 'unknown))
5728 (cond
5729 ((org-region-active-p)
5730 (setq beg (region-beginning) end (region-end)))
5731 ((org-on-heading-p)
5732 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5733 ((org-at-item-checkbox-p)
5734 (save-excursion
5735 (replace-match
5736 (cond (arg "[-]")
5737 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5738 (t "[ ]"))
5739 t t))
5740 (throw 'exit t))
5741 (t (error "Not at a checkbox or heading, and no active region")))
5742 (save-excursion
5743 (goto-char beg)
5744 (while (< (point) end)
5745 (when (org-at-item-checkbox-p)
5746 (setq status (equal (match-string 0) "[X]"))
5747 (when (eq firstnew 'unknown)
5748 (setq firstnew (not status)))
5749 (replace-match
5750 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5751 (beginning-of-line 2)))))
5752 (org-update-checkbox-count-maybe))
5754 (defun org-update-checkbox-count-maybe ()
5755 "Update checkbox statistics unless turned off by user."
5756 (when org-provide-checkbox-statistics
5757 (org-update-checkbox-count)))
5759 (defun org-update-checkbox-count (&optional all)
5760 "Update the checkbox statistics in the current section.
5761 This will find all statistic cookies like [57%] and [6/12] and update them
5762 with the current numbers. With optional prefix argument ALL, do this for
5763 the whole buffer."
5764 (interactive "P")
5765 (save-excursion
5766 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5767 (beg (condition-case nil
5768 (progn (outline-back-to-heading) (point))
5769 (error (point-min))))
5770 (end (move-marker (make-marker)
5771 (progn (outline-next-heading) (point))))
5772 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
5773 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5774 b1 e1 f1 c-on c-off lim (cstat 0))
5775 (when all
5776 (goto-char (point-min))
5777 (outline-next-heading)
5778 (setq beg (point) end (point-max)))
5779 (goto-char beg)
5780 (while (re-search-forward re end t)
5781 (setq cstat (1+ cstat)
5782 b1 (match-beginning 0)
5783 e1 (match-end 0)
5784 f1 (match-beginning 1)
5785 lim (cond
5786 ((org-on-heading-p) (outline-next-heading) (point))
5787 ((org-at-item-p) (org-end-of-item) (point))
5788 (t nil))
5789 c-on 0 c-off 0)
5790 (goto-char e1)
5791 (when lim
5792 (while (re-search-forward re-box lim t)
5793 (if (member (match-string 2) '("[ ]" "[-]"))
5794 (setq c-off (1+ c-off))
5795 (setq c-on (1+ c-on))))
5796 (delete-region b1 e1)
5797 (goto-char b1)
5798 (insert (if f1
5799 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5800 (format "[%d/%d]" c-on (+ c-on c-off))))))
5801 (when (interactive-p)
5802 (message "Checkbox satistics updated %s (%d places)"
5803 (if all "in entire file" "in current outline entry") cstat)))))
5805 (defun org-get-checkbox-statistics-face ()
5806 "Select the face for checkbox statistics.
5807 The face will be `org-done' when all relevant boxes are checked. Otherwise
5808 it will be `org-todo'."
5809 (if (match-end 1)
5810 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5811 (if (and (> (match-end 2) (match-beginning 2))
5812 (equal (match-string 2) (match-string 3)))
5813 'org-done
5814 'org-todo)))
5816 (defun org-get-indentation (&optional line)
5817 "Get the indentation of the current line, interpreting tabs.
5818 When LINE is given, assume it represents a line and compute its indentation."
5819 (if line
5820 (if (string-match "^ *" (org-remove-tabs line))
5821 (match-end 0))
5822 (save-excursion
5823 (beginning-of-line 1)
5824 (skip-chars-forward " \t")
5825 (current-column))))
5827 (defun org-remove-tabs (s &optional width)
5828 "Replace tabulators in S with spaces.
5829 Assumes that s is a single line, starting in column 0."
5830 (setq width (or width tab-width))
5831 (while (string-match "\t" s)
5832 (setq s (replace-match
5833 (make-string
5834 (- (* width (/ (+ (match-beginning 0) width) width))
5835 (match-beginning 0)) ?\ )
5836 t t s)))
5839 (defun org-fix-indentation (line ind)
5840 "Fix indentation in LINE.
5841 IND is a cons cell with target and minimum indentation.
5842 If the current indenation in LINE is smaller than the minimum,
5843 leave it alone. If it is larger than ind, set it to the target."
5844 (let* ((l (org-remove-tabs line))
5845 (i (org-get-indentation l))
5846 (i1 (car ind)) (i2 (cdr ind)))
5847 (if (>= i i2) (setq l (substring line i2)))
5848 (if (> i1 0)
5849 (concat (make-string i1 ?\ ) l)
5850 l)))
5852 (defcustom org-empty-line-terminates-plain-lists nil
5853 "Non-nil means, an empty line ends all plain list levels.
5854 When nil, empty lines are part of the preceeding item."
5855 :group 'org-plain-lists
5856 :type 'boolean)
5858 (defun org-beginning-of-item ()
5859 "Go to the beginning of the current hand-formatted item.
5860 If the cursor is not in an item, throw an error."
5861 (interactive)
5862 (let ((pos (point))
5863 (limit (save-excursion
5864 (condition-case nil
5865 (progn
5866 (org-back-to-heading)
5867 (beginning-of-line 2) (point))
5868 (error (point-min)))))
5869 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5870 ind ind1)
5871 (if (org-at-item-p)
5872 (beginning-of-line 1)
5873 (beginning-of-line 1)
5874 (skip-chars-forward " \t")
5875 (setq ind (current-column))
5876 (if (catch 'exit
5877 (while t
5878 (beginning-of-line 0)
5879 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5881 (if (looking-at "[ \t]*$")
5882 (setq ind1 ind-empty)
5883 (skip-chars-forward " \t")
5884 (setq ind1 (current-column)))
5885 (if (< ind1 ind)
5886 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5888 (goto-char pos)
5889 (error "Not in an item")))))
5891 (defun org-end-of-item ()
5892 "Go to the end of the current hand-formatted item.
5893 If the cursor is not in an item, throw an error."
5894 (interactive)
5895 (let* ((pos (point))
5896 ind1
5897 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5898 (limit (save-excursion (outline-next-heading) (point)))
5899 (ind (save-excursion
5900 (org-beginning-of-item)
5901 (skip-chars-forward " \t")
5902 (current-column)))
5903 (end (catch 'exit
5904 (while t
5905 (beginning-of-line 2)
5906 (if (eobp) (throw 'exit (point)))
5907 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5908 (if (looking-at "[ \t]*$")
5909 (setq ind1 ind-empty)
5910 (skip-chars-forward " \t")
5911 (setq ind1 (current-column)))
5912 (if (<= ind1 ind)
5913 (throw 'exit (point-at-bol)))))))
5914 (if end
5915 (goto-char end)
5916 (goto-char pos)
5917 (error "Not in an item"))))
5919 (defun org-next-item ()
5920 "Move to the beginning of the next item in the current plain list.
5921 Error if not at a plain list, or if this is the last item in the list."
5922 (interactive)
5923 (let (ind ind1 (pos (point)))
5924 (org-beginning-of-item)
5925 (setq ind (org-get-indentation))
5926 (org-end-of-item)
5927 (setq ind1 (org-get-indentation))
5928 (unless (and (org-at-item-p) (= ind ind1))
5929 (goto-char pos)
5930 (error "On last item"))))
5932 (defun org-previous-item ()
5933 "Move to the beginning of the previous item in the current plain list.
5934 Error if not at a plain list, or if this is the first item in the list."
5935 (interactive)
5936 (let (beg ind ind1 (pos (point)))
5937 (org-beginning-of-item)
5938 (setq beg (point))
5939 (setq ind (org-get-indentation))
5940 (goto-char beg)
5941 (catch 'exit
5942 (while t
5943 (beginning-of-line 0)
5944 (if (looking-at "[ \t]*$")
5946 (if (<= (setq ind1 (org-get-indentation)) ind)
5947 (throw 'exit t)))))
5948 (condition-case nil
5949 (if (or (not (org-at-item-p))
5950 (< ind1 (1- ind)))
5951 (error "")
5952 (org-beginning-of-item))
5953 (error (goto-char pos)
5954 (error "On first item")))))
5956 (defun org-move-item-down ()
5957 "Move the plain list item at point down, i.e. swap with following item.
5958 Subitems (items with larger indentation) are considered part of the item,
5959 so this really moves item trees."
5960 (interactive)
5961 (let (beg end ind ind1 (pos (point)) txt)
5962 (org-beginning-of-item)
5963 (setq beg (point))
5964 (setq ind (org-get-indentation))
5965 (org-end-of-item)
5966 (setq end (point))
5967 (setq ind1 (org-get-indentation))
5968 (if (and (org-at-item-p) (= ind ind1))
5969 (progn
5970 (org-end-of-item)
5971 (setq txt (buffer-substring beg end))
5972 (save-excursion
5973 (delete-region beg end))
5974 (setq pos (point))
5975 (insert txt)
5976 (goto-char pos)
5977 (org-maybe-renumber-ordered-list))
5978 (goto-char pos)
5979 (error "Cannot move this item further down"))))
5981 (defun org-move-item-up (arg)
5982 "Move the plain list item at point up, i.e. swap with previous item.
5983 Subitems (items with larger indentation) are considered part of the item,
5984 so this really moves item trees."
5985 (interactive "p")
5986 (let (beg end ind ind1 (pos (point)) txt)
5987 (org-beginning-of-item)
5988 (setq beg (point))
5989 (setq ind (org-get-indentation))
5990 (org-end-of-item)
5991 (setq end (point))
5992 (goto-char beg)
5993 (catch 'exit
5994 (while t
5995 (beginning-of-line 0)
5996 (if (looking-at "[ \t]*$")
5997 (if org-empty-line-terminates-plain-lists
5998 (progn
5999 (goto-char pos)
6000 (error "Cannot move this item further up"))
6001 nil)
6002 (if (<= (setq ind1 (org-get-indentation)) ind)
6003 (throw 'exit t)))))
6004 (condition-case nil
6005 (org-beginning-of-item)
6006 (error (goto-char beg)
6007 (error "Cannot move this item further up")))
6008 (setq ind1 (org-get-indentation))
6009 (if (and (org-at-item-p) (= ind ind1))
6010 (progn
6011 (setq txt (buffer-substring beg end))
6012 (save-excursion
6013 (delete-region beg end))
6014 (setq pos (point))
6015 (insert txt)
6016 (goto-char pos)
6017 (org-maybe-renumber-ordered-list))
6018 (goto-char pos)
6019 (error "Cannot move this item further up"))))
6021 (defun org-maybe-renumber-ordered-list ()
6022 "Renumber the ordered list at point if setup allows it.
6023 This tests the user option `org-auto-renumber-ordered-lists' before
6024 doing the renumbering."
6025 (interactive)
6026 (when (and org-auto-renumber-ordered-lists
6027 (org-at-item-p))
6028 (if (match-beginning 3)
6029 (org-renumber-ordered-list 1)
6030 (org-fix-bullet-type 1))))
6032 (defun org-maybe-renumber-ordered-list-safe ()
6033 (condition-case nil
6034 (save-excursion
6035 (org-maybe-renumber-ordered-list))
6036 (error nil)))
6038 (defun org-cycle-list-bullet (&optional which)
6039 "Cycle through the different itemize/enumerate bullets.
6040 This cycle the entire list level through the sequence:
6042 `-' -> `+' -> `*' -> `1.' -> `1)'
6044 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6045 0 meand `-', 1 means `+' etc."
6046 (interactive "P")
6047 (org-preserve-lc
6048 (org-beginning-of-item-list)
6049 (org-at-item-p)
6050 (beginning-of-line 1)
6051 (let ((current (match-string 0)) new)
6052 (setq new (cond
6053 ((and which (nth (1- which) '("-" "+" "*" "1." "1)"))))
6054 ((string-match "-" current) "+")
6055 ((string-match "\\+" current)
6056 (if (looking-at "\\S-") "1." "*"))
6057 ((string-match "\\*" current) "1.")
6058 ((string-match "\\." current) "1)")
6059 ((string-match ")" current) "-")
6060 (t (error "This should not happen"))))
6061 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6062 (org-fix-bullet-type 1)
6063 (org-maybe-renumber-ordered-list))))
6065 (defun org-get-string-indentation (s)
6066 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6067 (let ((n -1) (i 0) (w tab-width) c)
6068 (catch 'exit
6069 (while (< (setq n (1+ n)) (length s))
6070 (setq c (aref s n))
6071 (cond ((= c ?\ ) (setq i (1+ i)))
6072 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6073 (t (throw 'exit t)))))
6076 (defun org-renumber-ordered-list (arg)
6077 "Renumber an ordered plain list.
6078 Cursor needs to be in the first line of an item, the line that starts
6079 with something like \"1.\" or \"2)\"."
6080 (interactive "p")
6081 (unless (and (org-at-item-p)
6082 (match-beginning 3))
6083 (error "This is not an ordered list"))
6084 (let ((line (org-current-line))
6085 (col (current-column))
6086 (ind (org-get-string-indentation
6087 (buffer-substring (point-at-bol) (match-beginning 3))))
6088 ;; (term (substring (match-string 3) -1))
6089 ind1 (n (1- arg))
6090 fmt)
6091 ;; find where this list begins
6092 (org-beginning-of-item-list)
6093 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6094 (setq fmt (concat "%d" (match-string 1)))
6095 (beginning-of-line 0)
6096 ;; walk forward and replace these numbers
6097 (catch 'exit
6098 (while t
6099 (catch 'next
6100 (beginning-of-line 2)
6101 (if (eobp) (throw 'exit nil))
6102 (if (looking-at "[ \t]*$") (throw 'next nil))
6103 (skip-chars-forward " \t") (setq ind1 (current-column))
6104 (if (> ind1 ind) (throw 'next t))
6105 (if (< ind1 ind) (throw 'exit t))
6106 (if (not (org-at-item-p)) (throw 'exit nil))
6107 (delete-region (match-beginning 2) (match-end 2))
6108 (goto-char (match-beginning 2))
6109 (insert (format fmt (setq n (1+ n)))))))
6110 (goto-line line)
6111 (move-to-column col)))
6113 (defun org-fix-bullet-type (arg)
6114 "Make sure all items in this list have the same bullet."
6115 (interactive "p")
6116 (unless (org-at-item-p) (error "This is not a list"))
6117 (let ((line (org-current-line))
6118 (col (current-column))
6119 (ind (current-indentation))
6120 ind1 bullet)
6121 ;; find where this list begins
6122 (org-beginning-of-item-list)
6123 (beginning-of-line 1)
6124 ;; find out what the bullet type is
6125 (looking-at "[ \t]*\\(\\S-+\\)")
6126 (setq bullet (match-string 1))
6127 ;; walk forward and replace these numbers
6128 (beginning-of-line 0)
6129 (catch 'exit
6130 (while t
6131 (catch 'next
6132 (beginning-of-line 2)
6133 (if (eobp) (throw 'exit nil))
6134 (if (looking-at "[ \t]*$") (throw 'next nil))
6135 (skip-chars-forward " \t") (setq ind1 (current-column))
6136 (if (> ind1 ind) (throw 'next t))
6137 (if (< ind1 ind) (throw 'exit t))
6138 (if (not (org-at-item-p)) (throw 'exit nil))
6139 (skip-chars-forward " \t")
6140 (looking-at "\\S-+")
6141 (replace-match bullet))))
6142 (goto-line line)
6143 (move-to-column col)
6144 (if (string-match "[0-9]" bullet)
6145 (org-renumber-ordered-list 1))))
6147 (defun org-beginning-of-item-list ()
6148 "Go to the beginning of the current item list.
6149 I.e. to the first item in this list."
6150 (interactive)
6151 (org-beginning-of-item)
6152 (let ((pos (point-at-bol))
6153 (ind (org-get-indentation))
6154 ind1)
6155 ;; find where this list begins
6156 (catch 'exit
6157 (while t
6158 (catch 'next
6159 (beginning-of-line 0)
6160 (if (looking-at "[ \t]*$") (throw 'next t))
6161 (skip-chars-forward " \t") (setq ind1 (current-column))
6162 (if (or (< ind1 ind)
6163 (and (= ind1 ind)
6164 (not (org-at-item-p))))
6165 (throw 'exit t)
6166 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6167 (goto-char pos)))
6169 (defvar org-last-indent-begin-marker (make-marker))
6170 (defvar org-last-indent-end-marker (make-marker))
6172 (defun org-outdent-item (arg)
6173 "Outdent a local list item."
6174 (interactive "p")
6175 (org-indent-item (- arg)))
6177 (defun org-indent-item (arg)
6178 "Indent a local list item."
6179 (interactive "p")
6180 (unless (org-at-item-p)
6181 (error "Not on an item"))
6182 (save-excursion
6183 (let (beg end ind ind1 tmp delta ind-down ind-up)
6184 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6185 (setq beg org-last-indent-begin-marker
6186 end org-last-indent-end-marker)
6187 (org-beginning-of-item)
6188 (setq beg (move-marker org-last-indent-begin-marker (point)))
6189 (org-end-of-item)
6190 (setq end (move-marker org-last-indent-end-marker (point))))
6191 (goto-char beg)
6192 (setq tmp (org-item-indent-positions)
6193 ind (car tmp)
6194 ind-down (nth 2 tmp)
6195 ind-up (nth 1 tmp)
6196 delta (if (> arg 0)
6197 (if ind-down (- ind-down ind) (+ 2 ind))
6198 (if ind-up (- ind-up ind) (- ind 2))))
6199 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6200 (while (< (point) end)
6201 (beginning-of-line 1)
6202 (skip-chars-forward " \t") (setq ind1 (current-column))
6203 (delete-region (point-at-bol) (point))
6204 (or (eolp) (indent-to-column (+ ind1 delta)))
6205 (beginning-of-line 2))))
6206 (org-maybe-renumber-ordered-list-safe)
6207 (save-excursion
6208 (beginning-of-line 0)
6209 (condition-case nil (org-beginning-of-item) (error nil))
6210 (org-maybe-renumber-ordered-list-safe)))
6213 (defun org-item-indent-positions ()
6214 "Assumes cursor in item line. FIXME"
6215 (let* ((bolpos (point-at-bol))
6216 (ind (org-get-indentation))
6217 ind-down ind-up pos)
6218 (save-excursion
6219 (org-beginning-of-item-list)
6220 (skip-chars-backward "\n\r \t")
6221 (when (org-in-item-p)
6222 (org-beginning-of-item)
6223 (setq ind-up (org-get-indentation))))
6224 (setq pos (point))
6225 (save-excursion
6226 (cond
6227 ((and (condition-case nil (progn (org-previous-item) t)
6228 (error nil))
6229 (or (forward-char 1) t)
6230 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6231 (setq ind-down (org-get-indentation)))
6232 ((and (goto-char pos)
6233 (org-at-item-p))
6234 (goto-char (match-end 0))
6235 (skip-chars-forward " \t")
6236 (setq ind-down (current-column)))))
6237 (list ind ind-up ind-down)))
6239 ;;; The orgstruct minor mode
6241 ;; Define a minor mode which can be used in other modes in order to
6242 ;; integrate the org-mode structure editing commands.
6244 ;; This is really a hack, because the org-mode structure commands use
6245 ;; keys which normally belong to the major mode. Here is how it
6246 ;; works: The minor mode defines all the keys necessary to operate the
6247 ;; structure commands, but wraps the commands into a function which
6248 ;; tests if the cursor is currently at a headline or a plain list
6249 ;; item. If that is the case, the structure command is used,
6250 ;; temporarily setting many Org-mode variables like regular
6251 ;; expressions for filling etc. However, when any of those keys is
6252 ;; used at a different location, function uses `key-binding' to look
6253 ;; up if the key has an associated command in another currently active
6254 ;; keymap (minor modes, major mode, global), and executes that
6255 ;; command. There might be problems if any of the keys is otherwise
6256 ;; used as a prefix key.
6258 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6259 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6260 ;; addresses this by checking explicitly for both bindings.
6262 (defvar orgstruct-mode-map (make-sparse-keymap)
6263 "Keymap for the minor `org-cdlatex-mode'.")
6265 ;;;###autoload
6266 (define-minor-mode orgstruct-mode
6267 "Toggle the minor more `orgstruct-mode'.
6268 This mode is for using Org-mode structure commands in other modes.
6269 The following key behave as if Org-mode was active, if the cursor
6270 is on a headline, or on a plain list item (both in the definition
6271 of Org-mode).
6273 M-up Move entry/item up
6274 M-down Move entry/item down
6275 M-left Promote
6276 M-right Demote
6277 M-S-up Move entry/item up
6278 M-S-down Move entry/item down
6279 M-S-left Promote subtree
6280 M-S-right Demote subtree
6281 M-q Fill paragraph and items like in Org-mode
6282 C-c ^ Sort entries
6283 C-c - Cycle list bullet
6284 TAB Cycle item visibility
6285 M-RET Insert new heading/item
6286 S-M-RET Insert new TODO heading / Chekbox item
6287 C-c C-c Set tags / toggle checkbox"
6288 nil " OrgStruct" nil
6289 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6291 ;;;###autoload
6292 (defun turn-on-orgstruct ()
6293 "Unconditionally turn on `orgstruct-mode'."
6294 (orgstruct-mode 1))
6296 (defun orgstruct-error ()
6297 "Error when there is no default binding for a structure key."
6298 (interactive)
6299 (error "This key is has no function outside structure elements"))
6301 (defvar org-local-vars nil
6302 "List of local variables, for use by `orgstruct-mode'")
6304 (defun orgstruct-setup ()
6305 "Setup orgstruct keymaps."
6306 (let ((nfunc 0)
6307 (bindings
6308 (list
6309 '([(meta up)] org-metaup)
6310 '([(meta down)] org-metadown)
6311 '([(meta left)] org-metaleft)
6312 '([(meta right)] org-metaright)
6313 '([(meta shift up)] org-shiftmetaup)
6314 '([(meta shift down)] org-shiftmetadown)
6315 '([(meta shift left)] org-shiftmetaleft)
6316 '([(meta shift right)] org-shiftmetaright)
6317 '([(shift up)] org-shiftup)
6318 '([(shift down)] org-shiftdown)
6319 '("\M-q" fill-paragraph)
6320 '("\C-c^" org-sort)
6321 '("\C-c-" org-cycle-list-bullet)))
6322 elt key fun cmd)
6323 (while (setq elt (pop bindings))
6324 (setq nfunc (1+ nfunc))
6325 (setq key (org-key (car elt))
6326 fun (nth 1 elt)
6327 cmd (orgstruct-make-binding fun nfunc key))
6328 (org-defkey orgstruct-mode-map key cmd))
6330 ;; Special treatment needed for TAB and RET
6331 (org-defkey orgstruct-mode-map [(tab)]
6332 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6333 (org-defkey orgstruct-mode-map "\C-i"
6334 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6336 (org-defkey orgstruct-mode-map "\M-\C-m"
6337 (orgstruct-make-binding 'org-insert-heading 105
6338 "\M-\C-m" [(meta return)]))
6339 (org-defkey orgstruct-mode-map [(meta return)]
6340 (orgstruct-make-binding 'org-insert-heading 106
6341 [(meta return)] "\M-\C-m"))
6343 (org-defkey orgstruct-mode-map [(shift meta return)]
6344 (orgstruct-make-binding 'org-insert-todo-heading 107
6345 [(meta return)] "\M-\C-m"))
6347 (org-defkey orgstruct-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
6348 (setq org-local-vars (org-get-local-variables))
6352 (defun orgstruct-make-binding (fun n &rest keys)
6353 "Create a function for binding in the structure minor mode.
6354 FUN is the command to call inside a table. N is used to create a unique
6355 command name. KEYS are keys that should be checked in for a command
6356 to execute outside of tables."
6357 (eval
6358 (list 'defun
6359 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6360 '(arg)
6361 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6362 "Outside of structure, run the binding of `"
6363 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6364 "'.")
6365 '(interactive "p")
6366 (list 'if
6367 '(org-context-p 'headline 'item)
6368 (list 'org-run-like-in-org-mode (list 'quote fun))
6369 (list 'let '(orgstruct-mode)
6370 (list 'call-interactively
6371 (append '(or)
6372 (mapcar (lambda (k)
6373 (list 'key-binding k))
6374 keys)
6375 '('orgstruct-error))))))))
6377 (defun org-context-p (&rest contexts)
6378 "FIXME:"
6379 (let ((pos (point)))
6380 (goto-char (point-at-bol))
6381 (prog1 (or (and (memq 'table contexts)
6382 (looking-at "[ \t]*|"))
6383 (and (memq 'headline contexts)
6384 (looking-at "\\*+"))
6385 (and (memq 'item contexts)
6386 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6387 (goto-char pos))))
6389 (defun org-get-local-variables ()
6390 "Return a list of all local variables in an org-mode buffer."
6391 (let (varlist)
6392 (with-current-buffer (get-buffer-create "*Org tmp*")
6393 (erase-buffer)
6394 (org-mode)
6395 (setq varlist (buffer-local-variables)))
6396 (kill-buffer "*Org tmp*")
6397 (delq nil
6398 (mapcar
6399 (lambda (x)
6400 (setq x
6401 (if (symbolp x)
6402 (list x)
6403 (list (car x) (list 'quote (cdr x)))))
6404 (if (string-match
6405 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6406 (symbol-name (car x)))
6407 x nil))
6408 varlist))))
6410 (defun org-run-like-in-org-mode (cmd)
6411 (eval (list 'let org-local-vars
6412 (list 'call-interactively (list 'quote cmd)))))
6414 ;;;; Archiving
6416 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6418 (defun org-archive-subtree (&optional find-done)
6419 "Move the current subtree to the archive.
6420 The archive can be a certain top-level heading in the current file, or in
6421 a different file. The tree will be moved to that location, the subtree
6422 heading be marked DONE, and the current time will be added.
6424 When called with prefix argument FIND-DONE, find whole trees without any
6425 open TODO items and archive them (after getting confirmation from the user).
6426 If the cursor is not at a headline when this comand is called, try all level
6427 1 trees. If the cursor is on a headline, only try the direct children of
6428 this heading."
6429 (interactive "P")
6430 (if find-done
6431 (org-archive-all-done)
6432 ;; Save all relevant TODO keyword-relatex variables
6434 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6435 (tr-org-todo-keywords-1 org-todo-keywords-1)
6436 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6437 (tr-org-done-keywords org-done-keywords)
6438 (tr-org-todo-regexp org-todo-regexp)
6439 (tr-org-todo-line-regexp org-todo-line-regexp)
6440 (tr-org-odd-levels-only org-odd-levels-only)
6441 (this-buffer (current-buffer))
6442 (org-archive-location org-archive-location)
6443 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6444 file heading buffer level newfile-p)
6446 ;; Try to find a local archive location
6447 (save-excursion
6448 (save-restriction
6449 (widen)
6450 (if (or (re-search-backward re nil t) (re-search-forward re nil t))
6451 (setq org-archive-location (match-string 1)))))
6453 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6454 (progn
6455 (setq file (format (match-string 1 org-archive-location)
6456 (file-name-nondirectory buffer-file-name))
6457 heading (match-string 2 org-archive-location)))
6458 (error "Invalid `org-archive-location'"))
6459 (if (> (length file) 0)
6460 (setq newfile-p (not (file-exists-p file))
6461 buffer (find-file-noselect file))
6462 (setq buffer (current-buffer)))
6463 (unless buffer
6464 (error "Cannot access file \"%s\"" file))
6465 (if (and (> (length heading) 0)
6466 (string-match "^\\*+" heading))
6467 (setq level (match-end 0))
6468 (setq heading nil level 0))
6469 (save-excursion
6470 ;; We first only copy, in case something goes wrong
6471 ;; we need to protect this-command, to avoid kill-region sets it,
6472 ;; which would lead to duplication of subtrees
6473 (let (this-command) (org-copy-subtree))
6474 (set-buffer buffer)
6475 ;; Enforce org-mode for the archive buffer
6476 (if (not (org-mode-p))
6477 ;; Force the mode for future visits.
6478 (let ((org-insert-mode-line-in-empty-file t)
6479 (org-inhibit-startup t))
6480 (call-interactively 'org-mode)))
6481 (when newfile-p
6482 (goto-char (point-max))
6483 (insert (format "\nArchived entries from file %s\n\n"
6484 (buffer-file-name this-buffer))))
6485 ;; Force the TODO keywords of the original buffer
6486 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6487 (org-todo-keywords-1 tr-org-todo-keywords-1)
6488 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6489 (org-done-keywords tr-org-done-keywords)
6490 (org-todo-regexp tr-org-todo-regexp)
6491 (org-todo-line-regexp tr-org-todo-line-regexp)
6492 (org-odd-levels-only
6493 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6494 org-odd-levels-only
6495 tr-org-odd-levels-only)))
6496 (goto-char (point-min))
6497 (if heading
6498 (progn
6499 (if (re-search-forward
6500 (concat "^" (regexp-quote heading)
6501 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6502 nil t)
6503 (goto-char (match-end 0))
6504 ;; Heading not found, just insert it at the end
6505 (goto-char (point-max))
6506 (or (bolp) (insert "\n"))
6507 (insert "\n" heading "\n")
6508 (end-of-line 0))
6509 ;; Make the subtree visible
6510 (show-subtree)
6511 (org-end-of-subtree t)
6512 (skip-chars-backward " \t\r\n")
6513 (and (looking-at "[ \t\r\n]*")
6514 (replace-match "\n\n")))
6515 ;; No specific heading, just go to end of file.
6516 (goto-char (point-max)) (insert "\n"))
6517 ;; Paste
6518 (org-paste-subtree (org-get-legal-level level 1))
6519 ;; Mark the entry as done, i.e. set to last word in org-todo-keywords-1 FIXME: not right anymore!!!!!!!
6520 (when (and org-archive-mark-done
6521 (looking-at org-todo-line-regexp)
6522 (or (not (match-end 3))
6523 (not (member (match-string 3) org-done-keywords))))
6524 (let (org-log-done)
6525 (org-todo (car org-done-keywords))))
6527 ;; Move cursor to right after the TODO keyword
6528 (when org-archive-stamp-time
6529 (org-add-planning-info 'archived (org-current-time)))
6530 ;; Save the buffer, if it is not the same buffer.
6531 (if (not (eq this-buffer buffer)) (save-buffer))))
6532 ;; Here we are back in the original buffer. Everything seems to have
6533 ;; worked. So now cut the tree and finish up.
6534 (let (this-command) (org-cut-subtree))
6535 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6536 (message "Subtree archived %s"
6537 (if (eq this-buffer buffer)
6538 (concat "under heading: " heading)
6539 (concat "in file: " (abbreviate-file-name file)))))))
6541 (defun org-archive-all-done (&optional tag)
6542 "Archive sublevels of the current tree without open TODO items.
6543 If the cursor is not on a headline, try all level 1 trees. If
6544 it is on a headline, try all direct children.
6545 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6546 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6547 (rea (concat ".*:" org-archive-tag ":"))
6548 (begm (make-marker))
6549 (endm (make-marker))
6550 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6551 "Move subtree to archive (no open TODO items)? "))
6552 beg end (cntarch 0))
6553 (if (org-on-heading-p)
6554 (progn
6555 (setq re1 (concat "^" (regexp-quote
6556 (make-string
6557 (1+ (- (match-end 0) (match-beginning 0)))
6558 ?*))
6559 " "))
6560 (move-marker begm (point))
6561 (move-marker endm (org-end-of-subtree t)))
6562 (setq re1 "^* ")
6563 (move-marker begm (point-min))
6564 (move-marker endm (point-max)))
6565 (save-excursion
6566 (goto-char begm)
6567 (while (re-search-forward re1 endm t)
6568 (setq beg (match-beginning 0)
6569 end (save-excursion (org-end-of-subtree t) (point)))
6570 (goto-char beg)
6571 (if (re-search-forward re end t)
6572 (goto-char end)
6573 (goto-char beg)
6574 (if (and (or (not tag) (not (looking-at rea)))
6575 (y-or-n-p question))
6576 (progn
6577 (if tag
6578 (org-toggle-tag org-archive-tag 'on)
6579 (org-archive-subtree))
6580 (setq cntarch (1+ cntarch)))
6581 (goto-char end)))))
6582 (message "%d trees archived" cntarch)))
6584 (defun org-cycle-hide-drawers (state)
6585 "Re-hide all archived subtrees after a visibility state change."
6586 (when (not (memq state '(overview folded)))
6587 (save-excursion
6588 (let* ((globalp (memq state '(contents all)))
6589 (beg (if globalp (point-min) (point)))
6590 (end (if globalp (point-max) (org-end-of-subtree t))))
6591 (goto-char beg)
6592 (while (re-search-forward org-drawer-regexp end t)
6593 (org-flag-drawer t))))))
6595 (defun org-flag-drawer (flag)
6596 (save-excursion
6597 (beginning-of-line 1)
6598 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6599 (let ((b (match-end 0)))
6600 (if (re-search-forward
6601 "^[ \t]*:END:"
6602 (save-excursion (outline-next-heading) (point)) t)
6603 (outline-flag-region b (point-at-eol) flag)
6604 (error ":END: line missing"))))))
6606 (defun org-cycle-hide-archived-subtrees (state)
6607 "Re-hide all archived subtrees after a visibility state change."
6608 (when (and (not org-cycle-open-archived-trees)
6609 (not (memq state '(overview folded))))
6610 (save-excursion
6611 (let* ((globalp (memq state '(contents all)))
6612 (beg (if globalp (point-min) (point)))
6613 (end (if globalp (point-max) (org-end-of-subtree t))))
6614 (org-hide-archived-subtrees beg end)
6615 (goto-char beg)
6616 (if (looking-at (concat ".*:" org-archive-tag ":"))
6617 (message (substitute-command-keys
6618 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6620 (defun org-force-cycle-archived ()
6621 "Cycle subtree even if it is archived."
6622 (interactive)
6623 (setq this-command 'org-cycle)
6624 (let ((org-cycle-open-archived-trees t))
6625 (call-interactively 'org-cycle)))
6627 (defun org-hide-archived-subtrees (beg end)
6628 "Re-hide all archived subtrees after a visibility state change."
6629 (save-excursion
6630 (let* ((re (concat ":" org-archive-tag ":")))
6631 (goto-char beg)
6632 (while (re-search-forward re end t)
6633 (and (org-on-heading-p) (hide-subtree))
6634 (org-end-of-subtree t)))))
6636 (defun org-toggle-tag (tag &optional onoff)
6637 "Toggle the tag TAG for the current line.
6638 If ONOFF is `on' or `off', don't toggle but set to this state."
6639 (unless (org-on-heading-p t) (error "Not on headling"))
6640 (let (res current)
6641 (save-excursion
6642 (beginning-of-line)
6643 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6644 (point-at-eol) t)
6645 (progn
6646 (setq current (match-string 1))
6647 (replace-match ""))
6648 (setq current ""))
6649 (setq current (nreverse (org-split-string current ":")))
6650 (cond
6651 ((eq onoff 'on)
6652 (setq res t)
6653 (or (member tag current) (push tag current)))
6654 ((eq onoff 'off)
6655 (or (not (member tag current)) (setq current (delete tag current))))
6656 (t (if (member tag current)
6657 (setq current (delete tag current))
6658 (setq res t)
6659 (push tag current))))
6660 (end-of-line 1)
6661 (when current
6662 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
6663 (org-set-tags nil t))
6664 res))
6666 (defun org-toggle-archive-tag (&optional arg)
6667 "Toggle the archive tag for the current headline.
6668 With prefix ARG, check all children of current headline and offer tagging
6669 the children that do not contain any open TODO items."
6670 (interactive "P")
6671 (if arg
6672 (org-archive-all-done 'tag)
6673 (let (set)
6674 (save-excursion
6675 (org-back-to-heading t)
6676 (setq set (org-toggle-tag org-archive-tag))
6677 (when set (hide-subtree)))
6678 (and set (beginning-of-line 1))
6679 (message "Subtree %s" (if set "archived" "unarchived")))))
6682 ;;;; Tables
6684 ;;; The table editor
6686 ;; Watch out: Here we are talking about two different kind of tables.
6687 ;; Most of the code is for the tables created with the Org-mode table editor.
6688 ;; Sometimes, we talk about tables created and edited with the table.el
6689 ;; Emacs package. We call the former org-type tables, and the latter
6690 ;; table.el-type tables.
6692 (defun org-before-change-function (beg end)
6693 "Every change indicates that a table might need an update."
6694 (setq org-table-may-need-update t))
6696 (defconst org-table-line-regexp "^[ \t]*|"
6697 "Detects an org-type table line.")
6698 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
6699 "Detects an org-type table line.")
6700 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
6701 "Detects a table line marked for automatic recalculation.")
6702 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
6703 "Detects a table line marked for automatic recalculation.")
6704 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
6705 "Detects a table line marked for automatic recalculation.")
6706 (defconst org-table-hline-regexp "^[ \t]*|-"
6707 "Detects an org-type table hline.")
6708 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
6709 "Detects a table-type table hline.")
6710 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
6711 "Detects an org-type or table-type table.")
6712 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
6713 "Searching from within a table (any type) this finds the first line
6714 outside the table.")
6715 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
6716 "Searching from within a table (any type) this finds the first line
6717 outside the table.")
6719 (defvar org-table-last-highlighted-reference nil)
6720 (defvar org-table-formula-history nil)
6722 (defvar org-table-column-names nil
6723 "Alist with column names, derived from the `!' line.")
6724 (defvar org-table-column-name-regexp nil
6725 "Regular expression matching the current column names.")
6726 (defvar org-table-local-parameters nil
6727 "Alist with parameter names, derived from the `$' line.")
6728 (defvar org-table-named-field-locations nil
6729 "Alist with locations of named fields.")
6731 (defvar org-table-current-line-types nil
6732 "Table row types, non-nil only for the duration of a comand.")
6733 (defvar org-table-current-begin-line nil
6734 "Table begin line, non-nil only for the duration of a comand.")
6735 (defvar org-table-current-begin-pos nil
6736 "Table begin position, non-nil only for the duration of a comand.")
6737 (defvar org-table-dlines nil
6738 "Vector of data line line numbers in the current table.")
6739 (defvar org-table-hlines nil
6740 "Vector of hline line numbers in the current table.")
6742 (defconst org-table-range-regexp
6743 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
6744 ;; 1 2 3 4 5
6745 "Regular expression for matching ranges in formulas.")
6747 (defconst org-table-range-regexp2
6748 (concat
6749 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
6750 "\\.\\."
6751 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
6752 "Match a range for reference display.")
6754 (defconst org-table-translate-regexp
6755 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
6756 "Match a reference that needs translation, for reference display.")
6758 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
6760 (defun org-table-create-with-table.el ()
6761 "Use the table.el package to insert a new table.
6762 If there is already a table at point, convert between Org-mode tables
6763 and table.el tables."
6764 (interactive)
6765 (require 'table)
6766 (cond
6767 ((org-at-table.el-p)
6768 (if (y-or-n-p "Convert table to Org-mode table? ")
6769 (org-table-convert)))
6770 ((org-at-table-p)
6771 (if (y-or-n-p "Convert table to table.el table? ")
6772 (org-table-convert)))
6773 (t (call-interactively 'table-insert))))
6775 (defun org-table-create-or-convert-from-region (arg)
6776 "Convert region to table, or create an empty table.
6777 If there is an active region, convert it to a table, using the function
6778 `org-table-convert-region'.
6779 If there is no such region, create an empty table with `org-table-create'."
6780 (interactive "P")
6781 (if (org-region-active-p)
6782 (org-table-convert-region (region-beginning) (region-end) arg)
6783 (org-table-create arg)))
6785 (defun org-table-create (&optional size)
6786 "Query for a size and insert a table skeleton.
6787 SIZE is a string Columns x Rows like for example \"3x2\"."
6788 (interactive "P")
6789 (unless size
6790 (setq size (read-string
6791 (concat "Table size Columns x Rows [e.g. "
6792 org-table-default-size "]: ")
6793 "" nil org-table-default-size)))
6795 (let* ((pos (point))
6796 (indent (make-string (current-column) ?\ ))
6797 (split (org-split-string size " *x *"))
6798 (rows (string-to-number (nth 1 split)))
6799 (columns (string-to-number (car split)))
6800 (line (concat (apply 'concat indent "|" (make-list columns " |"))
6801 "\n")))
6802 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
6803 (point-at-bol) (point)))
6804 (beginning-of-line 1)
6805 (newline))
6806 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
6807 (dotimes (i rows) (insert line))
6808 (goto-char pos)
6809 (if (> rows 1)
6810 ;; Insert a hline after the first row.
6811 (progn
6812 (end-of-line 1)
6813 (insert "\n|-")
6814 (goto-char pos)))
6815 (org-table-align)))
6817 (defun org-table-convert-region (beg0 end0 &optional nspace)
6818 "Convert region to a table.
6819 The region goes from BEG0 to END0, but these borders will be moved
6820 slightly, to make sure a beginning of line in the first line is included.
6821 When NSPACE is non-nil, it indicates the minimum number of spaces that
6822 separate columns. By default, the function first checks if every line
6823 contains at lease one TAB. If yes, it assumes that the material is TAB
6824 separated. If not, it assumes a single space as separator."
6825 (interactive "rP")
6826 (let* ((beg (min beg0 end0))
6827 (end (max beg0 end0))
6828 (tabsep t)
6830 (goto-char beg)
6831 (beginning-of-line 1)
6832 (setq beg (move-marker (make-marker) (point)))
6833 (goto-char end)
6834 (if (bolp) (backward-char 1) (end-of-line 1))
6835 (setq end (move-marker (make-marker) (point)))
6836 ;; Lets see if this is tab-separated material. If every nonempty line
6837 ;; contains a tab, we will assume that it is tab-separated material
6838 (if nspace
6839 (setq tabsep nil)
6840 (goto-char beg)
6841 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
6842 (if nspace (setq tabsep nil))
6843 (if tabsep
6844 (setq re "^\\|\t")
6845 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
6846 (max 1 (prefix-numeric-value nspace)))))
6847 (goto-char beg)
6848 (while (re-search-forward re end t)
6849 (replace-match "| " t t))
6850 (goto-char beg)
6851 (insert " ")
6852 (org-table-align)))
6854 (defun org-table-import (file arg)
6855 "Import FILE as a table.
6856 The file is assumed to be tab-separated. Such files can be produced by most
6857 spreadsheet and database applications. If no tabs (at least one per line)
6858 are found, lines will be split on whitespace into fields."
6859 (interactive "f\nP")
6860 (or (bolp) (newline))
6861 (let ((beg (point))
6862 (pm (point-max)))
6863 (insert-file-contents file)
6864 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
6866 (defun org-table-export ()
6867 "Export table as a tab-separated file.
6868 Such a file can be imported into a spreadsheet program like Excel."
6869 (interactive)
6870 (let* ((beg (org-table-begin))
6871 (end (org-table-end))
6872 (table (buffer-substring beg end))
6873 (file (read-file-name "Export table to: "))
6874 buf)
6875 (unless (or (not (file-exists-p file))
6876 (y-or-n-p (format "Overwrite file %s? " file)))
6877 (error "Abort"))
6878 (with-current-buffer (find-file-noselect file)
6879 (setq buf (current-buffer))
6880 (erase-buffer)
6881 (fundamental-mode)
6882 (insert table)
6883 (goto-char (point-min))
6884 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
6885 (replace-match "" t t)
6886 (end-of-line 1))
6887 (goto-char (point-min))
6888 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
6889 (replace-match "" t t)
6890 (goto-char (min (1+ (point)) (point-max))))
6891 (goto-char (point-min))
6892 (while (re-search-forward "^-[-+]*$" nil t)
6893 (replace-match "")
6894 (if (looking-at "\n")
6895 (delete-char 1)))
6896 (goto-char (point-min))
6897 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
6898 (replace-match "\t" t t))
6899 (save-buffer))
6900 (kill-buffer buf)))
6902 (defvar org-table-aligned-begin-marker (make-marker)
6903 "Marker at the beginning of the table last aligned.
6904 Used to check if cursor still is in that table, to minimize realignment.")
6905 (defvar org-table-aligned-end-marker (make-marker)
6906 "Marker at the end of the table last aligned.
6907 Used to check if cursor still is in that table, to minimize realignment.")
6908 (defvar org-table-last-alignment nil
6909 "List of flags for flushright alignment, from the last re-alignment.
6910 This is being used to correctly align a single field after TAB or RET.")
6911 (defvar org-table-last-column-widths nil
6912 "List of max width of fields in each column.
6913 This is being used to correctly align a single field after TAB or RET.")
6914 (defvar org-table-overlay-coordinates nil
6915 "Overlay coordinates after each align of a table.")
6916 (make-variable-buffer-local 'org-table-overlay-coordinates)
6918 (defvar org-last-recalc-line nil)
6919 (defconst org-narrow-column-arrow "=>"
6920 "Used as display property in narrowed table columns.")
6922 (defun org-table-align ()
6923 "Align the table at point by aligning all vertical bars."
6924 (interactive)
6925 (let* (
6926 ;; Limits of table
6927 (beg (org-table-begin))
6928 (end (org-table-end))
6929 ;; Current cursor position
6930 (linepos (org-current-line))
6931 (colpos (org-table-current-column))
6932 (winstart (window-start))
6933 (winstartline (org-current-line (min winstart (1- (point-max)))))
6934 lines (new "") lengths l typenums ty fields maxfields i
6935 column
6936 (indent "") cnt frac
6937 rfmt hfmt
6938 (spaces '(1 . 1))
6939 (sp1 (car spaces))
6940 (sp2 (cdr spaces))
6941 (rfmt1 (concat
6942 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6943 (hfmt1 (concat
6944 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6945 emptystrings links dates narrow fmax f1 len c e)
6946 (untabify beg end)
6947 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
6948 ;; Check if we have links or dates
6949 (goto-char beg)
6950 (setq links (re-search-forward org-bracket-link-regexp end t))
6951 (goto-char beg)
6952 (setq dates (and org-display-custom-times
6953 (re-search-forward org-ts-regexp-both end t)))
6954 ;; Make sure the link properties are right
6955 (when links (goto-char beg) (while (org-activate-bracket-links end)))
6956 ;; Make sure the date properties are right
6957 (when dates (goto-char beg) (while (org-activate-dates end)))
6959 ;; Check if we are narrowing any columns
6960 (goto-char beg)
6961 (setq narrow (and org-format-transports-properties-p
6962 (re-search-forward "<[0-9]+>" end t)))
6963 ;; Get the rows
6964 (setq lines (org-split-string
6965 (buffer-substring beg end) "\n"))
6966 ;; Store the indentation of the first line
6967 (if (string-match "^ *" (car lines))
6968 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6969 ;; Mark the hlines by setting the corresponding element to nil
6970 ;; At the same time, we remove trailing space.
6971 (setq lines (mapcar (lambda (l)
6972 (if (string-match "^ *|-" l)
6974 (if (string-match "[ \t]+$" l)
6975 (substring l 0 (match-beginning 0))
6976 l)))
6977 lines))
6978 ;; Get the data fields by splitting the lines.
6979 (setq fields (mapcar
6980 (lambda (l)
6981 (org-split-string l " *| *"))
6982 (delq nil (copy-sequence lines))))
6983 ;; How many fields in the longest line?
6984 (condition-case nil
6985 (setq maxfields (apply 'max (mapcar 'length fields)))
6986 (error
6987 (kill-region beg end)
6988 (org-table-create org-table-default-size)
6989 (error "Empty table - created default table")))
6990 ;; A list of empty strings to fill any short rows on output
6991 (setq emptystrings (make-list maxfields ""))
6992 ;; Check for special formatting.
6993 (setq i -1)
6994 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6995 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6996 ;; Check if there is an explicit width specified
6997 (when narrow
6998 (setq c column fmax nil)
6999 (while c
7000 (setq e (pop c))
7001 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7002 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7003 ;; Find fields that are wider than fmax, and shorten them
7004 (when fmax
7005 (loop for xx in column do
7006 (when (and (stringp xx)
7007 (> (org-string-width xx) fmax))
7008 (org-add-props xx nil
7009 'help-echo
7010 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7011 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7012 (unless (> f1 1)
7013 (error "Cannot narrow field starting with wide link \"%s\""
7014 (match-string 0 xx)))
7015 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7016 (add-text-properties (- f1 2) f1
7017 (list 'display org-narrow-column-arrow)
7018 xx)))))
7019 ;; Get the maximum width for each column
7020 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7021 ;; Get the fraction of numbers, to decide about alignment of the column
7022 (setq cnt 0 frac 0.0)
7023 (loop for x in column do
7024 (if (equal x "")
7026 (setq frac ( / (+ (* frac cnt)
7027 (if (string-match org-table-number-regexp x) 1 0))
7028 (setq cnt (1+ cnt))))))
7029 (push (>= frac org-table-number-fraction) typenums))
7030 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7032 ;; Store the alignment of this table, for later editing of single fields
7033 (setq org-table-last-alignment typenums
7034 org-table-last-column-widths lengths)
7036 ;; With invisible characters, `format' does not get the field width right
7037 ;; So we need to make these fields wide by hand.
7038 (when links
7039 (loop for i from 0 upto (1- maxfields) do
7040 (setq len (nth i lengths))
7041 (loop for j from 0 upto (1- (length fields)) do
7042 (setq c (nthcdr i (car (nthcdr j fields))))
7043 (if (and (stringp (car c))
7044 (string-match org-bracket-link-regexp (car c))
7045 (< (org-string-width (car c)) len))
7046 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7048 ;; Compute the formats needed for output of the table
7049 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7050 (while (setq l (pop lengths))
7051 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7052 (setq rfmt (concat rfmt (format rfmt1 ty l))
7053 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7054 (setq rfmt (concat rfmt "\n")
7055 hfmt (concat (substring hfmt 0 -1) "|\n"))
7057 (setq new (mapconcat
7058 (lambda (l)
7059 (if l (apply 'format rfmt
7060 (append (pop fields) emptystrings))
7061 hfmt))
7062 lines ""))
7063 ;; Replace the old one
7064 (delete-region beg end)
7065 (move-marker end nil)
7066 (move-marker org-table-aligned-begin-marker (point))
7067 (insert new)
7068 (move-marker org-table-aligned-end-marker (point))
7069 (when (and orgtbl-mode (not (org-mode-p)))
7070 (goto-char org-table-aligned-begin-marker)
7071 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7072 ;; Try to move to the old location
7073 (goto-line winstartline)
7074 (setq winstart (point-at-bol))
7075 (goto-line linepos)
7076 (set-window-start (selected-window) winstart 'noforce)
7077 (org-table-goto-column colpos)
7078 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7079 (setq org-table-may-need-update nil)
7082 (defun org-string-width (s)
7083 "Compute width of string, ignoring invisible characters.
7084 This ignores character with invisibility property `org-link', and also
7085 characters with property `org-cwidth', because these will become invisible
7086 upon the next fontification round."
7087 (let (b l)
7088 (when (or (eq t buffer-invisibility-spec)
7089 (assq 'org-link buffer-invisibility-spec))
7090 (while (setq b (text-property-any 0 (length s)
7091 'invisible 'org-link s))
7092 (setq s (concat (substring s 0 b)
7093 (substring s (or (next-single-property-change
7094 b 'invisible s) (length s)))))))
7095 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7096 (setq s (concat (substring s 0 b)
7097 (substring s (or (next-single-property-change
7098 b 'org-cwidth s) (length s))))))
7099 (setq l (string-width s) b -1)
7100 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7101 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7104 (defun org-table-begin (&optional table-type)
7105 "Find the beginning of the table and return its position.
7106 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7107 (save-excursion
7108 (if (not (re-search-backward
7109 (if table-type org-table-any-border-regexp
7110 org-table-border-regexp)
7111 nil t))
7112 (progn (goto-char (point-min)) (point))
7113 (goto-char (match-beginning 0))
7114 (beginning-of-line 2)
7115 (point))))
7117 (defun org-table-end (&optional table-type)
7118 "Find the end of the table and return its position.
7119 With argument TABLE-TYPE, go to the end of a table.el-type table."
7120 (save-excursion
7121 (if (not (re-search-forward
7122 (if table-type org-table-any-border-regexp
7123 org-table-border-regexp)
7124 nil t))
7125 (goto-char (point-max))
7126 (goto-char (match-beginning 0)))
7127 (point-marker)))
7129 (defun org-table-justify-field-maybe (&optional new)
7130 "Justify the current field, text to left, number to right.
7131 Optional argument NEW may specify text to replace the current field content."
7132 (cond
7133 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7134 ((org-at-table-hline-p))
7135 ((and (not new)
7136 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7137 (current-buffer)))
7138 (< (point) org-table-aligned-begin-marker)
7139 (>= (point) org-table-aligned-end-marker)))
7140 ;; This is not the same table, force a full re-align
7141 (setq org-table-may-need-update t))
7142 (t ;; realign the current field, based on previous full realign
7143 (let* ((pos (point)) s
7144 (col (org-table-current-column))
7145 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7146 l f n o e)
7147 (when (> col 0)
7148 (skip-chars-backward "^|\n")
7149 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7150 (progn
7151 (setq s (match-string 1)
7152 o (match-string 0)
7153 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7154 e (not (= (match-beginning 2) (match-end 2))))
7155 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7156 l (if e "|" (setq org-table-may-need-update t) ""))
7157 n (format f s))
7158 (if new
7159 (if (<= (length new) l) ;; FIXME: length -> str-width?
7160 (setq n (format f new))
7161 (setq n (concat new "|") org-table-may-need-update t)))
7162 (or (equal n o)
7163 (let (org-table-may-need-update)
7164 (replace-match n t t))))
7165 (setq org-table-may-need-update t))
7166 (goto-char pos))))))
7168 (defun org-table-next-field ()
7169 "Go to the next field in the current table, creating new lines as needed.
7170 Before doing so, re-align the table if necessary."
7171 (interactive)
7172 (org-table-maybe-eval-formula)
7173 (org-table-maybe-recalculate-line)
7174 (if (and org-table-automatic-realign
7175 org-table-may-need-update)
7176 (org-table-align))
7177 (let ((end (org-table-end)))
7178 (if (org-at-table-hline-p)
7179 (end-of-line 1))
7180 (condition-case nil
7181 (progn
7182 (re-search-forward "|" end)
7183 (if (looking-at "[ \t]*$")
7184 (re-search-forward "|" end))
7185 (if (and (looking-at "-")
7186 org-table-tab-jumps-over-hlines
7187 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7188 (goto-char (match-beginning 1)))
7189 (if (looking-at "-")
7190 (progn
7191 (beginning-of-line 0)
7192 (org-table-insert-row 'below))
7193 (if (looking-at " ") (forward-char 1))))
7194 (error
7195 (org-table-insert-row 'below)))))
7197 (defun org-table-previous-field ()
7198 "Go to the previous field in the table.
7199 Before doing so, re-align the table if necessary."
7200 (interactive)
7201 (org-table-justify-field-maybe)
7202 (org-table-maybe-recalculate-line)
7203 (if (and org-table-automatic-realign
7204 org-table-may-need-update)
7205 (org-table-align))
7206 (if (org-at-table-hline-p)
7207 (end-of-line 1))
7208 (re-search-backward "|" (org-table-begin))
7209 (re-search-backward "|" (org-table-begin))
7210 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7211 (re-search-backward "|" (org-table-begin)))
7212 (if (looking-at "| ?")
7213 (goto-char (match-end 0))))
7215 (defun org-table-next-row ()
7216 "Go to the next row (same column) in the current table.
7217 Before doing so, re-align the table if necessary."
7218 (interactive)
7219 (org-table-maybe-eval-formula)
7220 (org-table-maybe-recalculate-line)
7221 (if (or (looking-at "[ \t]*$")
7222 (save-excursion (skip-chars-backward " \t") (bolp)))
7223 (newline)
7224 (if (and org-table-automatic-realign
7225 org-table-may-need-update)
7226 (org-table-align))
7227 (let ((col (org-table-current-column)))
7228 (beginning-of-line 2)
7229 (if (or (not (org-at-table-p))
7230 (org-at-table-hline-p))
7231 (progn
7232 (beginning-of-line 0)
7233 (org-table-insert-row 'below)))
7234 (org-table-goto-column col)
7235 (skip-chars-backward "^|\n\r")
7236 (if (looking-at " ") (forward-char 1)))))
7238 (defun org-table-copy-down (n)
7239 "Copy a field down in the current column.
7240 If the field at the cursor is empty, copy into it the content of the nearest
7241 non-empty field above. With argument N, use the Nth non-empty field.
7242 If the current field is not empty, it is copied down to the next row, and
7243 the cursor is moved with it. Therefore, repeating this command causes the
7244 column to be filled row-by-row.
7245 If the variable `org-table-copy-increment' is non-nil and the field is an
7246 integer or a timestamp, it will be incremented while copying. In the case of
7247 a timestamp, if the cursor is on the year, change the year. If it is on the
7248 month or the day, change that. Point will stay on the current date field
7249 in order to easily repeat the interval."
7250 (interactive "p")
7251 (let* ((colpos (org-table-current-column))
7252 (col (current-column))
7253 (field (org-table-get-field))
7254 (non-empty (string-match "[^ \t]" field))
7255 (beg (org-table-begin))
7256 txt)
7257 (org-table-check-inside-data-field)
7258 (if non-empty
7259 (progn
7260 (setq txt (org-trim field))
7261 (org-table-next-row)
7262 (org-table-blank-field))
7263 (save-excursion
7264 (setq txt
7265 (catch 'exit
7266 (while (progn (beginning-of-line 1)
7267 (re-search-backward org-table-dataline-regexp
7268 beg t))
7269 (org-table-goto-column colpos t)
7270 (if (and (looking-at
7271 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7272 (= (setq n (1- n)) 0))
7273 (throw 'exit (match-string 1))))))))
7274 (if txt
7275 (progn
7276 (if (and org-table-copy-increment
7277 (string-match "^[0-9]+$" txt))
7278 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7279 (insert txt)
7280 (move-to-column col)
7281 (if (and org-table-copy-increment (org-at-timestamp-p t))
7282 (org-timestamp-up 1)
7283 (org-table-maybe-recalculate-line))
7284 (org-table-align)
7285 (move-to-column col))
7286 (error "No non-empty field found"))))
7288 (defun org-table-check-inside-data-field ()
7289 "Is point inside a table data field?
7290 I.e. not on a hline or before the first or after the last column?
7291 This actually throws an error, so it aborts the current command."
7292 (if (or (not (org-at-table-p))
7293 (= (org-table-current-column) 0)
7294 (org-at-table-hline-p)
7295 (looking-at "[ \t]*$"))
7296 (error "Not in table data field")))
7298 (defvar org-table-clip nil
7299 "Clipboard for table regions.")
7301 (defun org-table-blank-field ()
7302 "Blank the current table field or active region."
7303 (interactive)
7304 (org-table-check-inside-data-field)
7305 (if (and (interactive-p) (org-region-active-p))
7306 (let (org-table-clip)
7307 (org-table-cut-region (region-beginning) (region-end)))
7308 (skip-chars-backward "^|")
7309 (backward-char 1)
7310 (if (looking-at "|[^|\n]+")
7311 (let* ((pos (match-beginning 0))
7312 (match (match-string 0))
7313 (len (org-string-width match)))
7314 (replace-match (concat "|" (make-string (1- len) ?\ )))
7315 (goto-char (+ 2 pos))
7316 (substring match 1)))))
7318 (defun org-table-get-field (&optional n replace)
7319 "Return the value of the field in column N of current row.
7320 N defaults to current field.
7321 If REPLACE is a string, replace field with this value. The return value
7322 is always the old value."
7323 (and n (org-table-goto-column n))
7324 (skip-chars-backward "^|\n")
7325 (backward-char 1)
7326 (if (looking-at "|[^|\r\n]*")
7327 (let* ((pos (match-beginning 0))
7328 (val (buffer-substring (1+ pos) (match-end 0))))
7329 (if replace
7330 (replace-match (concat "|" replace) t t))
7331 (goto-char (min (point-at-eol) (+ 2 pos)))
7332 val)
7333 (forward-char 1) ""))
7335 (defun org-table-field-info (arg)
7336 "Show info about the current field, and highlight any reference at point."
7337 (interactive "P")
7338 (org-table-get-specials)
7339 (save-excursion
7340 (let* ((pos (point))
7341 (col (org-table-current-column))
7342 (cname (car (rassoc (int-to-string col) org-table-column-names)))
7343 (name (car (rassoc (list (org-current-line) col)
7344 org-table-named-field-locations)))
7345 (eql (org-table-get-stored-formulas))
7346 (dline (org-table-current-dline))
7347 (ref (format "@%d$%d" dline col))
7348 (ref1 (org-table-convert-refs-to-an ref))
7349 (fequation (or (assoc name eql) (assoc ref eql)))
7350 (cequation (assoc (int-to-string col) eql))
7351 (eqn (or fequation cequation)))
7352 (goto-char pos)
7353 (condition-case nil
7354 (org-table-show-reference 'local)
7355 (error nil))
7356 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
7357 dline col
7358 (if cname (concat " or $" cname) "")
7359 dline col ref1
7360 (if name (concat " or $" name) "")
7361 ;; FIXME: formula info not correct if special table line
7362 (if eqn
7363 (concat ", formula: "
7364 (org-table-formula-to-user
7365 (concat
7366 (if (string-match "^[$@]"(car eqn)) "" "$")
7367 (car eqn) "=" (cdr eqn))))
7368 "")))))
7370 (defun org-table-current-column ()
7371 "Find out which column we are in.
7372 When called interactively, column is also displayed in echo area."
7373 (interactive)
7374 (if (interactive-p) (org-table-check-inside-data-field))
7375 (save-excursion
7376 (let ((cnt 0) (pos (point)))
7377 (beginning-of-line 1)
7378 (while (search-forward "|" pos t)
7379 (setq cnt (1+ cnt)))
7380 (if (interactive-p) (message "This is table column %d" cnt))
7381 cnt)))
7383 (defun org-table-current-dline ()
7384 "Find out what table data line we are in.
7385 Only datalins count for this."
7386 (interactive)
7387 (if (interactive-p) (org-table-check-inside-data-field))
7388 (save-excursion
7389 (let ((cnt 0) (pos (point)))
7390 (goto-char (org-table-begin))
7391 (while (<= (point) pos)
7392 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
7393 (beginning-of-line 2))
7394 (if (interactive-p) (message "This is table line %d" cnt))
7395 cnt)))
7397 (defun org-table-goto-column (n &optional on-delim force)
7398 "Move the cursor to the Nth column in the current table line.
7399 With optional argument ON-DELIM, stop with point before the left delimiter
7400 of the field.
7401 If there are less than N fields, just go to after the last delimiter.
7402 However, when FORCE is non-nil, create new columns if necessary."
7403 (interactive "p")
7404 (let ((pos (point-at-eol)))
7405 (beginning-of-line 1)
7406 (when (> n 0)
7407 (while (and (> (setq n (1- n)) -1)
7408 (or (search-forward "|" pos t)
7409 (and force
7410 (progn (end-of-line 1)
7411 (skip-chars-backward "^|")
7412 (insert " | "))))))
7413 ; (backward-char 2) t)))))
7414 (when (and force (not (looking-at ".*|")))
7415 (save-excursion (end-of-line 1) (insert " | ")))
7416 (if on-delim
7417 (backward-char 1)
7418 (if (looking-at " ") (forward-char 1))))))
7420 (defun org-at-table-p (&optional table-type)
7421 "Return t if the cursor is inside an org-type table.
7422 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7423 (if org-enable-table-editor
7424 (save-excursion
7425 (beginning-of-line 1)
7426 (looking-at (if table-type org-table-any-line-regexp
7427 org-table-line-regexp)))
7428 nil))
7430 (defun org-at-table.el-p ()
7431 "Return t if and only if we are at a table.el table."
7432 (and (org-at-table-p 'any)
7433 (save-excursion
7434 (goto-char (org-table-begin 'any))
7435 (looking-at org-table1-hline-regexp))))
7437 (defun org-table-recognize-table.el ()
7438 "If there is a table.el table nearby, recognize it and move into it."
7439 (if org-table-tab-recognizes-table.el
7440 (if (org-at-table.el-p)
7441 (progn
7442 (beginning-of-line 1)
7443 (if (looking-at org-table-dataline-regexp)
7445 (if (looking-at org-table1-hline-regexp)
7446 (progn
7447 (beginning-of-line 2)
7448 (if (looking-at org-table-any-border-regexp)
7449 (beginning-of-line -1)))))
7450 (if (re-search-forward "|" (org-table-end t) t)
7451 (progn
7452 (require 'table)
7453 (if (table--at-cell-p (point))
7455 (message "recognizing table.el table...")
7456 (table-recognize-table)
7457 (message "recognizing table.el table...done")))
7458 (error "This should not happen..."))
7460 nil)
7461 nil))
7463 (defun org-at-table-hline-p ()
7464 "Return t if the cursor is inside a hline in a table."
7465 (if org-enable-table-editor
7466 (save-excursion
7467 (beginning-of-line 1)
7468 (looking-at org-table-hline-regexp))
7469 nil))
7471 (defun org-table-insert-column ()
7472 "Insert a new column into the table."
7473 (interactive)
7474 (if (not (org-at-table-p))
7475 (error "Not at a table"))
7476 (org-table-find-dataline)
7477 (let* ((col (max 1 (org-table-current-column)))
7478 (beg (org-table-begin))
7479 (end (org-table-end))
7480 ;; Current cursor position
7481 (linepos (org-current-line))
7482 (colpos col))
7483 (goto-char beg)
7484 (while (< (point) end)
7485 (if (org-at-table-hline-p)
7487 (org-table-goto-column col t)
7488 (insert "| "))
7489 (beginning-of-line 2))
7490 (move-marker end nil)
7491 (goto-line linepos)
7492 (org-table-goto-column colpos)
7493 (org-table-align)
7494 (org-table-fix-formulas "$" nil (1- col) 1)))
7496 (defun org-table-find-dataline ()
7497 "Find a dataline in the current table, which is needed for column commands."
7498 (if (and (org-at-table-p)
7499 (not (org-at-table-hline-p)))
7501 (let ((col (current-column))
7502 (end (org-table-end)))
7503 (move-to-column col)
7504 (while (and (< (point) end)
7505 (or (not (= (current-column) col))
7506 (org-at-table-hline-p)))
7507 (beginning-of-line 2)
7508 (move-to-column col))
7509 (if (and (org-at-table-p)
7510 (not (org-at-table-hline-p)))
7512 (error
7513 "Please position cursor in a data line for column operations")))))
7515 (defun org-table-delete-column ()
7516 "Delete a column from the table."
7517 (interactive)
7518 (if (not (org-at-table-p))
7519 (error "Not at a table"))
7520 (org-table-find-dataline)
7521 (org-table-check-inside-data-field)
7522 (let* ((col (org-table-current-column))
7523 (beg (org-table-begin))
7524 (end (org-table-end))
7525 ;; Current cursor position
7526 (linepos (org-current-line))
7527 (colpos col))
7528 (goto-char beg)
7529 (while (< (point) end)
7530 (if (org-at-table-hline-p)
7532 (org-table-goto-column col t)
7533 (and (looking-at "|[^|\n]+|")
7534 (replace-match "|")))
7535 (beginning-of-line 2))
7536 (move-marker end nil)
7537 (goto-line linepos)
7538 (org-table-goto-column colpos)
7539 (org-table-align)
7540 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
7541 col -1 col)))
7543 (defun org-table-move-column-right ()
7544 "Move column to the right."
7545 (interactive)
7546 (org-table-move-column nil))
7547 (defun org-table-move-column-left ()
7548 "Move column to the left."
7549 (interactive)
7550 (org-table-move-column 'left))
7552 (defun org-table-move-column (&optional left)
7553 "Move the current column to the right. With arg LEFT, move to the left."
7554 (interactive "P")
7555 (if (not (org-at-table-p))
7556 (error "Not at a table"))
7557 (org-table-find-dataline)
7558 (org-table-check-inside-data-field)
7559 (let* ((col (org-table-current-column))
7560 (col1 (if left (1- col) col))
7561 (beg (org-table-begin))
7562 (end (org-table-end))
7563 ;; Current cursor position
7564 (linepos (org-current-line))
7565 (colpos (if left (1- col) (1+ col))))
7566 (if (and left (= col 1))
7567 (error "Cannot move column further left"))
7568 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
7569 (error "Cannot move column further right"))
7570 (goto-char beg)
7571 (while (< (point) end)
7572 (if (org-at-table-hline-p)
7574 (org-table-goto-column col1 t)
7575 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
7576 (replace-match "|\\2|\\1|")))
7577 (beginning-of-line 2))
7578 (move-marker end nil)
7579 (goto-line linepos)
7580 (org-table-goto-column colpos)
7581 (org-table-align)
7582 (org-table-fix-formulas
7583 "$" (list (cons (number-to-string col) (number-to-string colpos))
7584 (cons (number-to-string colpos) (number-to-string col))))))
7586 (defun org-table-move-row-down ()
7587 "Move table row down."
7588 (interactive)
7589 (org-table-move-row nil))
7590 (defun org-table-move-row-up ()
7591 "Move table row up."
7592 (interactive)
7593 (org-table-move-row 'up))
7595 (defun org-table-move-row (&optional up)
7596 "Move the current table line down. With arg UP, move it up."
7597 (interactive "P")
7598 (let* ((col (current-column))
7599 (pos (point))
7600 (hline1p (save-excursion (beginning-of-line 1)
7601 (looking-at org-table-hline-regexp)))
7602 (dline1 (org-table-current-dline))
7603 (dline2 (+ dline1 (if up -1 1)))
7604 (tonew (if up 0 2))
7605 txt hline2p)
7606 (beginning-of-line tonew)
7607 (unless (org-at-table-p)
7608 (goto-char pos)
7609 (error "Cannot move row further"))
7610 (setq hline2p (looking-at org-table-hline-regexp))
7611 (goto-char pos)
7612 (beginning-of-line 1)
7613 (setq pos (point))
7614 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
7615 (delete-region (point) (1+ (point-at-eol)))
7616 (beginning-of-line tonew)
7617 (insert txt)
7618 (beginning-of-line 0)
7619 (move-to-column col)
7620 (unless (or hline1p hline2p)
7621 (org-table-fix-formulas
7622 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
7623 (cons (number-to-string dline2) (number-to-string dline1)))))))
7625 (defun org-table-insert-row (&optional arg)
7626 "Insert a new row above the current line into the table.
7627 With prefix ARG, insert below the current line."
7628 (interactive "P")
7629 (if (not (org-at-table-p))
7630 (error "Not at a table"))
7631 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
7632 (new (org-table-clean-line line)))
7633 ;; Fix the first field if necessary
7634 (if (string-match "^[ \t]*| *[#$] *|" line)
7635 (setq new (replace-match (match-string 0 line) t t new)))
7636 (beginning-of-line (if arg 2 1))
7637 (let (org-table-may-need-update) (insert-before-markers new "\n"))
7638 (beginning-of-line 0)
7639 (re-search-forward "| ?" (point-at-eol) t)
7640 (and (or org-table-may-need-update org-table-overlay-coordinates)
7641 (org-table-align))
7642 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
7644 (defun org-table-insert-hline (&optional above)
7645 "Insert a horizontal-line below the current line into the table.
7646 With prefix ABOVE, insert above the current line."
7647 (interactive "P")
7648 (if (not (org-at-table-p))
7649 (error "Not at a table"))
7650 (let ((line (org-table-clean-line
7651 (buffer-substring (point-at-bol) (point-at-eol))))
7652 (col (current-column)))
7653 (while (string-match "|\\( +\\)|" line)
7654 (setq line (replace-match
7655 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
7656 ?-) "|") t t line)))
7657 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
7658 (beginning-of-line (if above 1 2))
7659 (insert line "\n")
7660 (beginning-of-line (if above 1 -1))
7661 (move-to-column col)
7662 (and org-table-overlay-coordinates (org-table-align))))
7664 (defun org-table-hline-and-move (&optional same-column)
7665 "Insert a hline and move to the row below that line."
7666 (interactive "P")
7667 (let ((col (org-table-current-column)))
7668 (org-table-maybe-eval-formula)
7669 (org-table-maybe-recalculate-line)
7670 (org-table-insert-hline)
7671 (end-of-line 2)
7672 (if (looking-at "\n[ \t]*|-")
7673 (progn (insert "\n|") (org-table-align))
7674 (org-table-next-field))
7675 (if same-column (org-table-goto-column col))))
7677 (defun org-table-clean-line (s)
7678 "Convert a table line S into a string with only \"|\" and space.
7679 In particular, this does handle wide and invisible characters."
7680 (if (string-match "^[ \t]*|-" s)
7681 ;; It's a hline, just map the characters
7682 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
7683 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
7684 (setq s (replace-match
7685 (concat "|" (make-string (org-string-width (match-string 1 s))
7686 ?\ ) "|")
7687 t t s)))
7690 (defun org-table-kill-row ()
7691 "Delete the current row or horizontal line from the table."
7692 (interactive)
7693 (if (not (org-at-table-p))
7694 (error "Not at a table"))
7695 (let ((col (current-column))
7696 (dline (org-table-current-dline)))
7697 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
7698 (if (not (org-at-table-p)) (beginning-of-line 0))
7699 (move-to-column col)
7700 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
7701 dline -1 dline)))
7704 (defun org-table-sort-lines (with-case &optional sorting-type)
7705 "Sort table lines according to the column at point.
7707 The position of point indicates the column to be used for
7708 sorting, and the range of lines is the range between the nearest
7709 horizontal separator lines, or the entire table of no such lines
7710 exist. If point is before the first column, you will be prompted
7711 for the sorting column. If there is an active region, the mark
7712 specifies the first line and the sorting column, while point
7713 should be in the last line to be included into the sorting.
7715 The command then prompts for the sorting type which can be
7716 alphabetically, numerically, or by time (as given in a time stamp
7717 in the field). Sorting in reverse order is also possible.
7719 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
7721 If SORTING-TYPE is specified when this function is called from a Lisp
7722 program, no prompting will take place. SORTING-TYPE must be a character,
7723 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
7724 should be done in reverse order."
7725 (interactive "P")
7726 (let* ((thisline (org-current-line))
7727 (thiscol (org-table-current-column))
7728 beg end bcol ecol tend tbeg column lns pos)
7729 (when (equal thiscol 0)
7730 (if (interactive-p)
7731 (setq thiscol
7732 (string-to-number
7733 (read-string "Use column N for sorting: ")))
7734 (setq thiscol 1))
7735 (org-table-goto-column thiscol))
7736 (org-table-check-inside-data-field)
7737 (if (org-region-active-p)
7738 (progn
7739 (setq beg (region-beginning) end (region-end))
7740 (goto-char beg)
7741 (setq column (org-table-current-column)
7742 beg (point-at-bol))
7743 (goto-char end)
7744 (setq end (point-at-bol 2)))
7745 (setq column (org-table-current-column)
7746 pos (point)
7747 tbeg (org-table-begin)
7748 tend (org-table-end))
7749 (if (re-search-backward org-table-hline-regexp tbeg t)
7750 (setq beg (point-at-bol 2))
7751 (goto-char tbeg)
7752 (setq beg (point-at-bol 1)))
7753 (goto-char pos)
7754 (if (re-search-forward org-table-hline-regexp tend t)
7755 (setq end (point-at-bol 1))
7756 (goto-char tend)
7757 (setq end (point-at-bol))))
7758 (setq beg (move-marker (make-marker) beg)
7759 end (move-marker (make-marker) end))
7760 (untabify beg end)
7761 (goto-char beg)
7762 (org-table-goto-column column)
7763 (skip-chars-backward "^|")
7764 (setq bcol (current-column))
7765 (org-table-goto-column (1+ column))
7766 (skip-chars-backward "^|")
7767 (setq ecol (1- (current-column)))
7768 (org-table-goto-column column)
7769 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
7770 (org-split-string (buffer-substring beg end) "\n")))
7771 (setq lns (org-do-sort lns "Table" with-case sorting-type))
7772 (delete-region beg end)
7773 (move-marker beg nil)
7774 (move-marker end nil)
7775 (insert (mapconcat 'cdr lns "\n") "\n")
7776 (goto-line thisline)
7777 (org-table-goto-column thiscol)
7778 (message "%d lines sorted, based on column %d" (length lns) column)))
7780 (defun org-table-cut-region (beg end)
7781 "Copy region in table to the clipboard and blank all relevant fields."
7782 (interactive "r")
7783 (org-table-copy-region beg end 'cut))
7785 (defun org-table-copy-region (beg end &optional cut)
7786 "Copy rectangular region in table to clipboard.
7787 A special clipboard is used which can only be accessed
7788 with `org-table-paste-rectangle'."
7789 (interactive "rP")
7790 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
7791 region cols
7792 (rpl (if cut " " nil)))
7793 (goto-char beg)
7794 (org-table-check-inside-data-field)
7795 (setq l01 (org-current-line)
7796 c01 (org-table-current-column))
7797 (goto-char end)
7798 (org-table-check-inside-data-field)
7799 (setq l02 (org-current-line)
7800 c02 (org-table-current-column))
7801 (setq l1 (min l01 l02) l2 (max l01 l02)
7802 c1 (min c01 c02) c2 (max c01 c02))
7803 (catch 'exit
7804 (while t
7805 (catch 'nextline
7806 (if (> l1 l2) (throw 'exit t))
7807 (goto-line l1)
7808 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
7809 (setq cols nil ic1 c1 ic2 c2)
7810 (while (< ic1 (1+ ic2))
7811 (push (org-table-get-field ic1 rpl) cols)
7812 (setq ic1 (1+ ic1)))
7813 (push (nreverse cols) region)
7814 (setq l1 (1+ l1)))))
7815 (setq org-table-clip (nreverse region))
7816 (if cut (org-table-align))
7817 org-table-clip))
7819 (defun org-table-paste-rectangle ()
7820 "Paste a rectangular region into a table.
7821 The upper right corner ends up in the current field. All involved fields
7822 will be overwritten. If the rectangle does not fit into the present table,
7823 the table is enlarged as needed. The process ignores horizontal separator
7824 lines."
7825 (interactive)
7826 (unless (and org-table-clip (listp org-table-clip))
7827 (error "First cut/copy a region to paste!"))
7828 (org-table-check-inside-data-field)
7829 (let* ((clip org-table-clip)
7830 (line (org-current-line))
7831 (col (org-table-current-column))
7832 (org-enable-table-editor t)
7833 (org-table-automatic-realign nil)
7834 c cols field)
7835 (while (setq cols (pop clip))
7836 (while (org-at-table-hline-p) (beginning-of-line 2))
7837 (if (not (org-at-table-p))
7838 (progn (end-of-line 0) (org-table-next-field)))
7839 (setq c col)
7840 (while (setq field (pop cols))
7841 (org-table-goto-column c nil 'force)
7842 (org-table-get-field nil field)
7843 (setq c (1+ c)))
7844 (beginning-of-line 2))
7845 (goto-line line)
7846 (org-table-goto-column col)
7847 (org-table-align)))
7849 (defun org-table-convert ()
7850 "Convert from `org-mode' table to table.el and back.
7851 Obviously, this only works within limits. When an Org-mode table is
7852 converted to table.el, all horizontal separator lines get lost, because
7853 table.el uses these as cell boundaries and has no notion of horizontal lines.
7854 A table.el table can be converted to an Org-mode table only if it does not
7855 do row or column spanning. Multiline cells will become multiple cells.
7856 Beware, Org-mode does not test if the table can be successfully converted - it
7857 blindly applies a recipe that works for simple tables."
7858 (interactive)
7859 (require 'table)
7860 (if (org-at-table.el-p)
7861 ;; convert to Org-mode table
7862 (let ((beg (move-marker (make-marker) (org-table-begin t)))
7863 (end (move-marker (make-marker) (org-table-end t))))
7864 (table-unrecognize-region beg end)
7865 (goto-char beg)
7866 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
7867 (replace-match ""))
7868 (goto-char beg))
7869 (if (org-at-table-p)
7870 ;; convert to table.el table
7871 (let ((beg (move-marker (make-marker) (org-table-begin)))
7872 (end (move-marker (make-marker) (org-table-end))))
7873 ;; first, get rid of all horizontal lines
7874 (goto-char beg)
7875 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
7876 (replace-match ""))
7877 ;; insert a hline before first
7878 (goto-char beg)
7879 (org-table-insert-hline 'above)
7880 (beginning-of-line -1)
7881 ;; insert a hline after each line
7882 (while (progn (beginning-of-line 3) (< (point) end))
7883 (org-table-insert-hline))
7884 (goto-char beg)
7885 (setq end (move-marker end (org-table-end)))
7886 ;; replace "+" at beginning and ending of hlines
7887 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
7888 (replace-match "\\1+-"))
7889 (goto-char beg)
7890 (while (re-search-forward "-|[ \t]*$" end t)
7891 (replace-match "-+"))
7892 (goto-char beg)))))
7894 (defun org-table-wrap-region (arg)
7895 "Wrap several fields in a column like a paragraph.
7896 This is useful if you'd like to spread the contents of a field over several
7897 lines, in order to keep the table compact.
7899 If there is an active region, and both point and mark are in the same column,
7900 the text in the column is wrapped to minimum width for the given number of
7901 lines. Generally, this makes the table more compact. A prefix ARG may be
7902 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
7903 formats the selected text to two lines. If the region was longer than two
7904 lines, the remaining lines remain empty. A negative prefix argument reduces
7905 the current number of lines by that amount. The wrapped text is pasted back
7906 into the table. If you formatted it to more lines than it was before, fields
7907 further down in the table get overwritten - so you might need to make space in
7908 the table first.
7910 If there is no region, the current field is split at the cursor position and
7911 the text fragment to the right of the cursor is prepended to the field one
7912 line down.
7914 If there is no region, but you specify a prefix ARG, the current field gets
7915 blank, and the content is appended to the field above."
7916 (interactive "P")
7917 (org-table-check-inside-data-field)
7918 (if (org-region-active-p)
7919 ;; There is a region: fill as a paragraph
7920 (let* ((beg (region-beginning))
7921 (cline (save-excursion (goto-char beg) (org-current-line)))
7922 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
7923 nlines)
7924 (org-table-cut-region (region-beginning) (region-end))
7925 (if (> (length (car org-table-clip)) 1)
7926 (error "Region must be limited to single column"))
7927 (setq nlines (if arg
7928 (if (< arg 1)
7929 (+ (length org-table-clip) arg)
7930 arg)
7931 (length org-table-clip)))
7932 (setq org-table-clip
7933 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
7934 nil nlines)))
7935 (goto-line cline)
7936 (org-table-goto-column ccol)
7937 (org-table-paste-rectangle))
7938 ;; No region, split the current field at point
7939 (if arg
7940 ;; combine with field above
7941 (let ((s (org-table-blank-field))
7942 (col (org-table-current-column)))
7943 (beginning-of-line 0)
7944 (while (org-at-table-hline-p) (beginning-of-line 0))
7945 (org-table-goto-column col)
7946 (skip-chars-forward "^|")
7947 (skip-chars-backward " ")
7948 (insert " " (org-trim s))
7949 (org-table-align))
7950 ;; split field
7951 (when (looking-at "\\([^|]+\\)+|")
7952 (let ((s (match-string 1)))
7953 (replace-match " |")
7954 (goto-char (match-beginning 0))
7955 (org-table-next-row)
7956 (insert (org-trim s) " ")
7957 (org-table-align))))))
7959 (defvar org-field-marker nil)
7961 (defun org-table-edit-field (arg)
7962 "Edit table field in a different window.
7963 This is mainly useful for fields that contain hidden parts.
7964 When called with a \\[universal-argument] prefix, just make the full field visible so that
7965 it can be edited in place."
7966 (interactive "P")
7967 (if arg
7968 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
7969 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
7970 (remove-text-properties b e '(org-cwidth t invisible t
7971 display t intangible t))
7972 (if (and (boundp 'font-lock-mode) font-lock-mode)
7973 (font-lock-fontify-block)))
7974 (let ((pos (move-marker (make-marker) (point)))
7975 (field (org-table-get-field))
7976 (cw (current-window-configuration))
7978 (switch-to-buffer-other-window "*Org tmp*")
7979 (erase-buffer)
7980 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
7981 (let ((org-inhibit-startup t)) (org-mode))
7982 (goto-char (setq p (point-max)))
7983 (insert (org-trim field))
7984 (remove-text-properties p (point-max)
7985 '(invisible t org-cwidth t display t
7986 intangible t))
7987 (goto-char p)
7988 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
7989 (org-set-local 'org-window-configuration cw)
7990 (org-set-local 'org-field-marker pos)
7991 (message "Edit and finish with C-c C-c"))))
7993 (defun org-table-finish-edit-field ()
7994 "Finish editing a table data field.
7995 Remove all newline characters, insert the result into the table, realign
7996 the table and kill the editing buffer."
7997 (let ((pos org-field-marker)
7998 (cw org-window-configuration)
7999 (cb (current-buffer))
8000 text)
8001 (goto-char (point-min))
8002 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8003 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8004 (replace-match " "))
8005 (setq text (org-trim (buffer-string)))
8006 (set-window-configuration cw)
8007 (kill-buffer cb)
8008 (select-window (get-buffer-window (marker-buffer pos)))
8009 (goto-char pos)
8010 (move-marker pos nil)
8011 (org-table-check-inside-data-field)
8012 (org-table-get-field nil text)
8013 (org-table-align)
8014 (message "New field value inserted")))
8016 (defun org-trim (s)
8017 "Remove whitespace at beginning and end of string."
8018 (if (string-match "^[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8019 (if (string-match "[ \t\n\r]+$" s) (setq s (replace-match "" t t s)))
8022 (defun org-wrap (string &optional width lines)
8023 "Wrap string to either a number of lines, or a width in characters.
8024 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8025 that costs. If there is a word longer than WIDTH, the text is actually
8026 wrapped to the length of that word.
8027 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8028 many lines, whatever width that takes.
8029 The return value is a list of lines, without newlines at the end."
8030 (let* ((words (org-split-string string "[ \t\n]+"))
8031 (maxword (apply 'max (mapcar 'org-string-width words)))
8032 w ll)
8033 (cond (width
8034 (org-do-wrap words (max maxword width)))
8035 (lines
8036 (setq w maxword)
8037 (setq ll (org-do-wrap words maxword))
8038 (if (<= (length ll) lines)
8040 (setq ll words)
8041 (while (> (length ll) lines)
8042 (setq w (1+ w))
8043 (setq ll (org-do-wrap words w)))
8044 ll))
8045 (t (error "Cannot wrap this")))))
8048 (defun org-do-wrap (words width)
8049 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8050 (let (lines line)
8051 (while words
8052 (setq line (pop words))
8053 (while (and words (< (+ (length line) (length (car words))) width))
8054 (setq line (concat line " " (pop words))))
8055 (setq lines (push line lines)))
8056 (nreverse lines)))
8058 (defun org-split-string (string &optional separators)
8059 "Splits STRING into substrings at SEPARATORS.
8060 No empty strings are returned if there are matches at the beginning
8061 and end of string."
8062 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8063 (start 0)
8064 notfirst
8065 (list nil))
8066 (while (and (string-match rexp string
8067 (if (and notfirst
8068 (= start (match-beginning 0))
8069 (< start (length string)))
8070 (1+ start) start))
8071 (< (match-beginning 0) (length string)))
8072 (setq notfirst t)
8073 (or (eq (match-beginning 0) 0)
8074 (and (eq (match-beginning 0) (match-end 0))
8075 (eq (match-beginning 0) start))
8076 (setq list
8077 (cons (substring string start (match-beginning 0))
8078 list)))
8079 (setq start (match-end 0)))
8080 (or (eq start (length string))
8081 (setq list
8082 (cons (substring string start)
8083 list)))
8084 (nreverse list)))
8086 (defun org-table-map-tables (function)
8087 "Apply FUNCTION to the start of all tables in the buffer."
8088 (save-excursion
8089 (save-restriction
8090 (widen)
8091 (goto-char (point-min))
8092 (while (re-search-forward org-table-any-line-regexp nil t)
8093 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8094 (beginning-of-line 1)
8095 (if (looking-at org-table-line-regexp)
8096 (save-excursion (funcall function)))
8097 (re-search-forward org-table-any-border-regexp nil 1))))
8098 (message "Mapping tables: done"))
8100 (defvar org-timecnt) ; dynamically scoped parameter
8102 (defun org-table-sum (&optional beg end nlast)
8103 "Sum numbers in region of current table column.
8104 The result will be displayed in the echo area, and will be available
8105 as kill to be inserted with \\[yank].
8107 If there is an active region, it is interpreted as a rectangle and all
8108 numbers in that rectangle will be summed. If there is no active
8109 region and point is located in a table column, sum all numbers in that
8110 column.
8112 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8113 numbers are assumed to be times as well (in decimal hours) and the
8114 numbers are added as such.
8116 If NLAST is a number, only the NLAST fields will actually be summed."
8117 (interactive)
8118 (save-excursion
8119 (let (col (org-timecnt 0) diff h m s org-table-clip)
8120 (cond
8121 ((and beg end)) ; beg and end given explicitly
8122 ((org-region-active-p)
8123 (setq beg (region-beginning) end (region-end)))
8125 (setq col (org-table-current-column))
8126 (goto-char (org-table-begin))
8127 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8128 (error "No table data"))
8129 (org-table-goto-column col)
8130 (setq beg (point))
8131 (goto-char (org-table-end))
8132 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8133 (error "No table data"))
8134 (org-table-goto-column col)
8135 (setq end (point))))
8136 (let* ((items (apply 'append (org-table-copy-region beg end)))
8137 (items1 (cond ((not nlast) items)
8138 ((>= nlast (length items)) items)
8139 (t (setq items (reverse items))
8140 (setcdr (nthcdr (1- nlast) items) nil)
8141 (nreverse items))))
8142 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8143 items1)))
8144 (res (apply '+ numbers))
8145 (sres (if (= org-timecnt 0)
8146 (format "%g" res)
8147 (setq diff (* 3600 res)
8148 h (floor (/ diff 3600)) diff (mod diff 3600)
8149 m (floor (/ diff 60)) diff (mod diff 60)
8150 s diff)
8151 (format "%d:%02d:%02d" h m s))))
8152 (kill-new sres)
8153 (if (interactive-p)
8154 (message "%s"
8155 (substitute-command-keys
8156 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8157 (length numbers) sres))))
8158 sres))))
8160 (defun org-table-get-number-for-summing (s)
8161 (let (n)
8162 (if (string-match "^ *|? *" s)
8163 (setq s (replace-match "" nil nil s)))
8164 (if (string-match " *|? *$" s)
8165 (setq s (replace-match "" nil nil s)))
8166 (setq n (string-to-number s))
8167 (cond
8168 ((and (string-match "0" s)
8169 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8170 ((string-match "\\`[ \t]+\\'" s) nil)
8171 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8172 (let ((h (string-to-number (or (match-string 1 s) "0")))
8173 (m (string-to-number (or (match-string 2 s) "0")))
8174 (s (string-to-number (or (match-string 4 s) "0"))))
8175 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8176 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8177 ((equal n 0) nil)
8178 (t n))))
8180 (defun org-table-current-field-formula (&optional key noerror)
8181 "Return the formula active for the current field.
8182 Assumes that specials are in place.
8183 If KEY is given, return the key to this formula.
8184 Otherwise return the formula preceeded with \"=\" or \":=\"."
8185 (let* ((name (car (rassoc (list (org-current-line)
8186 (org-table-current-column))
8187 org-table-named-field-locations)))
8188 (col (org-table-current-column))
8189 (scol (int-to-string col))
8190 (ref (format "@%d$%d" (org-table-current-dline) col))
8191 (stored-list (org-table-get-stored-formulas noerror))
8192 (ass (or (assoc name stored-list)
8193 (assoc ref stored-list)
8194 (assoc scol stored-list))))
8195 (if key
8196 (car ass)
8197 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8198 (cdr ass))))))
8200 (defun org-table-get-formula (&optional equation named)
8201 "Read a formula from the minibuffer, offer stored formula as default.
8202 When NAMED is non-nil, look for a named equation."
8203 (let* ((stored-list (org-table-get-stored-formulas))
8204 (name (car (rassoc (list (org-current-line)
8205 (org-table-current-column))
8206 org-table-named-field-locations)))
8207 (ref (format "@%d$%d" (org-table-current-dline)
8208 (org-table-current-column)))
8209 (refass (assoc ref stored-list))
8210 (scol (if named
8211 (if name name ref)
8212 (int-to-string (org-table-current-column))))
8213 (dummy (and (or name refass) (not named)
8214 (not (y-or-n-p "Replace field formula with column formula? " ))
8215 (error "Abort")))
8216 (name (or name ref))
8217 (org-table-may-need-update nil)
8218 (stored (cdr (assoc scol stored-list)))
8219 (eq (cond
8220 ((and stored equation (string-match "^ *=? *$" equation))
8221 stored)
8222 ((stringp equation)
8223 equation)
8224 (t (org-table-formula-from-user
8225 (read-string
8226 (org-table-formula-to-user
8227 (format "%s formula %s%s="
8228 (if named "Field" "Column")
8229 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
8230 scol))
8231 (if stored (org-table-formula-to-user stored) "")
8232 'org-table-formula-history
8233 )))))
8234 mustsave)
8235 (when (not (string-match "\\S-" eq))
8236 ;; remove formula
8237 (setq stored-list (delq (assoc scol stored-list) stored-list))
8238 (org-table-store-formulas stored-list)
8239 (error "Formula removed"))
8240 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8241 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8242 (if (and name (not named))
8243 ;; We set the column equation, delete the named one.
8244 (setq stored-list (delq (assoc name stored-list) stored-list)
8245 mustsave t))
8246 (if stored
8247 (setcdr (assoc scol stored-list) eq)
8248 (setq stored-list (cons (cons scol eq) stored-list)))
8249 (if (or mustsave (not (equal stored eq)))
8250 (org-table-store-formulas stored-list))
8251 eq))
8253 (defun org-table-store-formulas (alist)
8254 "Store the list of formulas below the current table."
8255 (setq alist (sort alist 'org-table-formula-less-p))
8256 (save-excursion
8257 (goto-char (org-table-end))
8258 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
8259 (progn
8260 ;; don't overwrite TBLFM, we might use text properties to store stuff
8261 (goto-char (match-beginning 2))
8262 (delete-region (match-beginning 2) (match-end 0)))
8263 (insert "#+TBLFM:"))
8264 (insert " "
8265 (mapconcat (lambda (x)
8266 (concat
8267 (if (equal (string-to-char (car x)) ?@) "" "$")
8268 (car x) "=" (cdr x)))
8269 alist "::")
8270 "\n")))
8272 (defsubst org-table-formula-make-cmp-string (a)
8273 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
8274 (concat
8275 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
8276 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
8277 (if (match-end 5) (concat "@@" (match-string 5 a))))))
8279 (defun org-table-formula-less-p (a b)
8280 "Compare two formulas for sorting."
8281 (let ((as (org-table-formula-make-cmp-string (car a)))
8282 (bs (org-table-formula-make-cmp-string (car b))))
8283 (and as bs (string< as bs))))
8285 (defun org-table-get-stored-formulas (&optional noerror)
8286 "Return an alist with the stored formulas directly after current table."
8287 (interactive)
8288 (let (scol eq eq-alist strings string seen)
8289 (save-excursion
8290 (goto-char (org-table-end))
8291 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8292 (setq strings (org-split-string (match-string 2) " *:: *"))
8293 (while (setq string (pop strings))
8294 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
8295 (setq scol (if (match-end 2)
8296 (match-string 2 string)
8297 (match-string 1 string))
8298 eq (match-string 3 string)
8299 eq-alist (cons (cons scol eq) eq-alist))
8300 (if (member scol seen)
8301 (if noerror
8302 (progn
8303 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8304 (ding)
8305 (sit-for 2))
8306 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
8307 (push scol seen))))))
8308 (nreverse eq-alist)))
8310 (defun org-table-fix-formulas (key replace &optional limit delta remove)
8311 "Modify the equations after the table structure has been edited.
8312 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
8313 For all numbers larger than LIMIT, shift them by DELTA."
8314 (save-excursion
8315 (goto-char (org-table-end))
8316 (when (looking-at "#\\+TBLFM:")
8317 (let ((re (concat key "\\([0-9]+\\)"))
8318 (re2
8319 (when remove
8320 (if (equal key "$")
8321 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
8322 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
8323 s n a)
8324 (when remove
8325 (while (re-search-forward re2 (point-at-eol) t)
8326 (replace-match "")))
8327 (while (re-search-forward re (point-at-eol) t)
8328 (setq s (match-string 1) n (string-to-number s))
8329 (cond
8330 ((setq a (assoc s replace))
8331 (replace-match (concat key (cdr a)) t t))
8332 ((and limit (> n limit))
8333 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
8335 (defun org-table-get-specials ()
8336 "Get the column names and local parameters for this table."
8337 (save-excursion
8338 (let ((beg (org-table-begin)) (end (org-table-end))
8339 names name fields fields1 field cnt
8340 c v l line col types dlines hlines)
8341 (setq org-table-column-names nil
8342 org-table-local-parameters nil
8343 org-table-named-field-locations nil
8344 org-table-current-begin-line nil
8345 org-table-current-begin-pos nil
8346 org-table-current-line-types nil)
8347 (goto-char beg)
8348 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8349 (setq names (org-split-string (match-string 1) " *| *")
8350 cnt 1)
8351 (while (setq name (pop names))
8352 (setq cnt (1+ cnt))
8353 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8354 (push (cons name (int-to-string cnt)) org-table-column-names))))
8355 (setq org-table-column-names (nreverse org-table-column-names))
8356 (setq org-table-column-name-regexp
8357 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8358 (goto-char beg)
8359 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8360 (setq fields (org-split-string (match-string 1) " *| *"))
8361 (while (setq field (pop fields))
8362 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8363 (push (cons (match-string 1 field) (match-string 2 field))
8364 org-table-local-parameters))))
8365 (goto-char beg)
8366 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8367 (setq c (match-string 1)
8368 fields (org-split-string (match-string 2) " *| *"))
8369 (save-excursion
8370 (beginning-of-line (if (equal c "_") 2 0))
8371 (setq line (org-current-line) col 1)
8372 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8373 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8374 (while (and fields1 (setq field (pop fields)))
8375 (setq v (pop fields1) col (1+ col))
8376 (when (and (stringp field) (stringp v)
8377 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8378 (push (cons field v) org-table-local-parameters)
8379 (push (list field line col) org-table-named-field-locations))))
8380 ;; Analyse the line types
8381 (goto-char beg)
8382 (setq org-table-current-begin-line (org-current-line)
8383 org-table-current-begin-pos (point)
8384 l org-table-current-begin-line)
8385 (while (looking-at "[ \t]*|\\(-\\)?")
8386 (push (if (match-end 1) 'hline 'dline) types)
8387 (if (match-end 1) (push l hlines) (push l dlines))
8388 (beginning-of-line 2)
8389 (setq l (1+ l)))
8390 (setq org-table-current-line-types (apply 'vector (nreverse types))
8391 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
8392 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
8394 (defun org-table-maybe-eval-formula ()
8395 "Check if the current field starts with \"=\" or \":=\".
8396 If yes, store the formula and apply it."
8397 ;; We already know we are in a table. Get field will only return a formula
8398 ;; when appropriate. It might return a separator line, but no problem.
8399 (when org-table-formula-evaluate-inline
8400 (let* ((field (org-trim (or (org-table-get-field) "")))
8401 named eq)
8402 (when (string-match "^:?=\\(.*\\)" field)
8403 (setq named (equal (string-to-char field) ?:)
8404 eq (match-string 1 field))
8405 (if (or (fboundp 'calc-eval)
8406 (equal (substring eq 0 (min 2 (length eq))) "'("))
8407 (org-table-eval-formula (if named '(4) nil)
8408 (org-table-formula-from-user eq))
8409 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
8411 (defvar org-recalc-commands nil
8412 "List of commands triggering the recalculation of a line.
8413 Will be filled automatically during use.")
8415 (defvar org-recalc-marks
8416 '((" " . "Unmarked: no special line, no automatic recalculation")
8417 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8418 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8419 ("!" . "Column name definition line. Reference in formula as $name.")
8420 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8421 ("_" . "Names for values in row below this one.")
8422 ("^" . "Names for values in row above this one.")))
8424 (defun org-table-rotate-recalc-marks (&optional newchar)
8425 "Rotate the recalculation mark in the first column.
8426 If in any row, the first field is not consistent with a mark,
8427 insert a new column for the markers.
8428 When there is an active region, change all the lines in the region,
8429 after prompting for the marking character.
8430 After each change, a message will be displayed indicating the meaning
8431 of the new mark."
8432 (interactive)
8433 (unless (org-at-table-p) (error "Not at a table"))
8434 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8435 (beg (org-table-begin))
8436 (end (org-table-end))
8437 (l (org-current-line))
8438 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8439 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8440 (have-col
8441 (save-excursion
8442 (goto-char beg)
8443 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8444 (col (org-table-current-column))
8445 (forcenew (car (assoc newchar org-recalc-marks)))
8446 epos new)
8447 (when l1
8448 (message "Change region to what mark? Type # * ! $ or SPC: ")
8449 (setq newchar (char-to-string (read-char-exclusive))
8450 forcenew (car (assoc newchar org-recalc-marks))))
8451 (if (and newchar (not forcenew))
8452 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8453 newchar))
8454 (if l1 (goto-line l1))
8455 (save-excursion
8456 (beginning-of-line 1)
8457 (unless (looking-at org-table-dataline-regexp)
8458 (error "Not at a table data line")))
8459 (unless have-col
8460 (org-table-goto-column 1)
8461 (org-table-insert-column)
8462 (org-table-goto-column (1+ col)))
8463 (setq epos (point-at-eol))
8464 (save-excursion
8465 (beginning-of-line 1)
8466 (org-table-get-field
8467 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8468 (concat " "
8469 (setq new (or forcenew
8470 (cadr (member (match-string 1) marks))))
8471 " ")
8472 " # ")))
8473 (if (and l1 l2)
8474 (progn
8475 (goto-line l1)
8476 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8477 (and (looking-at org-table-dataline-regexp)
8478 (org-table-get-field 1 (concat " " new " "))))
8479 (goto-line l1)))
8480 (if (not (= epos (point-at-eol))) (org-table-align))
8481 (goto-line l)
8482 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8484 (defun org-table-maybe-recalculate-line ()
8485 "Recompute the current line if marked for it, and if we haven't just done it."
8486 (interactive)
8487 (and org-table-allow-automatic-line-recalculation
8488 (not (and (memq last-command org-recalc-commands)
8489 (equal org-last-recalc-line (org-current-line))))
8490 (save-excursion (beginning-of-line 1)
8491 (looking-at org-table-auto-recalculate-regexp))
8492 (org-table-recalculate) t))
8494 (defvar org-table-formula-debug nil
8495 "Non-nil means, debug table formulas.
8496 When nil, simply write \"#ERROR\" in corrupted fields.")
8497 (make-variable-buffer-local 'org-table-formula-debug)
8499 (defvar modes)
8500 (defsubst org-set-calc-mode (var &optional value)
8501 (if (stringp var)
8502 (setq var (assoc var '(("D" calc-angle-mode deg)
8503 ("R" calc-angle-mode rad)
8504 ("F" calc-prefer-frac t)
8505 ("S" calc-symbolic-mode t)))
8506 value (nth 2 var) var (nth 1 var)))
8507 (if (memq var modes)
8508 (setcar (cdr (memq var modes)) value)
8509 (cons var (cons value modes)))
8510 modes)
8512 (defun org-table-eval-formula (&optional arg equation
8513 suppress-align suppress-const
8514 suppress-store suppress-analysis)
8515 "Replace the table field value at the cursor by the result of a calculation.
8517 This function makes use of Dave Gillespie's Calc package, in my view the
8518 most exciting program ever written for GNU Emacs. So you need to have Calc
8519 installed in order to use this function.
8521 In a table, this command replaces the value in the current field with the
8522 result of a formula. It also installs the formula as the \"current\" column
8523 formula, by storing it in a special line below the table. When called
8524 with a `C-u' prefix, the current field must ba a named field, and the
8525 formula is installed as valid in only this specific field.
8527 When called with two `C-u' prefixes, insert the active equation
8528 for the field back into the current field, so that it can be
8529 edited there. This is useful in order to use \\[org-table-show-reference]
8530 to check the referenced fields.
8532 When called, the command first prompts for a formula, which is read in
8533 the minibuffer. Previously entered formulas are available through the
8534 history list, and the last used formula is offered as a default.
8535 These stored formulas are adapted correctly when moving, inserting, or
8536 deleting columns with the corresponding commands.
8538 The formula can be any algebraic expression understood by the Calc package.
8539 For details, see the Org-mode manual.
8541 This function can also be called from Lisp programs and offers
8542 additional arguments: EQUATION can be the formula to apply. If this
8543 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8544 used to speed-up recursive calls by by-passing unnecessary aligns.
8545 SUPPRESS-CONST suppresses the interpretation of constants in the
8546 formula, assuming that this has been done already outside the function.
8547 SUPPRESS-STORE means the formula should not be stored, either because
8548 it is already stored, or because it is a modified equation that should
8549 not overwrite the stored one."
8550 (interactive "P")
8551 (org-table-check-inside-data-field)
8552 (or suppress-analysis (org-table-get-specials))
8553 (if (equal arg '(16))
8554 (let ((eq (org-table-current-field-formula)))
8555 (or eq (error "No equation active for current field"))
8556 (org-table-get-field nil eq)
8557 (org-table-align)
8558 (setq org-table-may-need-update t))
8559 (let* (fields
8560 (ndown (if (integerp arg) arg 1))
8561 (org-table-automatic-realign nil)
8562 (case-fold-search nil)
8563 (down (> ndown 1))
8564 (formula (if (and equation suppress-store)
8565 equation
8566 (org-table-get-formula equation (equal arg '(4)))))
8567 (n0 (org-table-current-column))
8568 (modes (copy-sequence org-calc-default-modes))
8569 (numbers nil) ; was a variable, now fixed default
8570 (keep-empty nil)
8571 n form form0 bw fmt x ev orig c lispp literal)
8572 ;; Parse the format string. Since we have a lot of modes, this is
8573 ;; a lot of work. However, I think calc still uses most of the time.
8574 (if (string-match ";" formula)
8575 (let ((tmp (org-split-string formula ";")))
8576 (setq formula (car tmp)
8577 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8578 (nth 1 tmp)))
8579 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
8580 (setq c (string-to-char (match-string 1 fmt))
8581 n (string-to-number (match-string 2 fmt)))
8582 (if (= c ?p)
8583 (setq modes (org-set-calc-mode 'calc-internal-prec n))
8584 (setq modes (org-set-calc-mode
8585 'calc-float-format
8586 (list (cdr (assoc c '((?n . float) (?f . fix)
8587 (?s . sci) (?e . eng))))
8588 n))))
8589 (setq fmt (replace-match "" t t fmt)))
8590 (if (string-match "[NT]" fmt)
8591 (setq numbers (equal (match-string 0 fmt) "N")
8592 fmt (replace-match "" t t fmt)))
8593 (if (string-match "L" fmt)
8594 (setq literal t
8595 fmt (replace-match "" t t fmt)))
8596 (if (string-match "E" fmt)
8597 (setq keep-empty t
8598 fmt (replace-match "" t t fmt)))
8599 (while (string-match "[DRFS]" fmt)
8600 (setq modes (org-set-calc-mode (match-string 0 fmt)))
8601 (setq fmt (replace-match "" t t fmt)))
8602 (unless (string-match "\\S-" fmt)
8603 (setq fmt nil))))
8604 (if (and (not suppress-const) org-table-formula-use-constants)
8605 (setq formula (org-table-formula-substitute-names formula)))
8606 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
8607 (while (> ndown 0)
8608 (setq fields (org-split-string
8609 (org-no-properties
8610 (buffer-substring (point-at-bol) (point-at-eol)))
8611 " *| *"))
8612 (if (eq numbers t)
8613 (setq fields (mapcar
8614 (lambda (x) (number-to-string (string-to-number x)))
8615 fields)))
8616 (setq ndown (1- ndown))
8617 (setq form (copy-sequence formula)
8618 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
8619 (if (and lispp literal) (setq lispp 'literal))
8620 ;; Check for old vertical references
8621 (setq form (org-rewrite-old-row-references form))
8622 ;; Insert complex ranges
8623 (while (string-match org-table-range-regexp form)
8624 (setq form
8625 (replace-match
8626 (save-match-data
8627 (org-table-make-reference
8628 (org-table-get-range (match-string 0 form) nil n0)
8629 keep-empty numbers lispp))
8630 t t form)))
8631 ;; Insert simple ranges
8632 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
8633 (setq form
8634 (replace-match
8635 (save-match-data
8636 (org-table-make-reference
8637 (org-sublist
8638 fields (string-to-number (match-string 1 form))
8639 (string-to-number (match-string 2 form)))
8640 keep-empty numbers lispp))
8641 t t form)))
8642 (setq form0 form)
8643 ;; Insert the references to fields in same row
8644 (while (string-match "\\$\\([0-9]+\\)" form)
8645 (setq n (string-to-number (match-string 1 form))
8646 x (nth (1- (if (= n 0) n0 n)) fields))
8647 (unless x (error "Invalid field specifier \"%s\""
8648 (match-string 0 form)))
8649 (setq form (replace-match
8650 (save-match-data
8651 (org-table-make-reference x nil numbers lispp))
8652 t t form)))
8654 (if lispp
8655 (setq ev (condition-case nil
8656 (eval (eval (read form)))
8657 (error "#ERROR"))
8658 ev (if (numberp ev) (number-to-string ev) ev))
8659 (or (fboundp 'calc-eval)
8660 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
8661 (setq ev (calc-eval (cons form modes)
8662 (if numbers 'num))))
8664 (when org-table-formula-debug
8665 (with-output-to-temp-buffer "*Substitution History*"
8666 (princ (format "Substitution history of formula
8667 Orig: %s
8668 $xyz-> %s
8669 @r$c-> %s
8670 $1-> %s\n" orig formula form0 form))
8671 (if (listp ev)
8672 (princ (format " %s^\nError: %s"
8673 (make-string (car ev) ?\-) (nth 1 ev)))
8674 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
8675 ev (or fmt "NONE")
8676 (if fmt (format fmt (string-to-number ev)) ev)))))
8677 (setq bw (get-buffer-window "*Substitution History*"))
8678 (shrink-window-if-larger-than-buffer bw)
8679 (unless (and (interactive-p) (not ndown))
8680 (unless (let (inhibit-redisplay)
8681 (y-or-n-p "Debugging Formula. Continue to next? "))
8682 (org-table-align)
8683 (error "Abort"))
8684 (delete-window bw)
8685 (message "")))
8686 (if (listp ev) (setq fmt nil ev "#ERROR"))
8687 (org-table-justify-field-maybe
8688 (if fmt (format fmt (string-to-number ev)) ev))
8689 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
8690 (call-interactively 'org-return)
8691 (setq ndown 0)))
8692 (and down (org-table-maybe-recalculate-line))
8693 (or suppress-align (and org-table-may-need-update
8694 (org-table-align))))))
8696 (defun org-table-put-field-property (prop value)
8697 (save-excursion
8698 (put-text-property (progn (skip-chars-backward "^|") (point))
8699 (progn (skip-chars-forward "^|") (point))
8700 prop value)))
8702 (defun org-table-get-range (desc &optional tbeg col highlight)
8703 "Get a calc vector from a column, accorting to descriptor DESC.
8704 Optional arguments TBEG and COL can give the beginning of the table and
8705 the current column, to avoid unnecessary parsing.
8706 HIGHLIGHT means, just highlight the range."
8707 (if (not (equal (string-to-char desc) ?@))
8708 (setq desc (concat "@" desc)))
8709 (save-excursion
8710 (or tbeg (setq tbeg (org-table-begin)))
8711 (or col (setq col (org-table-current-column)))
8712 (let ((thisline (org-current-line))
8713 beg end c1 c2 r1 r2 rangep tmp)
8714 (unless (string-match org-table-range-regexp desc)
8715 (error "Invalid table range specifier `%s'" desc))
8716 (setq rangep (match-end 3)
8717 r1 (and (match-end 1) (match-string 1 desc))
8718 r2 (and (match-end 4) (match-string 4 desc))
8719 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
8720 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
8722 (and c1 (setq c1 (+ (string-to-number c1)
8723 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
8724 (and c2 (setq c2 (+ (string-to-number c2)
8725 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
8726 (if (equal r1 "") (setq r1 nil))
8727 (if (equal r2 "") (setq r2 nil))
8728 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
8729 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
8730 ; (setq r2 (or r2 r1) c2 (or c2 c1))
8731 (if (not r1) (setq r1 thisline))
8732 (if (not r2) (setq r2 thisline))
8733 (if (not c1) (setq c1 col))
8734 (if (not c2) (setq c2 col))
8735 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
8736 ;; just one field
8737 (progn
8738 (goto-line r1)
8739 (while (not (looking-at org-table-dataline-regexp))
8740 (beginning-of-line 2))
8741 (prog1 (org-trim (org-table-get-field c1))
8742 (if highlight (org-table-highlight-rectangle (point) (point)))))
8743 ;; A range, return a vector
8744 ;; First sort the numbers to get a regular ractangle
8745 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
8746 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
8747 (goto-line r1)
8748 (while (not (looking-at org-table-dataline-regexp))
8749 (beginning-of-line 2))
8750 (org-table-goto-column c1)
8751 (setq beg (point))
8752 (goto-line r2)
8753 (while (not (looking-at org-table-dataline-regexp))
8754 (beginning-of-line 0))
8755 (org-table-goto-column c2)
8756 (setq end (point))
8757 (if highlight
8758 (org-table-highlight-rectangle
8759 beg (progn (skip-chars-forward "^|\n") (point))))
8760 ;; return string representation of calc vector
8761 (mapcar 'org-trim
8762 (apply 'append (org-table-copy-region beg end)))))))
8764 (defun org-table-get-descriptor-line (desc &optional cline bline table)
8765 "Analyze descriptor DESC and retrieve the corresponding line number.
8766 The cursor is currently in line CLINE, the table begins in line BLINE,
8767 and TABLE is a vector with line types."
8768 (if (string-match "^[0-9]+$" desc)
8769 (aref org-table-dlines (string-to-number desc))
8770 (setq cline (or cline (org-current-line))
8771 bline (or bline org-table-current-begin-line)
8772 table (or table org-table-current-line-types))
8773 (if (or
8774 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
8775 ;; 1 2 3 4 5 6
8776 (and (not (match-end 3)) (not (match-end 6)))
8777 (and (match-end 3) (match-end 6) (not (match-end 5))))
8778 (error "invalid row descriptor `%s'" desc))
8779 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
8780 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
8781 (odir (and (match-end 5) (match-string 5 desc)))
8782 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
8783 (i (- cline bline))
8784 (rel (and (match-end 6)
8785 (or (and (match-end 1) (not (match-end 3)))
8786 (match-end 5)))))
8787 (if (and hn (not hdir))
8788 (progn
8789 (setq i 0 hdir "+")
8790 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
8791 (if (and (not hn) on (not odir))
8792 (error "should never happen");;(aref org-table-dlines on)
8793 (if (and hn (> hn 0))
8794 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
8795 (if on
8796 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
8797 (+ bline i)))))
8799 (defun org-find-row-type (table i type backwards relative n)
8800 (let ((l (length table)))
8801 (while (> n 0)
8802 (while (and (setq i (+ i (if backwards -1 1)))
8803 (>= i 0) (< i l)
8804 (not (eq (aref table i) type))
8805 (if (and relative (eq (aref table i) 'hline))
8806 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
8807 t)))
8808 (setq n (1- n)))
8809 (if (or (< i 0) (>= i l))
8810 (error "Row descriptior leads outside table")
8811 i)))
8813 (defun org-rewrite-old-row-references (s)
8814 (if (string-match "&[-+0-9I]" s)
8815 (error "Formula contains old &row reference, please rewrite using @-syntax")
8818 (defun org-table-make-reference (elements keep-empty numbers lispp)
8819 "Convert list ELEMENTS to something appropriate to insert into formula.
8820 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
8821 NUMBERS indicates that everything should be converted to numbers.
8822 LISPP means to return something appropriate for a Lisp list."
8823 (if (stringp elements) ; just a single val
8824 (if lispp
8825 (if (eq lispp 'literal)
8826 elements
8827 (prin1-to-string (if numbers (string-to-number elements) elements)))
8828 (if (equal elements "") (setq elements "0"))
8829 (if numbers (number-to-string (string-to-number elements)) elements))
8830 (unless keep-empty
8831 (setq elements
8832 (delq nil
8833 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
8834 elements))))
8835 (setq elements (or elements '("0")))
8836 (if lispp
8837 (mapconcat
8838 (lambda (x)
8839 (if (eq lispp 'literal)
8841 (prin1-to-string (if numbers (string-to-number x) x))))
8842 " ")
8843 (concat "[" (mapconcat
8844 (lambda (x)
8845 (if numbers (number-to-string (string-to-number x)) x))
8846 elements
8847 ",") "]"))))
8849 (defun org-table-recalculate (&optional all noalign)
8850 "Recalculate the current table line by applying all stored formulas.
8851 With prefix arg ALL, do this for all lines in the table."
8852 (interactive "P")
8853 (or (memq this-command org-recalc-commands)
8854 (setq org-recalc-commands (cons this-command org-recalc-commands)))
8855 (unless (org-at-table-p) (error "Not at a table"))
8856 (if (equal all '(16))
8857 (org-table-iterate)
8858 (org-table-get-specials)
8859 (let* ((eqlist (sort (org-table-get-stored-formulas)
8860 (lambda (a b) (string< (car a) (car b)))))
8861 (inhibit-redisplay (not debug-on-error))
8862 (line-re org-table-dataline-regexp)
8863 (thisline (org-current-line))
8864 (thiscol (org-table-current-column))
8865 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
8866 ;; Insert constants in all formulas
8867 (setq eqlist
8868 (mapcar (lambda (x)
8869 (setcdr x (org-table-formula-substitute-names (cdr x)))
8871 eqlist))
8872 ;; Split the equation list
8873 (while (setq eq (pop eqlist))
8874 (if (<= (string-to-char (car eq)) ?9)
8875 (push eq eqlnum)
8876 (push eq eqlname)))
8877 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
8878 (if all
8879 (progn
8880 (setq end (move-marker (make-marker) (1+ (org-table-end))))
8881 (goto-char (setq beg (org-table-begin)))
8882 (if (re-search-forward org-table-calculate-mark-regexp end t)
8883 ;; This is a table with marked lines, compute selected lines
8884 (setq line-re org-table-recalculate-regexp)
8885 ;; Move forward to the first non-header line
8886 (if (and (re-search-forward org-table-dataline-regexp end t)
8887 (re-search-forward org-table-hline-regexp end t)
8888 (re-search-forward org-table-dataline-regexp end t))
8889 (setq beg (match-beginning 0))
8890 nil))) ;; just leave beg where it is
8891 (setq beg (point-at-bol)
8892 end (move-marker (make-marker) (1+ (point-at-eol)))))
8893 (goto-char beg)
8894 (and all (message "Re-applying formulas to full table..."))
8896 ;; First find the named fields, and mark them untouchanble
8897 (remove-text-properties beg end '(org-untouchable t))
8898 (while (setq eq (pop eqlname))
8899 (setq name (car eq)
8900 a (assoc name org-table-named-field-locations))
8901 (and (not a)
8902 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
8903 (setq a (list name
8904 (aref org-table-dlines
8905 (string-to-number (match-string 1 name)))
8906 (string-to-number (match-string 2 name)))))
8907 (when (and a (or all (equal (nth 1 a) thisline)))
8908 (message "Re-applying formula to field: %s" name)
8909 (goto-line (nth 1 a))
8910 (org-table-goto-column (nth 2 a))
8911 (push (append a (list (cdr eq))) eqlname1)
8912 ;; FIXME (org-table-eval-formula nil (cdr eq) 'noalign 'nocst
8913 ;; FIXME 'nostore 'noanalysis)
8914 (org-table-put-field-property :org-untouchable t)))
8916 ;; Now evauluate the column formulas, but skip fields covered by
8917 ;; field formulas
8918 (goto-char beg)
8919 (while (re-search-forward line-re end t)
8920 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
8921 ;; Unprotected line, recalculate
8922 (and all (message "Re-applying formulas to full table...(line %d)"
8923 (setq cnt (1+ cnt))))
8924 (setq org-last-recalc-line (org-current-line))
8925 (setq eql eqlnum)
8926 (while (setq entry (pop eql))
8927 (goto-line org-last-recalc-line)
8928 (org-table-goto-column (string-to-number (car entry)) nil 'force)
8929 (unless (get-text-property (point) :org-untouchable)
8930 (org-table-eval-formula nil (cdr entry)
8931 'noalign 'nocst 'nostore 'noanalysis)))))
8933 ;; Now evaluate the field formulas
8934 (while (setq eq (pop eqlname1))
8935 (message "Re-applying formula to field: %s" (car eq))
8936 (goto-line (nth 1 eq))
8937 (org-table-goto-column (nth 2 eq))
8938 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
8939 'nostore 'noanalysis))
8941 (goto-line thisline)
8942 (org-table-goto-column thiscol)
8943 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
8944 (or noalign (and org-table-may-need-update (org-table-align))
8945 (and all (message "Re-applying formulas to %d lines...done" cnt)))
8947 ;; back to initial position
8948 (message "Re-applying formulas...done")
8949 (goto-line thisline)
8950 (org-table-goto-column thiscol)
8951 (or noalign (and org-table-may-need-update (org-table-align))
8952 (and all (message "Re-applying formulas...done"))))))
8954 (defun org-table-iterate (&optional arg)
8955 "Recalculate the table until it does not change anymore."
8956 (interactive "P")
8957 (let ((imax (if arg (prefix-numeric-value arg) 10))
8958 (i 0)
8959 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
8960 thistbl)
8961 (catch 'exit
8962 (while (< i imax)
8963 (setq i (1+ i))
8964 (org-table-recalculate 'all)
8965 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
8966 (if (not (string= lasttbl thistbl))
8967 (setq lasttbl thistbl)
8968 (if (> i 1)
8969 (message "Convergence after %d iterations" i)
8970 (message "Table was already stable"))
8971 (throw 'exit t)))
8972 (error "No convergence after %d iterations" i))))
8974 (defun org-table-formula-substitute-names (f)
8975 "Replace $const with values in string F."
8976 (let ((start 0) a (f1 f))
8977 ;; First, check for column names
8978 (while (setq start (string-match org-table-column-name-regexp f start))
8979 (setq start (1+ start))
8980 (setq a (assoc (match-string 1 f) org-table-column-names))
8981 (setq f (replace-match (concat "$" (cdr a)) t t f)))
8982 ;; Parameters and constants
8983 (setq start 0)
8984 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
8985 (setq start (1+ start))
8986 (if (setq a (save-match-data
8987 (org-table-get-constant (match-string 1 f))))
8988 (setq f (replace-match (concat "(" a ")") t t f))))
8989 (if org-table-formula-debug
8990 (put-text-property 0 (length f) :orig-formula f1 f))
8993 (defun org-table-get-constant (const)
8994 "Find the value for a parameter or constant in a formula.
8995 Parameters get priority."
8996 (or (cdr (assoc const org-table-local-parameters))
8997 (cdr (assoc const org-table-formula-constants-local))
8998 (cdr (assoc const org-table-formula-constants))
8999 (and (fboundp 'constants-get) (constants-get const))
9000 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9001 (org-entry-get nil (substring const 5) 'inherit))
9002 "#UNDEFINED_NAME"))
9004 (defvar org-table-fedit-map (make-sparse-keymap))
9005 (org-defkey org-table-fedit-map "\C-x\C-s" 'org-table-fedit-finish)
9006 (org-defkey org-table-fedit-map "\C-c\C-s" 'org-table-fedit-finish)
9007 (org-defkey org-table-fedit-map "\C-c\C-c" 'org-table-fedit-finish)
9008 (org-defkey org-table-fedit-map "\C-c\C-q" 'org-table-fedit-abort)
9009 (org-defkey org-table-fedit-map "\C-c?" 'org-table-show-reference)
9010 (org-defkey org-table-fedit-map [(meta shift up)] 'org-table-fedit-line-up)
9011 (org-defkey org-table-fedit-map [(meta shift down)] 'org-table-fedit-line-down)
9012 (org-defkey org-table-fedit-map [(shift up)] 'org-table-fedit-ref-up)
9013 (org-defkey org-table-fedit-map [(shift down)] 'org-table-fedit-ref-down)
9014 (org-defkey org-table-fedit-map [(shift left)] 'org-table-fedit-ref-left)
9015 (org-defkey org-table-fedit-map [(shift right)] 'org-table-fedit-ref-right)
9016 (org-defkey org-table-fedit-map [(meta up)] 'org-table-fedit-scroll-down)
9017 (org-defkey org-table-fedit-map [(meta down)] 'org-table-fedit-scroll)
9018 (org-defkey org-table-fedit-map [(meta tab)] 'lisp-complete-symbol)
9019 (org-defkey org-table-fedit-map "\M-\C-i" 'lisp-complete-symbol)
9020 (org-defkey org-table-fedit-map [(tab)] 'org-table-fedit-lisp-indent)
9021 (org-defkey org-table-fedit-map "\C-i" 'org-table-fedit-lisp-indent)
9022 (org-defkey org-table-fedit-map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9023 (org-defkey org-table-fedit-map "\C-c}" 'org-table-fedit-toggle-coordinates)
9025 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9026 '("Edit-Formulas"
9027 ["Finish and Install" org-table-fedit-finish t]
9028 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9029 ["Abort" org-table-fedit-abort t]
9030 "--"
9031 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9032 ["Complete Lisp Symbol" lisp-complete-symbol t]
9033 "--"
9034 "Shift Reference at Point"
9035 ["Up" org-table-fedit-ref-up t]
9036 ["Down" org-table-fedit-ref-down t]
9037 ["Left" org-table-fedit-ref-left t]
9038 ["Right" org-table-fedit-ref-right t]
9040 "Change Test Row for Column Formulas"
9041 ["Up" org-table-fedit-line-up t]
9042 ["Down" org-table-fedit-line-down t]
9043 "--"
9044 ["Scroll Table Window" org-table-fedit-scroll t]
9045 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9046 ["Show Table Grid" org-table-fedit-toggle-coordinates
9047 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9048 org-table-overlay-coordinates)]
9049 "--"
9050 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9051 :style toggle :selected org-table-buffer-is-an]))
9053 (defvar org-pos)
9055 (defun org-table-edit-formulas ()
9056 "Edit the formulas of the current table in a separate buffer."
9057 (interactive)
9058 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9059 (beginning-of-line 0))
9060 (unless (org-at-table-p) (error "Not at a table"))
9061 (org-table-get-specials)
9062 (let ((key (org-table-current-field-formula 'key 'noerror))
9063 (eql (sort (org-table-get-stored-formulas 'noerror)
9064 'org-table-formula-less-p))
9065 (pos (move-marker (make-marker) (point)))
9066 (startline 1)
9067 (wc (current-window-configuration))
9068 (titles '((column . "# Column Formulas\n")
9069 (field . "# Field Formulas\n")
9070 (named . "# Named Field Formulas\n")))
9071 entry s type title)
9072 (switch-to-buffer-other-window "*Edit Formulas*")
9073 (erase-buffer)
9074 ;; Keep global-font-lock-mode from turning on font-lock-mode
9075 (let ((font-lock-global-modes '(not fundamental-mode)))
9076 (fundamental-mode))
9077 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9078 (org-set-local 'org-pos pos)
9079 (org-set-local 'org-window-configuration wc)
9080 (use-local-map org-table-fedit-map)
9081 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9082 (easy-menu-add org-table-fedit-menu)
9083 (setq startline (org-current-line))
9084 (while (setq entry (pop eql))
9085 (setq type (cond
9086 ((equal (string-to-char (car entry)) ?@) 'field)
9087 ((string-match "^[0-9]" (car entry)) 'column)
9088 (t 'named)))
9089 (when (setq title (assq type titles))
9090 (or (bobp) (insert "\n"))
9091 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9092 (setq titles (delq title titles)))
9093 (if (equal key (car entry)) (setq startline (org-current-line)))
9094 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9095 (car entry) " = " (cdr entry) "\n"))
9096 (remove-text-properties 0 (length s) '(face nil) s)
9097 (insert s))
9098 (if (eq org-table-use-standard-references t)
9099 (org-table-fedit-toggle-ref-type))
9100 (goto-line startline)
9101 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9103 (defun org-table-fedit-post-command ()
9104 (when (not (memq this-command '(lisp-complete-symbol)))
9105 (let ((win (selected-window)))
9106 (save-excursion
9107 (condition-case nil
9108 (org-table-show-reference)
9109 (error nil))
9110 (select-window win)))))
9112 (defun org-table-formula-to-user (s)
9113 "Convert a formula from internal to user representation."
9114 (if (eq org-table-use-standard-references t)
9115 (org-table-convert-refs-to-an s)
9118 (defun org-table-formula-from-user (s)
9119 "Convert a formula from user to internal representation."
9120 (if org-table-use-standard-references
9121 (org-table-convert-refs-to-rc s)
9124 (defun org-table-convert-refs-to-rc (s)
9125 "Convert spreadsheet references from AB7 to @7$28.
9126 Works for single references, but also for entire formulas and even the
9127 full TBLFM line."
9128 (let ((start 0))
9129 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9130 (cond
9131 ((match-end 3)
9132 ;; format match, just advance
9133 (setq start (match-end 0)))
9134 ((and (> (match-beginning 0) 0)
9135 (equal ?. (aref s (max (1- (match-beginning 0)) 0))))
9136 ;; 3.e5 or something like this. FIXME: is this ok????
9137 (setq start (match-end 0)))
9139 (setq start (match-beginning 0)
9140 s (replace-match
9141 (if (equal (match-string 2 s) "&")
9142 (format "$%d" (org-letters-to-number (match-string 1 s)))
9143 (format "@%d$%d"
9144 (string-to-number (match-string 2 s))
9145 (org-letters-to-number (match-string 1 s))))
9146 t t s)))))
9149 (defun org-table-convert-refs-to-an (s)
9150 "Convert spreadsheet references from to @7$28 to AB7.
9151 Works for single references, but also for entire formulas and even the
9152 full TBLFM line."
9153 (while (string-match "@\\([0-9]+\\)$\\([0-9]+\\)" s)
9154 (setq s (replace-match
9155 (format "%s%d"
9156 (org-number-to-letters
9157 (string-to-number (match-string 2 s)))
9158 (string-to-number (match-string 1 s)))
9159 t t s)))
9160 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9161 (setq s (replace-match (concat "\\1"
9162 (org-number-to-letters
9163 (string-to-number (match-string 2 s))) "&")
9164 t nil s)))
9167 (defun org-letters-to-number (s)
9168 "Convert a base 26 number represented by letters into an integer.
9169 For example: AB -> 28."
9170 (let ((n 0))
9171 (setq s (upcase s))
9172 (while (> (length s) 0)
9173 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9174 s (substring s 1)))
9177 (defun org-number-to-letters (n)
9178 "Convert an integer into a base 26 number represented by letters.
9179 For example: 28 -> AB."
9180 (let ((s ""))
9181 (while (> n 0)
9182 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9183 n (/ (1- n) 26)))
9186 (defun org-table-fedit-convert-buffer (function)
9187 "Convert all references in this buffer, using FUNTION."
9188 (let ((line (org-current-line)))
9189 (goto-char (point-min))
9190 (while (not (eobp))
9191 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9192 (delete-region (point) (point-at-eol))
9193 (or (eobp) (forward-char 1)))
9194 (goto-line line)))
9196 (defun org-table-fedit-toggle-ref-type ()
9197 "Convert all references in the buffer from B3 to @3$2 and back."
9198 (interactive)
9199 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9200 (org-table-fedit-convert-buffer
9201 (if org-table-buffer-is-an
9202 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
9203 (message "Reference type switched to %s"
9204 (if org-table-buffer-is-an "A1 etc" "@row$column")))
9206 (defun org-table-fedit-ref-up ()
9207 "Shift the reference at point one row/hline up."
9208 (interactive)
9209 (org-table-fedit-shift-reference 'up))
9210 (defun org-table-fedit-ref-down ()
9211 "Shift the reference at point one row/hline down."
9212 (interactive)
9213 (org-table-fedit-shift-reference 'down))
9214 (defun org-table-fedit-ref-left ()
9215 "Shift the reference at point one field to the left."
9216 (interactive)
9217 (org-table-fedit-shift-reference 'left))
9218 (defun org-table-fedit-ref-right ()
9219 "Shift the reference at point one field to the right."
9220 (interactive)
9221 (org-table-fedit-shift-reference 'right))
9223 (defun org-table-fedit-shift-reference (dir)
9224 (cond
9225 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
9226 (if (memq dir '(left right))
9227 (org-rematch-and-replace 1 (eq dir 'left))
9228 (error "Cannot shift reference in this direction")))
9229 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
9230 ;; A B3-like reference
9231 (if (memq dir '(up down))
9232 (org-rematch-and-replace 2 (eq dir 'up))
9233 (org-rematch-and-replace 1 (eq dir 'left))))
9234 ((org-at-regexp-p
9235 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
9236 ;; An internal reference
9237 (if (memq dir '(up down))
9238 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
9239 (org-rematch-and-replace 5 (eq dir 'left))))))
9241 (defun org-rematch-and-replace (n &optional decr hline)
9242 "Re-match the group N, and replace it with the shifted refrence."
9243 (or (match-end n) (error "Cannot shift reference in this direction"))
9244 (goto-char (match-beginning n))
9245 (and (looking-at (regexp-quote (match-string n)))
9246 (replace-match (org-shift-refpart (match-string 0) decr hline)
9247 t t)))
9249 (defun org-shift-refpart (ref &optional decr hline)
9250 "Shift a refrence part REF.
9251 If DECR is set, decrease the references row/column, else increase.
9252 If HLINE is set, this may be a hline reference, it certainly is not
9253 a translation reference."
9254 (save-match-data
9255 (let* ((sign (string-match "^[-+]" ref)) n)
9257 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
9258 (cond
9259 ((and hline (string-match "^I+" ref))
9260 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
9261 (setq n (+ n (if decr -1 1)))
9262 (if (= n 0) (setq n (+ n (if decr -1 1))))
9263 (if sign
9264 (setq sign (if (< n 0) "-" "+") n (abs n))
9265 (setq n (max 1 n)))
9266 (concat sign (make-string n ?I)))
9268 ((string-match "^[0-9]+" ref)
9269 (setq n (string-to-number (concat sign ref)))
9270 (setq n (+ n (if decr -1 1)))
9271 (if sign
9272 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
9273 (number-to-string (max 1 n))))
9275 ((string-match "^[a-zA-Z]+" ref)
9276 (org-number-to-letters
9277 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
9279 (t (error "Cannot shift reference"))))))
9281 (defun org-table-fedit-toggle-coordinates ()
9282 "Toggle the display of coordinates in the refrenced table."
9283 (interactive)
9284 (let ((pos (marker-position org-pos)))
9285 (with-current-buffer (marker-buffer org-pos)
9286 (save-excursion
9287 (goto-char pos)
9288 (org-table-toggle-coordinate-overlays)))))
9290 (defun org-table-fedit-finish (&optional arg)
9291 "Parse the buffer for formula definitions and install them.
9292 With prefix ARG, apply the new formulas to the table."
9293 (interactive "P")
9294 (org-table-remove-rectangle-highlight)
9295 (if org-table-use-standard-references
9296 (progn
9297 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
9298 (setq org-table-buffer-is-an nil)))
9299 (let ((pos org-pos) eql var form)
9300 (goto-char (point-min))
9301 (while (re-search-forward
9302 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
9303 nil t)
9304 (setq var (if (match-end 2) (match-string 2) (match-string 1))
9305 form (match-string 3))
9306 (setq form (org-trim form))
9307 (when (not (equal form ""))
9308 (while (string-match "[ \t]*\n[ \t]*" form)
9309 (setq form (replace-match " " t t form)))
9310 (when (assoc var eql)
9311 (error "Double formulas for %s" var))
9312 (push (cons var form) eql)))
9313 (setq org-pos nil)
9314 (set-window-configuration org-window-configuration)
9315 (select-window (get-buffer-window (marker-buffer pos)))
9316 (goto-char pos)
9317 (unless (org-at-table-p)
9318 (error "Lost table position - cannot install formulae"))
9319 (org-table-store-formulas eql)
9320 (move-marker pos nil)
9321 (kill-buffer "*Edit Formulas*")
9322 (if arg
9323 (org-table-recalculate 'all)
9324 (message "New formulas installed - press C-u C-c C-c to apply."))))
9326 (defun org-table-fedit-abort ()
9327 "Abort editing formulas, without installing the changes."
9328 (interactive)
9329 (org-table-remove-rectangle-highlight)
9330 (let ((pos org-pos))
9331 (set-window-configuration org-window-configuration)
9332 (select-window (get-buffer-window (marker-buffer pos)))
9333 (goto-char pos)
9334 (move-marker pos nil)
9335 (message "Formula editing aborted without installing changes")))
9337 (defun org-table-fedit-lisp-indent ()
9338 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
9339 (interactive)
9340 (let ((pos (point)) beg end ind)
9341 (beginning-of-line 1)
9342 (cond
9343 ((looking-at "[ \t]")
9344 (goto-char pos)
9345 (call-interactively 'lisp-indent-line))
9346 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
9347 ((not (fboundp 'pp-buffer))
9348 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
9349 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
9350 (goto-char (- (match-end 0) 2))
9351 (setq beg (point))
9352 (setq ind (make-string (current-column) ?\ ))
9353 (condition-case nil (forward-sexp 1)
9354 (error
9355 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
9356 (setq end (point))
9357 (save-restriction
9358 (narrow-to-region beg end)
9359 (if (eq last-command this-command)
9360 (progn
9361 (goto-char (point-min))
9362 (setq this-command nil)
9363 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
9364 (replace-match " ")))
9365 (pp-buffer)
9366 (untabify (point-min) (point-max))
9367 (goto-char (1+ (point-min)))
9368 (while (re-search-forward "^." nil t)
9369 (beginning-of-line 1)
9370 (insert ind))
9371 (goto-char (point-max))
9372 (backward-delete-char 1)))
9373 (goto-char beg))
9374 (t nil))))
9376 (defvar org-show-positions nil)
9378 (defun org-table-show-reference (&optional local)
9379 "Show the location/value of the $ expression at point."
9380 (interactive)
9381 (org-table-remove-rectangle-highlight)
9382 (catch 'exit
9383 (let ((pos (if local (point) org-pos))
9384 (face2 'highlight)
9385 (org-inhibit-highlight-removal t)
9386 (win (selected-window))
9387 (org-show-positions nil)
9388 var name e what match dest)
9389 (if local (org-table-get-specials))
9390 (setq what (cond
9391 ((or (org-at-regexp-p org-table-range-regexp2)
9392 (org-at-regexp-p org-table-translate-regexp)
9393 (org-at-regexp-p org-table-range-regexp))
9394 (setq match
9395 (save-match-data
9396 (org-table-convert-refs-to-rc (match-string 0))))
9397 'range)
9398 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
9399 ((org-at-regexp-p "\\$[0-9]+") 'column)
9400 ((not local) nil)
9401 (t (error "No reference at point")))
9402 match (and what (or match (match-string 0))))
9403 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
9404 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
9405 'secondary-selection))
9406 (org-add-hook 'before-change-functions
9407 'org-table-remove-rectangle-highlight)
9408 (if (eq what 'name) (setq var (substring match 1)))
9409 (when (eq what 'range)
9410 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
9411 (setq match (org-table-formula-substitute-names match)))
9412 (unless local
9413 (save-excursion
9414 (end-of-line 1)
9415 (re-search-backward "^\\S-" nil t)
9416 (beginning-of-line 1)
9417 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
9418 (setq dest
9419 (save-match-data
9420 (org-table-convert-refs-to-rc (match-string 1))))
9421 (org-table-add-rectangle-overlay
9422 (match-beginning 1) (match-end 1) face2))))
9423 (if (and (markerp pos) (marker-buffer pos))
9424 (if (get-buffer-window (marker-buffer pos))
9425 (select-window (get-buffer-window (marker-buffer pos)))
9426 (switch-to-buffer-other-window (get-buffer-window
9427 (marker-buffer pos)))))
9428 (goto-char pos)
9429 (org-table-force-dataline)
9430 (when dest
9431 (setq name (substring dest 1))
9432 (cond
9433 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
9434 (setq e (assoc name org-table-named-field-locations))
9435 (goto-line (nth 1 e))
9436 (org-table-goto-column (nth 2 e)))
9437 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
9438 (let ((l (string-to-number (match-string 1 dest)))
9439 (c (string-to-number (match-string 2 dest))))
9440 (goto-line (aref org-table-dlines l))
9441 (org-table-goto-column c)))
9442 (t (org-table-goto-column (string-to-number name))))
9443 (move-marker pos (point))
9444 (org-table-highlight-rectangle nil nil face2))
9445 (cond
9446 ((equal dest match))
9447 ((not match))
9448 ((eq what 'range)
9449 (condition-case nil
9450 (save-excursion
9451 (org-table-get-range match nil nil 'highlight))
9452 (error nil)))
9453 ((setq e (assoc var org-table-named-field-locations))
9454 (goto-line (nth 1 e))
9455 (org-table-goto-column (nth 2 e))
9456 (org-table-highlight-rectangle (point) (point))
9457 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9458 ((setq e (assoc var org-table-column-names))
9459 (org-table-goto-column (string-to-number (cdr e)))
9460 (org-table-highlight-rectangle (point) (point))
9461 (goto-char (org-table-begin))
9462 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9463 (org-table-end) t)
9464 (progn
9465 (goto-char (match-beginning 1))
9466 (org-table-highlight-rectangle)
9467 (message "Named column (column %s)" (cdr e)))
9468 (error "Column name not found")))
9469 ((eq what 'column)
9470 ;; column number
9471 (org-table-goto-column (string-to-number (substring match 1)))
9472 (org-table-highlight-rectangle (point) (point))
9473 (message "Column %s" (substring match 1)))
9474 ((setq e (assoc var org-table-local-parameters))
9475 (goto-char (org-table-begin))
9476 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9477 (progn
9478 (goto-char (match-beginning 1))
9479 (org-table-highlight-rectangle)
9480 (message "Local parameter."))
9481 (error "Parameter not found")))
9483 (cond
9484 ((not var) (error "No reference at point"))
9485 ((setq e (assoc var org-table-formula-constants-local))
9486 (message "Local Constant: $%s=%s in #+CONSTANTS line."
9487 var (cdr e)))
9488 ((setq e (assoc var org-table-formula-constants))
9489 (message "Constant: $%s=%s in `org-table-formula-constants'."
9490 var (cdr e)))
9491 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9492 (message "Constant: $%s=%s, from `constants.el'%s."
9493 var e (format " (%s units)" constants-unit-system)))
9494 (t (error "Undefined name $%s" var)))))
9495 (goto-char pos)
9496 (when (and org-show-positions
9497 (not (memq this-command '(org-table-fedit-scroll
9498 org-table-fedit-scroll-down))))
9499 (push pos org-show-positions)
9500 (push org-table-current-begin-pos org-show-positions)
9501 (let ((min (apply 'min org-show-positions))
9502 (max (apply 'max org-show-positions)))
9503 (goto-char min) (recenter 0)
9504 (goto-char max)
9505 (or (pos-visible-in-window-p max) (recenter -1))))
9506 (select-window win))))
9508 (defun org-table-force-dataline ()
9509 "Make sure the cursor is in a dataline in a table."
9510 (unless (save-excursion
9511 (beginning-of-line 1)
9512 (looking-at org-table-dataline-regexp))
9513 (let* ((re org-table-dataline-regexp)
9514 (p1 (save-excursion (re-search-forward re nil 'move)))
9515 (p2 (save-excursion (re-search-backward re nil 'move))))
9516 (cond ((and p1 p2)
9517 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
9518 p1 p2)))
9519 ((or p1 p2) (goto-char (or p1 p2)))
9520 (t (error "No table dataline around here"))))))
9522 (defun org-table-fedit-line-up ()
9523 "Move cursor one line up in the window showing the table."
9524 (interactive)
9525 (org-table-fedit-move 'previous-line))
9527 (defun org-table-fedit-line-down ()
9528 "Move cursor one line down in the window showing the table."
9529 (interactive)
9530 (org-table-fedit-move 'next-line))
9532 (defun org-table-fedit-move (command)
9533 "Move the cursor in the window shoinw the table.
9534 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
9535 (let ((org-table-allow-automatic-line-recalculation nil)
9536 (pos org-pos) (win (selected-window)) p)
9537 (select-window (get-buffer-window (marker-buffer org-pos)))
9538 (setq p (point))
9539 (call-interactively command)
9540 (while (and (org-at-table-p)
9541 (org-at-table-hline-p))
9542 (call-interactively command))
9543 (or (org-at-table-p) (goto-char p))
9544 (move-marker pos (point))
9545 (select-window win)))
9547 (defun org-table-fedit-scroll (N)
9548 (interactive "p")
9549 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
9550 (scroll-other-window N)))
9552 (defun org-table-fedit-scroll-down (N)
9553 (interactive "p")
9554 (org-table-fedit-scroll (- N)))
9556 (defvar org-table-rectangle-overlays nil)
9558 (defun org-table-add-rectangle-overlay (beg end &optional face)
9559 "Add a new overlay."
9560 (let ((ov (org-make-overlay beg end)))
9561 (org-overlay-put ov 'face (or face 'secondary-selection))
9562 (push ov org-table-rectangle-overlays)))
9564 (defun org-table-highlight-rectangle (&optional beg end face)
9565 "Highlight rectangular region in a table."
9566 (setq beg (or beg (point)) end (or end (point)))
9567 (let ((b (min beg end))
9568 (e (max beg end))
9569 l1 c1 l2 c2 tmp)
9570 (and (boundp 'org-show-positions)
9571 (setq org-show-positions (cons b (cons e org-show-positions))))
9572 (goto-char (min beg end))
9573 (setq l1 (org-current-line)
9574 c1 (org-table-current-column))
9575 (goto-char (max beg end))
9576 (setq l2 (org-current-line)
9577 c2 (org-table-current-column))
9578 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
9579 (goto-line l1)
9580 (beginning-of-line 1)
9581 (loop for line from l1 to l2 do
9582 (when (looking-at org-table-dataline-regexp)
9583 (org-table-goto-column c1)
9584 (skip-chars-backward "^|\n") (setq beg (point))
9585 (org-table-goto-column c2)
9586 (skip-chars-forward "^|\n") (setq end (point))
9587 (org-table-add-rectangle-overlay beg end face))
9588 (beginning-of-line 2))
9589 (goto-char b))
9590 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
9592 (defun org-table-remove-rectangle-highlight (&rest ignore)
9593 "Remove the rectangle overlays."
9594 (unless org-inhibit-highlight-removal
9595 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
9596 (mapc 'org-delete-overlay org-table-rectangle-overlays)
9597 (setq org-table-rectangle-overlays nil)))
9599 (defvar org-table-coordinate-overlays nil
9600 "Collects the cooordinate grid overlays, so that they can be removed.")
9601 (make-variable-buffer-local 'org-table-coordinate-overlays)
9603 (defun org-table-overlay-coordinates ()
9604 "Add overlays to the table at point, to show row/column coordinates."
9605 (interactive)
9606 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9607 (setq org-table-coordinate-overlays nil)
9608 (save-excursion
9609 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
9610 (goto-char (org-table-begin))
9611 (while (org-at-table-p)
9612 (setq eol (point-at-eol))
9613 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
9614 (push ov org-table-coordinate-overlays)
9615 (setq hline (looking-at org-table-hline-regexp))
9616 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
9617 (format "%4d" (setq id (1+ id)))))
9618 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
9619 (when hline
9620 (setq ic 0)
9621 (while (re-search-forward "[+|]\\(-+\\)" eol t)
9622 (setq beg (1+ (match-beginning 0))
9623 ic (1+ ic)
9624 s1 (concat "$" (int-to-string ic))
9625 s2 (org-number-to-letters ic)
9626 str (if (eq org-table-use-standard-references t) s2 s1))
9627 (setq ov (org-make-overlay beg (+ beg (length str))))
9628 (push ov org-table-coordinate-overlays)
9629 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
9630 (beginning-of-line 2)))))
9632 (defun org-table-toggle-coordinate-overlays ()
9633 "Toggle the display of Row/Column numbers in tables."
9634 (interactive)
9635 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
9636 (message "Row/Column number display turned %s"
9637 (if org-table-overlay-coordinates "on" "off"))
9638 (if (and (org-at-table-p) org-table-overlay-coordinates)
9639 (org-table-align))
9640 (unless org-table-overlay-coordinates
9641 (mapc 'org-delete-overlay org-table-coordinate-overlays)
9642 (setq org-table-coordinate-overlays nil)))
9644 (defun org-table-toggle-formula-debugger ()
9645 "Toggle the formula debugger in tables."
9646 (interactive)
9647 (setq org-table-formula-debug (not org-table-formula-debug))
9648 (message "Formula debugging has been turned %s"
9649 (if org-table-formula-debug "on" "off")))
9651 ;;; The orgtbl minor mode
9653 ;; Define a minor mode which can be used in other modes in order to
9654 ;; integrate the org-mode table editor.
9656 ;; This is really a hack, because the org-mode table editor uses several
9657 ;; keys which normally belong to the major mode, for example the TAB and
9658 ;; RET keys. Here is how it works: The minor mode defines all the keys
9659 ;; necessary to operate the table editor, but wraps the commands into a
9660 ;; function which tests if the cursor is currently inside a table. If that
9661 ;; is the case, the table editor command is executed. However, when any of
9662 ;; those keys is used outside a table, the function uses `key-binding' to
9663 ;; look up if the key has an associated command in another currently active
9664 ;; keymap (minor modes, major mode, global), and executes that command.
9665 ;; There might be problems if any of the keys used by the table editor is
9666 ;; otherwise used as a prefix key.
9668 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9669 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9670 ;; addresses this by checking explicitly for both bindings.
9672 ;; The optimized version (see variable `orgtbl-optimized') takes over
9673 ;; all keys which are bound to `self-insert-command' in the *global map*.
9674 ;; Some modes bind other commands to simple characters, for example
9675 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9676 ;; active, this binding is ignored inside tables and replaced with a
9677 ;; modified self-insert.
9679 (defvar orgtbl-mode nil
9680 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9681 table editor in arbitrary modes.")
9682 (make-variable-buffer-local 'orgtbl-mode)
9684 (defvar orgtbl-mode-map (make-keymap)
9685 "Keymap for `orgtbl-mode'.")
9687 ;;;###autoload
9688 (defun turn-on-orgtbl ()
9689 "Unconditionally turn on `orgtbl-mode'."
9690 (orgtbl-mode 1))
9692 (defvar org-old-auto-fill-inhibit-regexp nil
9693 "Local variable used by `orgtbl-mode'")
9695 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
9696 "Matches a line belonging to an orgtbl.")
9698 (defconst orgtbl-extra-font-lock-keywords
9699 (list (list (concat "^" orgtbl-line-start-regexp ".*")
9700 0 (quote 'org-table) 'prepend))
9701 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
9703 ;;;###autoload
9704 (defun orgtbl-mode (&optional arg)
9705 "The `org-mode' table editor as a minor mode for use in other modes."
9706 (interactive)
9707 (if (org-mode-p)
9708 ;; Exit without error, in case some hook functions calls this
9709 ;; by accident in org-mode.
9710 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9711 (setq orgtbl-mode
9712 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9713 (if orgtbl-mode
9714 (progn
9715 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9716 ;; Make sure we are first in minor-mode-map-alist
9717 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9718 (and c (setq minor-mode-map-alist
9719 (cons c (delq c minor-mode-map-alist)))))
9720 (org-set-local (quote org-table-may-need-update) t)
9721 (org-add-hook 'before-change-functions 'org-before-change-function
9722 nil 'local)
9723 (org-set-local 'org-old-auto-fill-inhibit-regexp
9724 auto-fill-inhibit-regexp)
9725 (org-set-local 'auto-fill-inhibit-regexp
9726 (if auto-fill-inhibit-regexp
9727 (concat orgtbl-line-start-regexp "\\|"
9728 auto-fill-inhibit-regexp)
9729 orgtbl-line-start-regexp))
9730 (org-add-to-invisibility-spec '(org-cwidth))
9731 (when (fboundp 'font-lock-add-keywords)
9732 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
9733 (org-restart-font-lock))
9734 (easy-menu-add orgtbl-mode-menu)
9735 (run-hooks 'orgtbl-mode-hook))
9736 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9737 (org-cleanup-narrow-column-properties)
9738 (org-remove-from-invisibility-spec '(org-cwidth))
9739 (remove-hook 'before-change-functions 'org-before-change-function t)
9740 (when (fboundp 'font-lock-remove-keywords)
9741 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
9742 (org-restart-font-lock))
9743 (easy-menu-remove orgtbl-mode-menu)
9744 (force-mode-line-update 'all))))
9746 (defun org-cleanup-narrow-column-properties ()
9747 "Remove all properties related to narrow-column invisibility."
9748 (let ((s 1))
9749 (while (setq s (text-property-any s (point-max)
9750 'display org-narrow-column-arrow))
9751 (remove-text-properties s (1+ s) '(display t)))
9752 (setq s 1)
9753 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
9754 (remove-text-properties s (1+ s) '(org-cwidth t)))
9755 (setq s 1)
9756 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
9757 (remove-text-properties s (1+ s) '(invisible t)))))
9759 ;; Install it as a minor mode.
9760 (put 'orgtbl-mode :included t)
9761 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9762 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9764 (defun orgtbl-make-binding (fun n &rest keys)
9765 "Create a function for binding in the table minor mode.
9766 FUN is the command to call inside a table. N is used to create a unique
9767 command name. KEYS are keys that should be checked in for a command
9768 to execute outside of tables."
9769 (eval
9770 (list 'defun
9771 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9772 '(arg)
9773 (concat "In tables, run `" (symbol-name fun) "'.\n"
9774 "Outside of tables, run the binding of `"
9775 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9776 "'.")
9777 '(interactive "p")
9778 (list 'if
9779 '(org-at-table-p)
9780 (list 'call-interactively (list 'quote fun))
9781 (list 'let '(orgtbl-mode)
9782 (list 'call-interactively
9783 (append '(or)
9784 (mapcar (lambda (k)
9785 (list 'key-binding k))
9786 keys)
9787 '('orgtbl-error))))))))
9789 (defun orgtbl-error ()
9790 "Error when there is no default binding for a table key."
9791 (interactive)
9792 (error "This key is has no function outside tables"))
9794 (defun orgtbl-setup ()
9795 "Setup orgtbl keymaps."
9796 (let ((nfunc 0)
9797 (bindings
9798 (list
9799 '([(meta shift left)] org-table-delete-column)
9800 '([(meta left)] org-table-move-column-left)
9801 '([(meta right)] org-table-move-column-right)
9802 '([(meta shift right)] org-table-insert-column)
9803 '([(meta shift up)] org-table-kill-row)
9804 '([(meta shift down)] org-table-insert-row)
9805 '([(meta up)] org-table-move-row-up)
9806 '([(meta down)] org-table-move-row-down)
9807 '("\C-c\C-w" org-table-cut-region)
9808 '("\C-c\M-w" org-table-copy-region)
9809 '("\C-c\C-y" org-table-paste-rectangle)
9810 '("\C-c-" org-table-insert-hline)
9811 '("\C-c}" org-table-toggle-coordinate-overlays)
9812 '("\C-c{" org-table-toggle-formula-debugger)
9813 '("\C-m" org-table-next-row)
9814 '([(shift return)] org-table-copy-down)
9815 '("\C-c\C-q" org-table-wrap-region)
9816 '("\C-c?" org-table-field-info)
9817 '("\C-c " org-table-blank-field)
9818 '("\C-c+" org-table-sum)
9819 '("\C-c=" org-table-eval-formula)
9820 '("\C-c'" org-table-edit-formulas)
9821 '("\C-c`" org-table-edit-field)
9822 '("\C-c*" org-table-recalculate)
9823 '("\C-c|" org-table-create-or-convert-from-region)
9824 '("\C-c^" org-table-sort-lines)
9825 '([(control ?#)] org-table-rotate-recalc-marks)))
9826 elt key fun cmd)
9827 (while (setq elt (pop bindings))
9828 (setq nfunc (1+ nfunc))
9829 (setq key (org-key (car elt))
9830 fun (nth 1 elt)
9831 cmd (orgtbl-make-binding fun nfunc key))
9832 (org-defkey orgtbl-mode-map key cmd))
9834 ;; Special treatment needed for TAB and RET
9835 (org-defkey orgtbl-mode-map [(return)]
9836 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9837 (org-defkey orgtbl-mode-map "\C-m"
9838 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9840 (org-defkey orgtbl-mode-map [(tab)]
9841 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9842 (org-defkey orgtbl-mode-map "\C-i"
9843 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
9845 (org-defkey orgtbl-mode-map [(shift tab)]
9846 (orgtbl-make-binding 'org-table-previous-field 104
9847 [(shift tab)] [(tab)] "\C-i"))
9849 (org-defkey orgtbl-mode-map "\M-\C-m"
9850 (orgtbl-make-binding 'org-table-wrap-region 105
9851 "\M-\C-m" [(meta return)]))
9852 (org-defkey orgtbl-mode-map [(meta return)]
9853 (orgtbl-make-binding 'org-table-wrap-region 106
9854 [(meta return)] "\M-\C-m"))
9856 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
9857 (when orgtbl-optimized
9858 ;; If the user wants maximum table support, we need to hijack
9859 ;; some standard editing functions
9860 (org-remap orgtbl-mode-map
9861 'self-insert-command 'orgtbl-self-insert-command
9862 'delete-char 'org-delete-char
9863 'delete-backward-char 'org-delete-backward-char)
9864 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
9865 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9866 '("OrgTbl"
9867 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9868 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9869 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9870 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9871 "--"
9872 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9873 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
9874 ["Copy Field from Above"
9875 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9876 "--"
9877 ("Column"
9878 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9879 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9880 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9881 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9882 ("Row"
9883 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9884 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9885 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9886 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9887 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9888 "--"
9889 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9890 ("Rectangle"
9891 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9892 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9893 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9894 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9895 "--"
9896 ("Radio tables"
9897 ["Insert table template" orgtbl-insert-radio-table
9898 (assq major-mode orgtbl-radio-table-templates)]
9899 ["Comment/uncomment table" orgtbl-toggle-comment t])
9900 "--"
9901 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9902 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9903 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9904 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9905 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9906 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
9907 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9908 ["Sum Column/Rectangle" org-table-sum
9909 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9910 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9911 ["Debug Formulas"
9912 org-table-toggle-formula-debugger :active (org-at-table-p)
9913 :keys "C-c {"
9914 :style toggle :selected org-table-formula-debug]
9915 ["Show Col/Row Numbers"
9916 org-table-toggle-coordinate-overlays :active (org-at-table-p)
9917 :keys "C-c }"
9918 :style toggle :selected org-table-overlay-coordinates]
9922 (defun orgtbl-ctrl-c-ctrl-c (arg)
9923 "If the cursor is inside a table, realign the table.
9924 It it is a table to be sent away to a receiver, do it.
9925 With prefix arg, also recompute table."
9926 (interactive "P")
9927 (let ((pos (point)) action)
9928 (save-excursion
9929 (beginning-of-line 1)
9930 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
9931 ((looking-at "[ \t]*|") pos)
9932 ((looking-at "#\\+TBLFM:") 'recalc))))
9933 (cond
9934 ((integerp action)
9935 (goto-char action)
9936 (org-table-maybe-eval-formula)
9937 (if arg
9938 (call-interactively 'org-table-recalculate)
9939 (org-table-maybe-recalculate-line))
9940 (call-interactively 'org-table-align)
9941 (orgtbl-send-table 'maybe))
9942 ((eq action 'recalc)
9943 (save-excursion
9944 (beginning-of-line 1)
9945 (skip-chars-backward " \r\n\t")
9946 (if (org-at-table-p)
9947 (org-call-with-arg 'org-table-recalculate t))))
9948 (t (let (orgtbl-mode)
9949 (call-interactively (key-binding "\C-c\C-c")))))))
9951 (defun orgtbl-tab (arg)
9952 "Justification and field motion for `orgtbl-mode'."
9953 (interactive "P")
9954 (if arg (org-table-edit-field t)
9955 (org-table-justify-field-maybe)
9956 (org-table-next-field)))
9958 (defun orgtbl-ret ()
9959 "Justification and field motion for `orgtbl-mode'."
9960 (interactive)
9961 (org-table-justify-field-maybe)
9962 (org-table-next-row))
9964 (defun orgtbl-self-insert-command (N)
9965 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9966 If the cursor is in a table looking at whitespace, the whitespace is
9967 overwritten, and the table is not marked as requiring realignment."
9968 (interactive "p")
9969 (if (and (org-at-table-p)
9971 (and org-table-auto-blank-field
9972 (member last-command
9973 '(orgtbl-hijacker-command-100
9974 orgtbl-hijacker-command-101
9975 orgtbl-hijacker-command-102
9976 orgtbl-hijacker-command-103
9977 orgtbl-hijacker-command-104
9978 orgtbl-hijacker-command-105))
9979 (org-table-blank-field))
9981 (eq N 1)
9982 (looking-at "[^|\n]* +|"))
9983 (let (org-table-may-need-update)
9984 (goto-char (1- (match-end 0)))
9985 (delete-backward-char 1)
9986 (goto-char (match-beginning 0))
9987 (self-insert-command N))
9988 (setq org-table-may-need-update t)
9989 (let (orgtbl-mode)
9990 (call-interactively (key-binding (vector last-input-event))))))
9992 (defun org-force-self-insert (N)
9993 "Needed to enforce self-insert under remapping."
9994 (interactive "p")
9995 (self-insert-command N))
9997 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
9998 "Regula expression matching exponentials as produced by calc.")
10000 (defvar org-table-clean-did-remove-column nil)
10002 (defun orgtbl-export (table target)
10003 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10004 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10005 org-table-last-alignment org-table-last-column-widths
10006 maxcol column)
10007 (if (not (fboundp func))
10008 (error "Cannot export orgtbl table to %s" target))
10009 (setq lines (org-table-clean-before-export lines))
10010 (setq table
10011 (mapcar
10012 (lambda (x)
10013 (if (string-match org-table-hline-regexp x)
10014 'hline
10015 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10016 lines))
10017 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10018 table)))
10019 (loop for i from (1- maxcol) downto 0 do
10020 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10021 (setq column (delq nil column))
10022 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10023 (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))
10024 (funcall func table nil)))
10026 (defun orgtbl-send-table (&optional maybe)
10027 "Send a tranformed version of this table to the receiver position.
10028 With argument MAYBE, fail quietly if no transformation is defined for
10029 this table."
10030 (interactive)
10031 (catch 'exit
10032 (unless (org-at-table-p) (error "Not at a table"))
10033 ;; when non-interactive, we assume align has just happened.
10034 (when (interactive-p) (org-table-align))
10035 (save-excursion
10036 (goto-char (org-table-begin))
10037 (beginning-of-line 0)
10038 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10039 (if maybe
10040 (throw 'exit nil)
10041 (error "Don't know how to transform this table."))))
10042 (let* ((name (match-string 1))
10044 (transform (intern (match-string 2)))
10045 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10046 (skip (plist-get params :skip))
10047 (skipcols (plist-get params :skipcols))
10048 (txt (buffer-substring-no-properties
10049 (org-table-begin) (org-table-end)))
10050 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10051 (lines (org-table-clean-before-export lines))
10052 (i0 (if org-table-clean-did-remove-column 2 1))
10053 (table (mapcar
10054 (lambda (x)
10055 (if (string-match org-table-hline-regexp x)
10056 'hline
10057 (org-remove-by-index
10058 (org-split-string (org-trim x) "\\s-*|\\s-*")
10059 skipcols i0)))
10060 lines))
10061 (fun (if (= i0 2) 'cdr 'identity))
10062 (org-table-last-alignment
10063 (org-remove-by-index (funcall fun org-table-last-alignment)
10064 skipcols i0))
10065 (org-table-last-column-widths
10066 (org-remove-by-index (funcall fun org-table-last-column-widths)
10067 skipcols i0)))
10069 (unless (fboundp transform)
10070 (error "No such transformation function %s" transform))
10071 (setq txt (funcall transform table params))
10072 ;; Find the insertion place
10073 (save-excursion
10074 (goto-char (point-min))
10075 (unless (re-search-forward
10076 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10077 (error "Don't know where to insert translated table"))
10078 (goto-char (match-beginning 0))
10079 (beginning-of-line 2)
10080 (setq beg (point))
10081 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10082 (error "Cannot find end of insertion region"))
10083 (beginning-of-line 1)
10084 (delete-region beg (point))
10085 (goto-char beg)
10086 (insert txt "\n"))
10087 (message "Table converted and installed at receiver location"))))
10089 (defun org-remove-by-index (list indices &optional i0)
10090 "Remove the elements in LIST with indices in INDICES.
10091 First element has index 0, or I0 if given."
10092 (if (not indices)
10093 list
10094 (if (integerp indices) (setq indices (list indices)))
10095 (setq i0 (1- (or i0 0)))
10096 (delq :rm (mapcar (lambda (x)
10097 (setq i0 (1+ i0))
10098 (if (memq i0 indices) :rm x))
10099 list))))
10101 (defun orgtbl-toggle-comment ()
10102 "Comment or uncomment the orgtbl at point."
10103 (interactive)
10104 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10105 (re2 (concat "^" orgtbl-line-start-regexp))
10106 (commented (save-excursion (beginning-of-line 1)
10107 (cond ((looking-at re1) t)
10108 ((looking-at re2) nil)
10109 (t (error "Not at an org table")))))
10110 (re (if commented re1 re2))
10111 beg end)
10112 (save-excursion
10113 (beginning-of-line 1)
10114 (while (looking-at re) (beginning-of-line 0))
10115 (beginning-of-line 2)
10116 (setq beg (point))
10117 (while (looking-at re) (beginning-of-line 2))
10118 (setq end (point)))
10119 (comment-region beg end (if commented '(4) nil))))
10121 (defun orgtbl-insert-radio-table ()
10122 "Insert a radio table template appropriate for this major mode."
10123 (interactive)
10124 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10125 (txt (nth 1 e))
10126 name pos)
10127 (unless e (error "No radio table setup defined for %s" major-mode))
10128 (setq name (read-string "Table name: "))
10129 (while (string-match "%n" txt)
10130 (setq txt (replace-match name t t txt)))
10131 (or (bolp) (insert "\n"))
10132 (setq pos (point))
10133 (insert txt)
10134 (goto-char pos)))
10136 (defun org-get-param (params header i sym &optional hsym)
10137 "Get parameter value for symbol SYM.
10138 If this is a header line, actually get the value for the symbol with an
10139 additional \"h\" inserted after the colon.
10140 If the value is a protperty list, get the element for the current column.
10141 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10142 (let ((val (plist-get params sym)))
10143 (and hsym header (setq val (or (plist-get params hsym) val)))
10144 (if (consp val) (plist-get val i) val)))
10146 (defun orgtbl-to-generic (table params)
10147 "Convert the orgtbl-mode TABLE to some other format.
10148 This generic routine can be used for many standard cases.
10149 TABLE is a list, each entry either the symbol `hline' for a horizontal
10150 separator line, or a list of fields for that line.
10151 PARAMS is a property list of parameters that can influence the conversion.
10152 For the generic converter, some parameters are obligatory: You need to
10153 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10154 :splice, you must have :tstart and :tend.
10156 Valid parameters are
10158 :tstart String to start the table. Ignored when :splice is t.
10159 :tend String to end the table. Ignored when :splice is t.
10161 :splice When set to t, return only table body lines, don't wrap
10162 them into :tstart and :tend. Default is nil.
10164 :hline String to be inserted on horizontal separation lines.
10165 May be nil to ignore hlines.
10167 :lstart String to start a new table line.
10168 :lend String to end a table line
10169 :sep Separator between two fields
10170 :lfmt Format for entire line, with enough %s to capture all fields.
10171 If this is present, :lstart, :lend, and :sep are ignored.
10172 :fmt A format to be used to wrap the field, should contain
10173 %s for the original field value. For example, to wrap
10174 everything in dollars, you could use :fmt \"$%s$\".
10175 This may also be a property list with column numbers and
10176 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10178 :hlstart :hlend :hlsep :hlfmt :hfmt
10179 Same as above, specific for the header lines in the table.
10180 All lines before the first hline are treated as header.
10181 If any of these is not present, the data line value is used.
10183 :efmt Use this format to print numbers with exponentials.
10184 The format should have %s twice for inserting mantissa
10185 and exponent, for example \"%s\\\\times10^{%s}\". This
10186 may also be a property list with column numbers and
10187 formats. :fmt will still be applied after :efmt.
10189 In addition to this, the parameters :skip and :skipcols are always handled
10190 directly by `orgtbl-send-table'. See manual."
10191 (interactive)
10192 (let* ((p params)
10193 (splicep (plist-get p :splice))
10194 (hline (plist-get p :hline))
10195 rtn line i fm efm lfmt h)
10197 ;; Do we have a header?
10198 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10199 (setq h t))
10201 ;; Put header
10202 (unless splicep
10203 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
10205 ;; Now loop over all lines
10206 (while (setq line (pop table))
10207 (if (eq line 'hline)
10208 ;; A horizontal separator line
10209 (progn (if hline (push hline rtn))
10210 (setq h nil)) ; no longer in header
10211 ;; A normal line. Convert the fields, push line onto the result list
10212 (setq i 0)
10213 (setq line
10214 (mapcar
10215 (lambda (f)
10216 (setq i (1+ i)
10217 fm (org-get-param p h i :fmt :hfmt)
10218 efm (org-get-param p h i :efmt))
10219 (if (and efm (string-match orgtbl-exp-regexp f))
10220 (setq f (format
10221 efm (match-string 1 f) (match-string 2 f))))
10222 (if fm (setq f (format fm f)))
10224 line))
10225 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
10226 (push (apply 'format lfmt line) rtn)
10227 (push (concat
10228 (org-get-param p h i :lstart :hlstart)
10229 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
10230 (org-get-param p h i :lend :hlend))
10231 rtn))))
10233 (unless splicep
10234 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
10236 (mapconcat 'identity (nreverse rtn) "\n")))
10238 (defun orgtbl-to-latex (table params)
10239 "Convert the orgtbl-mode TABLE to LaTeX.
10240 TABLE is a list, each entry either the symbol `hline' for a horizontal
10241 separator line, or a list of fields for that line.
10242 PARAMS is a property list of parameters that can influence the conversion.
10243 Supports all parameters from `orgtbl-to-generic'. Most important for
10244 LaTeX are:
10246 :splice When set to t, return only table body lines, don't wrap
10247 them into a tabular environment. Default is nil.
10249 :fmt A format to be used to wrap the field, should contain %s for the
10250 original field value. For example, to wrap everything in dollars,
10251 use :fmt \"$%s$\". This may also be a property list with column
10252 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10254 :efmt Format for transforming numbers with exponentials. The format
10255 should have %s twice for inserting mantissa and exponent, for
10256 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
10257 This may also be a property list with column numbers and formats.
10259 The general parameters :skip and :skipcols have already been applied when
10260 this function is called."
10261 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
10262 org-table-last-alignment ""))
10263 (params2
10264 (list
10265 :tstart (concat "\\begin{tabular}{" alignment "}")
10266 :tend "\\end{tabular}"
10267 :lstart "" :lend " \\\\" :sep " & "
10268 :efmt "%s\\,(%s)" :hline "\\hline")))
10269 (orgtbl-to-generic table (org-combine-plists params2 params))))
10271 (defun orgtbl-to-html (table params)
10272 "Convert the orgtbl-mode TABLE to LaTeX.
10273 TABLE is a list, each entry either the symbol `hline' for a horizontal
10274 separator line, or a list of fields for that line.
10275 PARAMS is a property list of parameters that can influence the conversion.
10276 Currently this function recognizes the following parameters:
10278 :splice When set to t, return only table body lines, don't wrap
10279 them into a <table> environment. Default is nil.
10281 The general parameters :skip and :skipcols have already been applied when
10282 this function is called. The function does *not* use `orgtbl-to-generic',
10283 so you cannot specify parameters for it."
10284 (let* ((splicep (plist-get params :splice))
10285 html)
10286 ;; Just call the formatter we already have
10287 ;; We need to make text lines for it, so put the fields back together.
10288 (setq html (org-format-org-table-html
10289 (mapcar
10290 (lambda (x)
10291 (if (eq x 'hline)
10292 "|----+----|"
10293 (concat "| " (mapconcat 'identity x " | ") " |")))
10294 table)
10295 splicep))
10296 (if (string-match "\n+\\'" html)
10297 (setq html (replace-match "" t t html)))
10298 html))
10300 (defun orgtbl-to-texinfo (table params)
10301 "Convert the orgtbl-mode TABLE to TeXInfo.
10302 TABLE is a list, each entry either the symbol `hline' for a horizontal
10303 separator line, or a list of fields for that line.
10304 PARAMS is a property list of parameters that can influence the conversion.
10305 Supports all parameters from `orgtbl-to-generic'. Most important for
10306 TeXInfo are:
10308 :splice nil/t When set to t, return only table body lines, don't wrap
10309 them into a multitable environment. Default is nil.
10311 :fmt fmt A format to be used to wrap the field, should contain
10312 %s for the original field value. For example, to wrap
10313 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
10314 This may also be a property list with column numbers and
10315 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
10317 :cf \"f1 f2..\" The column fractions for the table. Bye default these
10318 are computed automatically from the width of the columns
10319 under org-mode.
10321 The general parameters :skip and :skipcols have already been applied when
10322 this function is called."
10323 (let* ((total (float (apply '+ org-table-last-column-widths)))
10324 (colfrac (or (plist-get params :cf)
10325 (mapconcat
10326 (lambda (x) (format "%.3f" (/ (float x) total)))
10327 org-table-last-column-widths " ")))
10328 (params2
10329 (list
10330 :tstart (concat "@multitable @columnfractions " colfrac)
10331 :tend "@end multitable"
10332 :lstart "@item " :lend "" :sep " @tab "
10333 :hlstart "@headitem ")))
10334 (orgtbl-to-generic table (org-combine-plists params2 params))))
10336 ;;;; Link Stuff
10338 ;;; Link abbreviations
10340 (defun org-link-expand-abbrev (link)
10341 "Apply replacements as defined in `org-link-abbrev-alist."
10342 (if (string-match "^\\([a-zA-Z]+\\)\\(::?\\(.*\\)\\)?$" link)
10343 (let* ((key (match-string 1 link))
10344 (as (or (assoc key org-link-abbrev-alist-local)
10345 (assoc key org-link-abbrev-alist)))
10346 (tag (and (match-end 2) (match-string 3 link)))
10347 rpl)
10348 (if (not as)
10349 link
10350 (setq rpl (cdr as))
10351 (cond
10352 ((symbolp rpl) (funcall rpl tag))
10353 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
10354 (t (concat rpl tag)))))
10355 link))
10357 ;;; Storing and inserting links
10359 (defvar org-insert-link-history nil
10360 "Minibuffer history for links inserted with `org-insert-link'.")
10362 (defvar org-stored-links nil
10363 "Contains the links stored with `org-store-link'.")
10365 (defvar org-store-link-plist nil
10366 "Plist with info about the most recently link created with `org-store-link'.")
10368 ;;;###autoload
10369 (defun org-store-link (arg)
10370 "\\<org-mode-map>Store an org-link to the current location.
10371 This link can later be inserted into an org-buffer with
10372 \\[org-insert-link].
10373 For some link types, a prefix arg is interpreted:
10374 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10375 For file links, arg negates `org-context-in-file-links'."
10376 (interactive "P")
10377 (setq org-store-link-plist nil) ; reset
10378 (let (link cpltxt desc description search txt)
10379 (cond
10381 ((eq major-mode 'bbdb-mode)
10382 (let ((name (bbdb-record-name (bbdb-current-record)))
10383 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
10384 (setq cpltxt (concat "bbdb:" (or name company))
10385 link (org-make-link cpltxt))
10386 (org-store-link-props :type "bbdb" :name name :company company)))
10388 ((eq major-mode 'Info-mode)
10389 (setq link (org-make-link "info:"
10390 (file-name-nondirectory Info-current-file)
10391 ":" Info-current-node))
10392 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10393 ":" Info-current-node))
10394 (org-store-link-props :type "info" :file Info-current-file
10395 :node Info-current-node))
10397 ((eq major-mode 'calendar-mode)
10398 (let ((cd (calendar-cursor-to-date)))
10399 (setq link
10400 (format-time-string
10401 (car org-time-stamp-formats)
10402 (apply 'encode-time
10403 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10404 nil nil nil))))
10405 (org-store-link-props :type "calendar" :date cd)))
10407 ((or (eq major-mode 'vm-summary-mode)
10408 (eq major-mode 'vm-presentation-mode))
10409 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10410 (vm-follow-summary-cursor)
10411 (save-excursion
10412 (vm-select-folder-buffer)
10413 (let* ((message (car vm-message-pointer))
10414 (folder buffer-file-name)
10415 (subject (vm-su-subject message))
10416 (to (vm-get-header-contents message "To"))
10417 (from (vm-get-header-contents message "From"))
10418 (message-id (vm-su-message-id message)))
10419 (org-store-link-props :type "vm" :from from :to to :subject subject
10420 :message-id message-id)
10421 (setq message-id (org-remove-angle-brackets message-id))
10422 (setq folder (abbreviate-file-name folder))
10423 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10424 folder)
10425 (setq folder (replace-match "" t t folder)))
10426 (setq cpltxt (org-email-link-description))
10427 (setq link (org-make-link "vm:" folder "#" message-id)))))
10429 ((eq major-mode 'wl-summary-mode)
10430 (let* ((msgnum (wl-summary-message-number))
10431 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10432 msgnum 'message-id))
10433 (wl-message-entity
10434 (if (fboundp 'elmo-message-entity)
10435 (elmo-message-entity
10436 wl-summary-buffer-elmo-folder msgnum)
10437 (elmo-msgdb-overview-get-entity
10438 msgnum (wl-summary-buffer-msgdb))))
10439 (from (wl-summary-line-from))
10440 (to (car (elmo-message-entity-field wl-message-entity 'to)))
10441 (subject (let (wl-thr-indent-string wl-parent-message-entity)
10442 (wl-summary-line-subject))))
10443 (org-store-link-props :type "wl" :from from :to to
10444 :subject subject :message-id message-id)
10445 (setq message-id (org-remove-angle-brackets message-id))
10446 (setq cpltxt (org-email-link-description))
10447 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10448 "#" message-id))))
10450 ((or (equal major-mode 'mh-folder-mode)
10451 (equal major-mode 'mh-show-mode))
10452 (let ((from (org-mhe-get-header "From:"))
10453 (to (org-mhe-get-header "To:"))
10454 (message-id (org-mhe-get-header "Message-Id:"))
10455 (subject (org-mhe-get-header "Subject:")))
10456 (org-store-link-props :type "mh" :from from :to to
10457 :subject subject :message-id message-id)
10458 (setq cpltxt (org-email-link-description))
10459 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10460 (org-remove-angle-brackets message-id)))))
10462 ((eq major-mode 'rmail-mode)
10463 (save-excursion
10464 (save-restriction
10465 (rmail-narrow-to-non-pruned-header)
10466 (let ((folder buffer-file-name)
10467 (message-id (mail-fetch-field "message-id"))
10468 (from (mail-fetch-field "from"))
10469 (to (mail-fetch-field "to"))
10470 (subject (mail-fetch-field "subject")))
10471 (org-store-link-props
10472 :type "rmail" :from from :to to
10473 :subject subject :message-id message-id)
10474 (setq message-id (org-remove-angle-brackets message-id))
10475 (setq cpltxt (org-email-link-description))
10476 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10478 ((eq major-mode 'gnus-group-mode)
10479 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10480 (gnus-group-group-name)) ; version
10481 ((fboundp 'gnus-group-name)
10482 (gnus-group-name))
10483 (t "???"))))
10484 (unless group (error "Not on a group"))
10485 (org-store-link-props :type "gnus" :group group)
10486 (setq cpltxt (concat
10487 (if (org-xor arg org-usenet-links-prefer-google)
10488 "http://groups.google.com/groups?group="
10489 "gnus:")
10490 group)
10491 link (org-make-link cpltxt))))
10493 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10494 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10495 (let* ((group gnus-newsgroup-name)
10496 (article (gnus-summary-article-number))
10497 (header (gnus-summary-article-header article))
10498 (from (mail-header-from header))
10499 (message-id (mail-header-id header))
10500 (date (mail-header-date header))
10501 (subject (gnus-summary-subject-string)))
10502 (org-store-link-props :type "gnus" :from from :subject subject
10503 :message-id message-id :group group)
10504 (setq cpltxt (org-email-link-description))
10505 (if (org-xor arg org-usenet-links-prefer-google)
10506 (setq link
10507 (concat
10508 cpltxt "\n "
10509 (format "http://groups.google.com/groups?as_umsgid=%s"
10510 (org-fixup-message-id-for-http message-id))))
10511 (setq link (org-make-link "gnus:" group
10512 "#" (number-to-string article))))))
10514 ((eq major-mode 'w3-mode)
10515 (setq cpltxt (url-view-url t)
10516 link (org-make-link cpltxt))
10517 (org-store-link-props :type "w3" :url (url-view-url t)))
10519 ((eq major-mode 'w3m-mode)
10520 (setq cpltxt (or w3m-current-title w3m-current-url)
10521 link (org-make-link w3m-current-url))
10522 (org-store-link-props :type "w3m" :url (url-view-url t)))
10524 ((setq search (run-hook-with-args-until-success
10525 'org-create-file-search-functions))
10526 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10527 "::" search))
10528 (setq cpltxt (or description link)))
10530 ((eq major-mode 'image-mode)
10531 (setq cpltxt (concat "file:"
10532 (abbreviate-file-name buffer-file-name))
10533 link (org-make-link cpltxt))
10534 (org-store-link-props :type "image" :file buffer-file-name))
10536 ((eq major-mode 'dired-mode)
10537 ;; link to the file in the current line
10538 (setq cpltxt (concat "file:"
10539 (abbreviate-file-name
10540 (expand-file-name
10541 (dired-get-filename nil t))))
10542 link (org-make-link cpltxt)))
10544 ((and buffer-file-name (org-mode-p))
10545 ;; Just link to current headline
10546 (setq cpltxt (concat "file:"
10547 (abbreviate-file-name buffer-file-name)))
10548 ;; Add a context search string
10549 (when (org-xor org-context-in-file-links arg)
10550 ;; Check if we are on a target
10551 (if (org-in-regexp "<<\\(.*?\\)>>")
10552 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10553 (setq txt (cond
10554 ((org-on-heading-p) nil)
10555 ((org-region-active-p)
10556 (buffer-substring (region-beginning) (region-end)))
10557 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10558 (when (or (null txt) (string-match "\\S-" txt))
10559 (setq cpltxt
10560 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10561 desc "NONE"))))
10562 (if (string-match "::\\'" cpltxt)
10563 (setq cpltxt (substring cpltxt 0 -2)))
10564 (setq link (org-make-link cpltxt)))
10566 (buffer-file-name
10567 ;; Just link to this file here.
10568 (setq cpltxt (concat "file:"
10569 (abbreviate-file-name buffer-file-name)))
10570 ;; Add a context string
10571 (when (org-xor org-context-in-file-links arg)
10572 (setq txt (if (org-region-active-p)
10573 (buffer-substring (region-beginning) (region-end))
10574 (buffer-substring (point-at-bol) (point-at-eol))))
10575 ;; Only use search option if there is some text.
10576 (when (string-match "\\S-" txt)
10577 (setq cpltxt
10578 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10579 desc "NONE")))
10580 (setq link (org-make-link cpltxt)))
10582 ((interactive-p)
10583 (error "Cannot link to a buffer which is not visiting a file"))
10585 (t (setq link nil)))
10587 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10588 (setq link (or link cpltxt)
10589 desc (or desc cpltxt))
10590 (if (equal desc "NONE") (setq desc nil))
10592 (if (and (interactive-p) link)
10593 (progn
10594 (setq org-stored-links
10595 (cons (list cpltxt link desc) org-stored-links))
10596 (message "Stored: %s" (or cpltxt link)))
10597 (org-make-link-string link desc))))
10599 (defun org-store-link-props (&rest plist)
10600 "Store link properties, extract names and addresses."
10601 (let (x adr)
10602 (when (setq x (plist-get plist :from))
10603 (setq adr (mail-extract-address-components x))
10604 (plist-put plist :fromname (car adr))
10605 (plist-put plist :fromaddress (nth 1 adr)))
10606 (when (setq x (plist-get plist :to))
10607 (setq adr (mail-extract-address-components x))
10608 (plist-put plist :toname (car adr))
10609 (plist-put plist :toaddress (nth 1 adr))))
10610 (let ((from (plist-get plist :from))
10611 (to (plist-get plist :to)))
10612 (when (and from to org-from-is-user-regexp)
10613 (plist-put plist :fromto
10614 (if (string-match org-from-is-user-regexp from)
10615 (concat "to %t")
10616 (concat "from %f")))))
10617 (setq org-store-link-plist plist))
10619 (defun org-email-link-description (&optional fmt)
10620 "Return the description part of an email link.
10621 This takes information from `org-store-link-plist' and formats it
10622 according to FMT (default from `org-email-link-description-format')."
10623 (setq fmt (or fmt org-email-link-description-format))
10624 (let* ((p org-store-link-plist)
10625 (to (plist-get p :toaddress))
10626 (from (plist-get p :fromaddress))
10627 (table
10628 (list
10629 (cons "%c" (plist-get p :fromto))
10630 (cons "%F" (plist-get p :from))
10631 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10632 (cons "%T" (plist-get p :to))
10633 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10634 (cons "%s" (plist-get p :subject))
10635 (cons "%m" (plist-get p :message-id)))))
10636 (when (string-match "%c" fmt)
10637 ;; Check if the user wrote this message
10638 (if (and org-from-is-user-regexp from to
10639 (save-match-data (string-match org-from-is-user-regexp from)))
10640 (setq fmt (replace-match "to %t" t t fmt))
10641 (setq fmt (replace-match "from %f" t t fmt))))
10642 (org-replace-escapes fmt table)))
10644 (defun org-make-org-heading-search-string (&optional string heading)
10645 "Make search string for STRING or current headline."
10646 (interactive)
10647 (let ((s (or string (org-get-heading))))
10648 (unless (and string (not heading))
10649 ;; We are using a headline, clean up garbage in there.
10650 (if (string-match org-todo-regexp s)
10651 (setq s (replace-match "" t t s)))
10652 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
10653 (setq s (replace-match "" t t s)))
10654 (setq s (org-trim s))
10655 (if (string-match (concat "^\\(" org-quote-string "\\|"
10656 org-comment-string "\\)") s)
10657 (setq s (replace-match "" t t s)))
10658 (while (string-match org-ts-regexp s)
10659 (setq s (replace-match "" t t s))))
10660 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10661 (setq s (replace-match " " t t s)))
10662 (or string (setq s (concat "*" s))) ; Add * for headlines
10663 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10665 (defun org-make-link (&rest strings)
10666 "Concatenate STRINGS, format resulting string with `org-link-format'."
10667 (apply 'concat strings))
10669 (defun org-make-link-string (link &optional description)
10670 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10671 (when (stringp description)
10672 ;; Remove brackets from the description, they are fatal.
10673 (while (string-match "\\[\\|\\]" description)
10674 (setq description (replace-match "" t t description))))
10675 (when (equal (org-link-escape link) description)
10676 ;; No description needed, it is identical
10677 (setq description nil))
10678 (when (and (not description)
10679 (not (equal link (org-link-escape link))))
10680 (setq description link))
10681 (concat "[[" (org-link-escape link) "]"
10682 (if description (concat "[" description "]") "")
10683 "]"))
10685 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10686 "Association list of escapes for some characters problematic in links.")
10688 (defun org-link-escape (text)
10689 "Escape charaters in TEXT that are problematic for links."
10690 (when text
10691 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10692 org-link-escape-chars "\\|")))
10693 (while (string-match re text)
10694 (setq text
10695 (replace-match
10696 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10697 t t text)))
10698 text)))
10700 (defun org-link-unescape (text)
10701 "Reverse the action of `org-link-escape'."
10702 (when text
10703 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10704 org-link-escape-chars "\\|")))
10705 (while (string-match re text)
10706 (setq text
10707 (replace-match
10708 (car (rassoc (match-string 0 text) org-link-escape-chars))
10709 t t text)))
10710 text)))
10712 (defun org-xor (a b)
10713 "Exclusive or."
10714 (if a (not b) b))
10716 (defun org-get-header (header)
10717 "Find a header field in the current buffer."
10718 (save-excursion
10719 (goto-char (point-min))
10720 (let ((case-fold-search t) s)
10721 (cond
10722 ((eq header 'from)
10723 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10724 (setq s (match-string 1)))
10725 (while (string-match "\"" s)
10726 (setq s (replace-match "" t t s)))
10727 (if (string-match "[<(].*" s)
10728 (setq s (replace-match "" t t s))))
10729 ((eq header 'message-id)
10730 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10731 (setq s (match-string 1))))
10732 ((eq header 'subject)
10733 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10734 (setq s (match-string 1)))))
10735 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10736 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10737 s)))
10740 (defun org-fixup-message-id-for-http (s)
10741 "Replace special characters in a message id, so it can be used in an http query."
10742 (while (string-match "<" s)
10743 (setq s (replace-match "%3C" t t s)))
10744 (while (string-match ">" s)
10745 (setq s (replace-match "%3E" t t s)))
10746 (while (string-match "@" s)
10747 (setq s (replace-match "%40" t t s)))
10750 (defun org-insert-link (&optional complete-file)
10751 "Insert a link. At the prompt, enter the link.
10753 Completion can be used to select a link previously stored with
10754 `org-store-link'. When the empty string is entered (i.e. if you just
10755 press RET at the prompt), the link defaults to the most recently
10756 stored link. As SPC triggers completion in the minibuffer, you need to
10757 use M-SPC or C-q SPC to force the insertion of a space character.
10759 You will also be prompted for a description, and if one is given, it will
10760 be displayed in the buffer instead of the link.
10762 If there is already a link at point, this command will allow you to edit link
10763 and description parts.
10765 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10766 selected using completion. The path to the file will be relative to
10767 the current directory if the file is in the current directory or a
10768 subdirectory. Otherwise, the link will be the absolute path as
10769 completed in the minibuffer (i.e. normally ~/path/to/file).
10771 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10772 is in the current directory or below.
10773 With three \\[universal-argument] prefixes, negate the meaning of
10774 `org-keep-stored-link-after-insertion'."
10775 (interactive "P")
10776 (let ((wcf (current-window-configuration))
10777 (region (if (org-region-active-p)
10778 (prog1 (buffer-substring (region-beginning) (region-end))
10779 (delete-region (region-beginning) (region-end)))))
10780 tmphist ; byte-compile incorrectly complains about this
10781 link desc entry remove file)
10782 (cond
10783 ((org-in-regexp org-bracket-link-regexp 1)
10784 ;; We do have a link at point, and we are going to edit it.
10785 (setq remove (list (match-beginning 0) (match-end 0)))
10786 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10787 (setq link (read-string "Link: "
10788 (org-link-unescape
10789 (org-match-string-no-properties 1)))))
10790 ((or (org-in-regexp org-angle-link-re)
10791 (org-in-regexp org-plain-link-re))
10792 ;; Convert to bracket link
10793 (setq remove (list (match-beginning 0) (match-end 0))
10794 link (read-string "Link: "
10795 (org-remove-angle-brackets (match-string 0)))))
10796 ((equal complete-file '(4))
10797 ;; Completing read for file names.
10798 (setq file (read-file-name "File: "))
10799 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10800 (pwd1 (file-name-as-directory (abbreviate-file-name
10801 (expand-file-name ".")))))
10802 (cond
10803 ((equal complete-file '(16))
10804 (setq link (org-make-link
10805 "file:"
10806 (abbreviate-file-name (expand-file-name file)))))
10807 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10808 (setq link (org-make-link "file:" (match-string 1 file))))
10809 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10810 (expand-file-name file))
10811 (setq link (org-make-link
10812 "file:" (match-string 1 (expand-file-name file)))))
10813 (t (setq link (org-make-link "file:" file))))))
10815 ;; Read link, with completion for stored links.
10816 (with-output-to-temp-buffer "*Org Links*"
10817 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
10818 (when org-stored-links
10819 (princ "\nStored links are available with <up>/<down> (most recent with RET):\n\n")
10820 (princ (mapconcat 'car (reverse org-stored-links) "\n"))))
10821 (let ((cw (selected-window)))
10822 (select-window (get-buffer-window "*Org Links*"))
10823 (shrink-window-if-larger-than-buffer)
10824 (setq truncate-lines t)
10825 (select-window cw))
10826 ;; Fake a link history, containing the stored links.
10827 (setq tmphist (append (mapcar 'car org-stored-links)
10828 org-insert-link-history))
10829 (unwind-protect
10830 (setq link (org-completing-read
10831 "Link: "
10832 (append
10833 (mapcar (lambda (x) (list (concat (car x) ":")))
10834 (append org-link-abbrev-alist-local org-link-abbrev-alist))
10835 (mapcar (lambda (x) (list (concat x ":")))
10836 org-link-types))
10837 nil nil nil
10838 'tmphist
10839 (or (car (car org-stored-links)))))
10840 (set-window-configuration wcf)
10841 (kill-buffer "*Org Links*"))
10842 (setq entry (assoc link org-stored-links))
10843 (or entry (push link org-insert-link-history))
10844 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10845 (not org-keep-stored-link-after-insertion))
10846 (setq org-stored-links (delq (assoc link org-stored-links)
10847 org-stored-links)))
10848 (setq link (if entry (nth 1 entry) link)
10849 desc (or region desc (nth 2 entry)))))
10851 (if (string-match org-plain-link-re link)
10852 ;; URL-like link, normalize the use of angular brackets.
10853 (setq link (org-make-link (org-remove-angle-brackets link))))
10855 ;; Check if we are linking to the current file with a search option
10856 ;; If yes, simplify the link by using only the search option.
10857 (when (and buffer-file-name
10858 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
10859 (let* ((path (match-string 1 link))
10860 (case-fold-search nil)
10861 (search (match-string 2 link)))
10862 (save-match-data
10863 (if (equal (file-truename buffer-file-name) (file-truename path))
10864 ;; We are linking to this same file, with a search option
10865 (setq link search)))))
10867 ;; Check if we can/should use a relative path. If yes, simplify the link
10868 (when (string-match "\\<file:\\(.*\\)" link)
10869 (let* ((path (match-string 1 link))
10870 (case-fold-search nil))
10871 (cond
10872 ((eq org-link-file-path-type 'absolute)
10873 (setq path (abbreviate-file-name (expand-file-name path))))
10874 ((eq org-link-file-path-type 'noabbrev)
10875 (setq path (expand-file-name path)))
10876 ((eq org-link-file-path-type 'relative)
10877 (setq path (file-relative-name path)))
10879 (save-match-data
10880 (if (string-match (concat "^" (regexp-quote
10881 (file-name-as-directory
10882 (expand-file-name "."))))
10883 (expand-file-name path))
10884 ;; We are linking a file with relative path name.
10885 (setq path (substring (expand-file-name path)
10886 (match-end 0)))))))
10887 (setq link (concat "file:" path))))
10889 (setq desc (read-string "Description: " desc))
10890 (unless (string-match "\\S-" desc) (setq desc nil))
10891 (if remove (apply 'delete-region remove))
10892 (insert (org-make-link-string link desc))))
10894 (defun org-completing-read (&rest args)
10895 (let ((minibuffer-local-completion-map
10896 (copy-keymap minibuffer-local-completion-map)))
10897 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10898 (apply 'completing-read args)))
10900 ;;; Opening/following a link
10901 (defvar org-link-search-failed nil)
10903 (defun org-next-link ()
10904 "Move forward to the next link.
10905 If the link is in hidden text, expose it."
10906 (interactive)
10907 (when (and org-link-search-failed (eq this-command last-command))
10908 (goto-char (point-min))
10909 (message "Link search wrapped back to beginning of buffer"))
10910 (setq org-link-search-failed nil)
10911 (let* ((pos (point))
10912 (ct (org-context))
10913 (a (assoc :link ct)))
10914 (if a (goto-char (nth 2 a)))
10915 (if (re-search-forward org-any-link-re nil t)
10916 (progn
10917 (goto-char (match-beginning 0))
10918 (if (org-invisible-p) (org-show-context)))
10919 (goto-char pos)
10920 (setq org-link-search-failed t)
10921 (error "No further link found"))))
10923 (defun org-previous-link ()
10924 "Move backward to the previous link.
10925 If the link is in hidden text, expose it."
10926 (interactive)
10927 (when (and org-link-search-failed (eq this-command last-command))
10928 (goto-char (point-max))
10929 (message "Link search wrapped back to end of buffer"))
10930 (setq org-link-search-failed nil)
10931 (let* ((pos (point))
10932 (ct (org-context))
10933 (a (assoc :link ct)))
10934 (if a (goto-char (nth 1 a)))
10935 (if (re-search-backward org-any-link-re nil t)
10936 (progn
10937 (goto-char (match-beginning 0))
10938 (if (org-invisible-p) (org-show-context)))
10939 (goto-char pos)
10940 (setq org-link-search-failed t)
10941 (error "No further link found"))))
10943 (defun org-find-file-at-mouse (ev)
10944 "Open file link or URL at mouse."
10945 (interactive "e")
10946 (mouse-set-point ev)
10947 (org-open-at-point 'in-emacs))
10949 (defun org-open-at-mouse (ev)
10950 "Open file link or URL at mouse."
10951 (interactive "e")
10952 (mouse-set-point ev)
10953 (org-open-at-point))
10955 (defvar org-window-config-before-follow-link nil
10956 "The window configuration before following a link.
10957 This is saved in case the need arises to restore it.")
10959 (defvar org-open-link-marker (make-marker)
10960 "Marker pointing to the location where `org-open-at-point; was called.")
10962 (defun org-open-at-point (&optional in-emacs)
10963 "Open link at or after point.
10964 If there is no link at point, this function will search forward up to
10965 the end of the current subtree.
10966 Normally, files will be opened by an appropriate application. If the
10967 optional argument IN-EMACS is non-nil, Emacs will visit the file."
10968 (interactive "P")
10969 (move-marker org-open-link-marker (point))
10970 (setq org-window-config-before-follow-link (current-window-configuration))
10971 (org-remove-occur-highlights nil nil t)
10972 (if (org-at-timestamp-p t)
10973 (org-follow-timestamp-link)
10974 (let (type path link line search (pos (point)))
10975 (catch 'match
10976 (save-excursion
10977 (skip-chars-forward "^]\n\r")
10978 (when (org-in-regexp org-bracket-link-regexp)
10979 (setq link (org-link-unescape (org-match-string-no-properties 1)))
10980 (while (string-match " *\n *" link)
10981 (setq link (replace-match " " t t link)))
10982 (setq link (org-link-expand-abbrev link))
10983 (if (string-match org-link-re-with-space2 link)
10984 (setq type (match-string 1 link) path (match-string 2 link))
10985 (setq type "thisfile" path link))
10986 (throw 'match t)))
10988 (when (get-text-property (point) 'org-linked-text)
10989 (setq type "thisfile"
10990 pos (if (get-text-property (1+ (point)) 'org-linked-text)
10991 (1+ (point)) (point))
10992 path (buffer-substring
10993 (previous-single-property-change pos 'org-linked-text)
10994 (next-single-property-change pos 'org-linked-text)))
10995 (throw 'match t))
10997 (save-excursion
10998 (when (or (org-in-regexp org-angle-link-re)
10999 (org-in-regexp org-plain-link-re))
11000 (setq type (match-string 1) path (match-string 2))
11001 (throw 'match t)))
11002 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11003 (setq type "tree-match"
11004 path (match-string 1))
11005 (throw 'match t))
11006 (save-excursion
11007 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11008 (setq type "tags"
11009 path (match-string 1))
11010 (while (string-match ":" path)
11011 (setq path (replace-match "+" t t path)))
11012 (throw 'match t))))
11013 (unless path
11014 (error "No link found"))
11015 ;; Remove any trailing spaces in path
11016 (if (string-match " +\\'" path)
11017 (setq path (replace-match "" t t path)))
11019 (cond
11021 ((equal type "mailto")
11022 (let ((cmd (car org-link-mailto-program))
11023 (args (cdr org-link-mailto-program)) args1
11024 (address path) (subject "") a)
11025 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11026 (setq address (match-string 1 path)
11027 subject (org-link-escape (match-string 2 path))))
11028 (while args
11029 (cond
11030 ((not (stringp (car args))) (push (pop args) args1))
11031 (t (setq a (pop args))
11032 (if (string-match "%a" a)
11033 (setq a (replace-match address t t a)))
11034 (if (string-match "%s" a)
11035 (setq a (replace-match subject t t a)))
11036 (push a args1))))
11037 (apply cmd (nreverse args1))))
11039 ((member type '("http" "https" "ftp" "news"))
11040 (browse-url (concat type ":" path)))
11042 ((string= type "tags")
11043 (org-tags-view in-emacs path))
11044 ((string= type "thisfile")
11045 (if in-emacs
11046 (switch-to-buffer-other-window
11047 (org-get-buffer-for-internal-link (current-buffer)))
11048 (org-mark-ring-push))
11049 (let ((cmd `(org-link-search
11050 ,path
11051 ,(cond ((equal in-emacs '(4)) 'occur)
11052 ((equal in-emacs '(16)) 'org-occur)
11053 (t nil))
11054 ,pos)))
11055 (condition-case nil (eval cmd)
11056 (error (progn (widen) (eval cmd))))))
11058 ((string= type "tree-match")
11059 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11061 ((string= type "file")
11062 (if (string-match "::\\([0-9]+\\)\\'" path)
11063 (setq line (string-to-number (match-string 1 path))
11064 path (substring path 0 (match-beginning 0)))
11065 (if (string-match "::\\(.+\\)\\'" path)
11066 (setq search (match-string 1 path)
11067 path (substring path 0 (match-beginning 0)))))
11068 (org-open-file path in-emacs line search))
11070 ((string= type "news")
11071 (org-follow-gnus-link path))
11073 ((string= type "bbdb")
11074 (org-follow-bbdb-link path))
11076 ((string= type "info")
11077 (org-follow-info-link path))
11079 ((string= type "gnus")
11080 (let (group article)
11081 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11082 (error "Error in Gnus link"))
11083 (setq group (match-string 1 path)
11084 article (match-string 3 path))
11085 (org-follow-gnus-link group article)))
11087 ((string= type "vm")
11088 (let (folder article)
11089 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11090 (error "Error in VM link"))
11091 (setq folder (match-string 1 path)
11092 article (match-string 3 path))
11093 ;; in-emacs is the prefix arg, will be interpreted as read-only
11094 (org-follow-vm-link folder article in-emacs)))
11096 ((string= type "wl")
11097 (let (folder article)
11098 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11099 (error "Error in Wanderlust link"))
11100 (setq folder (match-string 1 path)
11101 article (match-string 3 path))
11102 (org-follow-wl-link folder article)))
11104 ((string= type "mhe")
11105 (let (folder article)
11106 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11107 (error "Error in MHE link"))
11108 (setq folder (match-string 1 path)
11109 article (match-string 3 path))
11110 (org-follow-mhe-link folder article)))
11112 ((string= type "rmail")
11113 (let (folder article)
11114 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11115 (error "Error in RMAIL link"))
11116 (setq folder (match-string 1 path)
11117 article (match-string 3 path))
11118 (org-follow-rmail-link folder article)))
11120 ((string= type "shell")
11121 (let ((cmd path))
11122 ;; FIXME: the following is only for backward compatibility
11123 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
11124 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
11125 (if (or (not org-confirm-shell-link-function)
11126 (funcall org-confirm-shell-link-function
11127 (format "Execute \"%s\" in shell? "
11128 (org-add-props cmd nil
11129 'face 'org-warning))))
11130 (progn
11131 (message "Executing %s" cmd)
11132 (shell-command cmd))
11133 (error "Abort"))))
11135 ((string= type "elisp")
11136 (let ((cmd path))
11137 (if (or (not org-confirm-elisp-link-function)
11138 (funcall org-confirm-elisp-link-function
11139 (format "Execute \"%s\" as elisp? "
11140 (org-add-props cmd nil
11141 'face 'org-warning))))
11142 (message "%s => %s" cmd (eval (read cmd)))
11143 (error "Abort"))))
11146 (browse-url-at-point)))))
11147 (move-marker org-open-link-marker nil))
11150 ;;; File search
11152 (defvar org-create-file-search-functions nil
11153 "List of functions to construct the right search string for a file link.
11154 These functions are called in turn with point at the location to
11155 which the link should point.
11157 A function in the hook should first test if it would like to
11158 handle this file type, for example by checking the major-mode or
11159 the file extension. If it decides not to handle this file, it
11160 should just return nil to give other functions a chance. If it
11161 does handle the file, it must return the search string to be used
11162 when following the link. The search string will be part of the
11163 file link, given after a double colon, and `org-open-at-point'
11164 will automatically search for it. If special measures must be
11165 taken to make the search successful, another function should be
11166 added to the companion hook `org-execute-file-search-functions',
11167 which see.
11169 A function in this hook may also use `setq' to set the variable
11170 `description' to provide a suggestion for the descriptive text to
11171 be used for this link when it gets inserted into an Org-mode
11172 buffer with \\[org-insert-link].")
11174 (defvar org-execute-file-search-functions nil
11175 "List of functions to execute a file search triggered by a link.
11177 Functions added to this hook must accept a single argument, the
11178 search string that was part of the file link, the part after the
11179 double colon. The function must first check if it would like to
11180 handle this search, for example by checking the major-mode or the
11181 file extension. If it decides not to handle this search, it
11182 should just return nil to give other functions a chance. If it
11183 does handle the search, it must return a non-nil value to keep
11184 other functions from trying.
11186 Each function can access the current prefix argument through the
11187 variable `current-prefix-argument'. Note that a single prefix is
11188 used to force opening a link in Emacs, so it may be good to only
11189 use a numeric or double prefix to guide the search function.
11191 In case this is needed, a function in this hook can also restore
11192 the window configuration before `org-open-at-point' was called using:
11194 (set-window-configuration org-window-config-before-follow-link)")
11196 (defun org-link-search (s &optional type avoid-pos)
11197 "Search for a link search option.
11198 If S is surrounded by forward slashes, it is interpreted as a
11199 regular expression. In org-mode files, this will create an `org-occur'
11200 sparse tree. In ordinary files, `occur' will be used to list matches.
11201 If the current buffer is in `dired-mode', grep will be used to search
11202 in all files. If AVOID-POS is given, ignore matches near that position."
11203 (let ((case-fold-search t)
11204 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
11205 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
11206 (append '(("") (" ") ("\t") ("\n"))
11207 org-emphasis-alist)
11208 "\\|") "\\)"))
11209 (pos (point))
11210 (pre "") (post "")
11211 words re0 re1 re2 re3 re4 re5 re2a reall)
11212 (cond
11213 ;; First check if there are any special
11214 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11215 ;; Now try the builtin stuff
11216 ((save-excursion
11217 (goto-char (point-min))
11218 (and
11219 (re-search-forward
11220 (concat "<<" (regexp-quote s0) ">>") nil t)
11221 (setq pos (match-beginning 0))))
11222 ;; There is an exact target for this
11223 (goto-char pos))
11224 ((string-match "^/\\(.*\\)/$" s)
11225 ;; A regular expression
11226 (cond
11227 ((org-mode-p)
11228 (org-occur (match-string 1 s)))
11229 ;;((eq major-mode 'dired-mode)
11230 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
11231 (t (org-do-occur (match-string 1 s)))))
11233 ;; A normal search strings
11234 (when (equal (string-to-char s) ?*)
11235 ;; Anchor on headlines, post may include tags.
11236 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
11237 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
11238 s (substring s 1)))
11239 (remove-text-properties
11240 0 (length s)
11241 '(face nil mouse-face nil keymap nil fontified nil) s)
11242 ;; Make a series of regular expressions to find a match
11243 (setq words (org-split-string s "[ \n\r\t]+")
11244 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
11245 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
11246 "\\)" markers)
11247 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
11248 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
11249 re1 (concat pre re2 post)
11250 re3 (concat pre re4 post)
11251 re5 (concat pre ".*" re4)
11252 re2 (concat pre re2)
11253 re2a (concat pre re2a)
11254 re4 (concat pre re4)
11255 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
11256 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
11257 re5 "\\)"
11259 (cond
11260 ((eq type 'org-occur) (org-occur reall))
11261 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
11262 (t (goto-char (point-min))
11263 (if (or (org-search-not-self 1 re0 nil t)
11264 (org-search-not-self 1 re1 nil t)
11265 (org-search-not-self 1 re2 nil t)
11266 (org-search-not-self 1 re2a nil t)
11267 (org-search-not-self 1 re3 nil t)
11268 (org-search-not-self 1 re4 nil t)
11269 (org-search-not-self 1 re5 nil t)
11271 (goto-char (match-beginning 1))
11272 (goto-char pos)
11273 (error "No match")))))
11275 ;; Normal string-search
11276 (goto-char (point-min))
11277 (if (search-forward s nil t)
11278 (goto-char (match-beginning 0))
11279 (error "No match"))))
11280 (and (org-mode-p) (org-show-context 'link-search))))
11282 (defun org-search-not-self (group &rest args)
11283 "Execute `re-search-forward', but only accept matches that do not
11284 enclose the position of `org-open-link-marker'."
11285 (let ((m org-open-link-marker))
11286 (catch 'exit
11287 (while (apply 're-search-forward args)
11288 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
11289 (goto-char (match-end group))
11290 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
11291 (> (match-beginning 0) (marker-position m))
11292 (< (match-end 0) (marker-position m)))
11293 (save-match-data
11294 (or (not (org-in-regexp
11295 org-bracket-link-analytic-regexp 1))
11296 (not (match-end 4)) ; no description
11297 (and (<= (match-beginning 4) (point))
11298 (>= (match-end 4) (point))))))
11299 (throw 'exit (point))))))))
11301 (defun org-get-buffer-for-internal-link (buffer)
11302 "Return a buffer to be used for displaying the link target of internal links."
11303 (cond
11304 ((not org-display-internal-link-with-indirect-buffer)
11305 buffer)
11306 ((string-match "(Clone)$" (buffer-name buffer))
11307 (message "Buffer is already a clone, not making another one")
11308 ;; we also do not modify visibility in this case
11309 buffer)
11310 (t ; make a new indirect buffer for displaying the link
11311 (let* ((bn (buffer-name buffer))
11312 (ibn (concat bn "(Clone)"))
11313 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11314 (with-current-buffer ib (org-overview))
11315 ib))))
11317 (defun org-do-occur (regexp &optional cleanup)
11318 "Call the Emacs command `occur'.
11319 If CLEANUP is non-nil, remove the printout of the regular expression
11320 in the *Occur* buffer. This is useful if the regex is long and not useful
11321 to read."
11322 (occur regexp)
11323 (when cleanup
11324 (let ((cwin (selected-window)) win beg end)
11325 (when (setq win (get-buffer-window "*Occur*"))
11326 (select-window win))
11327 (goto-char (point-min))
11328 (when (re-search-forward "match[a-z]+" nil t)
11329 (setq beg (match-end 0))
11330 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
11331 (setq end (1- (match-beginning 0)))))
11332 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
11333 (goto-char (point-min))
11334 (select-window cwin))))
11336 ;;; The mark ring for links jumps
11338 (defvar org-mark-ring nil
11339 "Mark ring for positions before jumps in Org-mode.")
11340 (defvar org-mark-ring-last-goto nil
11341 "Last position in the mark ring used to go back.")
11342 ;; Fill and close the ring
11343 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11344 (loop for i from 1 to org-mark-ring-length do
11345 (push (make-marker) org-mark-ring))
11346 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11347 org-mark-ring)
11349 (defun org-mark-ring-push (&optional pos buffer)
11350 "Put the current position or POS into the mark ring and rotate it."
11351 (interactive)
11352 (setq pos (or pos (point)))
11353 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11354 (move-marker (car org-mark-ring)
11355 (or pos (point))
11356 (or buffer (current-buffer)))
11357 (message
11358 (substitute-command-keys
11359 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11361 (defun org-mark-ring-goto (&optional n)
11362 "Jump to the previous position in the mark ring.
11363 With prefix arg N, jump back that many stored positions. When
11364 called several times in succession, walk through the entire ring.
11365 Org-mode commands jumping to a different position in the current file,
11366 or to another Org-mode file, automatically push the old position
11367 onto the ring."
11368 (interactive "p")
11369 (let (p m)
11370 (if (eq last-command this-command)
11371 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11372 (setq p org-mark-ring))
11373 (setq org-mark-ring-last-goto p)
11374 (setq m (car p))
11375 (switch-to-buffer (marker-buffer m))
11376 (goto-char m)
11377 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11379 (defun org-remove-angle-brackets (s)
11380 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
11381 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11383 (defun org-add-angle-brackets (s)
11384 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
11385 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
11388 ;;; Following specific links
11390 (defun org-follow-timestamp-link ()
11391 (cond
11392 ((org-at-date-range-p t)
11393 (let ((org-agenda-start-on-weekday)
11394 (t1 (match-string 1))
11395 (t2 (match-string 2)))
11396 (setq t1 (time-to-days (org-time-string-to-time t1))
11397 t2 (time-to-days (org-time-string-to-time t2)))
11398 (org-agenda-list nil t1 (1+ (- t2 t1)))))
11399 ((org-at-timestamp-p t)
11400 (org-agenda-list nil (time-to-days (org-time-string-to-time
11401 (substring (match-string 1) 0 10)))
11403 (t (error "This should not happen"))))
11406 (defun org-follow-bbdb-link (name)
11407 "Follow a BBDB link to NAME."
11408 (require 'bbdb)
11409 (let ((inhibit-redisplay (not debug-on-error))
11410 (bbdb-electric-p nil))
11411 (catch 'exit
11412 ;; Exact match on name
11413 (bbdb-name (concat "\\`" name "\\'") nil)
11414 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11415 ;; Exact match on name
11416 (bbdb-company (concat "\\`" name "\\'") nil)
11417 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11418 ;; Partial match on name
11419 (bbdb-name name nil)
11420 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11421 ;; Partial match on company
11422 (bbdb-company name nil)
11423 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
11424 ;; General match including network address and notes
11425 (bbdb name nil)
11426 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
11427 (delete-window (get-buffer-window "*BBDB*"))
11428 (error "No matching BBDB record")))))
11430 (defun org-follow-info-link (name)
11431 "Follow an info file & node link to NAME."
11432 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
11433 (string-match "\\(.*\\)" name))
11434 (progn
11435 (require 'info)
11436 (if (match-string 2 name) ; If there isn't a node, choose "Top"
11437 (Info-find-node (match-string 1 name) (match-string 2 name))
11438 (Info-find-node (match-string 1 name) "Top")))
11439 (message (concat "Could not open: " name))))
11441 (defun org-follow-gnus-link (&optional group article)
11442 "Follow a Gnus link to GROUP and ARTICLE."
11443 (require 'gnus)
11444 (funcall (cdr (assq 'gnus org-link-frame-setup)))
11445 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
11446 (cond ((and group article)
11447 (gnus-group-read-group 1 nil group)
11448 (gnus-summary-goto-article (string-to-number article) nil t))
11449 (group (gnus-group-jump-to-group group))))
11451 (defun org-follow-vm-link (&optional folder article readonly)
11452 "Follow a VM link to FOLDER and ARTICLE."
11453 (require 'vm)
11454 (setq article (org-add-angle-brackets article))
11455 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
11456 ;; ange-ftp or efs or tramp access
11457 (let ((user (or (match-string 1 folder) (user-login-name)))
11458 (host (match-string 2 folder))
11459 (file (match-string 3 folder)))
11460 (cond
11461 ((featurep 'tramp)
11462 ;; use tramp to access the file
11463 (if (featurep 'xemacs)
11464 (setq folder (format "[%s@%s]%s" user host file))
11465 (setq folder (format "/%s@%s:%s" user host file))))
11467 ;; use ange-ftp or efs
11468 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
11469 (setq folder (format "/%s@%s:%s" user host file))))))
11470 (when folder
11471 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
11472 (sit-for 0.1)
11473 (when article
11474 (vm-select-folder-buffer)
11475 (widen)
11476 (let ((case-fold-search t))
11477 (goto-char (point-min))
11478 (if (not (re-search-forward
11479 (concat "^" "message-id: *" (regexp-quote article))))
11480 (error "Could not find the specified message in this folder"))
11481 (vm-isearch-update)
11482 (vm-isearch-narrow)
11483 (vm-beginning-of-message)
11484 (vm-summarize)))))
11486 (defun org-follow-wl-link (folder article)
11487 "Follow a Wanderlust link to FOLDER and ARTICLE."
11488 (if (and (string= folder "%")
11489 article
11490 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
11491 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
11492 ;; Thus, we recompose folder and article ids.
11493 (setq folder (format "%s#%s" folder (match-string 1 article))
11494 article (match-string 3 article)))
11495 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
11496 (error "No such folder: %s" folder))
11497 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
11498 (and article
11499 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
11500 (wl-summary-redisplay)))
11502 (defun org-follow-rmail-link (folder article)
11503 "Follow an RMAIL link to FOLDER and ARTICLE."
11504 (setq article (org-add-angle-brackets article))
11505 (let (message-number)
11506 (save-excursion
11507 (save-window-excursion
11508 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11509 (setq message-number
11510 (save-restriction
11511 (widen)
11512 (goto-char (point-max))
11513 (if (re-search-backward
11514 (concat "^Message-ID:\\s-+" (regexp-quote
11515 (or article "")))
11516 nil t)
11517 (rmail-what-message))))))
11518 (if message-number
11519 (progn
11520 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
11521 (rmail-show-message message-number)
11522 message-number)
11523 (error "Message not found"))))
11525 ;;; mh-e integration based on planner-mode
11526 (defun org-mhe-get-message-real-folder ()
11527 "Return the name of the current message real folder, so if you use
11528 sequences, it will now work."
11529 (save-excursion
11530 (let* ((folder
11531 (if (equal major-mode 'mh-folder-mode)
11532 mh-current-folder
11533 ;; Refer to the show buffer
11534 mh-show-folder-buffer))
11535 (end-index
11536 (if (boundp 'mh-index-folder)
11537 (min (length mh-index-folder) (length folder))))
11539 ;; a simple test on mh-index-data does not work, because
11540 ;; mh-index-data is always nil in a show buffer.
11541 (if (and (boundp 'mh-index-folder)
11542 (string= mh-index-folder (substring folder 0 end-index)))
11543 (if (equal major-mode 'mh-show-mode)
11544 (save-window-excursion
11545 (when (buffer-live-p (get-buffer folder))
11546 (progn
11547 (pop-to-buffer folder)
11548 (org-mhe-get-message-folder-from-index)
11551 (org-mhe-get-message-folder-from-index)
11553 folder
11557 (defun org-mhe-get-message-folder-from-index ()
11558 "Returns the name of the message folder in a index folder buffer."
11559 (save-excursion
11560 (mh-index-previous-folder)
11561 (re-search-forward "^\\(+.*\\)$" nil t)
11562 (message (match-string 1))))
11564 (defun org-mhe-get-message-folder ()
11565 "Return the name of the current message folder. Be careful if you
11566 use sequences."
11567 (save-excursion
11568 (if (equal major-mode 'mh-folder-mode)
11569 mh-current-folder
11570 ;; Refer to the show buffer
11571 mh-show-folder-buffer)))
11573 (defun org-mhe-get-message-num ()
11574 "Return the number of the current message. Be careful if you
11575 use sequences."
11576 (save-excursion
11577 (if (equal major-mode 'mh-folder-mode)
11578 (mh-get-msg-num nil)
11579 ;; Refer to the show buffer
11580 (mh-show-buffer-message-number))))
11582 (defun org-mhe-get-header (header)
11583 "Return a header of the message in folder mode. This will create a
11584 show buffer for the corresponding message. If you have a more clever
11585 idea..."
11586 (let* ((folder (org-mhe-get-message-folder))
11587 (num (org-mhe-get-message-num))
11588 (buffer (get-buffer-create (concat "show-" folder)))
11589 (header-field))
11590 (with-current-buffer buffer
11591 (mh-display-msg num folder)
11592 (if (equal major-mode 'mh-folder-mode)
11593 (mh-header-display)
11594 (mh-show-header-display))
11595 (set-buffer buffer)
11596 (setq header-field (mh-get-header-field header))
11597 (if (equal major-mode 'mh-folder-mode)
11598 (mh-show)
11599 (mh-show-show))
11600 header-field)))
11602 (defun org-follow-mhe-link (folder article)
11603 "Follow an MHE link to FOLDER and ARTICLE.
11604 If ARTICLE is nil FOLDER is shown. If the configuration variable
11605 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
11606 ARTICLE is searched in all folders. Indexed searches (swish++,
11607 namazu, and others supported by MH-E) will always search in all
11608 folders."
11609 (require 'mh-e)
11610 (require 'mh-search)
11611 (require 'mh-utils)
11612 (mh-find-path)
11613 (if (not article)
11614 (mh-visit-folder (mh-normalize-folder-name folder))
11615 (setq article (org-add-angle-brackets article))
11616 (mh-search-choose)
11617 (if (equal mh-searcher 'pick)
11618 (progn
11619 (mh-search folder (list "--message-id" article))
11620 (when (and org-mhe-search-all-folders
11621 (not (org-mhe-get-message-real-folder)))
11622 (kill-this-buffer)
11623 (mh-search "+" (list "--message-id" article))))
11624 (mh-search "+" article))
11625 (if (org-mhe-get-message-real-folder)
11626 (mh-show-msg 1)
11627 (kill-this-buffer)
11628 (error "Message not found"))))
11630 ;;; BibTeX links
11632 ;; Use the custom search meachnism to construct and use search strings for
11633 ;; file links to BibTeX database entries.
11635 (defun org-create-file-search-in-bibtex ()
11636 "Create the search string and description for a BibTeX database entry."
11637 (when (eq major-mode 'bibtex-mode)
11638 ;; yes, we want to construct this search string.
11639 ;; Make a good description for this entry, using names, year and the title
11640 ;; Put it into the `description' variable which is dynamically scoped.
11641 (let ((bibtex-autokey-names 1)
11642 (bibtex-autokey-names-stretch 1)
11643 (bibtex-autokey-name-case-convert-function 'identity)
11644 (bibtex-autokey-name-separator " & ")
11645 (bibtex-autokey-additional-names " et al.")
11646 (bibtex-autokey-year-length 4)
11647 (bibtex-autokey-name-year-separator " ")
11648 (bibtex-autokey-titlewords 3)
11649 (bibtex-autokey-titleword-separator " ")
11650 (bibtex-autokey-titleword-case-convert-function 'identity)
11651 (bibtex-autokey-titleword-length 'infty)
11652 (bibtex-autokey-year-title-separator ": "))
11653 (setq description (bibtex-generate-autokey)))
11654 ;; Now parse the entry, get the key and return it.
11655 (save-excursion
11656 (bibtex-beginning-of-entry)
11657 (cdr (assoc "=key=" (bibtex-parse-entry))))))
11659 (defun org-execute-file-search-in-bibtex (s)
11660 "Find the link search string S as a key for a database entry."
11661 (when (eq major-mode 'bibtex-mode)
11662 ;; Yes, we want to do the search in this file.
11663 ;; We construct a regexp that searches for "@entrytype{" followed by the key
11664 (goto-char (point-min))
11665 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
11666 (regexp-quote s) "[ \t\n]*,") nil t)
11667 (goto-char (match-beginning 0)))
11668 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
11669 ;; Use double prefix to indicate that any web link should be browsed
11670 (let ((b (current-buffer)) (p (point)))
11671 ;; Restore the window configuration because we just use the web link
11672 (set-window-configuration org-window-config-before-follow-link)
11673 (save-excursion (set-buffer b) (goto-char p)
11674 (bibtex-url)))
11675 (recenter 0)) ; Move entry start to beginning of window
11676 ;; return t to indicate that the search is done.
11679 ;; Finally add the functions to the right hooks.
11680 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
11681 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
11683 ;; end of Bibtex link setup
11685 ;;; Following file links
11687 (defun org-open-file (path &optional in-emacs line search)
11688 "Open the file at PATH.
11689 First, this expands any special file name abbreviations. Then the
11690 configuration variable `org-file-apps' is checked if it contains an
11691 entry for this file type, and if yes, the corresponding command is launched.
11692 If no application is found, Emacs simply visits the file.
11693 With optional argument IN-EMACS, Emacs will visit the file.
11694 Optional LINE specifies a line to go to, optional SEARCH a string to
11695 search for. If LINE or SEARCH is given, the file will always be
11696 opened in Emacs.
11697 If the file does not exist, an error is thrown."
11698 (setq in-emacs (or in-emacs line search))
11699 (let* ((file (if (equal path "")
11700 buffer-file-name
11701 (substitute-in-file-name (expand-file-name path))))
11702 (apps (append org-file-apps (org-default-apps)))
11703 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11704 (dirp (if remp nil (file-directory-p file)))
11705 (dfile (downcase file))
11706 (old-buffer (current-buffer))
11707 (old-pos (point))
11708 (old-mode major-mode)
11709 ext cmd)
11710 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
11711 (setq ext (match-string 1 dfile))
11712 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
11713 (setq ext (match-string 1 dfile))))
11714 (if in-emacs
11715 (setq cmd 'emacs)
11716 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
11717 (and dirp (cdr (assoc 'directory apps)))
11718 (cdr (assoc ext apps))
11719 (cdr (assoc t apps)))))
11720 (when (eq cmd 'mailcap)
11721 (require 'mailcap)
11722 (mailcap-parse-mailcaps)
11723 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11724 (command (mailcap-mime-info mime-type)))
11725 (if (stringp command)
11726 (setq cmd command)
11727 (setq cmd 'emacs))))
11728 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11729 (not (file-exists-p file))
11730 (not org-open-non-existing-files))
11731 (error "No such file: %s" file))
11732 (cond
11733 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11734 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11735 (if (string-match "['\"]%s['\"]" cmd)
11736 (setq cmd (replace-match "%s" t t cmd)))
11737 (setq cmd (format cmd (shell-quote-argument file)))
11738 (save-window-excursion
11739 (shell-command (concat cmd " &"))))
11740 ((or (stringp cmd)
11741 (eq cmd 'emacs))
11742 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11743 (widen)
11744 (if line (goto-line line)
11745 (if search (org-link-search search))))
11746 ((consp cmd)
11747 (eval cmd))
11748 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11749 (and (org-mode-p) (eq old-mode 'org-mode)
11750 (or (not (equal old-buffer (current-buffer)))
11751 (not (equal old-pos (point))))
11752 (org-mark-ring-push old-pos old-buffer))))
11754 (defun org-default-apps ()
11755 "Return the default applications for this operating system."
11756 (cond
11757 ((eq system-type 'darwin)
11758 org-file-apps-defaults-macosx)
11759 ((eq system-type 'windows-nt)
11760 org-file-apps-defaults-windowsnt)
11761 (t org-file-apps-defaults-gnu)))
11763 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11764 (defun org-file-remote-p (file)
11765 "Test whether FILE specifies a location on a remote system.
11766 Return non-nil if the location is indeed remote.
11768 For example, the filename \"/user@host:/foo\" specifies a location
11769 on the system \"/user@host:\"."
11770 (cond ((fboundp 'file-remote-p)
11771 (file-remote-p file))
11772 ((fboundp 'tramp-handle-file-remote-p)
11773 (tramp-handle-file-remote-p file))
11774 ((and (boundp 'ange-ftp-name-format)
11775 (string-match (car ange-ftp-name-format) file))
11777 (t nil)))
11780 ;;;; Hooks for remember.el
11782 ;;;###autoload
11783 (defun org-remember-annotation ()
11784 "Return a link to the current location as an annotation for remember.el.
11785 If you are using Org-mode files as target for data storage with
11786 remember.el, then the annotations should include a link compatible with the
11787 conventions in Org-mode. This function returns such a link."
11788 (org-store-link nil))
11790 (defconst org-remember-help
11791 "Select a destination location for the note.
11792 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
11793 RET at beg-of-buf -> Append to file as level 2 headline
11794 RET on headline -> Store as sublevel entry to current headline
11795 <left>/<right> -> before/after current headline, same headings level")
11797 ;;;###autoload
11798 (defun org-remember-apply-template (&optional use-char skip-interactive)
11799 "Initialize *remember* buffer with template, invoke `org-mode'.
11800 This function should be placed into `remember-mode-hook' and in fact requires
11801 to be run from that hook to fucntion properly."
11802 (if org-remember-templates
11804 (let* ((char (or use-char
11805 (if (= (length org-remember-templates) 1)
11806 (caar org-remember-templates)
11807 (message "Select template: %s"
11808 (mapconcat
11809 (lambda (x) (char-to-string (car x)))
11810 org-remember-templates " "))
11811 (read-char-exclusive))))
11812 (entry (cdr (assoc char org-remember-templates)))
11813 (tpl (car entry))
11814 (plist-p (if org-store-link-plist t nil))
11815 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
11816 (string-match "\\S-" (nth 1 entry)))
11817 (nth 1 entry)
11818 org-default-notes-file))
11819 (headline (nth 2 entry))
11820 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
11821 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
11822 (v-u (concat "[" (substring v-t 1 -1) "]"))
11823 (v-U (concat "[" (substring v-T 1 -1) "]"))
11824 (v-i initial) ; defined in `remember-mode'
11825 (v-a (if (equal annotation "[[]]") "" annotation)) ; likewise
11826 (v-n user-full-name)
11827 (org-startup-folded nil)
11828 org-time-was-given org-end-time-was-given x prompt char time)
11829 (setq org-store-link-plist
11830 (append (list :annotation v-a :initial v-i)
11831 org-store-link-plist))
11832 (unless tpl (setq tpl "") (message "No template") (ding))
11833 (erase-buffer)
11834 (insert (substitute-command-keys
11835 (format
11836 "## `C-c C-c' to file interactively, `C-u C-c C-c' to file directly.
11837 ## Target file \"%s\", headline \"%s\"
11838 ## To switch templates, use `\\[org-remember]'.\n\n"
11839 (abbreviate-file-name (or file org-default-notes-file))
11840 (or headline ""))))
11841 (insert tpl) (goto-char (point-min))
11842 ;; Simple %-escapes
11843 (while (re-search-forward "%\\([tTuUai]\\)" nil t)
11844 (when (and initial (equal (match-string 0) "%i"))
11845 (save-match-data
11846 (let* ((lead (buffer-substring
11847 (point-at-bol) (match-beginning 0))))
11848 (setq v-i (mapconcat 'identity
11849 (org-split-string initial "\n")
11850 (concat "\n" lead))))))
11851 (replace-match
11852 (or (eval (intern (concat "v-" (match-string 1)))) "")
11853 t t))
11854 ;; From the property list
11855 (when plist-p
11856 (goto-char (point-min))
11857 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
11858 (and (setq x (plist-get org-store-link-plist
11859 (intern (match-string 1))))
11860 (replace-match x t t))))
11861 ;; Turn on org-mode in the remember buffer, set local variables
11862 (org-mode)
11863 (org-set-local 'org-finish-function 'remember-buffer)
11864 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
11865 (org-set-local 'org-default-notes-file file))
11866 (if (and headline (stringp headline) (string-match "\\S-" headline))
11867 (org-set-local 'org-remember-default-headline headline))
11868 ;; Interactive template entries
11869 (goto-char (point-min))
11870 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
11871 (setq char (if (match-end 3) (match-string 3))
11872 prompt (if (match-end 2) (match-string 2)))
11873 (goto-char (match-beginning 0))
11874 (replace-match "")
11875 (cond
11876 ((member char '("G" "g"))
11877 (let* ((org-last-tags-completion-table
11878 (org-global-tags-completion-table
11879 (if (equal char "G") (org-agenda-files) (and file (list file)))))
11880 (org-add-colon-after-tag-completion t)
11881 (ins (completing-read
11882 (if prompt (concat prompt ": ") "Tags: ")
11883 'org-tags-completion-function nil nil nil
11884 'org-tags-history)))
11885 (setq ins (mapconcat 'identity
11886 (org-split-string ins (org-re "[^[:alnum:]]+"))
11887 ":"))
11888 (when (string-match "\\S-" ins)
11889 (or (equal (char-before) ?:) (insert ":"))
11890 (insert ins)
11891 (or (equal (char-after) ?:) (insert ":")))))
11892 (char
11893 (setq org-time-was-given (equal (upcase char) char))
11894 (setq time (org-read-date (equal (upcase char) "U") t nil
11895 prompt))
11896 (org-insert-time-stamp time org-time-was-given
11897 (member char '("u" "U"))
11898 nil nil (list org-end-time-was-given)))
11900 (insert (read-string
11901 (if prompt (concat prompt ": ") "Enter string"))))))
11902 (goto-char (point-min))
11903 (if (re-search-forward "%\\?" nil t)
11904 (replace-match "")
11905 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
11906 (org-mode)
11907 (org-set-local 'org-finish-function 'remember-buffer)))
11909 ;;;###autoload
11910 (defun org-remember ()
11911 "Call `remember'. If this is already a remember buffer, re-apply template.
11912 If there is an active region, make sure remember uses it as initial content
11913 of the remember buffer."
11914 (interactive)
11915 (if (eq org-finish-function 'remember-buffer)
11916 (progn
11917 (when (< (length org-remember-templates) 2)
11918 (error "No other template available"))
11919 (erase-buffer)
11920 (let ((annotation (plist-get org-store-link-plist :annotation))
11921 (initial (plist-get org-store-link-plist :initial)))
11922 (org-remember-apply-template))
11923 (message "Press C-c C-c to remember data"))
11924 (if (org-region-active-p)
11925 (remember (buffer-substring (point) (mark)))
11926 (call-interactively 'remember))))
11928 ;;;###autoload
11929 (defun org-remember-handler ()
11930 "Store stuff from remember.el into an org file.
11931 First prompts for an org file. If the user just presses return, the value
11932 of `org-default-notes-file' is used.
11933 Then the command offers the headings tree of the selected file in order to
11934 file the text at a specific location.
11935 You can either immediately press RET to get the note appended to the
11936 file, or you can use vertical cursor motion and visibility cycling (TAB) to
11937 find a better place. Then press RET or <left> or <right> in insert the note.
11939 Key Cursor position Note gets inserted
11940 -----------------------------------------------------------------------------
11941 RET buffer-start as level 2 heading at end of file
11942 RET on headline as sublevel of the heading at cursor
11943 RET no heading at cursor position, level taken from context.
11944 Or use prefix arg to specify level manually.
11945 <left> on headline as same level, before current heading
11946 <right> on headline as same level, after current heading
11948 So the fastest way to store the note is to press RET RET to append it to
11949 the default file. This way your current train of thought is not
11950 interrupted, in accordance with the principles of remember.el. But with
11951 little extra effort, you can push it directly to the correct location.
11953 Before being stored away, the function ensures that the text has a
11954 headline, i.e. a first line that starts with a \"*\". If not, a headline
11955 is constructed from the current date and some additional data.
11957 If the variable `org-adapt-indentation' is non-nil, the entire text is
11958 also indented so that it starts in the same column as the headline
11959 \(i.e. after the stars).
11961 See also the variable `org-reverse-note-order'."
11962 (goto-char (point-min))
11963 (while (looking-at "^[ \t]*\n\\|^##.*\n")
11964 (replace-match ""))
11965 (catch 'quit
11966 (let* ((txt (buffer-substring (point-min) (point-max)))
11967 (fastp (equal current-prefix-arg '(4)))
11968 (file (if fastp org-default-notes-file (org-get-org-file)))
11969 (heading org-remember-default-headline)
11970 (visiting (org-find-base-buffer-visiting file))
11971 (org-startup-folded nil)
11972 (org-startup-align-all-tables nil)
11973 (org-goto-start-pos 1)
11974 spos level indent reversed)
11975 (setq current-prefix-arg nil)
11976 ;; Modify text so that it becomes a nice subtree which can be inserted
11977 ;; into an org tree.
11978 (let* ((lines (split-string txt "\n"))
11979 first)
11980 (setq first (car lines) lines (cdr lines))
11981 (if (string-match "^\\*+ " first)
11982 ;; Is already a headline
11983 (setq indent nil)
11984 ;; We need to add a headline: Use time and first buffer line
11985 (setq lines (cons first lines)
11986 first (concat "* " (current-time-string)
11987 " (" (remember-buffer-desc) ")")
11988 indent " "))
11989 (if (and org-adapt-indentation indent)
11990 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
11991 (setq txt (concat first "\n"
11992 (mapconcat 'identity lines "\n"))))
11993 ;; Find the file
11994 (if (not visiting) (find-file-noselect file))
11995 (with-current-buffer (or visiting (get-file-buffer file))
11996 (save-excursion
11997 (save-restriction
11998 (widen)
11999 (and (goto-char (point-min))
12000 (not (re-search-forward "^\\* " nil t))
12001 (insert "\n* Notes\n"))
12002 (setq reversed (org-notes-order-reversed-p))
12004 ;; Find the default location
12005 (when (and heading (stringp heading) (string-match "\\S-" heading))
12006 (goto-char (point-min))
12007 (if (re-search-forward
12008 (concat "^\\*+[ \t]+" (regexp-quote heading)
12009 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12010 nil t)
12011 (setq org-goto-start-pos (match-beginning 0))))
12013 ;; Ask the User for a location
12014 (setq spos (if fastp
12015 org-goto-start-pos
12016 (org-get-location (current-buffer) org-remember-help)))
12017 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12018 ; not handle this note
12019 (goto-char spos)
12020 (cond ((and (bobp) (not reversed))
12021 ;; Put it at the end, one level below level 1
12022 (save-restriction
12023 (widen)
12024 (goto-char (point-max))
12025 (if (not (bolp)) (newline))
12026 (org-paste-subtree (org-get-legal-level 1 1) txt)))
12027 ((and (bobp) reversed)
12028 ;; Put it at the start, as level 1
12029 (save-restriction
12030 (widen)
12031 (goto-char (point-min))
12032 (re-search-forward "^\\*+ " nil t)
12033 (beginning-of-line 1)
12034 (org-paste-subtree 1 txt)))
12035 ((and (org-on-heading-p t) (not current-prefix-arg))
12036 ;; Put it below this entry, at the beg/end of the subtree
12037 (org-back-to-heading t)
12038 (setq level (funcall outline-level))
12039 (if reversed
12040 (outline-next-heading)
12041 (org-end-of-subtree t))
12042 (if (not (bolp)) (newline))
12043 (beginning-of-line 1)
12044 (org-paste-subtree (org-get-legal-level level 1) txt))
12046 ;; Put it right there, with automatic level determined by
12047 ;; org-paste-subtree or from prefix arg
12048 (org-paste-subtree
12049 (if (numberp current-prefix-arg) current-prefix-arg)
12050 txt)))
12051 (when remember-save-after-remembering
12052 (save-buffer)
12053 (if (not visiting) (kill-buffer (current-buffer)))))))))
12054 t) ;; return t to indicate that we took care of this note.
12056 (defun org-get-org-file ()
12057 "Read a filename, with default directory `org-directory'."
12058 (let ((default (or org-default-notes-file remember-data-file)))
12059 (read-file-name (format "File name [%s]: " default)
12060 (file-name-as-directory org-directory)
12061 default)))
12063 (defun org-notes-order-reversed-p ()
12064 "Check if the current file should receive notes in reversed order."
12065 (cond
12066 ((not org-reverse-note-order) nil)
12067 ((eq t org-reverse-note-order) t)
12068 ((not (listp org-reverse-note-order)) nil)
12069 (t (catch 'exit
12070 (let ((all org-reverse-note-order)
12071 entry)
12072 (while (setq entry (pop all))
12073 (if (string-match (car entry) buffer-file-name)
12074 (throw 'exit (cdr entry))))
12075 nil)))))
12077 ;;;; Dynamic blocks
12079 (defun org-find-dblock (name)
12080 "Find the first dynamic block with name NAME in the buffer.
12081 If not found, stay at current position and return nil."
12082 (let (pos)
12083 (save-excursion
12084 (goto-char (point-min))
12085 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
12086 nil t)
12087 (match-beginning 0))))
12088 (if pos (goto-char pos))
12089 pos))
12091 (defconst org-dblock-start-re
12092 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
12093 "Matches the startline of a dynamic block, with parameters.")
12095 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
12096 "Matches the end of a dyhamic block.")
12098 (defun org-create-dblock (plist)
12099 "Create a dynamic block section, with parameters taken from PLIST.
12100 PLIST must containe a :name entry which is used as name of the block."
12101 (unless (bolp) (newline))
12102 (let ((name (plist-get plist :name)))
12103 (insert "#+BEGIN: " name)
12104 (while plist
12105 (if (eq (car plist) :name)
12106 (setq plist (cddr plist))
12107 (insert " " (prin1-to-string (pop plist)))))
12108 (insert "\n\n#+END:\n")
12109 (beginning-of-line -2)))
12111 (defun org-prepare-dblock ()
12112 "Prepare dynamic block for refresh.
12113 This empties the block, puts the cursor at the insert position and returns
12114 the property list including an extra property :name with the block name."
12115 (unless (looking-at org-dblock-start-re)
12116 (error "Not at a dynamic block"))
12117 (let* ((begdel (1+ (match-end 0)))
12118 (name (match-string 1))
12119 (params (append (list :name name)
12120 (read (concat "(" (match-string 3) ")")))))
12121 (unless (re-search-forward org-dblock-end-re nil t)
12122 (error "Dynamic block not terminated"))
12123 (delete-region begdel (match-beginning 0))
12124 (goto-char begdel)
12125 (open-line 1)
12126 params))
12128 (defun org-map-dblocks (&optional command)
12129 "Apply COMMAND to all dynamic blocks in the current buffer.
12130 If COMMAND is not given, use `org-update-dblock'."
12131 (let ((cmd (or command 'org-update-dblock))
12132 pos)
12133 (save-excursion
12134 (goto-char (point-min))
12135 (while (re-search-forward org-dblock-start-re nil t)
12136 (goto-char (setq pos (match-beginning 0)))
12137 (condition-case nil
12138 (funcall cmd)
12139 (error (message "Error during update of dynamic block")))
12140 (goto-char pos)
12141 (unless (re-search-forward org-dblock-end-re nil t)
12142 (error "Dynamic block not terminated"))))))
12144 (defun org-dblock-update (&optional arg)
12145 "User command for updating dynamic blocks.
12146 Update the dynamic block at point. With prefix ARG, update all dynamic
12147 blocks in the buffer."
12148 (interactive "P")
12149 (if arg
12150 (org-update-all-dblocks)
12151 (or (looking-at org-dblock-start-re)
12152 (org-beginning-of-dblock))
12153 (org-update-dblock)))
12155 (defun org-update-dblock ()
12156 "Update the dynamic block at point
12157 This means to empty the block, parse for parameters and then call
12158 the correct writing function."
12159 (let* ((pos (point))
12160 (params (org-prepare-dblock))
12161 (name (plist-get params :name))
12162 (cmd (intern (concat "org-dblock-write:" name))))
12163 (funcall cmd params)
12164 (goto-char pos)))
12166 (defun org-beginning-of-dblock ()
12167 "Find the beginning of the dynamic block at point.
12168 Error if there is no scuh block at point."
12169 (let ((pos (point))
12170 beg)
12171 (end-of-line 1)
12172 (if (and (re-search-backward org-dblock-start-re nil t)
12173 (setq beg (match-beginning 0))
12174 (re-search-forward org-dblock-end-re nil t)
12175 (> (match-end 0) pos))
12176 (goto-char beg)
12177 (goto-char pos)
12178 (error "Not in a dynamic block"))))
12180 (defun org-update-all-dblocks ()
12181 "Update all dynamic blocks in the buffer.
12182 This function can be used in a hook."
12183 (when (org-mode-p)
12184 (org-map-dblocks 'org-update-dblock)))
12187 ;;;; Completion
12189 (defun org-complete (&optional arg)
12190 "Perform completion on word at point.
12191 At the beginning of a headline, this completes TODO keywords as given in
12192 `org-todo-keywords'.
12193 If the current word is preceded by a backslash, completes the TeX symbols
12194 that are supported for HTML support.
12195 If the current word is preceded by \"#+\", completes special words for
12196 setting file options.
12197 In the line after \"#+STARTUP:, complete valid keywords.\"
12198 At all other locations, this simply calls `ispell-complete-word'."
12199 (interactive "P")
12200 (catch 'exit
12201 (let* ((end (point))
12202 (beg1 (save-excursion
12203 (skip-chars-backward (org-re "[:alnum:]_@"))
12204 (point)))
12205 (beg (save-excursion
12206 (skip-chars-backward "a-zA-Z0-9_:$")
12207 (point)))
12208 (confirm (lambda (x) (stringp (car x))))
12209 (searchhead (equal (char-before beg) ?*))
12210 (tag (and (equal (char-before beg1) ?:)
12211 (equal (char-after (point-at-bol)) ?*)))
12212 (prop (and (equal (char-before beg1) ?:)
12213 (not (equal (char-after (point-at-bol)) ?*))))
12214 (texp (equal (char-before beg) ?\\))
12215 (link (equal (char-before beg) ?\[))
12216 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
12217 beg)
12218 "#+"))
12219 (startup (string-match "^#\\+STARTUP:.*"
12220 (buffer-substring (point-at-bol) (point))))
12221 (completion-ignore-case opt)
12222 (type nil)
12223 (tbl nil)
12224 (table (cond
12225 (opt
12226 (setq type :opt)
12227 (mapcar (lambda (x)
12228 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
12229 (cons (match-string 2 x) (match-string 1 x)))
12230 (org-split-string (org-get-current-options) "\n")))
12231 (startup
12232 (setq type :startup)
12233 org-startup-options)
12234 (link (append org-link-abbrev-alist-local
12235 org-link-abbrev-alist))
12236 (texp
12237 (setq type :tex)
12238 org-html-entities)
12239 ((string-match "\\`\\*+[ \t]+\\'"
12240 (buffer-substring (point-at-bol) beg))
12241 (setq type :todo)
12242 (mapcar 'list org-todo-keywords-1))
12243 (searchhead
12244 (setq type :searchhead)
12245 (save-excursion
12246 (goto-char (point-min))
12247 (while (re-search-forward org-todo-line-regexp nil t)
12248 (push (list
12249 (org-make-org-heading-search-string
12250 (match-string 3) t))
12251 tbl)))
12252 tbl)
12253 (tag (setq type :tag beg beg1)
12254 (or org-tag-alist (org-get-buffer-tags)))
12255 (prop (setq type :prop beg beg1)
12256 (mapcar 'list (org-buffer-property-keys)))
12257 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
12258 (pattern (buffer-substring-no-properties beg end))
12259 (completion (try-completion pattern table confirm)))
12260 (cond ((eq completion t)
12261 (if (equal type :opt)
12262 (insert (substring (cdr (assoc (upcase pattern) table))
12263 (length pattern)))
12264 (if (memq type '(:tag :prop)) (insert ":"))))
12265 ((null completion)
12266 (message "Can't find completion for \"%s\"" pattern)
12267 (ding))
12268 ((not (string= pattern completion))
12269 (delete-region beg end)
12270 (if (string-match " +$" completion)
12271 (setq completion (replace-match "" t t completion)))
12272 (insert completion)
12273 (if (get-buffer-window "*Completions*")
12274 (delete-window (get-buffer-window "*Completions*")))
12275 (if (assoc completion table)
12276 (if (eq type :todo) (insert " ")
12277 (if (memq type '(:tag :prop)) (insert ":"))))
12278 (if (and (equal type :opt) (assoc completion table))
12279 (message "%s" (substitute-command-keys
12280 "Press \\[org-complete] again to insert example settings"))))
12282 (message "Making completion list...")
12283 (let ((list (sort (all-completions pattern table confirm)
12284 'string<)))
12285 (with-output-to-temp-buffer "*Completions*"
12286 (condition-case nil
12287 ;; Protection needed for XEmacs and emacs 21
12288 (display-completion-list list pattern)
12289 (error (display-completion-list list)))))
12290 (message "Making completion list...%s" "done"))))))
12292 ;;;; TODO, DEADLINE, Comments
12294 (defun org-toggle-comment ()
12295 "Change the COMMENT state of an entry."
12296 (interactive)
12297 (save-excursion
12298 (org-back-to-heading)
12299 (if (looking-at (concat outline-regexp
12300 "\\( *\\<" org-comment-string "\\>\\)"))
12301 (replace-match "" t t nil 1)
12302 (if (looking-at outline-regexp)
12303 (progn
12304 (goto-char (match-end 0))
12305 (insert org-comment-string " "))))))
12307 (defvar org-last-todo-state-is-todo nil
12308 "This is non-nil when the last TODO state change led to a TODO state.
12309 If the last change removed the TODO tag or switched to DONE, then
12310 this is nil.")
12312 (defun org-todo (&optional arg)
12313 "Change the TODO state of an item.
12314 The state of an item is given by a keyword at the start of the heading,
12315 like
12316 *** TODO Write paper
12317 *** DONE Call mom
12319 The different keywords are specified in the variable `org-todo-keywords'.
12320 By default the available states are \"TODO\" and \"DONE\".
12321 So for this example: when the item starts with TODO, it is changed to DONE.
12322 When it starts with DONE, the DONE is removed. And when neither TODO nor
12323 DONE are present, add TODO at the beginning of the heading.
12325 With C-u prefix arg, use completion to determine the new state.
12326 With numeric prefix arg, switch to that state.
12328 For calling through lisp, arg is also interpreted in the following way:
12329 'none -> empty state
12330 \"\"(empty string) -> switch to empty state
12331 'done -> switch to DONE
12332 'nextset -> switch to the next set of keywords
12333 'previousset -> switch to the previous set of keywords
12334 \"WAITING\" -> switch to the specified keyword, but only if it
12335 really is a member of `org-todo-keywords'."
12336 (interactive "P")
12337 (save-excursion
12338 (org-back-to-heading)
12339 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
12340 (or (looking-at (concat " +" org-todo-regexp " *"))
12341 (looking-at " *"))
12342 (let* ((this (match-string 1))
12343 (head (org-get-todo-sequence-head this))
12344 (ass (assoc head org-todo-kwd-alist))
12345 (interpret (nth 1 ass))
12346 (done-word (nth 3 ass))
12347 (final-done-word (nth 4 ass))
12348 (last-state (or this ""))
12349 (completion-ignore-case t)
12350 (member (member this org-todo-keywords-1))
12351 (tail (cdr member))
12352 (state (cond
12353 ((equal arg '(4))
12354 ;; Read a state with completion
12355 (completing-read "State: " (mapcar (lambda(x) (list x))
12356 org-todo-keywords-1)
12357 nil t))
12358 ((eq arg 'right)
12359 (if this
12360 (if tail (car tail) nil)
12361 (car org-todo-keywords-1)))
12362 ((eq arg 'left)
12363 (if (equal member org-todo-keywords-1)
12365 (if this
12366 (nth (- (length org-todo-keywords-1) (length tail) 2)
12367 org-todo-keywords-1)
12368 (org-last org-todo-keywords-1))))
12369 (arg
12370 ;; user or caller requests a specific state
12371 (cond
12372 ((equal arg "") nil)
12373 ((eq arg 'none) nil)
12374 ((eq arg 'done) (or done-word (car org-done-keywords)))
12375 ((eq arg 'nextset)
12376 (or (car (cdr (member head org-todo-heads)))
12377 (car org-todo-heads)))
12378 ((eq arg 'previousset)
12379 (let ((org-todo-heads (reverse org-todo-heads)))
12380 (or (car (cdr (member head org-todo-heads)))
12381 (car org-todo-heads))))
12382 ((car (member arg org-todo-keywords-1)))
12383 ((nth (1- (prefix-numeric-value arg))
12384 org-todo-keywords-1))))
12385 ((null member) (or head (car org-todo-keywords-1)))
12386 ((equal this final-done-word) nil) ;; -> make empty
12387 ((null tail) nil) ;; -> first entry
12388 ((eq interpret 'sequence)
12389 (car tail))
12390 ((memq interpret '(type priority))
12391 (if (eq this-command last-command)
12392 (car tail)
12393 (if (> (length tail) 0)
12394 (or done-word (car org-done-keywords))
12395 nil)))
12396 (t nil)))
12397 (next (if state (concat " " state " ") " "))
12398 dostates)
12399 (replace-match next t t)
12400 (unless head
12401 (setq head (org-get-todo-sequence-head state)
12402 ass (assoc head org-todo-kwd-alist)
12403 interpret (nth 1 ass)
12404 done-word (nth 3 ass)
12405 final-done-word (nth 4 ass)))
12406 (when (memq arg '(nextset previousset))
12407 (message "Keyword set: %s"
12408 (mapconcat 'identity (assoc state org-todo-sets) " ")))
12409 (setq org-last-todo-state-is-todo
12410 (not (member state org-done-keywords)))
12411 (when (and org-log-done (not (memq arg '(nextset previousset))))
12412 (setq dostates (and (eq interpret 'sequence)
12413 (listp org-log-done) (memq 'state org-log-done)))
12414 (cond
12415 ((and state (not this))
12416 (org-add-planning-info nil nil 'closed)
12417 (and dostates (org-add-log-maybe 'state state 'findpos)))
12418 ((and state dostates)
12419 (org-add-log-maybe 'state state 'findpos))
12420 ((member state org-done-keywords)
12421 ;; Planning info calls the note-setting command.
12422 (org-add-planning-info 'closed (org-current-time)
12423 (if (org-get-repeat) nil 'scheduled))
12424 (org-add-log-maybe 'done state 'findpos))))
12425 ;; Fixup tag positioning
12426 (and org-auto-align-tags (org-set-tags nil t))
12427 (run-hooks 'org-after-todo-state-change-hook)
12428 (and (member state org-done-keywords) (org-auto-repeat-maybe))
12429 (if (and arg (not (member state org-done-keywords)))
12430 (setq head (org-get-todo-sequence-head state)))
12431 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)))
12432 ;; Fixup cursor location if close to the keyword
12433 (if (and (outline-on-heading-p)
12434 (not (bolp))
12435 (save-excursion (beginning-of-line 1)
12436 (looking-at org-todo-line-regexp))
12437 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12438 (progn
12439 (goto-char (or (match-end 2) (match-end 1)))
12440 (just-one-space))))
12442 (defun org-get-todo-sequence-head (kwd)
12443 "Return the head of the TODO sequence to which KWD belongs.
12444 If KWD is not set, check if there is a text property remembering the
12445 right sequence."
12446 (let (p)
12447 (cond
12448 ((not kwd)
12449 (or (get-text-property (point-at-bol) 'org-todo-head)
12450 (progn
12451 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12452 nil (point-at-eol)))
12453 (get-text-property p 'org-todo-head))))
12454 ((not (member kwd org-todo-keywords-1))
12455 (car org-todo-keywords-1))
12456 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12458 (defun org-get-repeat ()
12459 "Check if tere is a deadline/schedule with repeater in this entry."
12460 (save-match-data
12461 (save-excursion
12462 (org-back-to-heading t)
12463 (if (re-search-forward
12464 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
12465 (match-string 1)))))
12467 (defvar org-last-changed-timestamp)
12468 (defvar org-log-post-message)
12469 (defun org-auto-repeat-maybe ()
12470 "Check if the current headline contains a repeated deadline/schedule.
12471 If yes, set TODO state back to what it was and change the base date
12472 of repeating deadline/scheduled time stamps to new date.
12473 This function should be run in the `org-after-todo-state-change-hook'."
12474 ;; last-state is dynamically scoped into this function
12475 (let* ((repeat (org-get-repeat))
12476 (aa (assoc last-state org-todo-kwd-alist))
12477 (interpret (nth 1 aa))
12478 (head (nth 2 aa))
12479 (done-word (nth 3 aa))
12480 (whata '(("d" . day) ("m" . month) ("y" . year)))
12481 (msg "Entry repeats: ")
12482 (org-log-done)
12483 re type n what ts)
12484 (when repeat
12485 (org-todo (if (eq interpret 'type) last-state head))
12486 (when (and org-log-repeat
12487 (not (memq 'org-add-log-note
12488 (default-value 'post-command-hook))))
12489 ;; Make sure a note is taken
12490 (let ((org-log-done '(done)))
12491 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
12492 'findpos)))
12493 (org-back-to-heading t)
12494 (org-add-planning-info nil nil 'closed)
12495 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12496 org-deadline-time-regexp "\\)"))
12497 (while (re-search-forward
12498 re (save-excursion (outline-next-heading) (point)) t)
12499 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
12500 ts (match-string (if (match-end 2) 2 4)))
12501 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
12502 (setq n (string-to-number (match-string 1 ts))
12503 what (match-string 2 ts))
12504 (if (equal what "w") (setq n (* n 7) what "d"))
12505 (org-timestamp-change n (cdr (assoc what whata))))
12506 (setq msg (concat msg type org-last-changed-timestamp " ")))
12507 (setq org-log-post-message msg)
12508 (message msg))))
12510 (defun org-show-todo-tree (arg)
12511 "Make a compact tree which shows all headlines marked with TODO.
12512 The tree will show the lines where the regexp matches, and all higher
12513 headlines above the match.
12514 With \\[universal-argument] prefix, also show the DONE entries.
12515 With a numeric prefix N, construct a sparse tree for the Nth element
12516 of `org-todo-keywords-1'."
12517 (interactive "P")
12518 (let ((case-fold-search nil)
12519 (kwd-re
12520 (cond ((null arg) org-not-done-regexp)
12521 ((equal arg '(4))
12522 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
12523 (mapcar 'list org-todo-keywords-1))))
12524 (concat "\\("
12525 (mapconcat 'identity (org-split-string kwd "|") "\\|")
12526 "\\)\\>")))
12527 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
12528 (regexp-quote (nth (1- (prefix-numeric-value arg))
12529 org-todo-keywords-1)))
12530 (t (error "Invalid prefix argument: %s" arg)))))
12531 (message "%d TODO entries found"
12532 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
12534 (defun org-deadline ()
12535 "Insert the DEADLINE: string to make a deadline.
12536 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12537 to modify it to the correct date."
12538 (interactive)
12539 (org-add-planning-info 'deadline nil 'closed))
12541 (defun org-schedule ()
12542 "Insert the SCHEDULED: string to schedule a TODO item.
12543 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
12544 to modify it to the correct date."
12545 (interactive)
12546 (org-add-planning-info 'scheduled nil 'closed))
12548 (defun org-add-planning-info (what &optional time &rest remove)
12549 "Insert new timestamp with keyword in the line directly after the headline.
12550 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
12551 If non is given, the user is prompted for a date.
12552 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
12553 be removed."
12554 (interactive)
12555 (let (org-time-was-given org-end-time-was-given)
12556 (when what (setq time (or time (org-read-date nil 'to-time))))
12557 (when (and org-insert-labeled-timestamps-at-point
12558 (member what '(scheduled deadline)))
12559 (insert
12560 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
12561 (org-insert-time-stamp time org-time-was-given
12562 nil nil nil (list org-end-time-was-given))
12563 (setq what nil))
12564 (save-excursion
12565 (save-restriction
12566 (let (col list elt ts buffer-invisibility-spec)
12567 (org-back-to-heading t)
12568 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
12569 (goto-char (match-end 1))
12570 (setq col (current-column))
12571 (goto-char (match-end 0))
12572 (if (eobp) (insert "\n"))
12573 (forward-char 1)
12574 (when (looking-at "[ \t]*:PROPERTIES:[ \t]*$")
12575 (goto-char (match-end 0))
12576 (if (eobp) (insert "\n"))
12577 (forward-char 1))
12578 (if (and (not (looking-at outline-regexp))
12579 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
12580 "[^\r\n]*"))
12581 (not (equal (match-string 1) org-clock-string)))
12582 (narrow-to-region (match-beginning 0) (match-end 0))
12583 (insert "\n")
12584 (backward-char 1)
12585 (narrow-to-region (point) (point))
12586 (indent-to-column col))
12587 ;; Check if we have to remove something.
12588 (setq list (cons what remove))
12589 (while list
12590 (setq elt (pop list))
12591 (goto-char (point-min))
12592 (when (or (and (eq elt 'scheduled)
12593 (re-search-forward org-scheduled-time-regexp nil t))
12594 (and (eq elt 'deadline)
12595 (re-search-forward org-deadline-time-regexp nil t))
12596 (and (eq elt 'closed)
12597 (re-search-forward org-closed-time-regexp nil t)))
12598 (replace-match "")
12599 (if (looking-at "--+<[^>]+>") (replace-match ""))
12600 (if (looking-at " +") (replace-match ""))))
12601 (goto-char (point-max))
12602 (when what
12603 (insert
12604 (if (not (equal (char-before) ?\ )) " " "")
12605 (cond ((eq what 'scheduled) org-scheduled-string)
12606 ((eq what 'deadline) org-deadline-string)
12607 ((eq what 'closed) org-closed-string)
12608 ((eq what 'archived) org-archived-string))
12609 " ")
12610 (org-insert-time-stamp
12611 time
12612 (or org-time-was-given
12613 (and (eq what 'closed) org-log-done-with-time))
12614 (eq what 'closed)
12615 nil nil (list org-end-time-was-given))
12616 (end-of-line 1))
12617 (goto-char (point-min))
12618 (widen)
12619 (if (looking-at "[ \t]+\r?\n")
12620 (replace-match ""))
12621 ts)))))
12623 (defvar org-log-note-marker (make-marker))
12624 (defvar org-log-note-purpose nil)
12625 (defvar org-log-note-state nil)
12626 (defvar org-log-note-window-configuration nil)
12627 (defvar org-log-note-return-to (make-marker))
12628 (defvar org-log-post-message nil
12629 "Message to be displayed after a log note has been stored.
12630 The auto-repeater uses this.")
12632 (defun org-add-log-maybe (&optional purpose state findpos)
12633 "Set up the post command hook to take a note."
12634 (save-excursion
12635 (when (and (listp org-log-done)
12636 (memq purpose org-log-done))
12637 (when findpos
12638 (org-back-to-heading t)
12639 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
12640 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
12641 "[^\r\n]*\\)?"))
12642 (goto-char (match-end 0)))
12643 (move-marker org-log-note-marker (point))
12644 (setq org-log-note-purpose purpose)
12645 (setq org-log-note-state state)
12646 (add-hook 'post-command-hook 'org-add-log-note 'append))))
12648 (defun org-add-log-note (&optional purpose)
12649 "Pop up a window for taking a note, and add this note later at point."
12650 (remove-hook 'post-command-hook 'org-add-log-note)
12651 (setq org-log-note-window-configuration (current-window-configuration))
12652 (delete-other-windows)
12653 (move-marker org-log-note-return-to (point))
12654 (switch-to-buffer (marker-buffer org-log-note-marker))
12655 (goto-char org-log-note-marker)
12656 (switch-to-buffer-other-window "*Org Note*")
12657 (erase-buffer)
12658 (let ((org-inhibit-startup t)) (org-mode))
12659 (insert (format "# Insert note for %s, finish with C-c C-c.\n\n"
12660 (cond
12661 ((eq org-log-note-purpose 'clock-out) "stopped clock")
12662 ((eq org-log-note-purpose 'done) "closed todo item")
12663 ((eq org-log-note-purpose 'state) "state change")
12664 (t (error "This should not happen")))))
12665 (org-set-local 'org-finish-function 'org-store-log-note))
12667 (defun org-store-log-note ()
12668 "Finish taking a log note, and insert it to where it belongs."
12669 (let ((txt (buffer-string))
12670 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
12671 lines ind)
12672 (kill-buffer (current-buffer))
12673 (if (string-match "^#.*\n[ \t\n]*" txt)
12674 (setq txt (replace-match "" t t txt)))
12675 (if (string-match "\\s-+\\'" txt)
12676 (setq txt (replace-match "" t t txt)))
12677 (setq lines (org-split-string txt "\n"))
12678 (when (and note (string-match "\\S-" note))
12679 (setq note
12680 (org-replace-escapes
12681 note
12682 (list (cons "%u" (user-login-name))
12683 (cons "%U" user-full-name)
12684 (cons "%t" (format-time-string
12685 (org-time-stamp-format 'long 'inactive)
12686 (current-time)))
12687 (cons "%s" (if org-log-note-state
12688 (concat "\"" org-log-note-state "\"")
12689 "")))))
12690 (if lines (setq note (concat note " \\\\")))
12691 (push note lines))
12692 (when lines
12693 (save-excursion
12694 (set-buffer (marker-buffer org-log-note-marker))
12695 (save-excursion
12696 (goto-char org-log-note-marker)
12697 (move-marker org-log-note-marker nil)
12698 (end-of-line 1)
12699 (if (not (bolp)) (insert "\n")) (indent-relative nil)
12700 (setq ind (concat (buffer-substring (point-at-bol) (point)) " "))
12701 (insert " - " (pop lines))
12702 (while lines
12703 (insert "\n" ind (pop lines)))))))
12704 (set-window-configuration org-log-note-window-configuration)
12705 (with-current-buffer (marker-buffer org-log-note-return-to)
12706 (goto-char org-log-note-return-to))
12707 (move-marker org-log-note-return-to nil)
12708 (and org-log-post-message (message org-log-post-message)))
12710 (defvar org-occur-highlights nil)
12711 (make-variable-buffer-local 'org-occur-highlights)
12713 (defun org-occur (regexp &optional keep-previous callback)
12714 "Make a compact tree which shows all matches of REGEXP.
12715 The tree will show the lines where the regexp matches, and all higher
12716 headlines above the match. It will also show the heading after the match,
12717 to make sure editing the matching entry is easy.
12718 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
12719 call to `org-occur' will be kept, to allow stacking of calls to this
12720 command.
12721 If CALLBACK is non-nil, it is a function which is called to confirm
12722 that the match should indeed be shown."
12723 (interactive "sRegexp: \nP")
12724 (or keep-previous (org-remove-occur-highlights nil nil t))
12725 (let ((cnt 0))
12726 (save-excursion
12727 (goto-char (point-min))
12728 (if (or (not keep-previous) ; do not want to keep
12729 (not org-occur-highlights)) ; no previous matches
12730 ;; hide everything
12731 (org-overview))
12732 (while (re-search-forward regexp nil t)
12733 (when (or (not callback)
12734 (save-match-data (funcall callback)))
12735 (setq cnt (1+ cnt))
12736 (when org-highlight-sparse-tree-matches
12737 (org-highlight-new-match (match-beginning 0) (match-end 0)))
12738 (org-show-context 'occur-tree))))
12739 (when org-remove-highlights-with-change
12740 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
12741 nil 'local))
12742 (unless org-sparse-tree-open-archived-trees
12743 (org-hide-archived-subtrees (point-min) (point-max)))
12744 (run-hooks 'org-occur-hook)
12745 (if (interactive-p)
12746 (message "%d match(es) for regexp %s" cnt regexp))
12747 cnt))
12749 (defun org-show-context (&optional key)
12750 "Make sure point and context and visible.
12751 How much context is shown depends upon the variables
12752 `org-show-hierarchy-above', `org-show-following-heading'. and
12753 `org-show-siblings'."
12754 (let ((heading-p (org-on-heading-p t))
12755 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
12756 (following-p (org-get-alist-option org-show-following-heading key))
12757 (siblings-p (org-get-alist-option org-show-siblings key)))
12758 (catch 'exit
12759 ;; Show heading or entry text
12760 (if heading-p
12761 (org-flag-heading nil) ; only show the heading
12762 (and (or (org-invisible-p) (org-invisible-p2))
12763 (org-show-hidden-entry))) ; show entire entry
12764 (when following-p
12765 ;; Show next sibling, or heading below text
12766 (save-excursion
12767 (and (if heading-p (org-goto-sibling) (outline-next-heading))
12768 (org-flag-heading nil))))
12769 (when siblings-p (org-show-siblings))
12770 (when hierarchy-p
12771 ;; show all higher headings, possibly with siblings
12772 (save-excursion
12773 (while (and (condition-case nil
12774 (progn (org-up-heading-all 1) t)
12775 (error nil))
12776 (not (bobp)))
12777 (org-flag-heading nil)
12778 (when siblings-p (org-show-siblings))))))))
12780 (defun org-reveal (&optional siblings)
12781 "Show current entry, hierarchy above it, and the following headline.
12782 This can be used to show a consistent set of context around locations
12783 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
12784 not t for the search context.
12786 With optional argument SIBLINGS, on each level of the hierarchy all
12787 siblings are shown. This repairs the tree structure to what it would
12788 look like when opened with hierarchical calls to `org-cycle'."
12789 (interactive "P")
12790 (let ((org-show-hierarchy-above t)
12791 (org-show-following-heading t)
12792 (org-show-siblings (if siblings t org-show-siblings)))
12793 (org-show-context nil)))
12795 (defun org-highlight-new-match (beg end)
12796 "Highlight from BEG to END and mark the highlight is an occur headline."
12797 (let ((ov (org-make-overlay beg end)))
12798 (org-overlay-put ov 'face 'secondary-selection)
12799 (push ov org-occur-highlights)))
12801 (defun org-remove-occur-highlights (&optional beg end noremove)
12802 "Remove the occur highlights from the buffer.
12803 BEG and END are ignored. If NOREMOVE is nil, remove this function
12804 from the `before-change-functions' in the current buffer."
12805 (interactive)
12806 (unless org-inhibit-highlight-removal
12807 (mapc 'org-delete-overlay org-occur-highlights)
12808 (setq org-occur-highlights nil)
12809 (unless noremove
12810 (remove-hook 'before-change-functions
12811 'org-remove-occur-highlights 'local))))
12813 ;;;; Priorities
12815 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
12816 "Regular expression matching the priority indicator.")
12818 (defvar org-remove-priority-next-time nil)
12820 (defun org-priority-up ()
12821 "Increase the priority of the current item."
12822 (interactive)
12823 (org-priority 'up))
12825 (defun org-priority-down ()
12826 "Decrease the priority of the current item."
12827 (interactive)
12828 (org-priority 'down))
12830 (defun org-priority (&optional action)
12831 "Change the priority of an item by ARG.
12832 ACTION can be `set', `up', `down', or a character."
12833 (interactive)
12834 (setq action (or action 'set))
12835 (let (current new news have remove)
12836 (save-excursion
12837 (org-back-to-heading)
12838 (if (looking-at org-priority-regexp)
12839 (setq current (string-to-char (match-string 2))
12840 have t)
12841 (setq current org-default-priority))
12842 (cond
12843 ((or (eq action 'set) (integerp action))
12844 (if (integerp action)
12845 (setq new action)
12846 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
12847 (setq new (read-char-exclusive)))
12848 (cond ((equal new ?\ ) (setq remove t))
12849 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
12850 (error "Priority must be between `%c' and `%c'"
12851 org-highest-priority org-lowest-priority))))
12852 ((eq action 'up)
12853 (setq new (1- current)))
12854 ((eq action 'down)
12855 (setq new (1+ current)))
12856 (t (error "Invalid action")))
12857 (setq new (min (max org-highest-priority (upcase new)) org-lowest-priority))
12858 (setq news (format "%c" new))
12859 (if have
12860 (if remove
12861 (replace-match "" t t nil 1)
12862 (replace-match news t t nil 2))
12863 (if remove
12864 (error "No priority cookie found in line")
12865 (looking-at org-todo-line-regexp)
12866 (if (match-end 2)
12867 (progn
12868 (goto-char (match-end 2))
12869 (insert " [#" news "]"))
12870 (goto-char (match-beginning 3))
12871 (insert "[#" news "] ")))))
12872 (org-preserve-lc (org-set-tags nil 'align))
12873 (if remove
12874 (message "Priority removed")
12875 (message "Priority of current item set to %s" news))))
12878 (defun org-get-priority (s)
12879 "Find priority cookie and return priority."
12880 (save-match-data
12881 (if (not (string-match org-priority-regexp s))
12882 (* 1000 (- org-lowest-priority org-default-priority))
12883 (* 1000 (- org-lowest-priority
12884 (string-to-char (match-string 2 s)))))))
12886 ;;;; Tags
12888 (defun org-scan-tags (action matcher &optional todo-only)
12889 "Scan headline tags with inheritance and produce output ACTION.
12890 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
12891 evaluated, testing if a given set of tags qualifies a headline for
12892 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
12893 are included in the output."
12894 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
12895 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
12896 (org-re
12897 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
12898 (props (list 'face nil
12899 'done-face 'org-done
12900 'undone-face nil
12901 'mouse-face 'highlight
12902 'org-not-done-regexp org-not-done-regexp
12903 'org-todo-regexp org-todo-regexp
12904 'keymap org-agenda-keymap
12905 'help-echo
12906 (format "mouse-2 or RET jump to org file %s"
12907 (abbreviate-file-name buffer-file-name))))
12908 (case-fold-search nil)
12909 lspos
12910 tags tags-list tags-alist (llast 0) rtn level category i txt
12911 todo marker entry priority)
12912 (save-excursion
12913 (goto-char (point-min))
12914 (when (eq action 'sparse-tree) (org-overview))
12915 (while (re-search-forward re nil t)
12916 (catch :skip
12917 (setq todo (if (match-end 1) (match-string 2))
12918 tags (if (match-end 4) (match-string 4)))
12919 (goto-char (setq lspos (1+ (match-beginning 0))))
12920 (setq level (org-reduced-level (funcall outline-level))
12921 category (org-get-category))
12922 (setq i llast llast level)
12923 ;; remove tag lists from same and sublevels
12924 (while (>= i level)
12925 (when (setq entry (assoc i tags-alist))
12926 (setq tags-alist (delete entry tags-alist)))
12927 (setq i (1- i)))
12928 ;; add the nex tags
12929 (when tags
12930 (setq tags (mapcar 'downcase (org-split-string tags ":"))
12931 tags-alist
12932 (cons (cons level tags) tags-alist)))
12933 ;; compile tags for current headline
12934 (setq tags-list
12935 (if org-use-tag-inheritance
12936 (apply 'append (mapcar 'cdr tags-alist))
12937 tags))
12938 (when (and (or (not todo-only) (member todo org-not-done-keywords))
12939 (eval matcher)
12940 (or (not org-agenda-skip-archived-trees)
12941 (not (member org-archive-tag tags-list))))
12942 (and (eq action 'agenda) (org-agenda-skip))
12943 ;; list this headline
12944 (if (eq action 'sparse-tree)
12945 (progn
12946 (org-show-context 'tags-tree))
12947 (setq txt (org-format-agenda-item
12949 (concat
12950 (if org-tags-match-list-sublevels
12951 (make-string (1- level) ?.) "")
12952 (org-get-heading))
12953 category tags-list)
12954 priority (org-get-priority txt))
12955 (goto-char lspos)
12956 (setq marker (org-agenda-new-marker))
12957 (org-add-props txt props
12958 'org-marker marker 'org-hd-marker marker 'org-category category
12959 'priority priority 'type "tagsmatch")
12960 (push txt rtn))
12961 ;; if we are to skip sublevels, jump to end of subtree
12962 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
12963 (when (and (eq action 'sparse-tree)
12964 (not org-sparse-tree-open-archived-trees))
12965 (org-hide-archived-subtrees (point-min) (point-max)))
12966 (nreverse rtn)))
12968 (defvar todo-only) ;; dynamically scoped
12970 (defun org-tags-sparse-tree (&optional todo-only match)
12971 "Create a sparse tree according to tags string MATCH.
12972 MATCH can contain positive and negative selection of tags, like
12973 \"+WORK+URGENT-WITHBOSS\".
12974 If optional argument TODO_ONLY is non-nil, only select lines that are
12975 also TODO lines."
12976 (interactive "P")
12977 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
12979 (defvar org-cached-props nil)
12980 (defun org-cached-entry-get (pom property)
12981 (cdr (assoc property (or org-cached-props
12982 (setq org-cached-props
12983 (org-entry-properties pom))))))
12985 (defun org-global-tags-completion-table (&optional files)
12986 "Return the list of all tags in all agenda buffer/files."
12987 (save-excursion
12988 (org-uniquify
12989 (apply 'append
12990 (mapcar
12991 (lambda (file)
12992 (set-buffer (find-file-noselect file))
12993 (org-get-buffer-tags))
12994 (if (and files (car files))
12995 files
12996 (org-agenda-files)))))))
12998 (defun org-make-tags-matcher (match)
12999 "Create the TAGS//TODO matcher form for the selection string MATCH."
13000 ;; todo-only is scoped dynamically into this function, and the function
13001 ;; may change it it the matcher asksk for it.
13002 (unless match
13003 ;; Get a new match request, with completion
13004 (let ((org-last-tags-completion-table
13005 (org-global-tags-completion-table)))
13006 (setq match (completing-read
13007 "Match: " 'org-tags-completion-function nil nil nil
13008 'org-tags-history))))
13010 ;; Parse the string and create a lisp form
13011 (let ((match0 match)
13012 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
13013 minus tag mm
13014 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
13015 orterms term orlist re-p level-p prop-p pn pv)
13016 (if (string-match "/+" match)
13017 ;; match contains also a todo-matching request
13018 (progn
13019 (setq tagsmatch (substring match 0 (match-beginning 0))
13020 todomatch (substring match (match-end 0)))
13021 (if (string-match "^!" todomatch)
13022 (setq todo-only t todomatch (substring todomatch 1)))
13023 (if (string-match "^\\s-*$" todomatch)
13024 (setq todomatch nil)))
13025 ;; only matching tags
13026 (setq tagsmatch match todomatch nil))
13028 ;; Make the tags matcher
13029 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
13030 (setq tagsmatcher t)
13031 (setq orterms (org-split-string tagsmatch "|") orlist nil)
13032 (while (setq term (pop orterms))
13033 (while (and (equal (substring term -1) "\\") orterms)
13034 (setq term (concat term "|" (pop orterms)))) ; repair bad split
13035 (while (string-match re term)
13036 (setq minus (and (match-end 1)
13037 (equal (match-string 1 term) "-"))
13038 tag (match-string 2 term)
13039 re-p (equal (string-to-char tag) ?{)
13040 level-p (match-end 3)
13041 prop-p (match-end 4)
13042 mm (cond
13043 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
13044 (level-p `(= level ,(string-to-number
13045 (match-string 3 term))))
13046 (prop-p
13047 (setq pn (match-string 4 term)
13048 pv (match-string 5 term)
13049 re-p (equal (string-to-char pv) ?{)
13050 pv (substring pv 1 -1))
13051 (if re-p
13052 `(string-match ,pv (org-cached-entry-get nil ,pn))
13053 `(equal ,pv (org-cached-entry-get nil ,pn))))
13054 (t `(member ,(downcase tag) tags-list)))
13055 mm (if minus (list 'not mm) mm)
13056 term (substring term (match-end 0)))
13057 (push mm tagsmatcher))
13058 (push (if (> (length tagsmatcher) 1)
13059 (cons 'and tagsmatcher)
13060 (car tagsmatcher))
13061 orlist)
13062 (setq tagsmatcher nil))
13063 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
13064 (setq tagsmatcher
13065 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
13067 ;; Make the todo matcher
13068 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
13069 (setq todomatcher t)
13070 (setq orterms (org-split-string todomatch "|") orlist nil)
13071 (while (setq term (pop orterms))
13072 (while (string-match re term)
13073 (setq minus (and (match-end 1)
13074 (equal (match-string 1 term) "-"))
13075 kwd (match-string 2 term)
13076 re-p (equal (string-to-char kwd) ?{)
13077 term (substring term (match-end 0))
13078 mm (if re-p
13079 `(string-match ,(substring kwd 1 -1) todo)
13080 (list 'equal 'todo kwd))
13081 mm (if minus (list 'not mm) mm))
13082 (push mm todomatcher))
13083 (push (if (> (length todomatcher) 1)
13084 (cons 'and todomatcher)
13085 (car todomatcher))
13086 orlist)
13087 (setq todomatcher nil))
13088 (setq todomatcher (if (> (length orlist) 1)
13089 (cons 'or orlist) (car orlist))))
13091 ;; Return the string and lisp forms of the matcher
13092 (setq matcher (if todomatcher
13093 (list 'and tagsmatcher todomatcher)
13094 tagsmatcher))
13095 (cons match0 matcher)))
13097 (defun org-match-any-p (re list)
13098 "Does re match any element of list?"
13099 (setq list (mapcar (lambda (x) (string-match re x)) list))
13100 (delq nil list))
13102 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
13103 (defvar org-tags-overlay (org-make-overlay 1 1))
13104 (org-detach-overlay org-tags-overlay)
13106 (defun org-align-tags-here (to-col)
13107 ;; Assumes that this is a headline
13108 (let ((pos (point)) (col (current-column)) tags)
13109 (beginning-of-line 1)
13110 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13111 (< pos (match-beginning 2)))
13112 (progn
13113 (setq tags (match-string 2))
13114 (goto-char (match-beginning 1))
13115 (insert " ")
13116 (delete-region (point) (1+ (match-end 0)))
13117 (backward-char 1)
13118 (move-to-column
13119 (max (1+ (current-column))
13120 (1+ col)
13121 (if (> to-col 0)
13122 to-col
13123 (- (abs to-col) (length tags))))
13125 (insert tags)
13126 (move-to-column (min (current-column) col) t))
13127 (goto-char pos))))
13129 (defun org-set-tags (&optional arg just-align)
13130 "Set the tags for the current headline.
13131 With prefix ARG, realign all tags in headings in the current buffer."
13132 (interactive "P")
13133 (let* ((re (concat "^" outline-regexp))
13134 (current (org-get-tags))
13135 table current-tags inherited-tags ; computed below when needed
13136 tags p0 c0 c1 rpl)
13137 (if arg
13138 (save-excursion
13139 (goto-char (point-min))
13140 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
13141 (while (re-search-forward re nil t)
13142 (org-set-tags nil t)
13143 (end-of-line 1)))
13144 (message "All tags realigned to column %d" org-tags-column))
13145 (if just-align
13146 (setq tags current)
13147 ;; Get a new set of tags from the user
13148 (save-excursion
13149 (setq table (or org-tag-alist (org-get-buffer-tags))
13150 org-last-tags-completion-table table
13151 current-tags (org-split-string current ":")
13152 inherited-tags (nreverse
13153 (nthcdr (length current-tags)
13154 (nreverse (org-get-tags-at))))
13155 tags
13156 (if (or (eq t org-use-fast-tag-selection)
13157 (and org-use-fast-tag-selection
13158 (delq nil (mapcar 'cdr table))))
13159 (org-fast-tag-selection current-tags inherited-tags table)
13160 (let ((org-add-colon-after-tag-completion t))
13161 (org-trim
13162 (completing-read "Tags: " 'org-tags-completion-function
13163 nil nil current 'org-tags-history))))))
13164 (while (string-match "[-+&]+" tags)
13165 ;; No boolean logic, just a list
13166 (setq tags (replace-match ":" t t tags))))
13168 (if (string-match "\\`[\t ]*\\'" tags)
13169 (setq tags "")
13170 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
13171 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
13173 ;; Insert new tags at the correct column
13174 (beginning-of-line 1)
13175 (cond
13176 ((and (equal current "") (equal tags "")))
13177 ((re-search-forward
13178 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
13179 (point-at-eol) t)
13180 (if (equal tags "")
13181 (setq rpl "")
13182 (goto-char (match-beginning 0))
13183 (setq c0 (current-column) p0 (point)
13184 c1 (max (1+ c0) (if (> org-tags-column 0)
13185 org-tags-column
13186 (- (- org-tags-column) (length tags))))
13187 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
13188 (replace-match rpl t t)
13189 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
13190 tags)
13191 (t (error "Tags alignment failed"))))))
13193 (defun org-tags-completion-function (string predicate &optional flag)
13194 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
13195 (confirm (lambda (x) (stringp (car x)))))
13196 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
13197 (setq s1 (match-string 1 string)
13198 s2 (match-string 2 string))
13199 (setq s1 "" s2 string))
13200 (cond
13201 ((eq flag nil)
13202 ;; try completion
13203 (setq rtn (try-completion s2 ctable confirm))
13204 (if (stringp rtn)
13205 (setq rtn
13206 (concat s1 s2 (substring rtn (length s2))
13207 (if (and org-add-colon-after-tag-completion
13208 (assoc rtn ctable))
13209 ":" ""))))
13210 rtn)
13211 ((eq flag t)
13212 ;; all-completions
13213 (all-completions s2 ctable confirm)
13215 ((eq flag 'lambda)
13216 ;; exact match?
13217 (assoc s2 ctable)))
13220 (defun org-fast-tag-insert (kwd tags face &optional end)
13221 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
13222 (insert (format "%-12s" (concat kwd ":"))
13223 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
13224 (or end "")))
13226 (defun org-fast-tag-show-exit (flag)
13227 (save-excursion
13228 (goto-line 3)
13229 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
13230 (replace-match ""))
13231 (when flag
13232 (end-of-line 1)
13233 (move-to-column (- (window-width) 19) t)
13234 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
13236 (defun org-set-current-tags-overlay (current prefix)
13237 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
13238 (if (featurep 'xemacs)
13239 (org-overlay-display org-tags-overlay (concat prefix s)
13240 'secondary-selection)
13241 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
13242 (org-overlay-display org-tags-overlay (concat prefix s)))))
13244 (defun org-fast-tag-selection (current inherited table)
13245 "Fast tag selection with single keys.
13246 CURRENT is the current list of tags in the headline, INHERITED is the
13247 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
13248 possibly with grouping information.
13249 If the keys are nil, a-z are automatically assigned.
13250 Returns the new tags string, or nil to not change the current settings."
13251 (let* ((maxlen (apply 'max (mapcar
13252 (lambda (x)
13253 (if (stringp (car x)) (string-width (car x)) 0))
13254 table)))
13255 (buf (current-buffer))
13256 (expert (eq org-fast-tag-selection-single-key 'expert))
13257 (buffer-tags nil)
13258 (fwidth (+ maxlen 3 1 3))
13259 (ncol (/ (- (window-width) 4) fwidth))
13260 (i-face 'org-done)
13261 (c-face 'org-todo)
13262 tg cnt e c char c1 c2 ntable tbl rtn
13263 ov-start ov-end ov-prefix
13264 (exit-after-next org-fast-tag-selection-single-key)
13265 groups ingroup)
13266 (save-excursion
13267 (beginning-of-line 1)
13268 (if (looking-at
13269 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13270 (setq ov-start (match-beginning 1)
13271 ov-end (match-end 1)
13272 ov-prefix "")
13273 (setq ov-start (1- (point-at-eol))
13274 ov-end (1+ ov-start))
13275 (skip-chars-forward "^\n\r")
13276 (setq ov-prefix
13277 (concat
13278 (buffer-substring (1- (point)) (point))
13279 (if (> (current-column) org-tags-column)
13281 (make-string (- org-tags-column (current-column)) ?\ ))))))
13282 (org-move-overlay org-tags-overlay ov-start ov-end)
13283 (save-window-excursion
13284 (if expert
13285 (set-buffer (get-buffer-create " *Org tags*"))
13286 (delete-other-windows)
13287 (split-window-vertically)
13288 (switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13289 (erase-buffer)
13290 (org-fast-tag-insert "Inherited" inherited i-face "\n")
13291 (org-fast-tag-insert "Current" current c-face "\n\n")
13292 (org-fast-tag-show-exit exit-after-next)
13293 (org-set-current-tags-overlay current ov-prefix)
13294 (setq tbl table char ?a cnt 0)
13295 (while (setq e (pop tbl))
13296 (cond
13297 ((equal e '(:startgroup))
13298 (push '() groups) (setq ingroup t)
13299 (when (not (= cnt 0))
13300 (setq cnt 0)
13301 (insert "\n"))
13302 (insert "{ "))
13303 ((equal e '(:endgroup))
13304 (setq ingroup nil cnt 0)
13305 (insert "}\n"))
13307 (setq tg (car e) c2 nil)
13308 (if (cdr e)
13309 (setq c (cdr e))
13310 ;; automatically assign a character.
13311 (setq c1 (string-to-char
13312 (downcase (substring
13313 tg (if (= (string-to-char tg) ?@) 1 0)))))
13314 (if (or (rassoc c1 ntable) (rassoc c1 table))
13315 (while (or (rassoc char ntable) (rassoc char table))
13316 (setq char (1+ char)))
13317 (setq c2 c1))
13318 (setq c (or c2 char)))
13319 (if ingroup (push tg (car groups)))
13320 (setq tg (org-add-props tg nil 'face
13321 (cond
13322 ((member tg current) c-face)
13323 ((member tg inherited) i-face)
13324 (t nil))))
13325 (if (and (= cnt 0) (not ingroup)) (insert " "))
13326 (insert "[" c "] " tg (make-string
13327 (- fwidth 4 (length tg)) ?\ ))
13328 (push (cons tg c) ntable)
13329 (when (= (setq cnt (1+ cnt)) ncol)
13330 (insert "\n")
13331 (if ingroup (insert " "))
13332 (setq cnt 0)))))
13333 (setq ntable (nreverse ntable))
13334 (insert "\n")
13335 (goto-char (point-min))
13336 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13337 (fit-window-to-buffer))
13338 (setq rtn
13339 (catch 'exit
13340 (while t
13341 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
13342 (if groups " [!] no groups" " [!]groups")
13343 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
13344 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13345 (cond
13346 ((= c ?\r) (throw 'exit t))
13347 ((= c ?!)
13348 (setq groups (not groups))
13349 (goto-char (point-min))
13350 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
13351 ((= c ?\C-c)
13352 (if (not expert)
13353 (org-fast-tag-show-exit
13354 (setq exit-after-next (not exit-after-next)))
13355 (setq expert nil)
13356 (delete-other-windows)
13357 (split-window-vertically)
13358 (switch-to-buffer-other-window " *Org tags*")
13359 (and (fboundp 'fit-window-to-buffer)
13360 (fit-window-to-buffer))))
13361 ((or (= c ?\C-g)
13362 (and (= c ?q) (not (rassoc c ntable))))
13363 (org-detach-overlay org-tags-overlay)
13364 (setq quit-flag t))
13365 ((= c ?\ )
13366 (setq current nil)
13367 (if exit-after-next (setq exit-after-next 'now)))
13368 ((= c ?\t)
13369 (condition-case nil
13370 (setq tg (completing-read
13371 "Tag: "
13372 (or buffer-tags
13373 (with-current-buffer buf
13374 (org-get-buffer-tags)))))
13375 (quit (setq tg "")))
13376 (when (string-match "\\S-" tg)
13377 (add-to-list 'buffer-tags (list tg))
13378 (if (member tg current)
13379 (setq current (delete tg current))
13380 (push tg current)))
13381 (if exit-after-next (setq exit-after-next 'now)))
13382 ((setq e (rassoc c ntable) tg (car e))
13383 (if (member tg current)
13384 (setq current (delete tg current))
13385 (loop for g in groups do
13386 (if (member tg g)
13387 (mapcar (lambda (x)
13388 (setq current (delete x current)))
13389 g)))
13390 (push tg current))
13391 (if exit-after-next (setq exit-after-next 'now))))
13393 ;; Create a sorted list
13394 (setq current
13395 (sort current
13396 (lambda (a b)
13397 (assoc b (cdr (memq (assoc a ntable) ntable))))))
13398 (if (eq exit-after-next 'now) (throw 'exit t))
13399 (goto-char (point-min))
13400 (beginning-of-line 2)
13401 (delete-region (point) (point-at-eol))
13402 (org-fast-tag-insert "Current" current c-face)
13403 (org-set-current-tags-overlay current ov-prefix)
13404 (while (re-search-forward
13405 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
13406 (setq tg (match-string 1))
13407 (add-text-properties (match-beginning 1) (match-end 1)
13408 (list 'face
13409 (cond
13410 ((member tg current) c-face)
13411 ((member tg inherited) i-face)
13412 (t nil)))))
13413 (goto-char (point-min)))))
13414 (org-detach-overlay org-tags-overlay)
13415 (if rtn
13416 (mapconcat 'identity current ":")
13417 nil))))
13419 (defun org-get-tags ()
13420 "Get the TAGS string in the current headline."
13421 (unless (org-on-heading-p t)
13422 (error "Not on a heading"))
13423 (save-excursion
13424 (beginning-of-line 1)
13425 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13426 (org-match-string-no-properties 1)
13427 "")))
13429 (defun org-get-buffer-tags ()
13430 "Get a table of all tags used in the buffer, for completion."
13431 (let (tags)
13432 (save-excursion
13433 (goto-char (point-min))
13434 (while (re-search-forward
13435 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
13436 (when (equal (char-after (point-at-bol 0)) ?*)
13437 (mapc (lambda (x) (add-to-list 'tags x))
13438 (org-split-string (org-match-string-no-properties 1) ":")))))
13439 (mapcar 'list tags)))
13442 ;;;; Properties
13444 ;;; Setting and retrieving properties
13446 (defconst org-special-properties
13447 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED"
13448 "CLOCK" "PRIORITY")
13449 "The special properties valid in Org-mode.
13451 These are properties that are not defined in the property drawer,
13452 but in some other way.")
13454 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
13455 "Regular expression matching the first line of a property drawer.")
13457 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
13458 "Regular expression matching the first line of a property drawer.")
13460 (defun org-property-action ()
13461 "Do an action on properties."
13462 (interactive)
13463 (let (c prop)
13464 (org-at-property-p)
13465 (setq prop (match-string 2))
13466 (message "Property Action: [s]et [d]elete [D]delete globally")
13467 (setq c (read-char-exclusive))
13468 (cond
13469 ((equal c ?s)
13470 (call-interactively 'org-set-property))
13471 ((equal c ?d)
13472 (call-interactively 'org-delete-property))
13473 ((equal c ?D)
13474 (call-interactively 'org-delete-property-globally))
13475 (t (error "No such property action %c" c)))))
13477 (defun org-at-property-p ()
13478 "Is the cursor in a property line?"
13479 ;; FIXME: Does not check if we are actually in the drawer.
13480 ;; FIXME: also returns true on any drawers.....
13481 ;; This is used by C-c C-c for property action.
13482 (save-excursion
13483 (beginning-of-line 1)
13484 (looking-at "^[ \t]*\\(:\\([a-zA-Z_0-9]+\\):\\)[ \t]*\\(.*\\)")))
13486 (defmacro org-with-point-at (pom &rest body)
13487 "Move to buffer and point of point-or-marker POM for the duration of BODY."
13488 (declare (indent 1) (debug t))
13489 `(save-excursion
13490 (if (markerp pom) (set-buffer (marker-buffer pom)))
13491 (save-excursion
13492 (goto-char (or pom (point)))
13493 ,@body)))
13495 (defun org-get-property-block (&optional beg end force)
13496 "Return the (beg . end) range of the body of the property drawer.
13497 BEG and END can be beginning and end of subtree, if not given
13498 they will be found.
13499 If the drawer does not exist and FORCE is non-nil, create the drawer."
13500 (catch 'exit
13501 (save-excursion
13502 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
13503 (end (or end (progn (outline-next-heading) (point)))))
13504 (goto-char beg)
13505 (if (re-search-forward org-property-start-re end t)
13506 (setq beg (1+ (match-end 0)))
13507 (if force
13508 (save-excursion
13509 (org-insert-property-drawer)
13510 (setq end (progn (outline-next-heading) (point))))
13511 (throw 'exit nil))
13512 (goto-char beg)
13513 (if (re-search-forward org-property-start-re end t)
13514 (setq beg (1+ (match-end 0)))))
13515 (if (re-search-forward org-property-end-re end t)
13516 (setq end (match-beginning 0))
13517 (or force (throw 'exit nil))
13518 (goto-char beg)
13519 (setq end beg)
13520 (org-indent-line-function)
13521 (insert ":END:\n"))
13522 (cons beg end)))))
13524 (defun org-entry-properties (&optional pom which)
13525 "Get all properties of the entry at point-or-marker POM.
13526 This includes the TODO keyword, the tags, time strings for deadline,
13527 scheduled, and clocking, and any additional properties defined in the
13528 entry. The return value is an alist, keys may occur multiple times
13529 if the property key was used several times.
13530 POM may also be nil, in which case the current entry is used.
13531 If WHICH is nil or `all', get all properties. If WHICH is
13532 `special' or `standard', only get that subclass."
13533 (setq which (or which 'all))
13534 (org-with-point-at pom
13535 (let ((clockstr (substring org-clock-string 0 -1))
13536 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
13537 beg end range props sum-props key value)
13538 (save-excursion
13539 (when (condition-case nil (org-back-to-heading t) (error nil))
13540 (setq beg (point))
13541 (setq sum-props (get-text-property (point) 'org-summaries))
13542 (outline-next-heading)
13543 (setq end (point))
13544 (when (memq which '(all special))
13545 ;; Get the special properties, like TODO and tags
13546 (goto-char beg)
13547 (when (and (looking-at org-todo-line-regexp) (match-end 2))
13548 (push (cons "TODO" (org-match-string-no-properties 2)) props))
13549 (when (looking-at org-priority-regexp)
13550 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
13551 (when (and (setq value (org-get-tags)) (string-match "\\S-" value))
13552 (push (cons "TAGS" value) props))
13553 (when (setq value (org-get-tags-at))
13554 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
13555 props))
13556 (while (re-search-forward org-keyword-time-regexp end t)
13557 (setq key (substring (org-match-string-no-properties 1) 0 -1))
13558 (unless (member key excluded) (push key excluded))
13559 (push (cons key
13560 (if (equal key clockstr)
13561 (org-no-properties
13562 (org-trim
13563 (buffer-substring
13564 (match-beginning 2) (point-at-eol))))
13565 (org-match-string-no-properties 2)))
13566 props)))
13567 (when (memq which '(all standard))
13568 ;; Get the standard properties, like :PORP: ...
13569 (setq range (org-get-property-block beg end))
13570 (when range
13571 (goto-char (car range))
13572 (while (re-search-forward
13573 "^[ \t]*:\\([a-zA-Z][a-zA-Z_0-9]*\\):[ \t]*\\(\\S-.*\\)?"
13574 (cdr range) t)
13575 (setq key (org-match-string-no-properties 1)
13576 value (org-trim (or (org-match-string-no-properties 2) "")))
13577 (unless (member key excluded)
13578 (push (cons key (or value "")) props)))))
13579 (append sum-props (nreverse props)))))))
13581 (defun org-entry-get (pom property &optional inherit)
13582 "Get value of PROPERTY for entry at point-or-marker POM.
13583 If INHERIT is non-nil and the entry does not have the property,
13584 then also check higher levels of the hierarchy.
13585 If the property is present but empty, the return value is the empty string.
13586 If the property is not present at all, nil is returned."
13587 (org-with-point-at pom
13588 (if inherit
13589 (org-entry-get-with-inheritance property)
13590 (if (member property org-special-properties)
13591 ;; We need a special property. Use brute force, get all properties.
13592 (cdr (assoc property (org-entry-properties nil 'special)))
13593 (let ((range (org-get-property-block)))
13594 (if (and range
13595 (goto-char (car range))
13596 (re-search-forward
13597 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
13598 (cdr range) t))
13599 ;; Found the property, return it.
13600 (if (match-end 1)
13601 (org-match-string-no-properties 1)
13602 "")))))))
13604 (defun org-entry-delete (pom property)
13605 "Delete the property PROPERTY from entry at point-or-marker POM."
13606 (org-with-point-at pom
13607 (if (member property org-special-properties)
13608 nil ; cannot delete these properties.
13609 (let ((range (org-get-property-block)))
13610 (if (and range
13611 (goto-char (car range))
13612 (re-search-forward
13613 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
13614 (cdr range) t))
13615 (progn
13616 (delete-region (match-beginning 0) (1+ (point-at-eol)))
13618 nil)))))
13620 (defvar org-entry-property-inherited-from (make-marker))
13622 (defun org-entry-get-with-inheritance (property)
13623 "Get entry property, and search higher levels if not present."
13624 (let (tmp)
13625 (save-excursion
13626 (catch 'ex
13627 (while t
13628 (when (setq tmp (org-entry-get nil property))
13629 (org-back-to-heading t)
13630 (move-marker org-entry-property-inherited-from (point))
13631 (throw 'ex tmp))
13632 (condition-case nil
13633 (org-up-heading-all 1)
13634 (error (throw 'ex nil))))))))
13636 (defun org-entry-put (pom property value)
13637 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13638 (org-with-point-at pom
13639 (org-back-to-heading t)
13640 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13641 range)
13642 (cond
13643 ((equal property "TODO")
13644 (when (and (stringp value) (string-match "\\S-" value)
13645 (not (member value org-todo-keywords-1)))
13646 (error "\"%s\" is not a valid TODO state" value))
13647 (if (or (not value)
13648 (not (string-match "\\S-" value)))
13649 (setq value 'none))
13650 (org-todo value)
13651 (org-set-tags nil 'align))
13652 ((equal property "PRIORITY")
13653 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13654 (string-to-char value) ?\ ))
13655 (org-set-tags nil 'align))
13656 ((member property org-special-properties)
13657 (error "The %s property can not yet be set with `org-entry-put'"
13658 property))
13659 (t ; a non-special property
13660 (setq range (org-get-property-block beg end 'force))
13661 (goto-char (car range))
13662 (if (re-search-forward
13663 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13664 (progn
13665 (delete-region (match-beginning 1) (match-end 1))
13666 (goto-char (match-beginning 1)))
13667 (goto-char (cdr range))
13668 (insert "\n")
13669 (backward-char 1)
13670 (org-indent-line-function)
13671 (insert ":" property ":"))
13672 (and value (insert " " value))
13673 (org-indent-line-function))))))
13675 (defun org-buffer-property-keys (&optional include-specials)
13676 "Get all property keys in the current buffer."
13677 (let (rtn range)
13678 (save-excursion
13679 (save-restriction
13680 (widen)
13681 (goto-char (point-min))
13682 (while (re-search-forward org-property-start-re nil t)
13683 (setq range (org-get-property-block))
13684 (goto-char (car range))
13685 (while (re-search-forward "^[ \t]*:\\([a-zA-Z0-9]+\\):" (cdr range) t)
13686 (add-to-list 'rtn (org-match-string-no-properties 1)))
13687 (outline-next-heading))))
13688 (when include-specials
13689 (setq rtn (append org-special-properties rtn)))
13690 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13692 (defun org-insert-property-drawer ()
13693 "Insert a property drawer into the current entry."
13694 (interactive)
13695 (org-back-to-heading t)
13696 (let ((beg (point))
13697 (re (concat "^[ \t]*" org-keyword-time-regexp))
13698 end hiddenp)
13699 (outline-next-heading)
13700 (setq end (point))
13701 (goto-char beg)
13702 (while (re-search-forward re end t))
13703 (setq hiddenp (org-invisible-p))
13704 (end-of-line 1)
13705 (insert "\n:PROPERTIES:\n:END:")
13706 (beginning-of-line 0)
13707 (org-indent-line-function)
13708 (beginning-of-line 2)
13709 (org-indent-line-function)
13710 (beginning-of-line 0)
13711 (if hiddenp
13712 (save-excursion
13713 (org-back-to-heading t)
13714 (hide-entry))
13715 (org-flag-drawer t))))
13717 (defun org-set-property (property value)
13718 "In the current entry, set PROPERTY to VALUE."
13719 (interactive
13720 (let* ((prop (completing-read "Property: "
13721 (mapcar 'list (org-buffer-property-keys))))
13722 (cur (org-entry-get nil prop))
13723 (allowed (org-property-get-allowed-values nil prop 'table))
13724 (val (if allowed
13725 (completing-read "Value: " allowed nil 'req-match)
13726 (read-string
13727 (concat "Value" (if (and cur (string-match "\\S-" cur))
13728 (concat "[" cur "]") "")
13729 ": ")
13730 "" cur))))
13731 (list prop (if (equal val "") cur val))))
13732 (unless (equal (org-entry-get nil property) value)
13733 (org-entry-put nil property value)))
13735 (defun org-delete-property (property)
13736 "In the current entry, delete PROPERTY."
13737 (interactive
13738 (let* ((prop (completing-read
13739 "Property: " (org-entry-properties nil 'standard))))
13740 (list prop)))
13741 (message (concat "Property " property
13742 (if (org-entry-delete nil property)
13743 " deleted"
13744 " was not present in the entry"))))
13746 (defun org-delete-property-globally (property)
13747 "Remove PROPERTY globally, from all entries."
13748 (interactive
13749 (let* ((prop (completing-read
13750 "Globally remove property: "
13751 (mapcar 'list (org-buffer-property-keys)))))
13752 (list prop)))
13753 (save-excursion
13754 (save-restriction
13755 (widen)
13756 (goto-char (point-min))
13757 (let ((cnt 0))
13758 (while (re-search-forward
13759 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13760 nil t)
13761 (setq cnt (1+ cnt))
13762 (replace-match ""))
13763 (message "Property \"%s\" removed from %d entries" property cnt)))))
13765 (defun org-property-get-allowed-values (pom property &optional table)
13766 "Get allowed values for the property PROPERTY.
13767 When TABLE is non-nil, return an alist that can directly be used for
13768 completion."
13769 (let (vals)
13770 (cond
13771 ((equal property "TODO")
13772 (setq vals (org-with-point-at pom
13773 (append org-todo-keywords-1 '("")))))
13774 ((equal property "PRIORITY")
13775 (let ((n org-lowest-priority))
13776 (while (>= n org-highest-priority)
13777 (push (char-to-string n) vals)
13778 (setq n (1- n)))))
13779 ((member property org-special-properties))
13781 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13782 (when (and vals (string-match "\\S-" vals))
13783 (setq vals (car (read-from-string (concat "(" vals ")"))))
13784 (setq vals (mapcar (lambda (x)
13785 (cond ((stringp x) x)
13786 ((numberp x) (number-to-string x))
13787 ((symbolp x) (symbol-name x))
13788 (t "???")))
13789 vals)))))
13790 (if table (mapcar 'list vals) vals)))
13792 ;;; Column View
13794 (defvar org-columns-overlays nil
13795 "Holds the list of current column overlays.")
13797 (defvar org-columns-current-fmt nil
13798 "Local variable, holds the currently active column format.")
13799 (defvar org-columns-current-fmt-compiled nil
13800 "Local variable, holds the currently active column format.
13801 This is the compiled version of the format.")
13802 (defvar org-columns-current-maxwidths nil
13803 "Loval variable, holds the currently active maximum column widths.")
13804 (defvar org-columns-begin-marker (make-marker)
13805 "Points to the position where last a column creation command was called.")
13806 (defvar org-columns-top-level-marker (make-marker)
13807 "Points to the position where current columns region starts.")
13809 (defvar org-columns-map (make-sparse-keymap)
13810 "The keymap valid in column display.")
13812 (defun org-columns-content ()
13813 "Switch to contents view while in columns view."
13814 (interactive)
13815 (org-overview)
13816 (org-content))
13818 (org-defkey org-columns-map "c" 'org-columns-content)
13819 (org-defkey org-columns-map "o" 'org-overview)
13820 (org-defkey org-columns-map "e" 'org-columns-edit-value)
13821 (org-defkey org-columns-map "v" 'org-columns-show-value)
13822 (org-defkey org-columns-map "q" 'org-columns-quit)
13823 (org-defkey org-columns-map "r" 'org-columns-redo)
13824 (org-defkey org-columns-map [left] 'backward-char)
13825 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
13826 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
13827 (org-defkey org-columns-map [right] 'forward-char)
13828 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
13829 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-next-allowed-value)
13830 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
13831 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
13832 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
13833 (org-defkey org-columns-map "<" 'org-columns-narrow)
13834 (org-defkey org-columns-map ">" 'org-columns-widen)
13835 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
13836 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
13837 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
13838 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
13840 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
13841 '("Column"
13842 ["Edit property" org-columns-edit-value t]
13843 ["Next allowed value" org-columns-next-allowed-value t]
13844 ["Previous allowed value" org-columns-previous-allowed-value t]
13845 ["Show full value" org-columns-show-value t]
13846 ["Edit allowed" org-columns-edit-allowed t]
13847 "--"
13848 ["Edit column attributes" org-columns-edit-attributes t]
13849 ["Increase column width" org-columns-widen t]
13850 ["Decrease column width" org-columns-narrow t]
13851 "--"
13852 ["Move column right" org-columns-move-right t]
13853 ["Move column left" org-columns-move-left t]
13854 ["Add column" org-columns-new t]
13855 ["Delete column" org-columns-delete t]
13856 "--"
13857 ["CONTENTS" org-columns-content t]
13858 ["OVERVIEW" org-overview t]
13859 ["Refresh columns display" org-columns-redo t]
13860 "--"
13861 ["Quit" org-columns-quit t]))
13863 (defun org-columns-new-overlay (beg end &optional string face)
13864 "Create a new column overlay and add it to the list."
13865 (let ((ov (org-make-overlay beg end)))
13866 (org-overlay-put ov 'face (or face 'secondary-selection))
13867 (org-overlay-display ov string face)
13868 (push ov org-columns-overlays)
13869 ov))
13871 (defun org-columns-display-here (&optional props)
13872 "Overlay the current line with column display."
13873 (interactive)
13874 (let* ((fmt org-columns-current-fmt-compiled)
13875 (beg (point-at-bol))
13876 (level-face (save-excursion
13877 (beginning-of-line 1)
13878 (looking-at "\\(\\**\\)\\(\\* \\)")
13879 (org-get-level-face 2)))
13880 (color (list :foreground
13881 (face-attribute (or level-face 'default) :foreground)))
13882 props pom property ass width f string ov column)
13883 ;; Check if the entry is in another buffer.
13884 (unless props
13885 (if (eq major-mode 'org-agenda-mode)
13886 (setq pom (or (get-text-property (point) 'org-hd-marker)
13887 (get-text-property (point) 'org-marker))
13888 props (if pom (org-entry-properties pom) nil))
13889 (setq props (org-entry-properties nil))))
13890 ;; Walk the format
13891 (while (setq column (pop fmt))
13892 (setq property (car column)
13893 ass (if (equal property "ITEM")
13894 (cons "ITEM"
13895 (save-match-data
13896 (org-no-properties
13897 (org-remove-tabs
13898 (buffer-substring-no-properties
13899 (point-at-bol) (point-at-eol))))))
13900 (assoc property props))
13901 width (or (cdr (assoc property org-columns-current-maxwidths))
13902 (nth 2 column))
13903 f (format "%%-%d.%ds | " width width)
13904 string (format f (or (cdr ass) "")))
13905 ;; Create the overlay
13906 (org-unmodified
13907 (setq ov (org-columns-new-overlay
13908 beg (setq beg (1+ beg)) string
13909 (list color 'org-column)))
13910 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
13911 (org-overlay-put ov 'keymap org-columns-map)
13912 (org-overlay-put ov 'org-columns-key property)
13913 (org-overlay-put ov 'org-columns-value (cdr ass))
13914 (org-overlay-put ov 'org-columns-pom pom)
13915 (org-overlay-put ov 'org-columns-format f))
13916 (if (or (not (char-after beg))
13917 (equal (char-after beg) ?\n))
13918 (let ((inhibit-read-only t))
13919 (save-excursion
13920 (goto-char beg)
13921 (insert " ")))))
13922 ;; Make the rest of the line disappear.
13923 (org-unmodified
13924 (setq ov (org-columns-new-overlay beg (point-at-eol)))
13925 (org-overlay-put ov 'invisible t)
13926 (org-overlay-put ov 'keymap org-columns-map)
13927 (push ov org-columns-overlays)
13928 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
13929 (org-overlay-put ov 'keymap org-columns-map)
13930 (push ov org-columns-overlays)
13931 (let ((inhibit-read-only t))
13932 (put-text-property (1- (point-at-bol))
13933 (min (point-max) (1+ (point-at-eol)))
13934 'read-only "Type `e' to edit property")))))
13936 (defvar org-previous-header-line-format nil
13937 "The header line format before column view was turned on.")
13938 (defvar org-columns-inhibit-recalculation nil
13939 "Inhibit recomputing of columns on column view startup.")
13941 (defvar header-line-format)
13942 (defun org-columns-display-here-title ()
13943 "Overlay the newline before the current line with the table title."
13944 (interactive)
13945 (let ((fmt org-columns-current-fmt-compiled)
13946 string (title "")
13947 property width f column str)
13948 (while (setq column (pop fmt))
13949 (setq property (car column)
13950 str (or (nth 1 column) property)
13951 width (or (cdr (assoc property org-columns-current-maxwidths))
13952 (nth 2 column))
13953 f (format "%%-%d.%ds | " width width)
13954 string (format f str)
13955 title (concat title string)))
13956 (setq title (concat
13957 (org-add-props " " nil 'display '(space :align-to 0))
13958 (org-add-props title nil 'face '(:weight bold :underline t))))
13959 (org-set-local 'org-previous-header-line-format header-line-format)
13960 (setq header-line-format title)))
13962 (defun org-columns-remove-overlays ()
13963 "Remove all currently active column overlays."
13964 (interactive)
13965 (when (marker-buffer org-columns-begin-marker)
13966 (with-current-buffer (marker-buffer org-columns-begin-marker)
13967 (when (local-variable-p 'org-previous-header-line-format)
13968 (setq header-line-format org-previous-header-line-format)
13969 (kill-local-variable 'org-previous-header-line-format))
13970 (move-marker org-columns-begin-marker nil)
13971 (move-marker org-columns-top-level-marker nil)
13972 (org-unmodified
13973 (mapc 'org-delete-overlay org-columns-overlays)
13974 (setq org-columns-overlays nil)
13975 (let ((inhibit-read-only t))
13976 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
13978 (defun org-columns-show-value ()
13979 "Show the full value of the property."
13980 (interactive)
13981 (let ((value (get-char-property (point) 'org-columns-value)))
13982 (message "Value is: %s" (or value ""))))
13984 (defun org-columns-quit ()
13985 "Remove the column overlays and in this way exit column editing."
13986 (interactive)
13987 (org-unmodified
13988 (org-columns-remove-overlays)
13989 (let ((inhibit-read-only t))
13990 ;; FIXME: is this safe???
13991 ;; or are there other reasons why there may be a read-only property????
13992 (remove-text-properties (point-min) (point-max) '(read-only t))))
13993 (when (eq major-mode 'org-agenda-mode)
13994 (message "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
13996 (defun org-columns-edit-value ()
13997 "Edit the value of the property at point in column view.
13998 Where possible, use the standard interface for changing this line."
13999 (interactive)
14000 (let* ((col (current-column))
14001 (key (get-char-property (point) 'org-columns-key))
14002 (value (get-char-property (point) 'org-columns-value))
14003 (bol (point-at-bol)) (eol (point-at-eol))
14004 (pom (or (get-text-property bol 'org-hd-marker)
14005 (point))) ; keep despite of compiler waring
14006 (line-overlays
14007 (delq nil (mapcar (lambda (x)
14008 (and (eq (overlay-buffer x) (current-buffer))
14009 (>= (overlay-start x) bol)
14010 (<= (overlay-start x) eol)
14012 org-columns-overlays)))
14013 nval eval allowed)
14014 (when (equal key "ITEM")
14015 (error "Cannot edit item headline from here"))
14017 (cond
14018 ((equal key "TODO")
14019 (setq eval '(org-with-point-at pom
14020 (let ((current-prefix-arg '(4))) (org-todo '(4))))))
14021 ((equal key "PRIORITY")
14022 (setq eval '(org-with-point-at pom
14023 (call-interactively 'org-priority))))
14024 ((equal key "TAGS")
14025 (setq eval '(org-with-point-at pom
14026 (let ((org-fast-tag-selection-single-key
14027 (if (eq org-fast-tag-selection-single-key 'expert)
14028 t org-fast-tag-selection-single-key)))
14029 (call-interactively 'org-set-tags)))))
14030 ((equal key "DEADLINE")
14031 (setq eval '(org-with-point-at pom
14032 (call-interactively 'org-deadline))))
14033 ((equal key "SCHEDULED")
14034 (setq eval '(org-with-point-at pom
14035 (call-interactively 'org-deadline))))
14037 (setq allowed (org-property-get-allowed-values pom key 'table))
14038 (if allowed
14039 (setq nval (completing-read "Value: " allowed nil t))
14040 (setq nval (read-string "Edit: " value)))
14041 (setq nval (org-trim nval))
14042 (when (not (equal nval value))
14043 (setq eval '(org-entry-put pom key nval)))))
14044 (when eval
14045 (let ((inhibit-read-only t))
14046 (remove-text-properties (1- bol) eol '(read-only t))
14047 (unwind-protect
14048 (progn
14049 (setq org-columns-overlays
14050 (org-delete-all line-overlays org-columns-overlays))
14051 (mapc 'org-delete-overlay line-overlays)
14052 (org-columns-eval eval))
14053 (org-columns-display-here))))
14054 (move-to-column col)
14055 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14056 (org-columns-update key))))
14058 (defun org-columns-edit-allowed ()
14059 "Edit the list of allowed values for the current property."
14060 (interactive)
14061 (let* ((col (current-column))
14062 (key (get-char-property (point) 'org-columns-key))
14063 (key1 (concat key "_ALL"))
14064 (value (get-char-property (point) 'org-columns-value))
14065 (allowed (org-entry-get (point) key1 t))
14066 nval)
14067 (setq nval (read-string "Allowed: " allowed))
14068 (org-entry-put
14069 (cond ((marker-position org-entry-property-inherited-from)
14070 org-entry-property-inherited-from)
14071 ((marker-position org-columns-top-level-marker)
14072 org-columns-top-level-marker))
14073 key1 nval)))
14075 (defun org-columns-eval (form)
14076 (let (hidep)
14077 (save-excursion
14078 (beginning-of-line 1)
14079 (next-line 1)
14080 (setq hidep (org-on-heading-p 1)))
14081 (eval form)
14082 (and hidep (hide-entry))))
14084 (defun org-columns-previous-allowed-value ()
14085 "Switch to the previous allowed value for this column."
14086 (interactive)
14087 (org-columns-next-allowed-value t))
14089 (defun org-columns-next-allowed-value (&optional previous)
14090 "Switch to the next allowed value for this column."
14091 (interactive)
14092 (let* ((col (current-column))
14093 (key (get-char-property (point) 'org-columns-key))
14094 (value (get-char-property (point) 'org-columns-value))
14095 (bol (point-at-bol)) (eol (point-at-eol))
14096 (pom (or (get-text-property bol 'org-hd-marker)
14097 (point))) ; keep despite of compiler waring
14098 (line-overlays
14099 (delq nil (mapcar (lambda (x)
14100 (and (eq (overlay-buffer x) (current-buffer))
14101 (>= (overlay-start x) bol)
14102 (<= (overlay-start x) eol)
14104 org-columns-overlays)))
14105 (allowed (or (org-property-get-allowed-values pom key)
14106 (and (equal
14107 (nth 4 (assoc key org-columns-current-fmt-compiled))
14108 'checkbox) '("[ ]" "[X]"))))
14109 nval)
14110 (when (equal key "ITEM")
14111 (error "Cannot edit item headline from here"))
14112 (unless allowed
14113 (error "Allowed values for this property have not been defined"))
14114 (if previous (setq allowed (reverse allowed)))
14115 (if (member value allowed)
14116 (setq nval (car (cdr (member value allowed)))))
14117 (setq nval (or nval (car allowed)))
14118 (if (equal nval value)
14119 (error "Only one allowed value for this property"))
14120 (let ((inhibit-read-only t))
14121 (remove-text-properties (1- bol) eol '(read-only t))
14122 (unwind-protect
14123 (progn
14124 (setq org-columns-overlays
14125 (org-delete-all line-overlays org-columns-overlays))
14126 (mapc 'org-delete-overlay line-overlays)
14127 (org-columns-eval '(org-entry-put pom key nval)))
14128 (org-columns-display-here)))
14129 (move-to-column col)
14130 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
14131 (org-columns-update key))))
14133 (defun org-verify-version (task)
14134 (cond
14135 ((eq task 'columns)
14136 (if (or (featurep 'xemacs)
14137 (< emacs-major-version 22))
14138 (error "Emacs 22 is required for the columns feature")))))
14140 (defun org-columns ()
14141 "Turn on column view on an org-mode file."
14142 (interactive)
14143 (org-verify-version 'columns)
14144 (org-columns-remove-overlays)
14145 (move-marker org-columns-begin-marker (point))
14146 (let (beg end fmt cache maxwidths)
14147 (when (condition-case nil (org-back-to-heading) (error nil))
14148 (move-marker org-entry-property-inherited-from nil)
14149 (setq fmt (org-entry-get nil "COLUMNS" t)))
14150 (setq fmt (or fmt org-columns-default-format))
14151 (org-set-local 'org-columns-current-fmt fmt)
14152 (org-columns-compile-format fmt)
14153 (save-excursion
14154 (if (marker-position org-entry-property-inherited-from)
14155 (goto-char org-entry-property-inherited-from))
14156 (setq beg (point))
14157 (move-marker org-columns-top-level-marker (point))
14158 (unless org-columns-inhibit-recalculation
14159 (org-columns-compute-all))
14160 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
14161 (point-max)))
14162 (goto-char beg)
14163 ;; Get and cache the properties
14164 (while (re-search-forward (concat "^" outline-regexp) end t)
14165 (push (cons (org-current-line) (org-entry-properties)) cache))
14166 (when cache
14167 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14168 (org-set-local 'org-columns-current-maxwidths maxwidths)
14169 (goto-line (car (org-last cache)))
14170 (org-columns-display-here-title)
14171 (mapc (lambda (x)
14172 (goto-line (car x))
14173 (org-columns-display-here (cdr x)))
14174 cache)))))
14176 (defun org-columns-new (&optional prop title width op fmt)
14177 "Insert a new column, to the leeft o the current column."
14178 (interactive)
14179 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
14180 cell)
14181 (setq prop (completing-read
14182 "Property: " (mapcar 'list (org-buffer-property-keys t))
14183 nil nil prop))
14184 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
14185 (setq width (read-string "Column width: " (if width (number-to-string width))))
14186 (if (string-match "\\S-" width)
14187 (setq width (string-to-number width))
14188 (setq width nil))
14189 (setq fmt (completing-read "Summary [none]: "
14190 '(("none") ("add_numbers") ("add_times") ("checkbox"))
14191 nil t))
14192 (if (string-match "\\S-" fmt)
14193 (setq fmt (intern fmt))
14194 (setq fmt nil))
14195 (if (eq fmt 'none) (setq fmt nil))
14196 (if editp
14197 (progn
14198 (setcar editp prop)
14199 (setcdr editp (list title width nil fmt)))
14200 (setq cell (nthcdr (1- (current-column))
14201 org-columns-current-fmt-compiled))
14202 (setcdr cell (cons (list prop title width nil fmt)
14203 (cdr cell))))
14204 (org-columns-store-format)
14205 (org-columns-redo)))
14207 (defun org-columns-delete ()
14208 "Delete the column at point from columns view."
14209 (interactive)
14210 (let* ((n (current-column))
14211 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
14212 (when (y-or-n-p
14213 (format "Are you sure you want to remove column \"%s\"? " title))
14214 (setq org-columns-current-fmt-compiled
14215 (delq (nth n org-columns-current-fmt-compiled)
14216 org-columns-current-fmt-compiled))
14217 (org-columns-store-format)
14218 (org-columns-redo)
14219 (if (>= (current-column) (length org-columns-current-fmt-compiled))
14220 (backward-char 1)))))
14222 (defun org-columns-edit-attributes ()
14223 "Edit the attributes of the current column."
14224 (interactive)
14225 (let* ((n (current-column))
14226 (info (nth n org-columns-current-fmt-compiled)))
14227 (apply 'org-columns-new info)))
14229 (defun org-columns-widen (arg)
14230 "Make the column wider by ARG characters."
14231 (interactive "p")
14232 (let* ((n (current-column))
14233 (entry (nth n org-columns-current-fmt-compiled))
14234 (width (or (nth 2 entry)
14235 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
14236 (setq width (max 1 (+ width arg)))
14237 (setcar (nthcdr 2 entry) width)
14238 (org-columns-store-format)
14239 (org-columns-redo)))
14241 (defun org-columns-narrow (arg)
14242 "Make the column nrrower by ARG characters."
14243 (interactive "p")
14244 (org-columns-widen (- arg)))
14246 (defun org-columns-move-right ()
14247 "Swap this column with the one to the right."
14248 (interactive)
14249 (let* ((n (current-column))
14250 (cell (nthcdr n org-columns-current-fmt-compiled))
14252 (when (>= n (1- (length org-columns-current-fmt-compiled)))
14253 (error "Cannot shift this column further to the right"))
14254 (setq e (car cell))
14255 (setcar cell (car (cdr cell)))
14256 (setcdr cell (cons e (cdr (cdr cell))))
14257 (org-columns-store-format)
14258 (org-columns-redo)
14259 (forward-char 1)))
14261 (defun org-columns-move-left ()
14262 "Swap this column with the one to the left."
14263 (interactive)
14264 (let* ((n (current-column)))
14265 (when (= n 0)
14266 (error "Cannot shift this column further to the left"))
14267 (backward-char 1)
14268 (org-columns-move-right)
14269 (backward-char 1)))
14271 (defun org-columns-store-format ()
14272 "Store the text version of the current columns format in appropriate place.
14273 This is either in the COLUMNS property of the node starting the current column
14274 display, or in the #+COLUMNS line of the current buffer."
14275 (let (fmt)
14276 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
14277 (if (marker-position org-columns-top-level-marker)
14278 (save-excursion
14279 (goto-char org-columns-top-level-marker)
14280 (if (org-entry-get nil "COLUMNS")
14281 (org-entry-put nil "COLUMNS" fmt)
14282 (goto-char (point-min))
14283 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
14284 (replace-match (concat "#+COLUMNS: " fmt t t)))))
14285 (setq org-columns-current-fmt fmt))))
14287 (defvar org-overriding-columns-format nil
14288 "When set, overrides any other definition.")
14289 (defvar org-agenda-view-columns-initially nil
14290 "When set, switch to columns view immediately after creating the agenda.")
14292 (defun org-agenda-columns ()
14293 "Turn on column view in the agenda."
14294 (interactive)
14295 (org-verify-version 'columns)
14296 (org-columns-remove-overlays)
14297 (move-marker org-columns-begin-marker (point))
14298 (let (fmt cache maxwidths m)
14299 (cond
14300 ((and (local-variable-p 'org-overriding-columns-format)
14301 org-overriding-columns-format)
14302 (setq fmt org-overriding-columns-format))
14303 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
14304 (setq fmt (org-entry-get m "COLUMNS" t)))
14305 ((and (boundp 'org-columns-current-fmt)
14306 (local-variable-p 'org-columns-current-fmt)
14307 org-columns-current-fmt)
14308 (setq fmt org-columns-current-fmt))
14309 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
14310 (setq m (get-text-property m 'org-hd-marker))
14311 (setq fmt (org-entry-get m "COLUMNS" t))))
14312 (setq fmt (or fmt org-columns-default-format))
14313 (org-set-local 'org-columns-current-fmt fmt)
14314 (org-columns-compile-format fmt)
14315 (save-excursion
14316 ;; Get and cache the properties
14317 (goto-char (point-min))
14318 (while (not (eobp))
14319 (when (setq m (or (get-text-property (point) 'org-hd-marker)
14320 (get-text-property (point) 'org-marker)))
14321 (push (cons (org-current-line) (org-entry-properties m)) cache))
14322 (beginning-of-line 2))
14323 (when cache
14324 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
14325 (org-set-local 'org-columns-current-maxwidths maxwidths)
14326 (goto-line (car (org-last cache)))
14327 (org-columns-display-here-title)
14328 (mapc (lambda (x)
14329 (goto-line (car x))
14330 (org-columns-display-here (cdr x)))
14331 cache)))))
14333 (defun org-columns-get-autowidth-alist (s cache)
14334 "Derive the maximum column widths from the format and the cache."
14335 (let ((start 0) rtn)
14336 (while (string-match "%\\([a-zA-Z]\\S-*\\)" s start)
14337 (push (cons (match-string 1 s) 1) rtn)
14338 (setq start (match-end 0)))
14339 (mapc (lambda (x)
14340 (setcdr x (apply 'max
14341 (mapcar
14342 (lambda (y)
14343 (length (or (cdr (assoc (car x) (cdr y))) " ")))
14344 cache))))
14345 rtn)
14346 rtn))
14348 (defun org-columns-compute-all ()
14349 "Compute all columns that have operators defined."
14350 (remove-text-properties (point-min) (point-max) '(org-summaries t))
14351 (let ((columns org-columns-current-fmt-compiled) col)
14352 (while (setq col (pop columns))
14353 (when (nth 3 col)
14354 (save-excursion
14355 (org-columns-compute (car col)))))))
14357 (defun org-columns-update (property)
14358 "Recompute PROPERTY, and update the columns display for it."
14359 (org-columns-compute property)
14360 (let (fmt val pos)
14361 (save-excursion
14362 (mapc (lambda (ov)
14363 (when (equal (org-overlay-get ov 'org-columns-key) property)
14364 (setq pos (org-overlay-start ov))
14365 (goto-char pos)
14366 (when (setq val (cdr (assoc property
14367 (get-text-property (point-at-bol) 'org-summaries))))
14368 (setq fmt (org-overlay-get ov 'org-columns-format))
14369 (org-overlay-put ov 'display (format fmt val)))))
14370 org-columns-overlays))))
14372 (defun org-columns-compute (property)
14373 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
14374 (interactive)
14375 (let* ((re (concat "^" outline-regexp))
14376 (lmax 30) ; Does anyone use deeper levels???
14377 (lsum (make-vector lmax 0))
14378 (level 0)
14379 (ass (assoc property org-columns-current-fmt-compiled))
14380 (format (nth 4 ass))
14381 (beg org-columns-top-level-marker)
14382 last-level val end sumpos sum-alist sum str)
14383 (save-excursion
14384 ;; Find the region to compute
14385 (goto-char beg)
14386 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
14387 (goto-char end)
14388 ;; Walk the tree from the back and do the computations
14389 (while (re-search-backward re beg t)
14390 (setq sumpos (match-beginning 0)
14391 last-level level
14392 level (org-outline-level)
14393 val (org-entry-get nil property))
14394 (cond
14395 ((< level last-level)
14396 ;; put the sum of lower levels here as a property
14397 (setq sum (aref lsum last-level)
14398 str (org-column-number-to-string sum format)
14399 sum-alist (get-text-property sumpos 'org-summaries))
14400 (if (assoc property sum-alist)
14401 (setcdr (assoc property sum-alist) str)
14402 (push (cons property str) sum-alist)
14403 (add-text-properties sumpos (1+ sumpos)
14404 (list 'org-summaries sum-alist)))
14405 (when val
14406 (org-entry-put nil property str))
14407 ;; add current to current level accumulator
14408 (aset lsum level (+ (aref lsum level) sum))
14409 ;; clear accumulators for deeper levels
14410 (loop for l from (1+ level) to (1- lmax) do (aset lsum l 0)))
14411 ((>= level last-level)
14412 ;; add what we have here to the accumulator for this level
14413 (aset lsum level (+ (aref lsum level)
14414 (org-column-string-to-number (or val "0") format))))
14415 (t (error "This should not happen")))))))
14417 (defun org-columns-redo ()
14418 "Construct the column display again."
14419 (interactive)
14420 (message "Recomputing columns...")
14421 (save-excursion
14422 (if (marker-position org-columns-begin-marker)
14423 (goto-char org-columns-begin-marker))
14424 (org-columns-remove-overlays)
14425 (if (org-mode-p)
14426 (call-interactively 'org-columns)
14427 (call-interactively 'org-agenda-columns)))
14428 (message "Recomputing columns...done"))
14430 (defun org-columns-not-in-agenda ()
14431 (if (eq major-mode 'org-agenda-mode)
14432 (error "This command is only allowed in Org-mode buffers")))
14435 (defun org-string-to-number (s)
14436 "Convert string to number, and interpret hh:mm:ss."
14437 (if (not (string-match ":" s))
14438 (string-to-number s)
14439 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14440 (while l
14441 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14442 sum)))
14444 (defun org-column-number-to-string (n fmt)
14445 "Convert a computed column number to a string value, according to FMT."
14446 (cond
14447 ((eq fmt 'add_times)
14448 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
14449 (format "%d:%02d" h m)))
14450 ((eq fmt 'checkbox)
14451 (cond ((= n (floor n)) "[X]")
14452 ((> n 1.) "[-]")
14453 (t "[ ]")))
14454 (t (number-to-string n))))
14456 (defun org-column-string-to-number (s fmt)
14457 "Convert a column value to a number that can be used for column computing."
14458 (cond
14459 ((string-match ":" s)
14460 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
14461 (while l
14462 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
14463 sum))
14464 ((eq fmt 'checkbox)
14465 (if (equal s "[X]") 1. 0.000001))
14466 (t (string-to-number s))))
14468 (defun org-columns-uncompile-format (cfmt)
14469 "Turn the compiled columns format back into a string representation."
14470 (let ((rtn "") e s prop title op width fmt)
14471 (while (setq e (pop cfmt))
14472 (setq prop (car e)
14473 title (nth 1 e)
14474 width (nth 2 e)
14475 op (nth 3 e)
14476 fmt (nth 4 e))
14477 (cond
14478 ((eq fmt 'add_times) (setq op ":"))
14479 ((eq fmt 'checkbox) (setq op "X"))
14480 ((eq fmt 'add_numbers) (setq op "+")))
14481 (if (equal title prop) (setq title nil))
14482 (setq s (concat "%" (if width (number-to-string width))
14483 prop
14484 (if title (concat "(" title ")"))
14485 (if op (concat "{" op "}"))))
14486 (setq rtn (concat rtn " " s)))
14487 (org-trim rtn)))
14489 (defun org-columns-compile-format (fmt)
14490 "FIXME"
14491 (let ((start 0) width prop title op f)
14492 (setq org-columns-current-fmt-compiled nil)
14493 (while (string-match "%\\([0-9]+\\)?\\([a-zA-Z_0-9]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*"
14494 fmt start)
14495 (setq start (match-end 0)
14496 width (match-string 1 fmt)
14497 prop (match-string 2 fmt)
14498 title (or (match-string 3 fmt) prop)
14499 op (match-string 4 fmt)
14500 f nil)
14501 (if width (setq width (string-to-number width)))
14502 (cond
14503 ((equal op "+") (setq f 'add_numbers))
14504 ((equal op ":") (setq f 'add_times))
14505 ((equal op "X") (setq f 'checkbox)))
14506 (push (list prop title width op f) org-columns-current-fmt-compiled))
14507 (setq org-columns-current-fmt-compiled
14508 (nreverse org-columns-current-fmt-compiled))))
14510 ;;;; Timestamps
14512 (defvar org-last-changed-timestamp nil)
14513 (defvar org-time-was-given) ; dynamically scoped parameter
14514 (defvar org-end-time-was-given) ; dynamically scoped parameter
14515 (defvar org-ts-what) ; dynamically scoped parameter
14517 (defun org-time-stamp (arg)
14518 "Prompt for a date/time and insert a time stamp.
14519 If the user specifies a time like HH:MM, or if this command is called
14520 with a prefix argument, the time stamp will contain date and time.
14521 Otherwise, only the date will be included. All parts of a date not
14522 specified by the user will be filled in from the current date/time.
14523 So if you press just return without typing anything, the time stamp
14524 will represent the current date/time. If there is already a timestamp
14525 at the cursor, it will be modified."
14526 (interactive "P")
14527 (let (org-time-was-given org-end-time-was-given time)
14528 (cond
14529 ((and (org-at-timestamp-p)
14530 (eq last-command 'org-time-stamp)
14531 (eq this-command 'org-time-stamp))
14532 (insert "--")
14533 (setq time (let ((this-command this-command))
14534 (org-read-date arg 'totime)))
14535 (org-insert-time-stamp time (or org-time-was-given arg)))
14536 ((org-at-timestamp-p)
14537 (setq time (let ((this-command this-command))
14538 (org-read-date arg 'totime)))
14539 (when (org-at-timestamp-p) ; just to get the match data
14540 (replace-match "")
14541 (setq org-last-changed-timestamp
14542 (org-insert-time-stamp
14543 time (or org-time-was-given arg)
14544 nil nil nil (list org-end-time-was-given))))
14545 (message "Timestamp updated"))
14547 (setq time (let ((this-command this-command))
14548 (org-read-date arg 'totime)))
14549 (org-insert-time-stamp time (or org-time-was-given arg)
14550 nil nil nil (list org-end-time-was-given))))))
14552 (defun org-time-stamp-inactive (&optional arg)
14553 "Insert an inactive time stamp.
14554 An inactive time stamp is enclosed in square brackets instead of angle
14555 brackets. It is inactive in the sense that it does not trigger agenda entries,
14556 does not link to the calendar and cannot be changed with the S-cursor keys.
14557 So these are more for recording a certain time/date."
14558 (interactive "P")
14559 (let (org-time-was-given org-end-time-was-given time)
14560 (setq time (org-read-date arg 'totime))
14561 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
14562 nil nil (list org-end-time-was-given))))
14564 (defvar org-date-ovl (org-make-overlay 1 1))
14565 (org-overlay-put org-date-ovl 'face 'org-warning)
14566 (org-detach-overlay org-date-ovl)
14568 (defvar org-ans1) ; dynamically scoped parameter
14569 (defvar org-ans2) ; dynamically scoped parameter
14571 (defvar org-plain-time-of-day-regexp) ; defined below
14572 (defun org-read-date (&optional with-time to-time from-string prompt)
14573 "Read a date and make things smooth for the user.
14574 The prompt will suggest to enter an ISO date, but you can also enter anything
14575 which will at least partially be understood by `parse-time-string'.
14576 Unrecognized parts of the date will default to the current day, month, year,
14577 hour and minute. For example,
14578 3-2-5 --> 2003-02-05
14579 feb 15 --> currentyear-02-15
14580 sep 12 9 --> 2009-09-12
14581 12:45 --> today 12:45
14582 22 sept 0:34 --> currentyear-09-22 0:34
14583 12 --> currentyear-currentmonth-12
14584 Fri --> nearest Friday (today or later)
14585 +4 --> four days from today (only if +N is the only thing given)
14586 etc.
14587 The function understands only English month and weekday abbreviations,
14588 but this can be configured with the variables `parse-time-months' and
14589 `parse-time-weekdays'.
14591 While prompting, a calendar is popped up - you can also select the
14592 date with the mouse (button 1). The calendar shows a period of three
14593 months. To scroll it to other months, use the keys `>' and `<'.
14594 If you don't like the calendar, turn it off with
14595 \(setq org-popup-calendar-for-date-prompt nil)
14597 With optional argument TO-TIME, the date will immediately be converted
14598 to an internal time.
14599 With an optional argument WITH-TIME, the prompt will suggest to also
14600 insert a time. Note that when WITH-TIME is not set, you can still
14601 enter a time, and this function will inform the calling routine about
14602 this change. The calling routine may then choose to change the format
14603 used to insert the time stamp into the buffer to include the time."
14604 (require 'parse-time)
14605 (let* ((org-time-stamp-rounding-minutes
14606 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
14607 (ct (org-current-time))
14608 (default-time
14609 ;; Default time is either today, or, when entering a range,
14610 ;; the range start.
14611 (if (save-excursion
14612 (re-search-backward
14613 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
14614 (- (point) 20) t))
14615 (apply
14616 'encode-time
14617 (mapcar (lambda(x) (or x 0))
14618 (parse-time-string (match-string 1))))
14619 ct))
14620 (calendar-move-hook nil)
14621 (view-diary-entries-initially nil)
14622 (view-calendar-holidays-initially nil)
14623 (timestr (format-time-string
14624 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
14625 (prompt (concat (if prompt (concat prompt " ") "")
14626 (format "Date and/or time (default [%s]): " timestr)))
14627 ans (org-ans0 "") org-ans1 org-ans2 (deltadays 0)
14628 second minute hour day month year tl wday wday1 pm)
14630 (cond
14631 (from-string (setq ans from-string))
14632 (org-popup-calendar-for-date-prompt
14633 (save-excursion
14634 (save-window-excursion
14635 (calendar)
14636 (calendar-forward-day (- (time-to-days default-time)
14637 (calendar-absolute-from-gregorian
14638 (calendar-current-date))))
14639 (org-eval-in-calendar nil t)
14640 (let* ((old-map (current-local-map))
14641 (map (copy-keymap calendar-mode-map))
14642 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
14643 (org-defkey map (kbd "RET") 'org-calendar-select)
14644 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
14645 'org-calendar-select-mouse)
14646 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
14647 'org-calendar-select-mouse)
14648 (org-defkey minibuffer-local-map [(meta shift left)]
14649 (lambda () (interactive)
14650 (org-eval-in-calendar '(calendar-backward-month 1))))
14651 (org-defkey minibuffer-local-map [(meta shift right)]
14652 (lambda () (interactive)
14653 (org-eval-in-calendar '(calendar-forward-month 1))))
14654 (org-defkey minibuffer-local-map [(shift up)]
14655 (lambda () (interactive)
14656 (org-eval-in-calendar '(calendar-backward-week 1))))
14657 (org-defkey minibuffer-local-map [(shift down)]
14658 (lambda () (interactive)
14659 (org-eval-in-calendar '(calendar-forward-week 1))))
14660 (org-defkey minibuffer-local-map [(shift left)]
14661 (lambda () (interactive)
14662 (org-eval-in-calendar '(calendar-backward-day 1))))
14663 (org-defkey minibuffer-local-map [(shift right)]
14664 (lambda () (interactive)
14665 (org-eval-in-calendar '(calendar-forward-day 1))))
14666 (org-defkey minibuffer-local-map ">"
14667 (lambda () (interactive)
14668 (org-eval-in-calendar '(scroll-calendar-left 1))))
14669 (org-defkey minibuffer-local-map "<"
14670 (lambda () (interactive)
14671 (org-eval-in-calendar '(scroll-calendar-right 1))))
14672 (unwind-protect
14673 (progn
14674 (use-local-map map)
14675 (setq org-ans0 (read-string prompt "" nil nil))
14676 ;; org-ans0: from prompt
14677 ;; org-ans1: from mouse click
14678 ;; org-ans2: from calendar motion
14679 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
14680 (use-local-map old-map))))))
14681 (t ; Naked prompt only
14682 (setq ans (read-string prompt "" nil timestr))))
14683 (org-detach-overlay org-date-ovl)
14685 (if (string-match "^[ \t]*[-+][0-9]+[ \t]*$" org-ans0)
14686 (setq deltadays (string-to-number ans) ans ""))
14688 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
14689 (when (string-match
14690 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
14691 (setq year (if (match-end 2)
14692 (string-to-number (match-string 2 ans))
14693 (string-to-number (format-time-string "%Y")))
14694 month (string-to-number (match-string 3 ans))
14695 day (string-to-number (match-string 4 ans)))
14696 (if (< year 100) (setq year (+ 2000 year)))
14697 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
14698 t nil ans)))
14699 ;; Help matching am/pm times, because `parse-time-string' does not do that.
14700 ;; If there is a time with am/pm, and *no* time without it, we convert
14701 ;; so that matching will be successful.
14702 ;; FIXME: make this replace twice, so that we catch the end time.
14703 (when (and (not (string-match "[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
14704 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
14705 (setq hour (string-to-number (match-string 1 ans))
14706 minute (if (match-end 3) (string-to-number (match-string 3 ans)) 0)
14707 pm (equal ?p (string-to-char (downcase (match-string 4 ans)))))
14708 (if (and (= hour 12) (not pm))
14709 (setq hour 0)
14710 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
14711 (setq ans (replace-match (format "%02d:%02d" hour minute) t t ans)))
14713 ;; Check if there is a time range
14714 (when (and (boundp 'org-end-time-was-given)
14715 (string-match org-plain-time-of-day-regexp ans)
14716 (match-end 8))
14717 (setq org-end-time-was-given (match-string 8 ans))
14718 (setq ans (concat (substring ans 0 (match-beginning 7))
14719 (substring ans (match-end 7)))))
14721 (setq tl (parse-time-string ans)
14722 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
14723 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
14724 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
14725 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
14726 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
14727 second (or (nth 0 tl) 0)
14728 wday (nth 6 tl))
14729 (setq day (+ day deltadays))
14730 (when (and wday (not (nth 3 tl)))
14731 ;; Weekday was given, but no day, so pick that day in the week
14732 ;; on or after the derived date.
14733 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
14734 (unless (equal wday wday1)
14735 (setq day (+ day (% (- wday wday1 -7) 7)))))
14736 (if (and (boundp 'org-time-was-given)
14737 (nth 2 tl))
14738 (setq org-time-was-given t))
14739 (if (< year 100) (setq year (+ 2000 year)))
14740 (if to-time
14741 (encode-time second minute hour day month year)
14742 (if (or (nth 1 tl) (nth 2 tl))
14743 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
14744 (format "%04d-%02d-%02d" year month day)))))
14746 (defun org-eval-in-calendar (form &optional keepdate)
14747 "Eval FORM in the calendar window and return to current window.
14748 Also, store the cursor date in variable org-ans2."
14749 (let ((sw (selected-window)))
14750 (select-window (get-buffer-window "*Calendar*"))
14751 (eval form)
14752 (when (and (not keepdate) (calendar-cursor-to-date))
14753 (let* ((date (calendar-cursor-to-date))
14754 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14755 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
14756 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
14757 (select-window sw)
14758 ;; Update the prompt to show new default date
14759 (save-excursion
14760 (goto-char (point-min))
14761 (when (and org-ans2
14762 (re-search-forward "\\[[-0-9]+\\]" nil t)
14763 (get-text-property (match-end 0) 'field))
14764 (let ((inhibit-read-only t))
14765 (replace-match (concat "[" org-ans2 "]") t t)
14766 (add-text-properties (point-min) (1+ (match-end 0))
14767 (text-properties-at (1+ (point-min)))))))))
14769 (defun org-calendar-select ()
14770 "Return to `org-read-date' with the date currently selected.
14771 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14772 (interactive)
14773 (when (calendar-cursor-to-date)
14774 (let* ((date (calendar-cursor-to-date))
14775 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14776 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14777 (if (active-minibuffer-window) (exit-minibuffer))))
14779 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
14780 "Insert a date stamp for the date given by the internal TIME.
14781 WITH-HM means, use the stamp format that includes the time of the day.
14782 INACTIVE means use square brackets instead of angular ones, so that the
14783 stamp will not contribute to the agenda.
14784 PRE and POST are optional strings to be inserted before and after the
14785 stamp.
14786 The command returns the inserted time stamp."
14787 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
14788 stamp)
14789 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
14790 (insert (or pre ""))
14791 (insert (setq stamp (format-time-string fmt time)))
14792 (when (listp extra)
14793 (setq extra (car extra))
14794 (if (and (stringp extra)
14795 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
14796 (setq extra (format "-%02d:%02d"
14797 (string-to-number (match-string 1 extra))
14798 (string-to-number (match-string 2 extra))))
14799 (setq extra nil)))
14800 (when extra
14801 (backward-char 1)
14802 (insert extra)
14803 (forward-char 1))
14804 (insert (or post ""))
14805 stamp))
14807 (defun org-toggle-time-stamp-overlays ()
14808 "Toggle the use of custom time stamp formats."
14809 (interactive)
14810 (setq org-display-custom-times (not org-display-custom-times))
14811 (unless org-display-custom-times
14812 (let ((p (point-min)) (bmp (buffer-modified-p)))
14813 (while (setq p (next-single-property-change p 'display))
14814 (if (and (get-text-property p 'display)
14815 (eq (get-text-property p 'face) 'org-date))
14816 (remove-text-properties
14817 p (setq p (next-single-property-change p 'display))
14818 '(display t))))
14819 (set-buffer-modified-p bmp)))
14820 (if (featurep 'xemacs)
14821 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
14822 (org-restart-font-lock)
14823 (setq org-table-may-need-update t)
14824 (if org-display-custom-times
14825 (message "Time stamps are overlayed with custom format")
14826 (message "Time stamp overlays removed")))
14828 (defun org-display-custom-time (beg end)
14829 "Overlay modified time stamp format over timestamp between BED and END."
14830 (let* ((ts (buffer-substring beg end))
14831 t1 w1 with-hm tf time str w2 (off 0))
14832 (save-match-data
14833 (setq t1 (org-parse-time-string ts t))
14834 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
14835 (setq off (- (match-end 0) (match-beginning 0)))))
14836 (setq end (- end off))
14837 (setq w1 (- end beg)
14838 with-hm (and (nth 1 t1) (nth 2 t1))
14839 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
14840 time (org-fix-decoded-time t1)
14841 str (org-add-props
14842 (format-time-string
14843 (substring tf 1 -1) (apply 'encode-time time))
14844 nil 'mouse-face 'highlight)
14845 w2 (length str))
14846 (if (not (= w2 w1))
14847 (add-text-properties (1+ beg) (+ 2 beg)
14848 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
14849 (if (featurep 'xemacs)
14850 (progn
14851 (put-text-property beg end 'invisible t)
14852 (put-text-property beg end 'end-glyph (make-glyph str)))
14853 (put-text-property beg end 'display str))))
14855 (defun org-translate-time (string)
14856 "Translate all timestamps in STRING to custom format.
14857 But do this only if the variable `org-display-custom-times' is set."
14858 (when org-display-custom-times
14859 (save-match-data
14860 (let* ((start 0)
14861 (re org-ts-regexp-both)
14862 t1 with-hm inactive tf time str beg end)
14863 (while (setq start (string-match re string start))
14864 (setq beg (match-beginning 0)
14865 end (match-end 0)
14866 t1 (save-match-data
14867 (org-parse-time-string (substring string beg end) t))
14868 with-hm (and (nth 1 t1) (nth 2 t1))
14869 inactive (equal (substring string beg (1+ beg)) "[")
14870 tf (funcall (if with-hm 'cdr 'car)
14871 org-time-stamp-custom-formats)
14872 time (org-fix-decoded-time t1)
14873 str (format-time-string
14874 (concat
14875 (if inactive "[" "<") (substring tf 1 -1)
14876 (if inactive "]" ">"))
14877 (apply 'encode-time time))
14878 string (replace-match str t t string)
14879 start (+ start (length str)))))))
14880 string)
14882 (defun org-fix-decoded-time (time)
14883 "Set 0 instead of nil for the first 6 elements of time.
14884 Don't touch the rest."
14885 (let ((n 0))
14886 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14888 (defun org-days-to-time (timestamp-string)
14889 "Difference between TIMESTAMP-STRING and now in days."
14890 (- (time-to-days (org-time-string-to-time timestamp-string))
14891 (time-to-days (current-time))))
14893 (defun org-deadline-close (timestamp-string &optional ndays)
14894 "Is the time in TIMESTAMP-STRING close to the current date?"
14895 (and (< (org-days-to-time timestamp-string)
14896 (or ndays org-deadline-warning-days))
14897 (not (org-entry-is-done-p))))
14899 (defun org-calendar-select-mouse (ev)
14900 "Return to `org-read-date' with the date currently selected.
14901 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14902 (interactive "e")
14903 (mouse-set-point ev)
14904 (when (calendar-cursor-to-date)
14905 (let* ((date (calendar-cursor-to-date))
14906 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14907 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14908 (if (active-minibuffer-window) (exit-minibuffer))))
14910 (defun org-check-deadlines (ndays)
14911 "Check if there are any deadlines due or past due.
14912 A deadline is considered due if it happens within `org-deadline-warning-days'
14913 days from today's date. If the deadline appears in an entry marked DONE,
14914 it is not shown. The prefix arg NDAYS can be used to test that many
14915 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14916 (interactive "P")
14917 (let* ((org-warn-days
14918 (cond
14919 ((equal ndays '(4)) 100000)
14920 (ndays (prefix-numeric-value ndays))
14921 (t org-deadline-warning-days)))
14922 (case-fold-search nil)
14923 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14924 (callback
14925 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14927 (message "%d deadlines past-due or due within %d days"
14928 (org-occur regexp nil callback)
14929 org-warn-days)))
14931 (defun org-evaluate-time-range (&optional to-buffer)
14932 "Evaluate a time range by computing the difference between start and end.
14933 Normally the result is just printed in the echo area, but with prefix arg
14934 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14935 If the time range is actually in a table, the result is inserted into the
14936 next column.
14937 For time difference computation, a year is assumed to be exactly 365
14938 days in order to avoid rounding problems."
14939 (interactive "P")
14941 (org-clock-update-time-maybe)
14942 (save-excursion
14943 (unless (org-at-date-range-p)
14944 (goto-char (point-at-bol))
14945 (re-search-forward org-tr-regexp (point-at-eol) t))
14946 (if (not (org-at-date-range-p))
14947 (error "Not at a time-stamp range, and none found in current line")))
14948 (let* ((ts1 (match-string 1))
14949 (ts2 (match-string 2))
14950 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14951 (match-end (match-end 0))
14952 (time1 (org-time-string-to-time ts1))
14953 (time2 (org-time-string-to-time ts2))
14954 (t1 (time-to-seconds time1))
14955 (t2 (time-to-seconds time2))
14956 (diff (abs (- t2 t1)))
14957 (negative (< (- t2 t1) 0))
14958 ;; (ys (floor (* 365 24 60 60)))
14959 (ds (* 24 60 60))
14960 (hs (* 60 60))
14961 (fy "%dy %dd %02d:%02d")
14962 (fy1 "%dy %dd")
14963 (fd "%dd %02d:%02d")
14964 (fd1 "%dd")
14965 (fh "%02d:%02d")
14966 y d h m align)
14967 (if havetime
14968 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14970 d (floor (/ diff ds)) diff (mod diff ds)
14971 h (floor (/ diff hs)) diff (mod diff hs)
14972 m (floor (/ diff 60)))
14973 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14975 d (floor (+ (/ diff ds) 0.5))
14976 h 0 m 0))
14977 (if (not to-buffer)
14978 (message (org-make-tdiff-string y d h m))
14979 (when (org-at-table-p)
14980 (goto-char match-end)
14981 (setq align t)
14982 (and (looking-at " *|") (goto-char (match-end 0))))
14983 (if (looking-at
14984 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14985 (replace-match ""))
14986 (if negative (insert " -"))
14987 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14988 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14989 (insert " " (format fh h m))))
14990 (if align (org-table-align))
14991 (message "Time difference inserted")))))
14993 (defun org-make-tdiff-string (y d h m)
14994 (let ((fmt "")
14995 (l nil))
14996 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14997 l (push y l)))
14998 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14999 l (push d l)))
15000 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
15001 l (push h l)))
15002 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
15003 l (push m l)))
15004 (apply 'format fmt (nreverse l))))
15006 (defun org-time-string-to-time (s)
15007 (apply 'encode-time (org-parse-time-string s)))
15009 (defun org-time-string-to-absolute (s &optional daynr)
15010 "Convert a time stamp to an absolute day number.
15011 If there is a specifyer for a cyclic time stamp, get the closest date to
15012 DATE."
15013 (cond
15014 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
15015 (if (org-diary-sexp-entry (match-string 1 s) "" date)
15016 daynr
15017 (+ daynr 1000)))
15018 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
15019 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
15020 (time-to-days (current-time))) (match-string 0 s)))
15021 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
15023 (defun org-calendar-holiday ()
15024 "List of holidays, for Diary display in Org-mode."
15025 (let ((hl (check-calendar-holidays date)))
15026 (if hl (mapconcat 'identity hl "; "))))
15028 (defun org-diary-sexp-entry (sexp entry date)
15029 "Process a SEXP diary ENTRY for DATE."
15030 (let ((result (if calendar-debug-sexp
15031 (let ((stack-trace-on-error t))
15032 (eval (car (read-from-string sexp))))
15033 (condition-case nil
15034 (eval (car (read-from-string sexp)))
15035 (error
15036 (beep)
15037 (message "Bad sexp at line %d in %s: %s"
15038 (org-current-line)
15039 (buffer-file-name) sexp)
15040 (sleep-for 2))))))
15041 (cond ((stringp result) result)
15042 ((and (consp result)
15043 (stringp (cdr result))) (cdr result))
15044 (result entry)
15045 (t nil))))
15047 (defun org-diary-to-ical-string (frombuf)
15048 "FIXME"
15049 (let* ((tmpdir (if (featurep 'xemacs)
15050 (temp-directory)
15051 temporary-file-directory))
15052 (tmpfile (make-temp-name
15053 (expand-file-name "orgics" tmpdir)))
15054 buf rtn b e)
15055 (save-excursion
15056 (set-buffer frombuf)
15057 (icalendar-export-region (point-min) (point-max) tmpfile)
15058 (setq buf (find-buffer-visiting tmpfile))
15059 (set-buffer buf)
15060 (goto-char (point-min))
15061 (if (re-search-forward "^BEGIN:VEVENT" nil t)
15062 (setq b (match-beginning 0)))
15063 (goto-char (point-max))
15064 (if (re-search-backward "^END:VEVENT" nil t)
15065 (setq e (match-end 0)))
15066 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
15067 (kill-buffer buf)
15068 (kill-buffer frombuf)
15069 (delete-file tmpfile)
15070 rtn))
15072 (defun org-closest-date (start current change)
15073 "Find the date closest to CURRENT that is consistent with START and CHANGE."
15074 ;; Make the proper lists from the dates
15075 (catch 'exit
15076 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
15077 dn dw sday cday n1 n2
15078 d m y y1 y2 date1 date2 nmonths nm ny m2)
15080 (setq start (org-date-to-gregorian start)
15081 current (org-date-to-gregorian current)
15082 sday (calendar-absolute-from-gregorian start)
15083 cday (calendar-absolute-from-gregorian current))
15085 (if (<= cday sday) (throw 'exit sday))
15087 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
15088 (setq dn (string-to-number (match-string 1 change))
15089 dw (cdr (assoc (match-string 2 change) a1)))
15090 (error "Invalid change specifyer: %s" change))
15091 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
15092 (cond
15093 ((eq dw 'day)
15094 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
15095 n2 (+ n1 dn)))
15096 ((eq dw 'year)
15097 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
15098 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
15099 (setq date1 (list m d y1)
15100 n1 (calendar-absolute-from-gregorian date1)
15101 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
15102 n2 (calendar-absolute-from-gregorian date2)))
15103 ((eq dw 'month)
15104 ;; approx number of month between the tow dates
15105 (setq nmonths (floor (/ (- cday sday) 30.436875)))
15106 ;; How often does dn fit in there?
15107 (setq d (nth 1 start) m (car start) y (nth 2 start)
15108 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
15109 m (+ m nm)
15110 ny (floor (/ m 12))
15111 y (+ y ny)
15112 m (- m (* ny 12)))
15113 (while (> m 12) (setq m (- m 12) y (1+ y)))
15114 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
15115 (setq m2 (+ m dn) y2 y)
15116 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15117 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
15118 (while (< n2 cday)
15119 (setq n1 n2 m m2 y y2)
15120 (setq m2 (+ m dn) y2 y)
15121 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
15122 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
15124 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1))))
15126 (defun org-date-to-gregorian (date)
15127 "Turn any specification of DATE into a gregorian date for the calendar."
15128 (cond ((integerp date) (calendar-gregorian-from-absolute date))
15129 ((and (listp date) (= (length date) 3)) date)
15130 ((stringp date)
15131 (setq date (org-parse-time-string date))
15132 (list (nth 4 date) (nth 3 date) (nth 5 date)))
15133 ((listp date)
15134 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
15136 (defun org-parse-time-string (s &optional nodefault)
15137 "Parse the standard Org-mode time string.
15138 This should be a lot faster than the normal `parse-time-string'.
15139 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
15140 hour and minute fields will be nil if not given."
15141 (if (string-match org-ts-regexp0 s)
15142 (list 0
15143 (if (or (match-beginning 8) (not nodefault))
15144 (string-to-number (or (match-string 8 s) "0")))
15145 (if (or (match-beginning 7) (not nodefault))
15146 (string-to-number (or (match-string 7 s) "0")))
15147 (string-to-number (match-string 4 s))
15148 (string-to-number (match-string 3 s))
15149 (string-to-number (match-string 2 s))
15150 nil nil nil)
15151 (make-list 9 0)))
15153 (defun org-timestamp-up (&optional arg)
15154 "Increase the date item at the cursor by one.
15155 If the cursor is on the year, change the year. If it is on the month or
15156 the day, change that.
15157 With prefix ARG, change by that many units."
15158 (interactive "p")
15159 (org-timestamp-change (prefix-numeric-value arg)))
15161 (defun org-timestamp-down (&optional arg)
15162 "Decrease the date item at the cursor by one.
15163 If the cursor is on the year, change the year. If it is on the month or
15164 the day, change that.
15165 With prefix ARG, change by that many units."
15166 (interactive "p")
15167 (org-timestamp-change (- (prefix-numeric-value arg))))
15169 (defun org-timestamp-up-day (&optional arg)
15170 "Increase the date in the time stamp by one day.
15171 With prefix ARG, change that many days."
15172 (interactive "p")
15173 (if (and (not (org-at-timestamp-p t))
15174 (org-on-heading-p))
15175 (org-todo 'up)
15176 (org-timestamp-change (prefix-numeric-value arg) 'day)))
15178 (defun org-timestamp-down-day (&optional arg)
15179 "Decrease the date in the time stamp by one day.
15180 With prefix ARG, change that many days."
15181 (interactive "p")
15182 (if (and (not (org-at-timestamp-p t))
15183 (org-on-heading-p))
15184 (org-todo 'down)
15185 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
15187 (defsubst org-pos-in-match-range (pos n)
15188 (and (match-beginning n)
15189 (<= (match-beginning n) pos)
15190 (>= (match-end n) pos)))
15192 (defun org-at-timestamp-p (&optional inactive-ok)
15193 "Determine if the cursor is in or at a timestamp."
15194 (interactive)
15195 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
15196 (pos (point))
15197 (ans (or (looking-at tsr)
15198 (save-excursion
15199 (skip-chars-backward "^[<\n\r\t")
15200 (if (> (point) 1) (backward-char 1))
15201 (and (looking-at tsr)
15202 (> (- (match-end 0) pos) -1))))))
15203 (and (boundp 'org-ts-what)
15204 (setq org-ts-what
15205 (cond
15206 ((org-pos-in-match-range pos 2) 'year)
15207 ((org-pos-in-match-range pos 3) 'month)
15208 ((org-pos-in-match-range pos 7) 'hour)
15209 ((org-pos-in-match-range pos 8) 'minute)
15210 ((or (org-pos-in-match-range pos 4)
15211 (org-pos-in-match-range pos 5)) 'day)
15212 ((and (> pos (or (match-end 8) (match-end 5)))
15213 (< pos (match-end 0)))
15214 (- pos (or (match-end 8) (match-end 5))))
15215 (t 'day))))
15216 ans))
15218 (defun org-timestamp-change (n &optional what)
15219 "Change the date in the time stamp at point.
15220 The date will be changed by N times WHAT. WHAT can be `day', `month',
15221 `year', `minute', `second'. If WHAT is not given, the cursor position
15222 in the timestamp determines what will be changed."
15223 (let ((pos (point))
15224 with-hm inactive
15225 org-ts-what
15226 extra
15227 ts time time0)
15228 (if (not (org-at-timestamp-p t))
15229 (error "Not at a timestamp"))
15230 (if (and (not what) (not (eq org-ts-what 'day))
15231 org-display-custom-times
15232 (get-text-property (point) 'display)
15233 (not (get-text-property (1- (point)) 'display)))
15234 (setq org-ts-what 'day))
15235 (setq org-ts-what (or what org-ts-what)
15236 inactive (= (char-after (match-beginning 0)) ?\[)
15237 ts (match-string 0))
15238 (replace-match "")
15239 (if (string-match
15240 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( \\+[0-9]+[dwmy]\\)?\\)[]>]"
15242 (setq extra (match-string 1 ts)))
15243 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
15244 (setq with-hm t))
15245 (setq time0 (org-parse-time-string ts))
15246 (setq time
15247 (apply 'encode-time
15248 (append
15249 (list (or (car time0) 0))
15250 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
15251 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
15252 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
15253 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
15254 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
15255 (nthcdr 6 time0))))
15256 (when (integerp org-ts-what)
15257 (setq extra (org-modify-ts-extra extra org-ts-what n)))
15258 (if (eq what 'calendar)
15259 (let ((cal-date
15260 (save-excursion
15261 (save-match-data
15262 (set-buffer "*Calendar*")
15263 (calendar-cursor-to-date)))))
15264 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
15265 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
15266 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
15267 (setcar time0 (or (car time0) 0))
15268 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
15269 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
15270 (setq time (apply 'encode-time time0))))
15271 (setq org-last-changed-timestamp
15272 (org-insert-time-stamp time with-hm inactive nil nil extra))
15273 (org-clock-update-time-maybe)
15274 (goto-char pos)
15275 ;; Try to recenter the calendar window, if any
15276 (if (and org-calendar-follow-timestamp-change
15277 (get-buffer-window "*Calendar*" t)
15278 (memq org-ts-what '(day month year)))
15279 (org-recenter-calendar (time-to-days time)))))
15281 (defun org-modify-ts-extra (s pos n)
15282 "FIXME"
15283 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
15284 ng h m new)
15285 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
15286 (cond
15287 ((or (org-pos-in-match-range pos 2)
15288 (org-pos-in-match-range pos 3))
15289 (setq m (string-to-number (match-string 3 s))
15290 h (string-to-number (match-string 2 s)))
15291 (if (org-pos-in-match-range pos 2)
15292 (setq h (+ h n))
15293 (setq m (+ m n)))
15294 (if (< m 0) (setq m (+ m 60) h (1- h)))
15295 (if (> m 59) (setq m (- m 60) h (1+ h)))
15296 (setq h (min 24 (max 0 h)))
15297 (setq ng 1 new (format "-%02d:%02d" h m)))
15298 ((org-pos-in-match-range pos 6)
15299 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
15300 ((org-pos-in-match-range pos 5)
15301 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
15303 (when ng
15304 (setq s (concat
15305 (substring s 0 (match-beginning ng))
15307 (substring s (match-end ng))))))
15310 (defun org-recenter-calendar (date)
15311 "If the calendar is visible, recenter it to DATE."
15312 (let* ((win (selected-window))
15313 (cwin (get-buffer-window "*Calendar*" t))
15314 (calendar-move-hook nil))
15315 (when cwin
15316 (select-window cwin)
15317 (calendar-goto-date (if (listp date) date
15318 (calendar-gregorian-from-absolute date)))
15319 (select-window win))))
15321 (defun org-goto-calendar (&optional arg)
15322 "Go to the Emacs calendar at the current date.
15323 If there is a time stamp in the current line, go to that date.
15324 A prefix ARG can be used to force the current date."
15325 (interactive "P")
15326 (let ((tsr org-ts-regexp) diff
15327 (calendar-move-hook nil)
15328 (view-calendar-holidays-initially nil)
15329 (view-diary-entries-initially nil))
15330 (if (or (org-at-timestamp-p)
15331 (save-excursion
15332 (beginning-of-line 1)
15333 (looking-at (concat ".*" tsr))))
15334 (let ((d1 (time-to-days (current-time)))
15335 (d2 (time-to-days
15336 (org-time-string-to-time (match-string 1)))))
15337 (setq diff (- d2 d1))))
15338 (calendar)
15339 (calendar-goto-today)
15340 (if (and diff (not arg)) (calendar-forward-day diff))))
15342 (defun org-date-from-calendar ()
15343 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
15344 If there is already a time stamp at the cursor position, update it."
15345 (interactive)
15346 (org-timestamp-change 0 'calendar))
15348 ;;; The clock for measuring work time.
15350 (defvar org-mode-line-string "")
15351 (put 'org-mode-line-string 'risky-local-variable t)
15353 (defvar org-mode-line-timer nil)
15354 (defvar org-clock-heading "")
15355 (defvar org-clock-start-time "")
15357 (defun org-update-mode-line ()
15358 (let* ((delta (- (time-to-seconds (current-time))
15359 (time-to-seconds org-clock-start-time)))
15360 (h (floor delta 3600))
15361 (m (floor (- delta (* 3600 h)) 60)))
15362 (setq org-mode-line-string
15363 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
15364 'help-echo "Org-mode clock is running"))
15365 (force-mode-line-update)))
15367 (defvar org-clock-marker (make-marker)
15368 "Marker recording the last clock-in.")
15369 (defvar org-clock-mode-line-entry nil
15370 "Information for the modeline about the running clock.")
15372 (defun org-clock-in ()
15373 "Start the clock on the current item.
15374 If necessary, clock-out of the currently active clock."
15375 (interactive)
15376 (org-clock-out t)
15377 (let (ts)
15378 (save-excursion
15379 (org-back-to-heading t)
15380 (if (looking-at org-todo-line-regexp)
15381 (setq org-clock-heading (match-string 3))
15382 (setq org-clock-heading "???"))
15383 (setq org-clock-heading (propertize org-clock-heading 'face nil))
15384 (beginning-of-line 2)
15385 (when (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15386 (not (equal (match-string 1) org-clock-string)))
15387 ;; First line hast scheduling info, move one further
15388 (beginning-of-line 2)
15389 (or (bolp) (newline)))
15390 (insert "\n") (backward-char 1)
15391 (indent-relative)
15392 (insert org-clock-string " ")
15393 (setq org-clock-start-time (current-time))
15394 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15395 (move-marker org-clock-marker (point) (buffer-base-buffer))
15396 (or global-mode-string (setq global-mode-string '("")))
15397 (or (memq 'org-mode-line-string global-mode-string)
15398 (setq global-mode-string
15399 (append global-mode-string '(org-mode-line-string))))
15400 (org-update-mode-line)
15401 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
15402 (message "Clock started at %s" ts))))
15404 (defun org-clock-out (&optional fail-quietly)
15405 "Stop the currently running clock.
15406 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
15407 (interactive)
15408 (catch 'exit
15409 (if (not (marker-buffer org-clock-marker))
15410 (if fail-quietly (throw 'exit t) (error "No active clock")))
15411 (let (ts te s h m)
15412 (save-excursion
15413 (set-buffer (marker-buffer org-clock-marker))
15414 (goto-char org-clock-marker)
15415 (beginning-of-line 1)
15416 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
15417 (equal (match-string 1) org-clock-string))
15418 (setq ts (match-string 2))
15419 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
15420 (goto-char (match-end 0))
15421 (delete-region (point) (point-at-eol))
15422 (insert "--")
15423 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
15424 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
15425 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
15426 h (floor (/ s 3600))
15427 s (- s (* 3600 h))
15428 m (floor (/ s 60))
15429 s (- s (* 60 s)))
15430 (insert " => " (format "%2d:%02d" h m))
15431 (move-marker org-clock-marker nil)
15432 (org-add-log-maybe 'clock-out)
15433 (when org-mode-line-timer
15434 (cancel-timer org-mode-line-timer)
15435 (setq org-mode-line-timer nil))
15436 (setq global-mode-string
15437 (delq 'org-mode-line-string global-mode-string))
15438 (force-mode-line-update)
15439 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
15441 (defun org-clock-cancel ()
15442 "Cancel the running clock be removing the start timestamp."
15443 (interactive)
15444 (if (not (marker-buffer org-clock-marker))
15445 (error "No active clock"))
15446 (save-excursion
15447 (set-buffer (marker-buffer org-clock-marker))
15448 (goto-char org-clock-marker)
15449 (delete-region (1- (point-at-bol)) (point-at-eol)))
15450 (message "Clock canceled"))
15452 (defvar org-clock-file-total-minutes nil
15453 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
15454 (make-variable-buffer-local 'org-clock-file-total-minutes)
15456 (defun org-clock-sum (&optional tstart tend)
15457 "Sum the times for each subtree.
15458 Puts the resulting times in minutes as a text property on each headline."
15459 (interactive)
15460 (let* ((bmp (buffer-modified-p))
15461 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
15462 org-clock-string
15463 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
15464 (lmax 30)
15465 (ltimes (make-vector lmax 0))
15466 (t1 0)
15467 (level 0)
15468 ts te dt
15469 time)
15470 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
15471 (save-excursion
15472 (goto-char (point-max))
15473 (while (re-search-backward re nil t)
15474 (cond
15475 ((match-end 2)
15476 ;; Two time stamps
15477 (setq ts (match-string 2)
15478 te (match-string 3)
15479 ts (time-to-seconds
15480 (apply 'encode-time (org-parse-time-string ts)))
15481 te (time-to-seconds
15482 (apply 'encode-time (org-parse-time-string te)))
15483 ts (if tstart (max ts tstart) ts)
15484 te (if tend (min te tend) te)
15485 dt (- te ts)
15486 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
15487 ((match-end 4)
15488 ;; A naket time
15489 (setq t1 (+ t1 (string-to-number (match-string 5))
15490 (* 60 (string-to-number (match-string 4))))))
15491 (t ;; A headline
15492 (setq level (- (match-end 1) (match-beginning 1)))
15493 (when (or (> t1 0) (> (aref ltimes level) 0))
15494 (loop for l from 0 to level do
15495 (aset ltimes l (+ (aref ltimes l) t1)))
15496 (setq t1 0 time (aref ltimes level))
15497 (loop for l from level to (1- lmax) do
15498 (aset ltimes l 0))
15499 (goto-char (match-beginning 0))
15500 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
15501 (setq org-clock-file-total-minutes (aref ltimes 0)))
15502 (set-buffer-modified-p bmp)))
15504 (defun org-clock-display (&optional total-only)
15505 "Show subtree times in the entire buffer.
15506 If TOTAL-ONLY is non-nil, only show the total time for the entire file
15507 in the echo area."
15508 (interactive)
15509 (org-remove-clock-overlays)
15510 (let (time h m p)
15511 (org-clock-sum)
15512 (unless total-only
15513 (save-excursion
15514 (goto-char (point-min))
15515 (while (setq p (next-single-property-change (point) :org-clock-minutes))
15516 (goto-char p)
15517 (when (setq time (get-text-property p :org-clock-minutes))
15518 (org-put-clock-overlay time (funcall outline-level))))
15519 (setq h (/ org-clock-file-total-minutes 60)
15520 m (- org-clock-file-total-minutes (* 60 h)))
15521 ;; Arrange to remove the overlays upon next change.
15522 (when org-remove-highlights-with-change
15523 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
15524 nil 'local))))
15525 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
15527 (defvar org-clock-overlays nil)
15528 (make-variable-buffer-local 'org-clock-overlays)
15530 (defun org-put-clock-overlay (time &optional level)
15531 "Put an overlays on the current line, displaying TIME.
15532 If LEVEL is given, prefix time with a corresponding number of stars.
15533 This creates a new overlay and stores it in `org-clock-overlays', so that it
15534 will be easy to remove."
15535 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
15536 (l (if level (org-get-legal-level level 0) 0))
15537 (off 0)
15538 ov tx)
15539 (move-to-column c)
15540 (unless (eolp) (skip-chars-backward "^ \t"))
15541 (skip-chars-backward " \t")
15542 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
15543 tx (concat (buffer-substring (1- (point)) (point))
15544 (make-string (+ off (max 0 (- c (current-column)))) ?.)
15545 (org-add-props (format "%s %2d:%02d%s"
15546 (make-string l ?*) h m
15547 (make-string (- 10 l) ?\ ))
15548 '(face secondary-selection))
15549 ""))
15550 (if (not (featurep 'xemacs))
15551 (org-overlay-put ov 'display tx)
15552 (org-overlay-put ov 'invisible t)
15553 (org-overlay-put ov 'end-glyph (make-glyph tx)))
15554 (push ov org-clock-overlays)))
15556 (defun org-remove-clock-overlays (&optional beg end noremove)
15557 "Remove the occur highlights from the buffer.
15558 BEG and END are ignored. If NOREMOVE is nil, remove this function
15559 from the `before-change-functions' in the current buffer."
15560 (interactive)
15561 (unless org-inhibit-highlight-removal
15562 (mapc 'org-delete-overlay org-clock-overlays)
15563 (setq org-clock-overlays nil)
15564 (unless noremove
15565 (remove-hook 'before-change-functions
15566 'org-remove-clock-overlays 'local))))
15568 (defun org-clock-out-if-current ()
15569 "Clock out if the current entry contains the running clock.
15570 This is used to stop the clock after a TODO entry is marked DONE."
15571 (when (and (member state org-done-keywords)
15572 (equal (marker-buffer org-clock-marker) (current-buffer))
15573 (< (point) org-clock-marker)
15574 (> (save-excursion (outline-next-heading) (point))
15575 org-clock-marker))
15576 ;; Clock out, but don't accept a logging message for this.
15577 (let ((org-log-done (if (and (listp org-log-done)
15578 (member 'clock-out org-log-done))
15579 '(done)
15580 org-log-done)))
15581 (org-clock-out))))
15583 (add-hook 'org-after-todo-state-change-hook
15584 'org-clock-out-if-current)
15586 (defun org-check-running-clock ()
15587 "Check if the current buffer contains the running clock.
15588 If yes, offer to stop it and to save the buffer with the changes."
15589 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
15590 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
15591 (buffer-name))))
15592 (org-clock-out)
15593 (when (y-or-n-p "Save changed buffer?")
15594 (save-buffer))))
15596 (defun org-clock-report ()
15597 "Create a table containing a report about clocked time.
15598 If the buffer contains lines
15599 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
15601 #+END: clocktable
15602 then the table will be inserted between these lines, replacing whatever
15603 is was there before. If these lines are not in the buffer, the table
15604 is inserted at point, surrounded by the special lines.
15605 The BEGIN line can contain parameters. Allowed are:
15606 :maxlevel The maximum level to be included in the table. Default is 3.
15607 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
15608 (interactive)
15609 (org-remove-clock-overlays)
15610 (unless (org-find-dblock "clocktable")
15611 (org-create-dblock (list :name "clocktable"
15612 :maxlevel 2 :emphasize nil)))
15613 (org-update-dblock))
15615 (defun org-clock-update-time-maybe ()
15616 "If this is a CLOCK line, update it and return t.
15617 Otherwise, return nil."
15618 (interactive)
15619 (save-excursion
15620 (beginning-of-line 1)
15621 (skip-chars-forward " \t")
15622 (when (looking-at org-clock-string)
15623 (let ((re (concat "[ \t]*" org-clock-string
15624 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
15625 "\\([ \t]*=>.*\\)?"))
15626 ts te h m s)
15627 (if (not (looking-at re))
15629 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
15630 (end-of-line 1)
15631 (setq ts (match-string 1)
15632 te (match-string 2))
15633 (setq s (- (time-to-seconds
15634 (apply 'encode-time (org-parse-time-string te)))
15635 (time-to-seconds
15636 (apply 'encode-time (org-parse-time-string ts))))
15637 h (floor (/ s 3600))
15638 s (- s (* 3600 h))
15639 m (floor (/ s 60))
15640 s (- s (* 60 s)))
15641 (insert " => " (format "%2d:%02d" h m))
15642 t)))))
15644 (defun org-clock-special-range (key &optional time as-strings)
15645 "Return two times bordering a special time range.
15646 Key is a symbol specifying the range and can be one of `today', `yesterday',
15647 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
15648 A week starts Monday 0:00 and ends Sunday 24:00.
15649 The range is determined relative to TIME. TIME defaults to the current time.
15650 The return value is a cons cell with two internal times like the ones
15651 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
15652 the returned times will be formatted strings."
15653 (let* ((tm (decode-time (or time (current-time))))
15654 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
15655 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
15656 (dow (nth 6 tm))
15657 s1 m1 h1 d1 month1 y1 diff ts te fm)
15658 (cond
15659 ((eq key 'today)
15660 (setq h 0 m 0 h1 24 m1 0))
15661 ((eq key 'yesterday)
15662 (setq d (1- d) h 0 m 0 h1 24 m1 0))
15663 ((eq key 'thisweek)
15664 (setq diff (if (= dow 0) 6 (1- dow))
15665 m 0 h 0 d (- d diff) d1 (+ 7 d)))
15666 ((eq key 'lastweek)
15667 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
15668 m 0 h 0 d (- d diff) d1 (+ 7 d)))
15669 ((eq key 'thismonth)
15670 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
15671 ((eq key 'lastmonth)
15672 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
15673 ((eq key 'thisyear)
15674 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
15675 ((eq key 'lastyear)
15676 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
15677 (t (error "No such time block %s" key)))
15678 (setq ts (encode-time s m h d month y)
15679 te (encode-time (or s1 s) (or m1 m) (or h1 h)
15680 (or d1 d) (or month1 month) (or y1 y)))
15681 (setq fm (cdr org-time-stamp-formats))
15682 (if as-strings
15683 (cons (format-time-string fm ts) (format-time-string fm te))
15684 (cons ts te))))
15686 (defun org-dblock-write:clocktable (params)
15687 "Write the standard clocktable."
15688 (let ((hlchars '((1 . "*") (2 . ?/)))
15689 (emph nil)
15690 (ins (make-marker))
15691 ipos time h m p level hlc hdl maxlevel
15692 ts te cc block)
15693 (setq maxlevel (or (plist-get params :maxlevel) 3)
15694 emph (plist-get params :emphasize)
15695 ts (plist-get params :tstart)
15696 te (plist-get params :tend)
15697 block (plist-get params :block))
15698 (when block
15699 (setq cc (org-clock-special-range block nil t)
15700 ts (car cc) te (cdr cc)))
15701 (if ts (setq ts (time-to-seconds
15702 (apply 'encode-time (org-parse-time-string ts)))))
15703 (if te (setq te (time-to-seconds
15704 (apply 'encode-time (org-parse-time-string te)))))
15705 (move-marker ins (point))
15706 (setq ipos (point))
15707 (insert-before-markers "Clock summary at ["
15708 (substring
15709 (format-time-string (cdr org-time-stamp-formats))
15710 1 -1)
15711 "]."
15712 (if block
15713 (format " Considered range is /%s/." block)
15715 "\n\n|L|Headline|Time|\n")
15716 (org-clock-sum ts te)
15717 (setq h (/ org-clock-file-total-minutes 60)
15718 m (- org-clock-file-total-minutes (* 60 h)))
15719 (insert-before-markers "|-\n|0|" "*Total file time*| "
15720 (format "*%d:%02d*" h m)
15721 "|\n")
15722 (goto-char (point-min))
15723 (while (setq p (next-single-property-change (point) :org-clock-minutes))
15724 (goto-char p)
15725 (when (setq time (get-text-property p :org-clock-minutes))
15726 (save-excursion
15727 (beginning-of-line 1)
15728 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
15729 (setq level (- (match-end 1) (match-beginning 1)))
15730 (<= level maxlevel))
15731 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
15732 hdl (match-string 2)
15733 h (/ time 60)
15734 m (- time (* 60 h)))
15735 (goto-char ins)
15736 (if (= level 1) (insert-before-markers "|-\n"))
15737 (insert-before-markers
15738 "| " (int-to-string level) "|" hlc hdl hlc " |"
15739 (make-string (1- level) ?|)
15741 (format "%d:%02d" h m)
15743 " |\n")))))
15744 (goto-char ins)
15745 (backward-delete-char 1)
15746 (goto-char ipos)
15747 (skip-chars-forward "^|")
15748 (org-table-align)))
15750 ;; FIXME: I don't think anybody uses this, ask David
15751 (defun org-collect-clock-time-entries ()
15752 "Return an internal list with clocking information.
15753 This list has one entry for each CLOCK interval.
15754 FIXME: describe the elements."
15755 (interactive)
15756 (let ((re (concat "^[ \t]*" org-clock-string
15757 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
15758 rtn beg end next cont level title total closedp leafp
15759 clockpos titlepos h m donep)
15760 (save-excursion
15761 (org-clock-sum)
15762 (goto-char (point-min))
15763 (while (re-search-forward re nil t)
15764 (setq clockpos (match-beginning 0)
15765 beg (match-string 1) end (match-string 2)
15766 cont (match-end 0))
15767 (setq beg (apply 'encode-time (org-parse-time-string beg))
15768 end (apply 'encode-time (org-parse-time-string end)))
15769 (org-back-to-heading t)
15770 (setq donep (org-entry-is-done-p))
15771 (setq titlepos (point)
15772 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
15773 h (/ total 60) m (- total (* 60 h))
15774 total (cons h m))
15775 (looking-at "\\(\\*+\\) +\\(.*\\)")
15776 (setq level (- (match-end 1) (match-beginning 1))
15777 title (org-match-string-no-properties 2))
15778 (save-excursion (outline-next-heading) (setq next (point)))
15779 (setq closedp (re-search-forward org-closed-time-regexp next t))
15780 (goto-char next)
15781 (setq leafp (and (looking-at "^\\*+ ")
15782 (<= (- (match-end 0) (point)) level)))
15783 (push (list beg end clockpos closedp donep
15784 total title titlepos level leafp)
15785 rtn)
15786 (goto-char cont)))
15787 (nreverse rtn)))
15789 ;;;; Agenda, and Diary Integration
15791 ;;; Define the Org-agenda-mode
15793 (defvar org-agenda-mode-map (make-sparse-keymap)
15794 "Keymap for `org-agenda-mode'.")
15796 (defvar org-agenda-menu) ; defined later in this file.
15797 (defvar org-agenda-follow-mode nil)
15798 (defvar org-agenda-show-log nil)
15799 (defvar org-agenda-redo-command nil)
15800 (defvar org-agenda-mode-hook nil)
15801 (defvar org-agenda-type nil)
15802 (defvar org-agenda-force-single-file nil)
15804 (defun org-agenda-mode ()
15805 "Mode for time-sorted view on action items in Org-mode files.
15807 The following commands are available:
15809 \\{org-agenda-mode-map}"
15810 (interactive)
15811 (kill-all-local-variables)
15812 (setq org-agenda-undo-list nil
15813 org-agenda-pending-undo-list nil)
15814 (setq major-mode 'org-agenda-mode)
15815 ;; Keep global-font-lock-mode from turning on font-lock-mode
15816 (org-set-local 'font-lock-global-modes (list 'not major-mode))
15817 (setq mode-name "Org-Agenda")
15818 (use-local-map org-agenda-mode-map)
15819 (easy-menu-add org-agenda-menu)
15820 (if org-startup-truncated (setq truncate-lines t))
15821 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
15822 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
15823 ;; Make sure properties are removed when copying text
15824 (when (boundp 'buffer-substring-filters)
15825 (org-set-local 'buffer-substring-filters
15826 (cons (lambda (x)
15827 (set-text-properties 0 (length x) nil x) x)
15828 buffer-substring-filters)))
15829 (unless org-agenda-keep-modes
15830 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
15831 org-agenda-show-log nil))
15832 (easy-menu-change
15833 '("Agenda") "Agenda Files"
15834 (append
15835 (list
15836 (vector
15837 (if (get 'org-agenda-files 'org-restrict)
15838 "Restricted to single file"
15839 "Edit File List")
15840 '(org-edit-agenda-file-list)
15841 (not (get 'org-agenda-files 'org-restrict)))
15842 "--")
15843 (mapcar 'org-file-menu-entry (org-agenda-files))))
15844 (org-agenda-set-mode-name)
15845 (apply
15846 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
15847 (list 'org-agenda-mode-hook)))
15849 (substitute-key-definition 'undo 'org-agenda-undo
15850 org-agenda-mode-map global-map)
15851 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
15852 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
15853 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
15854 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
15855 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
15856 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
15857 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
15858 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
15859 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
15860 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
15861 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
15862 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
15863 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
15864 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
15865 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
15866 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
15867 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
15868 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
15869 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
15870 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
15871 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
15872 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
15873 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
15874 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
15875 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
15876 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
15877 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
15878 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
15880 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
15881 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
15882 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
15883 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
15884 (while l (org-defkey org-agenda-mode-map
15885 (int-to-string (pop l)) 'digit-argument)))
15887 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
15888 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
15889 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
15890 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
15891 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
15892 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
15893 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
15894 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
15895 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
15896 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
15897 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
15898 (org-defkey org-agenda-mode-map "n" 'next-line)
15899 (org-defkey org-agenda-mode-map "p" 'previous-line)
15900 (org-defkey org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
15901 (org-defkey org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
15902 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
15903 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
15904 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
15905 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
15906 (eval-after-load "calendar"
15907 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
15908 'org-calendar-goto-agenda))
15909 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
15910 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
15911 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
15912 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
15913 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
15914 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
15915 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
15916 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
15917 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
15918 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
15919 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
15920 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
15921 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
15922 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
15923 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
15924 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
15925 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
15927 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
15928 "Local keymap for agenda entries from Org-mode.")
15930 (org-defkey org-agenda-keymap
15931 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
15932 (org-defkey org-agenda-keymap
15933 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
15934 (when org-agenda-mouse-1-follows-link
15935 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
15936 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
15937 '("Agenda"
15938 ("Agenda Files")
15939 "--"
15940 ["Show" org-agenda-show t]
15941 ["Go To (other window)" org-agenda-goto t]
15942 ["Go To (this window)" org-agenda-switch-to t]
15943 ["Follow Mode" org-agenda-follow-mode
15944 :style toggle :selected org-agenda-follow-mode :active t]
15945 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
15946 "--"
15947 ["Cycle TODO" org-agenda-todo t]
15948 ["Archive subtree" org-agenda-archive t]
15949 ["Delete subtree" org-agenda-kill t]
15950 "--"
15951 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
15952 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
15953 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
15954 "--"
15955 ("Tags and Properties"
15956 ["Show all Tags" org-agenda-show-tags t]
15957 ["Set Tags" org-agenda-set-tags t]
15958 "--"
15959 ["Column View" org-columns t])
15960 ("Date/Schedule"
15961 ["Schedule" org-agenda-schedule t]
15962 ["Set Deadline" org-agenda-deadline t]
15963 "--"
15964 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
15965 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
15966 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
15967 ("Priority"
15968 ["Set Priority" org-agenda-priority t]
15969 ["Increase Priority" org-agenda-priority-up t]
15970 ["Decrease Priority" org-agenda-priority-down t]
15971 ["Show Priority" org-agenda-show-priority t])
15972 ("Calendar/Diary"
15973 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
15974 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
15975 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
15976 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
15977 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
15978 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
15979 "--"
15980 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
15981 "--"
15982 ("View"
15983 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
15984 :style radio :selected (equal org-agenda-ndays 1)]
15985 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
15986 :style radio :selected (equal org-agenda-ndays 7)]
15987 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
15988 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
15989 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
15990 :style radio :selected (member org-agenda-ndays '(365 366))]
15991 "--"
15992 ["Show Logbook entries" org-agenda-log-mode
15993 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
15994 ["Include Diary" org-agenda-toggle-diary
15995 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
15996 ["Use Time Grid" org-agenda-toggle-time-grid
15997 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
15998 ["Write view to file" org-write-agenda t]
15999 ["Rebuild buffer" org-agenda-redo t]
16000 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
16001 "--"
16002 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
16003 "--"
16004 ["Quit" org-agenda-quit t]
16005 ["Exit and Release Buffers" org-agenda-exit t]
16008 ;;; Agenda undo
16010 (defvar org-agenda-allow-remote-undo t
16011 "Non-nil means, allow remote undo from the agenda buffer.")
16012 (defvar org-agenda-undo-list nil
16013 "List of undoable operations in the agenda since last refresh.")
16014 (defvar org-agenda-undo-has-started-in nil
16015 "Buffers that have already seen `undo-start' in the current undo sequence.")
16016 (defvar org-agenda-pending-undo-list nil
16017 "In a series of undo commands, this is the list of remaning undo items.")
16019 (defmacro org-if-unprotected (&rest body)
16020 "Execute BODY if ther is no `org-protected' text property at point."
16021 (declare (debug t))
16022 `(unless (get-text-property (point) 'org-protected)
16023 ,@body))
16025 (defmacro org-with-remote-undo (_buffer &rest _body)
16026 "Execute BODY while recording undo information in two buffers."
16027 (declare (indent 1) (debug t))
16028 `(let ((_cline (org-current-line))
16029 (_cmd this-command)
16030 (_buf1 (current-buffer))
16031 (_buf2 ,_buffer)
16032 (_undo1 buffer-undo-list)
16033 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
16034 _c1 _c2)
16035 ,@_body
16036 (when org-agenda-allow-remote-undo
16037 (setq _c1 (org-verify-change-for-undo
16038 _undo1 (with-current-buffer _buf1 buffer-undo-list))
16039 _c2 (org-verify-change-for-undo
16040 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
16041 (when (or _c1 _c2)
16042 ;; make sure there are undo boundaries
16043 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
16044 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
16045 ;; remember which buffer to undo
16046 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
16047 org-agenda-undo-list)))))
16049 (defun org-agenda-undo ()
16050 "Undo a remote editing step in the agenda.
16051 This undoes changes both in the agenda buffer and in the remote buffer
16052 that have been changed along."
16053 (interactive)
16054 (or org-agenda-allow-remote-undo
16055 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
16056 (if (not (eq this-command last-command))
16057 (setq org-agenda-undo-has-started-in nil
16058 org-agenda-pending-undo-list org-agenda-undo-list))
16059 (if (not org-agenda-pending-undo-list)
16060 (error "No further undo information"))
16061 (let* ((entry (pop org-agenda-pending-undo-list))
16062 buf line cmd rembuf)
16063 (setq cmd (pop entry) line (pop entry))
16064 (setq rembuf (nth 2 entry))
16065 (org-with-remote-undo rembuf
16066 (while (bufferp (setq buf (pop entry)))
16067 (if (pop entry)
16068 (with-current-buffer buf
16069 (let ((last-undo-buffer buf)
16070 buffer-read-only)
16071 (unless (memq buf org-agenda-undo-has-started-in)
16072 (push buf org-agenda-undo-has-started-in)
16073 (make-local-variable 'pending-undo-list)
16074 (undo-start))
16075 (while (and pending-undo-list
16076 (listp pending-undo-list)
16077 (not (car pending-undo-list)))
16078 (pop pending-undo-list))
16079 (undo-more 1))))))
16080 (goto-line line)
16081 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
16083 (defun org-verify-change-for-undo (l1 l2)
16084 "Verify that a real change occurred between the undo lists L1 and L2."
16085 (while (and l1 (listp l1) (null (car l1))) (pop l1))
16086 (while (and l2 (listp l2) (null (car l2))) (pop l2))
16087 (not (eq l1 l2)))
16089 ;;; Agenda dispatch
16091 (defvar org-agenda-restrict nil)
16092 (defvar org-agenda-restrict-begin (make-marker))
16093 (defvar org-agenda-restrict-end (make-marker))
16094 (defvar org-agenda-last-dispatch-buffer nil)
16096 ;;;###autoload
16097 (defun org-agenda (arg)
16098 "Dispatch agenda commands to collect entries to the agenda buffer.
16099 Prompts for a character to select a command. Any prefix arg will be passed
16100 on to the selected command. The default selections are:
16102 a Call `org-agenda-list' to display the agenda for current day or week.
16103 t Call `org-todo-list' to display the global todo list.
16104 T Call `org-todo-list' to display the global todo list, select only
16105 entries with a specific TODO keyword (the user gets a prompt).
16106 m Call `org-tags-view' to display headlines with tags matching
16107 a condition (the user is prompted for the condition).
16108 M Like `m', but select only TODO entries, no ordinary headlines.
16109 l Create a timeline for the current buffer.
16110 e Export views to associated files.
16112 More commands can be added by configuring the variable
16113 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
16114 searches can be pre-defined in this way.
16116 If the current buffer is in Org-mode and visiting a file, you can also
16117 first press `1' to indicate that the agenda should be temporarily (until the
16118 next use of \\[org-agenda]) restricted to the current file."
16119 (interactive "P")
16120 (catch 'exit
16121 (let* ((buf (current-buffer))
16122 (bfn (buffer-file-name (buffer-base-buffer)))
16123 (restrict-ok (and bfn (org-mode-p)))
16124 (custom org-agenda-custom-commands)
16125 c entry key type match lprops)
16126 ;; Turn off restriction
16127 (put 'org-agenda-files 'org-restrict nil)
16128 (setq org-agenda-restrict nil)
16129 (move-marker org-agenda-restrict-begin nil)
16130 (move-marker org-agenda-restrict-end nil)
16131 ;; Remember where this call originated
16132 (setq org-agenda-last-dispatch-buffer (current-buffer))
16133 (save-window-excursion
16134 (delete-other-windows)
16135 (switch-to-buffer-other-window " *Agenda Commands*")
16136 (erase-buffer)
16137 (insert (eval-when-compile
16138 (let ((header
16139 "Press key for an agenda command:
16140 -------------------------------- C Configure custom agenda commands
16141 a Agenda for current week or day e Export agenda views
16142 t List of all TODO entries T Entries with special TODO kwd
16143 m Match a TAGS query M Like m, but only TODO entries
16144 L Timeline for current buffer # List stuck projects (!=configure)
16146 (start 0))
16147 (while (string-match "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)" header start)
16148 (setq start (match-end 0))
16149 (add-text-properties (match-beginning 2) (match-end 2)
16150 '(face bold) header))
16151 header)))
16152 (while (setq entry (pop custom))
16153 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
16154 (insert (format "\n%-4s%-14s: %s"
16155 (org-add-props (copy-sequence key)
16156 '(face bold))
16157 (cond
16158 ((stringp type) type)
16159 ((eq type 'agenda) "Agenda for current week or day")
16160 ((eq type 'alltodo) "List of all TODO entries")
16161 ((eq type 'stuck) "List of stuck projects")
16162 ((eq type 'todo) "TODO keyword")
16163 ((eq type 'tags) "Tags query")
16164 ((eq type 'tags-todo) "Tags (TODO)")
16165 ((eq type 'tags-tree) "Tags tree")
16166 ((eq type 'todo-tree) "TODO kwd tree")
16167 ((eq type 'occur-tree) "Occur tree")
16168 ((functionp type) (symbol-name type))
16169 (t "???"))
16170 (if (stringp match)
16171 (org-add-props match nil 'face 'org-warning)
16172 (format "set of %d commands" (length match))))))
16173 (if restrict-ok
16174 (insert "\n"
16175 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
16176 (goto-char (point-min))
16177 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
16178 (message "Press key for agenda command%s"
16179 (if restrict-ok ", or [1] or [0] to restrict" ""))
16180 (setq c (read-char-exclusive))
16181 (message "")
16182 (when (memq c '(?L ?1 ?0))
16183 (if restrict-ok
16184 (put 'org-agenda-files 'org-restrict (list bfn))
16185 (error "Cannot restrict agenda to current buffer"))
16186 (with-current-buffer " *Agenda Commands*"
16187 (goto-char (point-max))
16188 (delete-region (point-at-bol) (point))
16189 (goto-char (point-min)))
16190 (when (eq c ?0)
16191 (setq org-agenda-restrict t)
16192 (with-current-buffer buf
16193 (if (org-region-active-p)
16194 (progn
16195 (move-marker org-agenda-restrict-begin (region-beginning))
16196 (move-marker org-agenda-restrict-end (region-end)))
16197 (save-excursion
16198 (org-back-to-heading t)
16199 (move-marker org-agenda-restrict-begin (point))
16200 (move-marker org-agenda-restrict-end
16201 (progn (org-end-of-subtree t)))))))
16202 (unless (eq c ?L)
16203 (message "Press key for agenda command%s"
16204 (if restrict-ok " (restricted to current file)" ""))
16205 (setq c (read-char-exclusive)))
16206 (message "")))
16207 (require 'calendar) ; FIXME: can we avoid this for some commands?
16208 ;; For example the todo list should not need it (but does...)
16209 (cond
16210 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
16211 (if (symbolp (nth 1 entry))
16212 (progn
16213 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
16214 lprops (nth 3 entry))
16215 (cond
16216 ((eq type 'agenda)
16217 (org-let lprops '(org-agenda-list current-prefix-arg)))
16218 ((eq type 'alltodo)
16219 (org-let lprops '(org-todo-list current-prefix-arg)))
16220 ((eq type 'stuck)
16221 (org-let lprops '(org-agenda-list-stuck-projects
16222 current-prefix-arg)))
16223 ((eq type 'tags)
16224 (org-let lprops '(org-tags-view current-prefix-arg match)))
16225 ((eq type 'tags-todo)
16226 (org-let lprops '(org-tags-view '(4) match)))
16227 ((eq type 'todo)
16228 (org-let lprops '(org-todo-list match)))
16229 ((eq type 'tags-tree)
16230 (org-check-for-org-mode)
16231 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
16232 ((eq type 'todo-tree)
16233 (org-check-for-org-mode)
16234 (org-let lprops
16235 '(org-occur (concat "^" outline-regexp "[ \t]*"
16236 (regexp-quote match) "\\>"))))
16237 ((eq type 'occur-tree)
16238 (org-check-for-org-mode)
16239 (org-let lprops '(org-occur match)))
16240 ((fboundp type)
16241 (org-let lprops '(funcall type match)))
16242 (t (error "Invalid custom agenda command type %s" type))))
16243 (org-run-agenda-series (nth 1 entry) (cddr entry))))
16244 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
16245 ((equal c ?a) (call-interactively 'org-agenda-list))
16246 ((equal c ?t) (call-interactively 'org-todo-list))
16247 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
16248 ((equal c ?m) (call-interactively 'org-tags-view))
16249 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
16250 ((equal c ?e) (call-interactively 'org-store-agenda-views))
16251 ((equal c ?L)
16252 (unless restrict-ok
16253 (error "This is not an Org-mode file"))
16254 (org-call-with-arg 'org-timeline arg))
16255 ((equal c ?#) (call-interactively 'org-agenda-list-stuck-projects))
16256 ((equal c ?!) (customize-variable 'org-stuck-projects))
16257 (t (error "Invalid key"))))))
16259 (defun org-run-agenda-series (name series)
16260 (org-prepare-agenda name)
16261 (let* ((org-agenda-multi t)
16262 (redo (list 'org-run-agenda-series name (list 'quote series)))
16263 (cmds (car series))
16264 (gprops (nth 1 series))
16265 match ;; The byte compiler incorrectly complains about this. Keep it!
16266 cmd type lprops)
16267 (while (setq cmd (pop cmds))
16268 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
16269 (cond
16270 ((eq type 'agenda)
16271 (org-let2 gprops lprops
16272 '(call-interactively 'org-agenda-list)))
16273 ((eq type 'alltodo)
16274 (org-let2 gprops lprops
16275 '(call-interactively 'org-todo-list)))
16276 ((eq type 'stuck)
16277 (org-let2 gprops lprops
16278 '(call-interactively 'org-agenda-list-stuck-projects)))
16279 ((eq type 'tags)
16280 (org-let2 gprops lprops
16281 '(org-tags-view current-prefix-arg match)))
16282 ((eq type 'tags-todo)
16283 (org-let2 gprops lprops
16284 '(org-tags-view '(4) match)))
16285 ((eq type 'todo)
16286 (org-let2 gprops lprops
16287 '(org-todo-list match)))
16288 ((fboundp type)
16289 (org-let2 gprops lprops
16290 '(funcall type match)))
16291 (t (error "Invalid type in command series"))))
16292 (widen)
16293 (setq org-agenda-redo-command redo)
16294 (goto-char (point-min)))
16295 (org-finalize-agenda))
16297 ;;;###autoload
16298 (defmacro org-batch-agenda (cmd-key &rest parameters)
16299 "Run an agenda command in batch mode and send the result to STDOUT.
16300 If CMD-KEY is a string of length 1, it is used as a key in
16301 `org-agenda-custom-commands' and triggers this command. If it is a
16302 longer string is is used as a tags/todo match string.
16303 Paramters are alternating variable names and values that will be bound
16304 before running the agenda command."
16305 (let (pars)
16306 (while parameters
16307 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16308 (if (> (length cmd-key) 1)
16309 (eval (list 'let (nreverse pars)
16310 (list 'org-tags-view nil cmd-key)))
16311 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16312 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16313 (set-buffer "*Org Agenda*")
16314 (princ (org-encode-for-stdout (buffer-string)))))
16316 (defun org-encode-for-stdout (string)
16317 (if (fboundp 'encode-coding-string)
16318 (encode-coding-string string buffer-file-coding-system)
16319 string))
16321 (defvar org-agenda-info nil)
16323 ;;;###autoload
16324 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
16325 "Run an agenda command in batch mode and send the result to STDOUT.
16326 If CMD-KEY is a string of length 1, it is used as a key in
16327 `org-agenda-custom-commands' and triggers this command. If it is a
16328 longer string is is used as a tags/todo match string.
16329 Paramters are alternating variable names and values that will be bound
16330 before running the agenda command.
16332 The output gives a line for each selected agenda item. Each
16333 item is a list of comma-separated values, like this:
16335 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
16337 category The category of the item
16338 head The headline, without TODO kwd, TAGS and PRIORITY
16339 type The type of the agenda entry, can be
16340 todo selected in TODO match
16341 tagsmatch selected in tags match
16342 diary imported from diary
16343 deadline a deadline on given date
16344 scheduled scheduled on given date
16345 timestamp entry has timestamp on given date
16346 closed entry was closed on given date
16347 upcoming-deadline warning about deadline
16348 past-scheduled forwarded scheduled item
16349 block entry has date block including g. date
16350 todo The todo keyword, if any
16351 tags All tags including inherited ones, separated by colons
16352 date The relevant date, like 2007-2-14
16353 time The time, like 15:00-16:50
16354 extra Sting with extra planning info
16355 priority-l The priority letter if any was given
16356 priority-n The computed numerical priority
16357 agenda-day The day in the agenda where this is listed"
16359 (let (pars)
16360 (while parameters
16361 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16362 (push (list 'org-agenda-remove-tags t) pars)
16363 (if (> (length cmd-key) 1)
16364 (eval (list 'let (nreverse pars)
16365 (list 'org-tags-view nil cmd-key)))
16366 (flet ((read-char-exclusive () (string-to-char cmd-key)))
16367 (eval (list 'let (nreverse pars) '(org-agenda nil)))))
16368 (set-buffer "*Org Agenda*")
16369 (let* ((lines (org-split-string (buffer-string) "\n"))
16370 line)
16371 (while (setq line (pop lines))
16372 (catch 'next
16373 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
16374 (setq org-agenda-info
16375 (org-fix-agenda-info (text-properties-at 0 line)))
16376 (princ
16377 (org-encode-for-stdout
16378 (mapconcat 'org-agenda-export-csv-mapper
16379 '(org-category txt type todo tags date time-of-day extra
16380 priority-letter priority agenda-day)
16381 ",")))
16382 (princ "\n"))))))
16384 (defun org-fix-agenda-info (props)
16385 "FIXME"
16386 (let (tmp re)
16387 (when (setq tmp (plist-get props 'tags))
16388 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
16389 (when (setq tmp (plist-get props 'date))
16390 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16391 (let ((calendar-date-display-form '(year "-" month "-" day)))
16392 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
16394 (setq tmp (calendar-date-string tmp)))
16395 (setq props (plist-put props 'date tmp)))
16396 (when (setq tmp (plist-get props 'day))
16397 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
16398 (let ((calendar-date-display-form '(year "-" month "-" day)))
16399 (setq tmp (calendar-date-string tmp)))
16400 (setq props (plist-put props 'day tmp))
16401 (setq props (plist-put props 'agenda-day tmp)))
16402 (when (setq tmp (plist-get props 'txt))
16403 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
16404 (plist-put props 'priority-letter (match-string 1 tmp))
16405 (setq tmp (replace-match "" t t tmp)))
16406 (when (and (setq re (plist-get props 'org-todo-regexp))
16407 (setq re (concat "\\`\\.*" re " ?"))
16408 (string-match re tmp))
16409 (plist-put props 'todo (match-string 1 tmp))
16410 (setq tmp (replace-match "" t t tmp)))
16411 (plist-put props 'txt tmp)))
16412 props)
16414 (defun org-agenda-export-csv-mapper (prop)
16415 (let ((res (plist-get org-agenda-info prop)))
16416 (setq res
16417 (cond
16418 ((not res) "")
16419 ((stringp res) res)
16420 (t (prin1-to-string res))))
16421 (while (string-match "," res)
16422 (setq res (replace-match ";" t t res)))
16423 (org-trim res)))
16426 ;;;###autoload
16427 (defun org-store-agenda-views (&rest parameters)
16428 (interactive)
16429 (eval (list 'org-batch-store-agenda-views)))
16431 (defvar org-agenda-buffer-name)
16433 ;; FIXME, why is this a macro?????
16434 ;;;###autoload
16435 (defmacro org-batch-store-agenda-views (&rest parameters)
16436 "Run all custom agenda commands that have a file argument."
16437 (let ((cmds org-agenda-custom-commands)
16438 (dir (default-directory))
16439 pars cmd thiscmdkey files opts)
16440 (while parameters
16441 (push (list (pop parameters) (if parameters (pop parameters))) pars))
16442 (setq pars (reverse pars))
16443 (save-window-excursion
16444 (while cmds
16445 (setq cmd (pop cmds)
16446 thiscmdkey (car cmd)
16447 opts (nth 3 cmd)
16448 files (org-last cmd))
16449 (if (stringp files) (setq files (list files)))
16450 (when files
16451 (flet ((read-char-exclusive () (string-to-char thiscmdkey)))
16452 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16453 '(org-agenda nil))))
16454 (set-buffer "*Org Agenda*")
16455 (while files
16456 (eval (list 'let (append org-agenda-exporter-settings opts pars)
16457 (list 'org-write-agenda
16458 (expand-file-name (pop files) dir) t)))))
16459 (kill-buffer org-agenda-buffer-name)))))
16461 (defun org-write-agenda (file &optional nosettings)
16462 "Write the current buffer (an agenda view) as a file.
16463 Depending on the extension of the file name, plain text (.txt),
16464 HTML (.html or .htm) or Postscript (.ps) is produced.
16465 If NOSETTINGS is given, do not scope the settings of
16466 `org-agenda-exporter-settings' into the export commands. This is used when
16467 the settings have already been scoped and we do not wish to overrule other,
16468 higher priority settings."
16469 (interactive "FWrite agenda to file: ")
16470 (if (not (file-writable-p file))
16471 (error "Cannot write agenda to file %s" file))
16472 (cond
16473 ((string-match "\\.html?\\'" file) (require 'htmlize))
16474 ((string-match "\\.ps\\'" file) (require 'ps-print)))
16475 (org-let (if nosettings nil org-agenda-exporter-settings)
16476 '(save-excursion
16477 (save-window-excursion
16478 (cond
16479 ((string-match "\\.html?\\'" file)
16480 (set-buffer (htmlize-buffer (current-buffer)))
16482 (when (and org-agenda-export-html-style
16483 (string-match "<style>" org-agenda-export-html-style))
16484 ;; replace <style> section with org-agenda-export-html-style
16485 (goto-char (point-min))
16486 (kill-region (- (search-forward "<style") 6)
16487 (search-forward "</style>"))
16488 (insert org-agenda-export-html-style))
16489 (write-file file)
16490 (kill-buffer (current-buffer))
16491 (message "HTML written to %s" file))
16492 ((string-match "\\.ps\\'" file)
16493 (ps-print-buffer-with-faces file)
16494 (message "Postscript written to %s" file))
16496 (let ((bs (buffer-string)))
16497 (find-file file)
16498 (insert bs)
16499 (save-buffer 0)
16500 (kill-buffer (current-buffer))
16501 (message "Plain text written to %s" file))))))
16502 (set-buffer org-agenda-buffer-name)))
16504 (defmacro org-no-read-only (&rest body)
16505 "Inhibit read-only for BODY."
16506 `(let ((inhibit-read-only t)) ,@body))
16508 (defun org-check-for-org-mode ()
16509 "Make sure current buffer is in org-mode. Error if not."
16510 (or (org-mode-p)
16511 (error "Cannot execute org-mode agenda command on buffer in %s."
16512 major-mode)))
16514 (defun org-fit-agenda-window ()
16515 "Fit the window to the buffer size."
16516 (and (memq org-agenda-window-setup '(reorganize-frame))
16517 (fboundp 'fit-window-to-buffer)
16518 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
16519 (/ (frame-height) 2))))
16521 ;;; Agenda file list
16523 (defun org-agenda-files (&optional unrestricted)
16524 "Get the list of agenda files.
16525 Optional UNRESTRICTED means return the full list even if a restriction
16526 is currently in place."
16527 (cond
16528 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
16529 ((stringp org-agenda-files) (org-read-agenda-file-list))
16530 ((listp org-agenda-files) org-agenda-files)
16531 (t (error "Invalid value of `org-agenda-files'"))))
16533 (defun org-edit-agenda-file-list ()
16534 "Edit the list of agenda files.
16535 Depending on setup, this either uses customize to edit the variable
16536 `org-agenda-files', or it visits the file that is holding the list. In the
16537 latter case, the buffer is set up in a way that saving it automatically kills
16538 the buffer and restores the previous window configuration."
16539 (interactive)
16540 (if (stringp org-agenda-files)
16541 (let ((cw (current-window-configuration)))
16542 (find-file org-agenda-files)
16543 (org-set-local 'org-window-configuration cw)
16544 (org-add-hook 'after-save-hook
16545 (lambda ()
16546 (set-window-configuration
16547 (prog1 org-window-configuration
16548 (kill-buffer (current-buffer))))
16549 (org-install-agenda-files-menu)
16550 (message "New agenda file list installed"))
16551 nil 'local)
16552 (message (substitute-command-keys
16553 "Edit list and finish with \\[save-buffer]")))
16554 (customize-variable 'org-agenda-files)))
16556 (defun org-store-new-agenda-file-list (list)
16557 "Set new value for the agenda file list and save it correcly."
16558 (if (stringp org-agenda-files)
16559 (let ((f org-agenda-files) b)
16560 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
16561 (with-temp-file f
16562 (insert (mapconcat 'identity list "\n") "\n")))
16563 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
16564 (setq org-agenda-files list)
16565 (customize-save-variable 'org-agenda-files org-agenda-files))))
16567 (defun org-read-agenda-file-list ()
16568 "Read the list of agenda files from a file."
16569 (when (stringp org-agenda-files)
16570 (with-temp-buffer
16571 (insert-file-contents org-agenda-files)
16572 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
16575 ;;;###autoload
16576 (defun org-cycle-agenda-files ()
16577 "Cycle through the files in `org-agenda-files'.
16578 If the current buffer visits an agenda file, find the next one in the list.
16579 If the current buffer does not, find the first agenda file."
16580 (interactive)
16581 (let* ((fs (org-agenda-files t))
16582 (files (append fs (list (car fs))))
16583 (tcf (if buffer-file-name (file-truename buffer-file-name)))
16584 file)
16585 (unless files (error "No agenda files"))
16586 (catch 'exit
16587 (while (setq file (pop files))
16588 (if (equal (file-truename file) tcf)
16589 (when (car files)
16590 (find-file (car files))
16591 (throw 'exit t))))
16592 (find-file (car fs)))
16593 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
16595 (defun org-agenda-file-to-front (&optional to-end)
16596 "Move/add the current file to the top of the agenda file list.
16597 If the file is not present in the list, it is added to the front. If it is
16598 present, it is moved there. With optional argument TO-END, add/move to the
16599 end of the list."
16600 (interactive "P")
16601 (let ((file-alist (mapcar (lambda (x)
16602 (cons (file-truename x) x))
16603 (org-agenda-files t)))
16604 (ctf (file-truename buffer-file-name))
16605 x had)
16606 (setq x (assoc ctf file-alist) had x)
16608 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
16609 (if to-end
16610 (setq file-alist (append (delq x file-alist) (list x)))
16611 (setq file-alist (cons x (delq x file-alist))))
16612 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
16613 (org-install-agenda-files-menu)
16614 (message "File %s to %s of agenda file list"
16615 (if had "moved" "added") (if to-end "end" "front"))))
16617 (defun org-remove-file (&optional file)
16618 "Remove current file from the list of files in variable `org-agenda-files'.
16619 These are the files which are being checked for agenda entries.
16620 Optional argument FILE means, use this file instead of the current."
16621 (interactive)
16622 (let* ((file (or file buffer-file-name))
16623 (true-file (file-truename file))
16624 (afile (abbreviate-file-name file))
16625 (files (delq nil (mapcar
16626 (lambda (x)
16627 (if (equal true-file
16628 (file-truename x))
16629 nil x))
16630 (org-agenda-files t)))))
16631 (if (not (= (length files) (length (org-agenda-files t))))
16632 (progn
16633 (org-store-new-agenda-file-list files)
16634 (org-install-agenda-files-menu)
16635 (message "Removed file: %s" afile))
16636 (message "File was not in list: %s" afile))))
16638 (defun org-file-menu-entry (file)
16639 (vector file (list 'find-file file) t))
16641 (defun org-check-agenda-file (file)
16642 "Make sure FILE exists. If not, ask user what to do."
16643 (when (not (file-exists-p file))
16644 (message "non-existent file %s. [R]emove from list or [A]bort?"
16645 (abbreviate-file-name file))
16646 (let ((r (downcase (read-char-exclusive))))
16647 (cond
16648 ((equal r ?r)
16649 (org-remove-file file)
16650 (throw 'nextfile t))
16651 (t (error "Abort"))))))
16653 ;;; Agenda prepare and finalize
16655 (defvar org-agenda-multi nil) ; dynammically scoped
16656 (defvar org-agenda-buffer-name "*Org Agenda*")
16657 (defvar org-pre-agenda-window-conf nil)
16658 (defvar org-agenda-name nil)
16659 (defun org-prepare-agenda (&optional name)
16660 (setq org-todo-keywords-for-agenda nil)
16661 (setq org-done-keywords-for-agenda nil)
16662 (if org-agenda-multi
16663 (progn
16664 (setq buffer-read-only nil)
16665 (goto-char (point-max))
16666 (unless (= (point) 1)
16667 (insert "\n" (make-string (window-width) ?=) "\n"))
16668 (narrow-to-region (point) (point-max)))
16669 (org-agenda-maybe-reset-markers 'force)
16670 (org-prepare-agenda-buffers (org-agenda-files))
16671 (setq org-todo-keywords-for-agenda
16672 (org-uniquify org-todo-keywords-for-agenda))
16673 (setq org-done-keywords-for-agenda
16674 (org-uniquify org-done-keywords-for-agenda))
16675 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
16676 (awin (get-buffer-window abuf)))
16677 (cond
16678 ((equal (current-buffer) abuf) nil)
16679 (awin (select-window awin))
16680 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
16681 ((equal org-agenda-window-setup 'current-window)
16682 (switch-to-buffer abuf))
16683 ((equal org-agenda-window-setup 'other-window)
16684 (switch-to-buffer-other-window abuf))
16685 ((equal org-agenda-window-setup 'other-frame)
16686 (switch-to-buffer-other-frame abuf))
16687 ((equal org-agenda-window-setup 'reorganize-frame)
16688 (delete-other-windows)
16689 (switch-to-buffer-other-window abuf))))
16690 (setq buffer-read-only nil)
16691 (erase-buffer)
16692 (org-agenda-mode)
16693 (and name (not org-agenda-name)
16694 (org-set-local 'org-agenda-name name)))
16695 (setq buffer-read-only nil))
16697 (defun org-finalize-agenda ()
16698 "Finishing touch for the agenda buffer, called just before displaying it."
16699 (unless org-agenda-multi
16700 (save-excursion
16701 (let ((buffer-read-only))
16702 (goto-char (point-min))
16703 (while (org-activate-bracket-links (point-max))
16704 (add-text-properties (match-beginning 0) (match-end 0)
16705 '(face org-link)))
16706 (org-agenda-align-tags)
16707 (unless org-agenda-with-colors
16708 (remove-text-properties (point-min) (point-max) '(face nil))))
16709 (if (and (boundp 'org-overriding-columns-format)
16710 org-overriding-columns-format)
16711 (org-set-local 'org-overriding-columns-format
16712 org-overriding-columns-format))
16713 (if (and (boundp 'org-agenda-view-columns-initially)
16714 org-agenda-view-columns-initially)
16715 (org-agenda-columns))
16716 (run-hooks 'org-finalize-agenda-hook))))
16718 (defun org-prepare-agenda-buffers (files)
16719 "Create buffers for all agenda files, protect archived trees and comments."
16720 (interactive)
16721 (let ((pa '(:org-archived t))
16722 (pc '(:org-comment t))
16723 (pall '(:org-archived t :org-comment t))
16724 (rea (concat ":" org-archive-tag ":"))
16725 bmp file re)
16726 (save-excursion
16727 (save-restriction
16728 (while (setq file (pop files))
16729 (org-check-agenda-file file)
16730 (set-buffer (org-get-agenda-file-buffer file))
16731 (widen)
16732 (setq bmp (buffer-modified-p))
16733 (setq org-todo-keywords-for-agenda
16734 (append org-todo-keywords-for-agenda org-todo-keywords-1))
16735 (setq org-done-keywords-for-agenda
16736 (append org-done-keywords-for-agenda org-done-keywords))
16737 (save-excursion
16738 (remove-text-properties (point-min) (point-max) pall)
16739 (when org-agenda-skip-archived-trees
16740 (goto-char (point-min))
16741 (while (re-search-forward rea nil t)
16742 (if (org-on-heading-p t)
16743 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
16744 (goto-char (point-min))
16745 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
16746 (while (re-search-forward re nil t)
16747 (add-text-properties
16748 (match-beginning 0) (org-end-of-subtree t) pc)))
16749 (set-buffer-modified-p bmp))))))
16751 (defvar org-agenda-skip-function nil
16752 "Function to be called at each match during agenda construction.
16753 If this function return nil, the current match should not be skipped.
16754 Otherwise, the function must return a position from where the search
16755 should be continued.
16756 Never set this variable using `setq' or so, because then it will apply
16757 to all future agenda commands. Instead, bind it with `let' to scope
16758 it dynamically into the agenda-constructing command.")
16760 (defun org-agenda-skip ()
16761 "Throw to `:skip' in places that should be skipped.
16762 Also moves point to the end of the skipped region, so that search can
16763 continue from there."
16764 (let ((p (point-at-bol)) to)
16765 (and org-agenda-skip-archived-trees
16766 (get-text-property p :org-archived)
16767 (org-end-of-subtree t)
16768 (throw :skip t))
16769 (and (get-text-property p :org-comment)
16770 (org-end-of-subtree t)
16771 (throw :skip t))
16772 (if (equal (char-after p) ?#) (throw :skip t))
16773 (when (and (functionp org-agenda-skip-function)
16774 (setq to (save-excursion
16775 (save-match-data
16776 (funcall org-agenda-skip-function)))))
16777 (goto-char to)
16778 (throw :skip t))))
16780 (defvar org-agenda-markers nil
16781 "List of all currently active markers created by `org-agenda'.")
16782 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
16783 "Creation time of the last agenda marker.")
16785 (defun org-agenda-new-marker (&optional pos)
16786 "Return a new agenda marker.
16787 Org-mode keeps a list of these markers and resets them when they are
16788 no longer in use."
16789 (let ((m (copy-marker (or pos (point)))))
16790 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
16791 (push m org-agenda-markers)
16794 (defun org-agenda-maybe-reset-markers (&optional force)
16795 "Reset markers created by `org-agenda'. But only if they are old enough."
16796 (if (or (and force (not org-agenda-multi))
16797 (> (- (time-to-seconds (current-time))
16798 org-agenda-last-marker-time)
16800 (while org-agenda-markers
16801 (move-marker (pop org-agenda-markers) nil))))
16803 (defvar org-agenda-new-buffers nil
16804 "Buffers created to visit agenda files.")
16806 (defun org-get-agenda-file-buffer (file)
16807 "Get a buffer visiting FILE. If the buffer needs to be created, add
16808 it to the list of buffers which might be released later."
16809 (let ((buf (org-find-base-buffer-visiting file)))
16810 (if buf
16811 buf ; just return it
16812 ;; Make a new buffer and remember it
16813 (setq buf (find-file-noselect file))
16814 (if buf (push buf org-agenda-new-buffers))
16815 buf)))
16817 (defun org-release-buffers (blist)
16818 "Release all buffers in list, asking the user for confirmation when needed.
16819 When a buffer is unmodified, it is just killed. When modified, it is saved
16820 \(if the user agrees) and then killed."
16821 (let (buf file)
16822 (while (setq buf (pop blist))
16823 (setq file (buffer-file-name buf))
16824 (when (and (buffer-modified-p buf)
16825 file
16826 (y-or-n-p (format "Save file %s? " file)))
16827 (with-current-buffer buf (save-buffer)))
16828 (kill-buffer buf))))
16830 (defvar org-category-table nil)
16831 (defun org-get-category-table ()
16832 "Get the table of categories and positions in current buffer."
16833 (let (tbl)
16834 (save-excursion
16835 (save-restriction
16836 (widen)
16837 (goto-char (point-min))
16838 (while (re-search-forward "^#\\+CATEGORY:[ \t]*\\(.*\\)"
16839 nil t)
16840 (push (cons (match-beginning 1)
16841 (org-trim (match-string 1))) tbl))))
16842 tbl))
16844 (defun org-get-category (&optional pos)
16845 "Get the category applying to position POS."
16846 (if (not org-category-table)
16847 (cond
16848 ((null org-category)
16849 (setq org-category
16850 (if buffer-file-name
16851 (file-name-sans-extension
16852 (file-name-nondirectory buffer-file-name))
16853 "???")))
16854 ((symbolp org-category) (symbol-name org-category))
16855 (t org-category))
16856 (let ((tbl org-category-table)
16857 (pos (or pos (point))))
16858 (while (and tbl (> (caar tbl) pos))
16859 (pop tbl))
16860 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
16861 org-category-table))))))
16862 ;;; Agenda timeline
16864 (defun org-timeline (&optional include-all)
16865 "Show a time-sorted view of the entries in the current org file.
16866 Only entries with a time stamp of today or later will be listed. With
16867 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
16868 under the current date.
16869 If the buffer contains an active region, only check the region for
16870 dates."
16871 (interactive "P")
16872 (require 'calendar)
16873 (org-compile-prefix-format 'timeline)
16874 (org-set-sorting-strategy 'timeline)
16875 (let* ((dopast t)
16876 (dotodo include-all)
16877 (doclosed org-agenda-show-log)
16878 (entry buffer-file-name)
16879 (date (calendar-current-date))
16880 (beg (if (org-region-active-p) (region-beginning) (point-min)))
16881 (end (if (org-region-active-p) (region-end) (point-max)))
16882 (day-numbers (org-get-all-dates beg end 'no-ranges
16883 t doclosed ; always include today
16884 org-timeline-show-empty-dates))
16885 (today (time-to-days (current-time)))
16886 (past t)
16887 args
16888 s e rtn d emptyp)
16889 (setq org-agenda-redo-command
16890 (list 'progn
16891 (list 'switch-to-buffer-other-window (current-buffer))
16892 (list 'org-timeline (list 'quote include-all))))
16893 (if (not dopast)
16894 ;; Remove past dates from the list of dates.
16895 (setq day-numbers (delq nil (mapcar (lambda(x)
16896 (if (>= x today) x nil))
16897 day-numbers))))
16898 (org-prepare-agenda (concat "Timeline "
16899 (file-name-nondirectory buffer-file-name)))
16900 (if doclosed (push :closed args))
16901 (push :timestamp args)
16902 (push :sexp args)
16903 (if dotodo (push :todo args))
16904 (while (setq d (pop day-numbers))
16905 (if (and (listp d) (eq (car d) :omitted))
16906 (progn
16907 (setq s (point))
16908 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
16909 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
16910 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
16911 (if (and (>= d today)
16912 dopast
16913 past)
16914 (progn
16915 (setq past nil)
16916 (insert (make-string 79 ?-) "\n")))
16917 (setq date (calendar-gregorian-from-absolute d))
16918 (setq s (point))
16919 (setq rtn (and (not emptyp)
16920 (apply 'org-agenda-get-day-entries
16921 entry date args)))
16922 (if (or rtn (equal d today) org-timeline-show-empty-dates)
16923 (progn
16924 (insert (calendar-day-name date) " "
16925 (number-to-string (extract-calendar-day date)) " "
16926 (calendar-month-name (extract-calendar-month date)) " "
16927 (number-to-string (extract-calendar-year date)) "\n")
16928 ; FIXME: this gives a timezone problem
16929 ; (insert (format-time-string org-agenda-date-format
16930 ; (calendar-time-from-absolute d 0))
16931 ; "\n")
16932 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
16933 (put-text-property s (1- (point)) 'org-date-line t)
16934 (if (equal d today)
16935 (put-text-property s (1- (point)) 'org-today t))
16936 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
16937 (put-text-property s (1- (point)) 'day d)))))
16938 (goto-char (point-min))
16939 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
16940 (point-min)))
16941 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
16942 (org-finalize-agenda)
16943 (setq buffer-read-only t)))
16945 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
16946 "Return a list of all relevant day numbers from BEG to END buffer positions.
16947 If NO-RANGES is non-nil, include only the start and end dates of a range,
16948 not every single day in the range. If FORCE-TODAY is non-nil, make
16949 sure that TODAY is included in the list. If INACTIVE is non-nil, also
16950 inactive time stamps (those in square brackets) are included.
16951 When EMPTY is non-nil, also include days without any entries."
16952 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
16953 dates dates1 date day day1 day2 ts1 ts2)
16954 (if force-today
16955 (setq dates (list (time-to-days (current-time)))))
16956 (save-excursion
16957 (goto-char beg)
16958 (while (re-search-forward re end t)
16959 (setq day (time-to-days (org-time-string-to-time
16960 (substring (match-string 1) 0 10))))
16961 (or (memq day dates) (push day dates)))
16962 (unless no-ranges
16963 (goto-char beg)
16964 (while (re-search-forward org-tr-regexp end t)
16965 (setq ts1 (substring (match-string 1) 0 10)
16966 ts2 (substring (match-string 2) 0 10)
16967 day1 (time-to-days (org-time-string-to-time ts1))
16968 day2 (time-to-days (org-time-string-to-time ts2)))
16969 (while (< (setq day1 (1+ day1)) day2)
16970 (or (memq day1 dates) (push day1 dates)))))
16971 (setq dates (sort dates '<))
16972 (when empty
16973 (while (setq day (pop dates))
16974 (setq day2 (car dates))
16975 (push day dates1)
16976 (when (and day2 empty)
16977 (if (or (eq empty t)
16978 (and (numberp empty) (<= (- day2 day) empty)))
16979 (while (< (setq day (1+ day)) day2)
16980 (push (list day) dates1))
16981 (push (cons :omitted (- day2 day)) dates1))))
16982 (setq dates (nreverse dates1)))
16983 dates)))
16985 ;;; Agenda Daily/Weekly
16987 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
16988 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
16989 (defvar org-agenda-last-arguments nil
16990 "The arguments of the previous call to org-agenda")
16991 (defvar org-starting-day nil) ; local variable in the agenda buffer
16992 (defvar org-agenda-span nil) ; local variable in the agenda buffer
16993 (defvar org-include-all-loc nil) ; local variable
16996 ;;;###autoload
16997 (defun org-agenda-list (&optional include-all start-day ndays)
16998 "Produce a weekly view from all files in variable `org-agenda-files'.
16999 The view will be for the current week, but from the overview buffer you
17000 will be able to go to other weeks.
17001 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
17002 also be shown, under the current date.
17003 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
17004 on the days are also shown. See the variable `org-log-done' for how
17005 to turn on logging.
17006 START-DAY defaults to TODAY, or to the most recent match for the weekday
17007 given in `org-agenda-start-on-weekday'.
17008 NDAYS defaults to `org-agenda-ndays'."
17009 (interactive "P")
17010 (setq ndays (or ndays org-agenda-ndays)
17011 start-day (or start-day org-agenda-start-day))
17012 (if org-agenda-overriding-arguments
17013 (setq include-all (car org-agenda-overriding-arguments)
17014 start-day (nth 1 org-agenda-overriding-arguments)
17015 ndays (nth 2 org-agenda-overriding-arguments)))
17016 (if (stringp start-day)
17017 ;; Convert to an absolute day number
17018 (setq start-day (time-to-days (org-read-date nil t start-day))))
17019 (setq org-agenda-last-arguments (list include-all start-day ndays))
17020 (org-compile-prefix-format 'agenda)
17021 (org-set-sorting-strategy 'agenda)
17022 (require 'calendar)
17023 (let* ((org-agenda-start-on-weekday
17024 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
17025 org-agenda-start-on-weekday nil))
17026 (thefiles (org-agenda-files))
17027 (files thefiles)
17028 (today (time-to-days (current-time)))
17029 (sd (or start-day today))
17030 (start (if (or (null org-agenda-start-on-weekday)
17031 (< org-agenda-ndays 7))
17033 (let* ((nt (calendar-day-of-week
17034 (calendar-gregorian-from-absolute sd)))
17035 (n1 org-agenda-start-on-weekday)
17036 (d (- nt n1)))
17037 (- sd (+ (if (< d 0) 7 0) d)))))
17038 (day-numbers (list start))
17039 (inhibit-redisplay (not debug-on-error))
17040 s e rtn rtnall file date d start-pos end-pos todayp nd)
17041 (setq org-agenda-redo-command
17042 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
17043 ;; Make the list of days
17044 (setq ndays (or ndays org-agenda-ndays)
17045 nd ndays)
17046 (while (> ndays 1)
17047 (push (1+ (car day-numbers)) day-numbers)
17048 (setq ndays (1- ndays)))
17049 (setq day-numbers (nreverse day-numbers))
17050 (org-prepare-agenda "Day/Week")
17051 (org-set-local 'org-starting-day (car day-numbers))
17052 (org-set-local 'org-include-all-loc include-all)
17053 (org-set-local 'org-agenda-span
17054 (org-agenda-ndays-to-span nd))
17055 (when (and (or include-all org-agenda-include-all-todo)
17056 (member today day-numbers))
17057 (setq files thefiles
17058 rtnall nil)
17059 (while (setq file (pop files))
17060 (catch 'nextfile
17061 (org-check-agenda-file file)
17062 (setq date (calendar-gregorian-from-absolute today)
17063 rtn (org-agenda-get-day-entries
17064 file date :todo))
17065 (setq rtnall (append rtnall rtn))))
17066 (when rtnall
17067 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
17068 (add-text-properties (point-min) (1- (point))
17069 (list 'face 'org-agenda-structure))
17070 (insert (org-finalize-agenda-entries rtnall) "\n")))
17071 (setq s (point))
17072 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
17073 "-agenda:\n")
17074 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
17075 'org-date-line t))
17076 (while (setq d (pop day-numbers))
17077 (setq date (calendar-gregorian-from-absolute d)
17078 s (point))
17079 (if (or (setq todayp (= d today))
17080 (and (not start-pos) (= d sd)))
17081 (setq start-pos (point))
17082 (if (and start-pos (not end-pos))
17083 (setq end-pos (point))))
17084 (setq files thefiles
17085 rtnall nil)
17086 (while (setq file (pop files))
17087 (catch 'nextfile
17088 (org-check-agenda-file file)
17089 (if org-agenda-show-log
17090 (setq rtn (org-agenda-get-day-entries
17091 file date
17092 :deadline :scheduled :timestamp :sexp :closed))
17093 (setq rtn (org-agenda-get-day-entries
17094 file date
17095 :deadline :scheduled :sexp :timestamp)))
17096 (setq rtnall (append rtnall rtn))))
17097 (if org-agenda-include-diary
17098 (progn
17099 (require 'diary-lib)
17100 (setq rtn (org-get-entries-from-diary date))
17101 (setq rtnall (append rtnall rtn))))
17102 (if (or rtnall org-agenda-show-all-dates)
17103 (progn
17104 (insert (format "%-9s %2d %s %4d\n"
17105 (calendar-day-name date)
17106 (extract-calendar-day date)
17107 (calendar-month-name (extract-calendar-month date))
17108 (extract-calendar-year date)))
17109 ; FIXME: this gives a timezone problem
17110 ; (insert (format-time-string org-agenda-date-format
17111 ; (calendar-time-from-absolute d 0)) "\n")
17112 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
17113 (put-text-property s (1- (point)) 'org-date-line t)
17114 (if todayp (put-text-property s (1- (point)) 'org-today t))
17115 (if rtnall (insert
17116 (org-finalize-agenda-entries
17117 (org-agenda-add-time-grid-maybe
17118 rtnall nd todayp))
17119 "\n"))
17120 (put-text-property s (1- (point)) 'day d))))
17121 (goto-char (point-min))
17122 (org-fit-agenda-window)
17123 (unless (and (pos-visible-in-window-p (point-min))
17124 (pos-visible-in-window-p (point-max)))
17125 (goto-char (1- (point-max)))
17126 (recenter -1)
17127 (if (not (pos-visible-in-window-p (or start-pos 1)))
17128 (progn
17129 (goto-char (or start-pos 1))
17130 (recenter 1))))
17131 (goto-char (or start-pos 1))
17132 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
17133 (org-finalize-agenda)
17134 (setq buffer-read-only t)
17135 (message "")))
17137 (defun org-agenda-ndays-to-span (n)
17138 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
17140 ;;; Agenda TODO list
17142 (defvar org-select-this-todo-keyword nil)
17143 (defvar org-last-arg nil)
17145 ;;;###autoload
17146 (defun org-todo-list (arg)
17147 "Show all TODO entries from all agenda file in a single list.
17148 The prefix arg can be used to select a specific TODO keyword and limit
17149 the list to these. When using \\[universal-argument], you will be prompted
17150 for a keyword. A numeric prefix directly selects the Nth keyword in
17151 `org-todo-keywords-1'."
17152 (interactive "P")
17153 (require 'calendar)
17154 (org-compile-prefix-format 'todo)
17155 (org-set-sorting-strategy 'todo)
17156 (org-prepare-agenda "TODO")
17157 (let* ((today (time-to-days (current-time)))
17158 (date (calendar-gregorian-from-absolute today))
17159 (kwds org-todo-keywords-for-agenda)
17160 (completion-ignore-case t)
17161 (org-select-this-todo-keyword
17162 (if (stringp arg) arg
17163 (and arg (integerp arg) (> arg 0)
17164 (nth (1- arg) kwds))))
17165 rtn rtnall files file pos)
17166 (when (equal arg '(4))
17167 (setq org-select-this-todo-keyword
17168 (completing-read "Keyword (or KWD1|K2D2|...): "
17169 (mapcar 'list kwds) nil nil)))
17170 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
17171 (org-set-local 'org-last-arg arg)
17172 (setq org-agenda-redo-command
17173 '(org-todo-list (or current-prefix-arg org-last-arg)))
17174 (setq files (org-agenda-files)
17175 rtnall nil)
17176 (while (setq file (pop files))
17177 (catch 'nextfile
17178 (org-check-agenda-file file)
17179 (setq rtn (org-agenda-get-day-entries file date :todo))
17180 (setq rtnall (append rtnall rtn))))
17181 (if org-agenda-overriding-header
17182 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17183 nil 'face 'org-agenda-structure) "\n")
17184 (insert "Global list of TODO items of type: ")
17185 (add-text-properties (point-min) (1- (point))
17186 (list 'face 'org-agenda-structure))
17187 (setq pos (point))
17188 (insert (or org-select-this-todo-keyword "ALL") "\n")
17189 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17190 (setq pos (point))
17191 (unless org-agenda-multi
17192 (insert "Available with `N r': (0)ALL")
17193 (let ((n 0) s)
17194 (mapc (lambda (x)
17195 (setq s (format "(%d)%s" (setq n (1+ n)) x))
17196 (if (> (+ (current-column) (string-width s) 1) (frame-width))
17197 (insert "\n "))
17198 (insert " " s))
17199 kwds))
17200 (insert "\n"))
17201 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17202 (when rtnall
17203 (insert (org-finalize-agenda-entries rtnall) "\n"))
17204 (goto-char (point-min))
17205 (org-fit-agenda-window)
17206 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
17207 (org-finalize-agenda)
17208 (setq buffer-read-only t)))
17210 ;;; Agenda tags match
17212 ;;;###autoload
17213 (defun org-tags-view (&optional todo-only match)
17214 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
17215 The prefix arg TODO-ONLY limits the search to TODO entries."
17216 (interactive "P")
17217 (org-compile-prefix-format 'tags)
17218 (org-set-sorting-strategy 'tags)
17219 (let* ((org-tags-match-list-sublevels
17220 (if todo-only t org-tags-match-list-sublevels))
17221 (completion-ignore-case t)
17222 rtn rtnall files file pos matcher
17223 buffer)
17224 (setq matcher (org-make-tags-matcher match)
17225 match (car matcher) matcher (cdr matcher))
17226 (org-prepare-agenda (concat "TAGS " match))
17227 (setq org-agenda-redo-command
17228 (list 'org-tags-view (list 'quote todo-only)
17229 (list 'if 'current-prefix-arg nil match)))
17230 (setq files (org-agenda-files)
17231 rtnall nil)
17232 (while (setq file (pop files))
17233 (catch 'nextfile
17234 (org-check-agenda-file file)
17235 (setq buffer (if (file-exists-p file)
17236 (org-get-agenda-file-buffer file)
17237 (error "No such file %s" file)))
17238 (if (not buffer)
17239 ;; If file does not exist, merror message to agenda
17240 (setq rtn (list
17241 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17242 rtnall (append rtnall rtn))
17243 (with-current-buffer buffer
17244 (unless (org-mode-p)
17245 (error "Agenda file %s is not in `org-mode'" file))
17246 (setq org-category-table (org-get-category-table))
17247 (save-excursion
17248 (save-restriction
17249 (if org-agenda-restrict
17250 (narrow-to-region org-agenda-restrict-begin
17251 org-agenda-restrict-end)
17252 (widen))
17253 (setq rtn (org-scan-tags 'agenda matcher todo-only))
17254 (setq rtnall (append rtnall rtn))))))))
17255 (if org-agenda-overriding-header
17256 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
17257 nil 'face 'org-agenda-structure) "\n")
17258 (insert "Headlines with TAGS match: ")
17259 (add-text-properties (point-min) (1- (point))
17260 (list 'face 'org-agenda-structure))
17261 (setq pos (point))
17262 (insert match "\n")
17263 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
17264 (setq pos (point))
17265 (unless org-agenda-multi
17266 (insert "Press `C-u r' to search again with new search string\n"))
17267 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
17268 (when rtnall
17269 (insert (org-finalize-agenda-entries rtnall) "\n"))
17270 (goto-char (point-min))
17271 (org-fit-agenda-window)
17272 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
17273 (org-finalize-agenda)
17274 (setq buffer-read-only t)))
17276 ;;; Agenda Finding stuck projects
17278 (defvar org-agenda-skip-regexp nil
17279 "Regular expression used in skipping subtrees for the agenda.
17280 This is basically a temporary global variable that can be set and then
17281 used by user-defined selections using `org-agenda-skip-function'.")
17283 (defvar org-agenda-overriding-header nil
17284 "When this is set during todo and tags searches, will replace header.")
17286 (defun org-agenda-skip-subtree-when-regexp-matches ()
17287 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
17288 If yes, it returns the end position of this tree, causing agenda commands
17289 to skip this subtree. This is a function that can be put into
17290 `org-agenda-skip-function' for the duration of a command."
17291 (save-match-data
17292 (let ((end (save-excursion (org-end-of-subtree t)))
17293 skip)
17294 (save-excursion
17295 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
17296 (and skip end))))
17298 (defun org-agenda-list-stuck-projects (&rest ignore)
17299 "Create agenda view for projects that are stuck.
17300 Stuck projects are project that have no next actions. For the definitions
17301 of what a project is and how to check if it stuck, customize the variable
17302 `org-stuck-projects'.
17303 MATCH is being ignored."
17304 (interactive)
17305 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
17306 (org-agenda-overriding-header "List of stuck projects: ")
17307 (matcher (nth 0 org-stuck-projects))
17308 (todo (nth 1 org-stuck-projects))
17309 (todo-wds (if (member "*" todo)
17310 (progn
17311 (org-prepare-agenda-buffers (org-agenda-files))
17312 (org-delete-all
17313 org-done-keywords-for-agenda
17314 (copy-sequence org-todo-keywords-for-agenda)))
17315 todo))
17316 (todo-re (concat "^\\*+[ \t]+\\("
17317 (mapconcat 'identity todo-wds "\\|")
17318 "\\)\\>"))
17319 (tags (nth 2 org-stuck-projects))
17320 (tags-re (if (member "*" tags)
17321 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
17322 (concat "^\\*+ .*:\\("
17323 (mapconcat 'identity tags "\\|")
17324 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
17325 (gen-re (nth 3 org-stuck-projects))
17326 (re-list
17327 (delq nil
17328 (list
17329 (if todo todo-re)
17330 (if tags tags-re)
17331 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
17332 gen-re)))))
17333 (setq org-agenda-skip-regexp
17334 (if re-list
17335 (mapconcat 'identity re-list "\\|")
17336 (error "No information how to identify unstuck projects")))
17337 (org-tags-view nil matcher)
17338 (with-current-buffer org-agenda-buffer-name
17339 (setq org-agenda-redo-command
17340 '(org-agenda-list-stuck-projects
17341 (or current-prefix-arg org-last-arg))))))
17343 ;;; Diary integration
17345 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
17347 (defun org-get-entries-from-diary (date)
17348 "Get the (Emacs Calendar) diary entries for DATE."
17349 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
17350 (diary-display-hook '(fancy-diary-display))
17351 (list-diary-entries-hook
17352 (cons 'org-diary-default-entry list-diary-entries-hook))
17353 (diary-file-name-prefix-function nil) ; turn this feature off
17354 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
17355 entries
17356 (org-disable-agenda-to-diary t))
17357 (save-excursion
17358 (save-window-excursion
17359 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
17360 (if (not (get-buffer fancy-diary-buffer))
17361 (setq entries nil)
17362 (with-current-buffer fancy-diary-buffer
17363 (setq buffer-read-only nil)
17364 (if (= (point-max) 1)
17365 ;; No entries
17366 (setq entries nil)
17367 ;; Omit the date and other unnecessary stuff
17368 (org-agenda-cleanup-fancy-diary)
17369 ;; Add prefix to each line and extend the text properties
17370 (if (= (point-max) 1)
17371 (setq entries nil)
17372 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
17373 (set-buffer-modified-p nil)
17374 (kill-buffer fancy-diary-buffer)))
17375 (when entries
17376 (setq entries (org-split-string entries "\n"))
17377 (setq entries
17378 (mapcar
17379 (lambda (x)
17380 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
17381 ;; Extend the text properties to the beginning of the line
17382 (org-add-props x (text-properties-at (1- (length x)) x)
17383 'type "diary" 'date date))
17384 entries)))))
17386 (defun org-agenda-cleanup-fancy-diary ()
17387 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
17388 This gets rid of the date, the underline under the date, and
17389 the dummy entry installed by `org-mode' to ensure non-empty diary for each
17390 date. It also removes lines that contain only whitespace."
17391 (goto-char (point-min))
17392 (if (looking-at ".*?:[ \t]*")
17393 (progn
17394 (replace-match "")
17395 (re-search-forward "\n=+$" nil t)
17396 (replace-match "")
17397 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
17398 (re-search-forward "\n=+$" nil t)
17399 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
17400 (goto-char (point-min))
17401 (while (re-search-forward "^ +\n" nil t)
17402 (replace-match ""))
17403 (goto-char (point-min))
17404 (if (re-search-forward "^Org-mode dummy\n?" nil t)
17405 (replace-match "")))
17407 ;; Make sure entries from the diary have the right text properties.
17408 (eval-after-load "diary-lib"
17409 '(if (boundp 'diary-modify-entry-list-string-function)
17410 ;; We can rely on the hook, nothing to do
17412 ;; Hook not avaiable, must use advice to make this work
17413 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
17414 "Make the position visible."
17415 (if (and org-disable-agenda-to-diary ;; called from org-agenda
17416 (stringp string)
17417 buffer-file-name)
17418 (setq string (org-modify-diary-entry-string string))))))
17420 (defun org-modify-diary-entry-string (string)
17421 "Add text properties to string, allowing org-mode to act on it."
17422 (org-add-props string nil
17423 'mouse-face 'highlight
17424 'keymap org-agenda-keymap
17425 'help-echo (if buffer-file-name
17426 (format "mouse-2 or RET jump to diary file %s"
17427 (abbreviate-file-name buffer-file-name))
17429 'org-agenda-diary-link t
17430 'org-marker (org-agenda-new-marker (point-at-bol))))
17432 (defun org-diary-default-entry ()
17433 "Add a dummy entry to the diary.
17434 Needed to avoid empty dates which mess up holiday display."
17435 ;; Catch the error if dealing with the new add-to-diary-alist
17436 (when org-disable-agenda-to-diary
17437 (condition-case nil
17438 (add-to-diary-list original-date "Org-mode dummy" "")
17439 (error
17440 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
17442 ;;;###autoload
17443 (defun org-diary (&rest args)
17444 "Return diary information from org-files.
17445 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
17446 It accesses org files and extracts information from those files to be
17447 listed in the diary. The function accepts arguments specifying what
17448 items should be listed. The following arguments are allowed:
17450 :timestamp List the headlines of items containing a date stamp or
17451 date range matching the selected date. Deadlines will
17452 also be listed, on the expiration day.
17454 :sexp FIXME
17456 :deadline List any deadlines past due, or due within
17457 `org-deadline-warning-days'. The listing occurs only
17458 in the diary for *today*, not at any other date. If
17459 an entry is marked DONE, it is no longer listed.
17461 :scheduled List all items which are scheduled for the given date.
17462 The diary for *today* also contains items which were
17463 scheduled earlier and are not yet marked DONE.
17465 :todo List all TODO items from the org-file. This may be a
17466 long list - so this is not turned on by default.
17467 Like deadlines, these entries only show up in the
17468 diary for *today*, not at any other date.
17470 The call in the diary file should look like this:
17472 &%%(org-diary) ~/path/to/some/orgfile.org
17474 Use a separate line for each org file to check. Or, if you omit the file name,
17475 all files listed in `org-agenda-files' will be checked automatically:
17477 &%%(org-diary)
17479 If you don't give any arguments (as in the example above), the default
17480 arguments (:deadline :scheduled :timestamp :sexp) are used.
17481 So the example above may also be written as
17483 &%%(org-diary :deadline :timestamp :sexp :scheduled)
17485 The function expects the lisp variables `entry' and `date' to be provided
17486 by the caller, because this is how the calendar works. Don't use this
17487 function from a program - use `org-agenda-get-day-entries' instead."
17488 (org-agenda-maybe-reset-markers)
17489 (org-compile-prefix-format 'agenda)
17490 (org-set-sorting-strategy 'agenda)
17491 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17492 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
17493 (list entry)
17494 (org-agenda-files t)))
17495 file rtn results)
17496 (org-prepare-agenda-buffers files)
17497 ;; If this is called during org-agenda, don't return any entries to
17498 ;; the calendar. Org Agenda will list these entries itself.
17499 (if org-disable-agenda-to-diary (setq files nil))
17500 (while (setq file (pop files))
17501 (setq rtn (apply 'org-agenda-get-day-entries file date args))
17502 (setq results (append results rtn)))
17503 (if results
17504 (concat (org-finalize-agenda-entries results) "\n"))))
17506 ;;; Agenda entry finders
17508 (defun org-agenda-get-day-entries (file date &rest args)
17509 "Does the work for `org-diary' and `org-agenda'.
17510 FILE is the path to a file to be checked for entries. DATE is date like
17511 the one returned by `calendar-current-date'. ARGS are symbols indicating
17512 which kind of entries should be extracted. For details about these, see
17513 the documentation of `org-diary'."
17514 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
17515 (let* ((org-startup-folded nil)
17516 (org-startup-align-all-tables nil)
17517 (buffer (if (file-exists-p file)
17518 (org-get-agenda-file-buffer file)
17519 (error "No such file %s" file)))
17520 arg results rtn)
17521 (if (not buffer)
17522 ;; If file does not exist, make sure an error message ends up in diary
17523 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
17524 (with-current-buffer buffer
17525 (unless (org-mode-p)
17526 (error "Agenda file %s is not in `org-mode'" file))
17527 (setq org-category-table (org-get-category-table))
17528 (let ((case-fold-search nil))
17529 (save-excursion
17530 (save-restriction
17531 (if org-agenda-restrict
17532 (narrow-to-region org-agenda-restrict-begin
17533 org-agenda-restrict-end)
17534 (widen))
17535 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
17536 (while (setq arg (pop args))
17537 (cond
17538 ((and (eq arg :todo)
17539 (equal date (calendar-current-date)))
17540 (setq rtn (org-agenda-get-todos))
17541 (setq results (append results rtn)))
17542 ((eq arg :timestamp)
17543 (setq rtn (org-agenda-get-blocks))
17544 (setq results (append results rtn))
17545 (setq rtn (org-agenda-get-timestamps))
17546 (setq results (append results rtn)))
17547 ((eq arg :sexp)
17548 (setq rtn (org-agenda-get-sexps))
17549 (setq results (append results rtn)))
17550 ((eq arg :scheduled)
17551 (setq rtn (org-agenda-get-scheduled))
17552 (setq results (append results rtn)))
17553 ((eq arg :closed)
17554 (setq rtn (org-agenda-get-closed))
17555 (setq results (append results rtn)))
17556 ((and (eq arg :deadline)
17557 (equal date (calendar-current-date)))
17558 (setq rtn (org-agenda-get-deadlines))
17559 (setq results (append results rtn))))))))
17560 results))))
17562 ;; FIXME: this works only if the cursor is not at the
17563 ;; beginning of the entry
17564 (defun org-entry-is-done-p ()
17565 "Is the current entry marked DONE?"
17566 (save-excursion
17567 (and (re-search-backward "[\r\n]\\* " nil t)
17568 (looking-at org-nl-done-regexp))))
17570 (defun org-at-date-range-p (&optional inactive-ok)
17571 "Is the cursor inside a date range?"
17572 (interactive)
17573 (save-excursion
17574 (catch 'exit
17575 (let ((pos (point)))
17576 (skip-chars-backward "^[<\r\n")
17577 (skip-chars-backward "<[")
17578 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
17579 (>= (match-end 0) pos)
17580 (throw 'exit t))
17581 (skip-chars-backward "^<[\r\n")
17582 (skip-chars-backward "<[")
17583 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
17584 (>= (match-end 0) pos)
17585 (throw 'exit t)))
17586 nil)))
17588 (defun org-agenda-get-todos ()
17589 "Return the TODO information for agenda display."
17590 (let* ((props (list 'face nil
17591 'done-face 'org-done
17592 'org-not-done-regexp org-not-done-regexp
17593 'org-todo-regexp org-todo-regexp
17594 'mouse-face 'highlight
17595 'keymap org-agenda-keymap
17596 'help-echo
17597 (format "mouse-2 or RET jump to org file %s"
17598 (abbreviate-file-name buffer-file-name))))
17599 ;; FIXME: get rid of the \n at some point but watch out
17600 (regexp (concat "\n\\*+[ \t]+\\("
17601 (if org-select-this-todo-keyword
17602 (if (equal org-select-this-todo-keyword "*")
17603 org-todo-regexp
17604 (concat "\\<\\("
17605 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
17606 "\\)\\>"))
17607 org-not-done-regexp)
17608 "[^\n\r]*\\)"))
17609 marker priority category tags
17610 ee txt beg end)
17611 (goto-char (point-min))
17612 (while (re-search-forward regexp nil t)
17613 (catch :skip
17614 (save-match-data
17615 (beginning-of-line)
17616 (setq beg (point) end (progn (outline-next-heading) (point)))
17617 (when (or (and org-agenda-todo-ignore-scheduled (goto-char beg)
17618 (re-search-forward org-scheduled-time-regexp end t))
17619 (and org-agenda-todo-ignore-deadlines (goto-char beg)
17620 (re-search-forward org-deadline-time-regexp end t)
17621 (org-deadline-close (match-string 1))))
17622 (goto-char beg)
17623 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
17624 (throw :skip nil)))
17625 (goto-char beg)
17626 (org-agenda-skip)
17627 (goto-char (match-beginning 1))
17628 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
17629 category (org-get-category)
17630 tags (org-get-tags-at (point))
17631 txt (org-format-agenda-item "" (match-string 1) category tags)
17632 priority (1+ (org-get-priority txt)))
17633 (org-add-props txt props
17634 'org-marker marker 'org-hd-marker marker
17635 'priority priority 'org-category category
17636 'type "todo")
17637 (push txt ee)
17638 (if org-agenda-todo-list-sublevels
17639 (goto-char (match-end 1))
17640 (org-end-of-subtree 'invisible))))
17641 (nreverse ee)))
17643 (defconst org-agenda-no-heading-message
17644 "No heading for this item in buffer or region.")
17646 (defun org-agenda-get-timestamps ()
17647 "Return the date stamp information for agenda display."
17648 (let* ((props (list 'face nil
17649 'org-not-done-regexp org-not-done-regexp
17650 'org-todo-regexp org-todo-regexp
17651 'mouse-face 'highlight
17652 'keymap org-agenda-keymap
17653 'help-echo
17654 (format "mouse-2 or RET jump to org file %s"
17655 (abbreviate-file-name buffer-file-name))))
17656 ;???? (regexp (regexp-quote
17657 ; (substring
17658 ; (format-time-string
17659 ; (car org-time-stamp-formats)
17660 ; (apply 'encode-time ; DATE bound by calendar
17661 ; (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
17662 ; 0 11)))
17663 (d1 (calendar-absolute-from-gregorian date))
17664 (regexp
17665 (concat
17666 (regexp-quote
17667 (substring
17668 (format-time-string
17669 (car org-time-stamp-formats)
17670 (apply 'encode-time ; DATE bound by calendar
17671 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
17672 0 11))
17673 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
17674 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
17675 marker hdmarker deadlinep scheduledp donep tmp priority category
17676 ee txt timestr tags b0 b3 e3)
17677 (goto-char (point-min))
17678 (while (re-search-forward regexp nil t)
17679 (setq b0 (match-beginning 0)
17680 b3 (match-beginning 3) e3 (match-end 3))
17681 (catch :skip
17682 (and (org-at-date-range-p) (throw :skip nil))
17683 (org-agenda-skip)
17684 (if (and (match-end 1)
17685 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
17686 (throw :skip nil))
17687 (if (and e3
17688 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
17689 (throw :skip nil))
17690 (setq marker (org-agenda-new-marker b0)
17691 category (org-get-category b0)
17692 tmp (buffer-substring (max (point-min)
17693 (- b0 org-ds-keyword-length))
17695 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
17696 deadlinep (string-match org-deadline-regexp tmp)
17697 scheduledp (string-match org-scheduled-regexp tmp)
17698 donep (org-entry-is-done-p))
17699 (and org-agenda-skip-scheduled-if-done
17700 scheduledp donep
17701 (throw :skip t))
17702 (and org-agenda-skip-deadline-if-done
17703 deadlinep donep
17704 (throw :skip t))
17705 (if (string-match ">" timestr)
17706 ;; substring should only run to end of time stamp
17707 (setq timestr (substring timestr 0 (match-end 0))))
17708 (save-excursion
17709 (if (re-search-backward "^\\*+ " nil t)
17710 (progn
17711 (goto-char (match-beginning 0))
17712 (setq hdmarker (org-agenda-new-marker)
17713 tags (org-get-tags-at))
17714 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
17715 (setq txt (org-format-agenda-item
17716 (format "%s%s"
17717 (if deadlinep "Deadline: " "")
17718 (if scheduledp "Scheduled: " ""))
17719 (match-string 1) category tags timestr)))
17720 (setq txt org-agenda-no-heading-message))
17721 (setq priority (org-get-priority txt))
17722 (org-add-props txt props
17723 'org-marker marker 'org-hd-marker hdmarker)
17724 (if deadlinep
17725 (org-add-props txt nil
17726 'face (if donep 'org-done 'org-warning)
17727 'type "deadline" 'date date
17728 'undone-face 'org-warning 'done-face 'org-done
17729 'org-category category 'priority (+ 100 priority))
17730 (if scheduledp
17731 (org-add-props txt nil
17732 'face 'org-scheduled-today
17733 'type "scheduled" 'date date
17734 'undone-face 'org-scheduled-today 'done-face 'org-done
17735 'org-category category 'priority (+ 99 priority))
17736 (org-add-props txt nil 'priority priority
17737 'org-category category 'date date
17738 'type "timestamp")))
17739 (push txt ee))
17740 (outline-next-heading)))
17741 (nreverse ee)))
17743 (defun org-agenda-get-sexps ()
17744 "Return the sexp information for agenda display."
17745 (require 'diary-lib)
17746 (let* ((props (list 'face nil
17747 'mouse-face 'highlight
17748 'keymap org-agenda-keymap
17749 'help-echo
17750 (format "mouse-2 or RET jump to org file %s"
17751 (abbreviate-file-name buffer-file-name))))
17752 (regexp "^&?%%(")
17753 marker category ee txt tags entry result beg b sexp sexp-entry)
17754 (goto-char (point-min))
17755 (while (re-search-forward regexp nil t)
17756 (catch :skip
17757 (org-agenda-skip)
17758 (setq beg (match-beginning 0))
17759 (goto-char (1- (match-end 0)))
17760 (setq b (point))
17761 (forward-sexp 1)
17762 (setq sexp (buffer-substring b (point)))
17763 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
17764 (org-trim (match-string 1))
17765 ""))
17766 (setq result (org-diary-sexp-entry sexp sexp-entry date))
17767 (when result
17768 (setq marker (org-agenda-new-marker beg)
17769 category (org-get-category beg))
17771 (if (string-match "\\S-" result)
17772 (setq txt result)
17773 (setq txt "SEXP entry returned empty string"))
17775 (setq txt (org-format-agenda-item
17776 "" txt category tags 'time))
17777 (org-add-props txt props 'org-marker marker)
17778 (org-add-props txt nil
17779 'org-category category 'date date
17780 'type "sexp")
17781 (push txt ee))))
17782 (nreverse ee)))
17784 (defun org-agenda-get-closed ()
17785 "Return the logged TODO entries for agenda display."
17786 (let* ((props (list 'mouse-face 'highlight
17787 'org-not-done-regexp org-not-done-regexp
17788 'org-todo-regexp org-todo-regexp
17789 'keymap org-agenda-keymap
17790 'help-echo
17791 (format "mouse-2 or RET jump to org file %s"
17792 (abbreviate-file-name buffer-file-name))))
17793 (regexp (concat
17794 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
17795 (regexp-quote
17796 (substring
17797 (format-time-string
17798 (car org-time-stamp-formats)
17799 (apply 'encode-time ; DATE bound by calendar
17800 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
17801 1 11))))
17802 marker hdmarker priority category tags closedp
17803 ee txt timestr)
17804 (goto-char (point-min))
17805 (while (re-search-forward regexp nil t)
17806 (catch :skip
17807 (org-agenda-skip)
17808 (setq marker (org-agenda-new-marker (match-beginning 0))
17809 closedp (equal (match-string 1) org-closed-string)
17810 category (org-get-category (match-beginning 0))
17811 timestr (buffer-substring (match-beginning 0) (point-at-eol))
17812 ;; donep (org-entry-is-done-p)
17814 (if (string-match "\\]" timestr)
17815 ;; substring should only run to end of time stamp
17816 (setq timestr (substring timestr 0 (match-end 0))))
17817 (save-excursion
17818 (if (re-search-backward "^\\*+ " nil t)
17819 (progn
17820 (goto-char (match-beginning 0))
17821 (setq hdmarker (org-agenda-new-marker)
17822 tags (org-get-tags-at))
17823 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
17824 (setq txt (org-format-agenda-item
17825 (if closedp "Closed: " "Clocked: ")
17826 (match-string 1) category tags timestr)))
17827 (setq txt org-agenda-no-heading-message))
17828 (setq priority 100000)
17829 (org-add-props txt props
17830 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
17831 'priority priority 'org-category category
17832 'type "closed" 'date date
17833 'undone-face 'org-warning 'done-face 'org-done)
17834 (push txt ee))
17835 (outline-next-heading)))
17836 (nreverse ee)))
17838 (defun org-agenda-get-deadlines ()
17839 "Return the deadline information for agenda display."
17840 (let* ((wdays org-deadline-warning-days)
17841 (props (list 'mouse-face 'highlight
17842 'org-not-done-regexp org-not-done-regexp
17843 'org-todo-regexp org-todo-regexp
17844 'keymap org-agenda-keymap
17845 'help-echo
17846 (format "mouse-2 or RET jump to org file %s"
17847 (abbreviate-file-name buffer-file-name))))
17848 (regexp org-deadline-time-regexp)
17849 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
17850 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
17851 d2 diff pos pos1 category tags
17852 ee txt head face)
17853 (goto-char (point-min))
17854 (while (re-search-forward regexp nil t)
17855 (catch :skip
17856 (org-agenda-skip)
17857 (setq pos (1- (match-beginning 1))
17858 ;??? d2 (time-to-days
17859 ;??? (org-time-string-to-time (match-string 1)))
17860 d2 (org-time-string-to-absolute (match-string 1) d1)
17861 diff (- d2 d1))
17862 ;; When to show a deadline in the calendar:
17863 ;; If the expiration is within wdays warning time.
17864 ;; Past-due deadlines are only shown on the current date
17865 (if (and (< diff wdays) todayp (not (= diff 0)))
17866 (save-excursion
17867 (setq category (org-get-category))
17868 (if (re-search-backward "^\\*+[ \t]+" nil t)
17869 (progn
17870 (goto-char (match-end 0))
17871 (setq pos1 (match-beginning 0))
17872 (setq tags (org-get-tags-at pos1))
17873 (setq head (buffer-substring-no-properties
17874 (point)
17875 (progn (skip-chars-forward "^\r\n")
17876 (point))))
17877 (if (string-match org-looking-at-done-regexp head)
17878 (setq txt nil)
17879 (setq txt (org-format-agenda-item
17880 (format "In %3d d.: " diff) head category tags))))
17881 (setq txt org-agenda-no-heading-message))
17882 (when txt
17883 (setq face (cond ((<= diff 0) 'org-warning)
17884 ((<= diff 5) 'org-upcoming-deadline)
17885 (t nil)))
17886 (org-add-props txt props
17887 'org-marker (org-agenda-new-marker pos)
17888 'org-hd-marker (org-agenda-new-marker pos1)
17889 'priority (+ (- 10 diff) (org-get-priority txt))
17890 'org-category category
17891 'type "upcoming-deadline" 'date d2
17892 'face face 'undone-face face 'done-face 'org-done)
17893 (push txt ee))))))
17894 ee))
17896 (defun org-agenda-get-scheduled ()
17897 "Return the scheduled information for agenda display."
17898 (let* ((props (list 'face 'org-scheduled-previously
17899 'org-not-done-regexp org-not-done-regexp
17900 'org-todo-regexp org-todo-regexp
17901 'undone-face 'org-scheduled-previously
17902 'done-face 'org-done
17903 'mouse-face 'highlight
17904 'keymap org-agenda-keymap
17905 'help-echo
17906 (format "mouse-2 or RET jump to org file %s"
17907 (abbreviate-file-name buffer-file-name))))
17908 (regexp org-scheduled-time-regexp)
17909 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
17910 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
17911 d2 diff pos pos1 category tags
17912 ee txt head)
17913 (goto-char (point-min))
17914 (while (re-search-forward regexp nil t)
17915 (catch :skip
17916 (org-agenda-skip)
17917 (setq pos (1- (match-beginning 1))
17918 d2 (org-time-string-to-absolute (match-string 1) d1)
17919 ;??? d2 (time-to-days
17920 ;??? (org-time-string-to-time (match-string 1)))
17921 diff (- d2 d1))
17922 ;; When to show a scheduled item in the calendar:
17923 ;; If it is on or past the date.
17924 (if (and (< diff 0) todayp)
17925 (save-excursion
17926 (setq category (org-get-category))
17927 (if (re-search-backward "^\\*+[ \t]+" nil t)
17928 (progn
17929 (goto-char (match-end 0))
17930 (setq pos1 (match-beginning 0))
17931 (setq tags (org-get-tags-at))
17932 (setq head (buffer-substring-no-properties
17933 (point)
17934 (progn (skip-chars-forward "^\r\n") (point))))
17935 (if (string-match org-looking-at-done-regexp head)
17936 (setq txt nil)
17937 (setq txt (org-format-agenda-item
17938 (format "Sched.%2dx: " (- 1 diff)) head
17939 category tags))))
17940 (setq txt org-agenda-no-heading-message))
17941 (when txt
17942 (org-add-props txt props
17943 'org-marker (org-agenda-new-marker pos)
17944 'org-hd-marker (org-agenda-new-marker pos1)
17945 'type "past-scheduled" 'date d2
17946 'priority (+ (- 5 diff) (org-get-priority txt))
17947 'org-category category)
17948 (push txt ee))))))
17949 ee))
17951 (defun org-agenda-get-blocks ()
17952 "Return the date-range information for agenda display."
17953 (let* ((props (list 'face nil
17954 'org-not-done-regexp org-not-done-regexp
17955 'org-todo-regexp org-todo-regexp
17956 'mouse-face 'highlight
17957 'keymap org-agenda-keymap
17958 'help-echo
17959 (format "mouse-2 or RET jump to org file %s"
17960 (abbreviate-file-name buffer-file-name))))
17961 (regexp org-tr-regexp)
17962 (d0 (calendar-absolute-from-gregorian date))
17963 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
17964 (goto-char (point-min))
17965 (while (re-search-forward regexp nil t)
17966 (catch :skip
17967 (org-agenda-skip)
17968 (setq pos (point))
17969 (setq timestr (match-string 0)
17970 s1 (match-string 1)
17971 s2 (match-string 2)
17972 d1 (time-to-days (org-time-string-to-time s1))
17973 d2 (time-to-days (org-time-string-to-time s2)))
17974 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
17975 ;; Only allow days between the limits, because the normal
17976 ;; date stamps will catch the limits.
17977 (save-excursion
17978 (setq marker (org-agenda-new-marker (point)))
17979 (setq category (org-get-category))
17980 (if (re-search-backward "^\\*+ " nil t)
17981 (progn
17982 (goto-char (match-beginning 0))
17983 (setq hdmarker (org-agenda-new-marker (point)))
17984 (setq tags (org-get-tags-at))
17985 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
17986 (setq txt (org-format-agenda-item
17987 (format (if (= d1 d2) "" "(%d/%d): ")
17988 (1+ (- d0 d1)) (1+ (- d2 d1)))
17989 (match-string 1) category tags
17990 (if (= d0 d1) timestr))))
17991 (setq txt org-agenda-no-heading-message))
17992 (org-add-props txt props
17993 'org-marker marker 'org-hd-marker hdmarker
17994 'type "block" 'date date
17995 'priority (org-get-priority txt) 'org-category category)
17996 (push txt ee)))
17997 (goto-char pos)))
17998 ;; Sort the entries by expiration date.
17999 (nreverse ee)))
18001 ;;; Agenda presentation and sorting
18003 (defconst org-plain-time-of-day-regexp
18004 (concat
18005 "\\(\\<[012]?[0-9]"
18006 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18007 "\\(--?"
18008 "\\(\\<[012]?[0-9]"
18009 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
18010 "\\)?")
18011 "Regular expression to match a plain time or time range.
18012 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
18013 groups carry important information:
18014 0 the full match
18015 1 the first time, range or not
18016 8 the second time, if it is a range.")
18018 (defconst org-stamp-time-of-day-regexp
18019 (concat
18020 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
18021 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
18022 "\\(--?"
18023 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
18024 "Regular expression to match a timestamp time or time range.
18025 After a match, the following groups carry important information:
18026 0 the full match
18027 1 date plus weekday, for backreferencing to make sure both times on same day
18028 2 the first time, range or not
18029 4 the second time, if it is a range.")
18031 (defvar org-prefix-has-time nil
18032 "A flag, set by `org-compile-prefix-format'.
18033 The flag is set if the currently compiled format contains a `%t'.")
18034 (defvar org-prefix-has-tag nil
18035 "A flag, set by `org-compile-prefix-format'.
18036 The flag is set if the currently compiled format contains a `%T'.")
18038 (defun org-format-agenda-item (extra txt &optional category tags dotime
18039 noprefix)
18040 "Format TXT to be inserted into the agenda buffer.
18041 In particular, it adds the prefix and corresponding text properties. EXTRA
18042 must be a string and replaces the `%s' specifier in the prefix format.
18043 CATEGORY (string, symbol or nil) may be used to overrule the default
18044 category taken from local variable or file name. It will replace the `%c'
18045 specifier in the format. DOTIME, when non-nil, indicates that a
18046 time-of-day should be extracted from TXT for sorting of this entry, and for
18047 the `%t' specifier in the format. When DOTIME is a string, this string is
18048 searched for a time before TXT is. NOPREFIX is a flag and indicates that
18049 only the correctly processes TXT should be returned - this is used by
18050 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
18051 (save-match-data
18052 ;; Diary entries sometimes have extra whitespace at the beginning
18053 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
18054 (let* ((category (or category
18055 org-category
18056 (if buffer-file-name
18057 (file-name-sans-extension
18058 (file-name-nondirectory buffer-file-name))
18059 "")))
18060 (tag (if tags (nth (1- (length tags)) tags) ""))
18061 time ; time and tag are needed for the eval of the prefix format
18062 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
18063 (time-of-day (and dotime (org-get-time-of-day ts)))
18064 stamp plain s0 s1 s2 rtn srp)
18065 (when (and dotime time-of-day org-prefix-has-time)
18066 ;; Extract starting and ending time and move them to prefix
18067 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
18068 (setq plain (string-match org-plain-time-of-day-regexp ts)))
18069 (setq s0 (match-string 0 ts)
18070 srp (and stamp (match-end 3))
18071 s1 (match-string (if plain 1 2) ts)
18072 s2 (match-string (if plain 8 (if srp 4 6)) ts))
18074 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
18075 ;; them, we might want to remove them there to avoid duplication.
18076 ;; The user can turn this off with a variable.
18077 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
18078 (string-match (concat (regexp-quote s0) " *") txt)
18079 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
18080 (= (match-beginning 0) 0)
18082 (setq txt (replace-match "" nil nil txt))))
18083 ;; Normalize the time(s) to 24 hour
18084 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
18085 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
18087 (when (and s1 (not s2) org-agenda-default-appointment-duration
18088 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
18089 (let ((m (+ (string-to-number (match-string 2 s1))
18090 (* 60 (string-to-number (match-string 1 s1)))
18091 org-agenda-default-appointment-duration))
18093 (setq h (/ m 60) m (- m (* h 60)))
18094 (setq s2 (format "%02d:%02d" h m))))
18096 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
18097 txt)
18098 ;; Tags are in the string
18099 (if (or (eq org-agenda-remove-tags t)
18100 (and org-agenda-remove-tags
18101 org-prefix-has-tag))
18102 (setq txt (replace-match "" t t txt))
18103 (setq txt (replace-match
18104 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
18105 (match-string 2 txt))
18106 t t txt))))
18108 ;; Create the final string
18109 (if noprefix
18110 (setq rtn txt)
18111 ;; Prepare the variables needed in the eval of the compiled format
18112 (setq time (cond (s2 (concat s1 "-" s2))
18113 (s1 (concat s1 "......"))
18114 (t ""))
18115 extra (or extra "")
18116 category (if (symbolp category) (symbol-name category) category))
18117 ;; Evaluate the compiled format
18118 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
18120 ;; And finally add the text properties
18121 (org-add-props rtn nil
18122 'org-category (downcase category) 'tags tags
18123 'prefix-length (- (length rtn) (length txt))
18124 'time-of-day time-of-day
18125 'txt txt
18126 'time time
18127 'extra extra
18128 'dotime dotime))))
18130 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
18131 (defvar org-agenda-sorting-strategy-selected nil)
18133 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
18134 (catch 'exit
18135 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
18136 ((and todayp (member 'today (car org-agenda-time-grid))))
18137 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
18138 ((member 'weekly (car org-agenda-time-grid)))
18139 (t (throw 'exit list)))
18140 (let* ((have (delq nil (mapcar
18141 (lambda (x) (get-text-property 1 'time-of-day x))
18142 list)))
18143 (string (nth 1 org-agenda-time-grid))
18144 (gridtimes (nth 2 org-agenda-time-grid))
18145 (req (car org-agenda-time-grid))
18146 (remove (member 'remove-match req))
18147 new time)
18148 (if (and (member 'require-timed req) (not have))
18149 ;; don't show empty grid
18150 (throw 'exit list))
18151 (while (setq time (pop gridtimes))
18152 (unless (and remove (member time have))
18153 (setq time (int-to-string time))
18154 (push (org-format-agenda-item
18155 nil string "" nil
18156 (concat (substring time 0 -2) ":" (substring time -2)))
18157 new)
18158 (put-text-property
18159 1 (length (car new)) 'face 'org-time-grid (car new))))
18160 (if (member 'time-up org-agenda-sorting-strategy-selected)
18161 (append new list)
18162 (append list new)))))
18164 (defun org-compile-prefix-format (key)
18165 "Compile the prefix format into a Lisp form that can be evaluated.
18166 The resulting form is returned and stored in the variable
18167 `org-prefix-format-compiled'."
18168 (setq org-prefix-has-time nil org-prefix-has-tag nil)
18169 (let ((s (cond
18170 ((stringp org-agenda-prefix-format)
18171 org-agenda-prefix-format)
18172 ((assq key org-agenda-prefix-format)
18173 (cdr (assq key org-agenda-prefix-format)))
18174 (t " %-12:c%?-12t% s")))
18175 (start 0)
18176 varform vars var e c f opt)
18177 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
18178 s start)
18179 (setq var (cdr (assoc (match-string 4 s)
18180 '(("c" . category) ("t" . time) ("s" . extra)
18181 ("T" . tag))))
18182 c (or (match-string 3 s) "")
18183 opt (match-beginning 1)
18184 start (1+ (match-beginning 0)))
18185 (if (equal var 'time) (setq org-prefix-has-time t))
18186 (if (equal var 'tag) (setq org-prefix-has-tag t))
18187 (setq f (concat "%" (match-string 2 s) "s"))
18188 (if opt
18189 (setq varform
18190 `(if (equal "" ,var)
18192 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
18193 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
18194 (setq s (replace-match "%s" t nil s))
18195 (push varform vars))
18196 (setq vars (nreverse vars))
18197 (setq org-prefix-format-compiled `(format ,s ,@vars))))
18199 (defun org-set-sorting-strategy (key)
18200 (if (symbolp (car org-agenda-sorting-strategy))
18201 ;; the old format
18202 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
18203 (setq org-agenda-sorting-strategy-selected
18204 (or (cdr (assq key org-agenda-sorting-strategy))
18205 (cdr (assq 'agenda org-agenda-sorting-strategy))
18206 '(time-up category-keep priority-down)))))
18208 (defun org-get-time-of-day (s &optional string mod24)
18209 "Check string S for a time of day.
18210 If found, return it as a military time number between 0 and 2400.
18211 If not found, return nil.
18212 The optional STRING argument forces conversion into a 5 character wide string
18213 HH:MM."
18214 (save-match-data
18215 (when
18217 (string-match
18218 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
18219 (string-match
18220 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
18221 (let* ((h (string-to-number (match-string 1 s)))
18222 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
18223 (ampm (if (match-end 4) (downcase (match-string 4 s))))
18224 (am-p (equal ampm "am"))
18225 (h1 (cond ((not ampm) h)
18226 ((= h 12) (if am-p 0 12))
18227 (t (+ h (if am-p 0 12)))))
18228 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
18229 (mod h1 24) h1))
18230 (t0 (+ (* 100 h2) m))
18231 (t1 (concat (if (>= h1 24) "+" " ")
18232 (if (< t0 100) "0" "")
18233 (if (< t0 10) "0" "")
18234 (int-to-string t0))))
18235 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
18237 (defun org-finalize-agenda-entries (list &optional nosort)
18238 "Sort and concatenate the agenda items."
18239 (setq list (mapcar 'org-agenda-highlight-todo list))
18240 (if nosort
18241 list
18242 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
18244 (defun org-agenda-highlight-todo (x)
18245 (let (re pl)
18246 (if (eq x 'line)
18247 (save-excursion
18248 (beginning-of-line 1)
18249 (setq re (get-text-property (point) 'org-not-done-regexp))
18250 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
18251 (and (looking-at (concat "[ \t]*\\.*" re))
18252 (add-text-properties (match-beginning 0) (match-end 0)
18253 '(face org-todo))))
18254 (setq re (concat (get-text-property 0 'org-not-done-regexp x))
18255 pl (get-text-property 0 'prefix-length x))
18256 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
18257 (add-text-properties (or (match-end 1) (match-end 0)) (match-end 0)
18258 '(face org-todo) x))
18259 x)))
18261 (defsubst org-cmp-priority (a b)
18262 "Compare the priorities of string A and B."
18263 (let ((pa (or (get-text-property 1 'priority a) 0))
18264 (pb (or (get-text-property 1 'priority b) 0)))
18265 (cond ((> pa pb) +1)
18266 ((< pa pb) -1)
18267 (t nil))))
18269 (defsubst org-cmp-category (a b)
18270 "Compare the string values of categories of strings A and B."
18271 (let ((ca (or (get-text-property 1 'org-category a) ""))
18272 (cb (or (get-text-property 1 'org-category b) "")))
18273 (cond ((string-lessp ca cb) -1)
18274 ((string-lessp cb ca) +1)
18275 (t nil))))
18277 (defsubst org-cmp-tag (a b)
18278 "Compare the string values of categories of strings A and B."
18279 (let ((ta (car (last (get-text-property 1 'tags a))))
18280 (tb (car (last (get-text-property 1 'tags b)))))
18281 (cond ((not ta) +1)
18282 ((not tb) -1)
18283 ((string-lessp ta tb) -1)
18284 ((string-lessp tb ta) +1)
18285 (t nil))))
18287 (defsubst org-cmp-time (a b)
18288 "Compare the time-of-day values of strings A and B."
18289 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
18290 (ta (or (get-text-property 1 'time-of-day a) def))
18291 (tb (or (get-text-property 1 'time-of-day b) def)))
18292 (cond ((< ta tb) -1)
18293 ((< tb ta) +1)
18294 (t nil))))
18296 (defun org-entries-lessp (a b)
18297 "Predicate for sorting agenda entries."
18298 ;; The following variables will be used when the form is evaluated.
18299 ;; So even though the compiler complains, keep them.
18300 (let* ((time-up (org-cmp-time a b))
18301 (time-down (if time-up (- time-up) nil))
18302 (priority-up (org-cmp-priority a b))
18303 (priority-down (if priority-up (- priority-up) nil))
18304 (category-up (org-cmp-category a b))
18305 (category-down (if category-up (- category-up) nil))
18306 (category-keep (if category-up +1 nil))
18307 (tag-up (org-cmp-tag a b))
18308 (tag-down (if tag-up (- tag-up) nil)))
18309 (cdr (assoc
18310 (eval (cons 'or org-agenda-sorting-strategy-selected))
18311 '((-1 . t) (1 . nil) (nil . nil))))))
18313 ;;; Agenda commands
18315 (defun org-agenda-check-type (error &rest types)
18316 "Check if agenda buffer is of allowed type.
18317 If ERROR is non-nil, throw an error, otherwise just return nil."
18318 (if (memq org-agenda-type types)
18320 (if error
18321 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
18322 nil)))
18324 (defun org-agenda-quit ()
18325 "Exit agenda by removing the window or the buffer."
18326 (interactive)
18327 (let ((buf (current-buffer)))
18328 (if (not (one-window-p)) (delete-window))
18329 (kill-buffer buf)
18330 (org-agenda-maybe-reset-markers 'force)
18331 (org-columns-remove-overlays))
18332 ;; Maybe restore the pre-agenda window configuration.
18333 (and org-agenda-restore-windows-after-quit
18334 (not (eq org-agenda-window-setup 'other-frame))
18335 org-pre-agenda-window-conf
18336 (set-window-configuration org-pre-agenda-window-conf)))
18338 (defun org-agenda-exit ()
18339 "Exit agenda by removing the window or the buffer.
18340 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
18341 Org-mode buffers visited directly by the user will not be touched."
18342 (interactive)
18343 (org-release-buffers org-agenda-new-buffers)
18344 (setq org-agenda-new-buffers nil)
18345 (org-agenda-quit))
18347 (defun org-save-all-org-buffers ()
18348 "Save all Org-mode buffers without user confirmation."
18349 (interactive)
18350 (message "Saving all Org-mode buffers...")
18351 (save-some-buffers t 'org-mode-p)
18352 (message "Saving all Org-mode buffers... done"))
18354 (defun org-agenda-redo ()
18355 "Rebuild Agenda.
18356 When this is the global TODO list, a prefix argument will be interpreted."
18357 (interactive)
18358 (let* ((org-agenda-keep-modes t)
18359 (line (org-current-line))
18360 (window-line (- line (org-current-line (window-start)))))
18361 (message "Rebuilding agenda buffer...")
18362 (eval org-agenda-redo-command)
18363 (setq org-agenda-undo-list nil
18364 org-agenda-pending-undo-list nil)
18365 (message "Rebuilding agenda buffer...done")
18366 (goto-line line)
18367 (recenter window-line)))
18369 (defun org-agenda-goto-today ()
18370 "Go to today."
18371 (interactive)
18372 (org-agenda-check-type t 'timeline 'agenda)
18373 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
18374 (cond
18375 (tdpos (goto-char tdpos))
18376 ((eq org-agenda-type 'agenda)
18377 (let* ((sd (time-to-days (current-time)))
18378 (comp (org-agenda-compute-time-span sd org-agenda-span))
18379 (org-agenda-overriding-arguments org-agenda-last-arguments))
18380 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
18381 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
18382 (org-agenda-redo)
18383 (org-agenda-find-today-or-agenda)))
18384 (t (error "Cannot find today")))))
18386 (defun org-agenda-find-today-or-agenda ()
18387 (goto-char
18388 (or (text-property-any (point-min) (point-max) 'org-today t)
18389 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
18390 (point-min))))
18392 (defun org-agenda-later (arg)
18393 "Go forward in time by thee current span.
18394 With prefix ARG, go forward that many times the current span."
18395 (interactive "p")
18396 (org-agenda-check-type t 'agenda)
18397 (let* ((span org-agenda-span)
18398 (sd org-starting-day)
18399 (greg (calendar-gregorian-from-absolute sd))
18400 greg2 nd)
18401 (cond
18402 ((eq span 'day)
18403 (setq sd (+ arg sd) nd 1))
18404 ((eq span 'week)
18405 (setq sd (+ (* 7 arg) sd) nd 7))
18406 ((eq span 'month)
18407 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
18408 sd (calendar-absolute-from-gregorian greg2))
18409 (setcar greg2 (1+ (car greg2)))
18410 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
18411 ((eq span 'year)
18412 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
18413 sd (calendar-absolute-from-gregorian greg2))
18414 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
18415 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
18416 (let ((org-agenda-overriding-arguments
18417 (list (car org-agenda-last-arguments) sd nd t)))
18418 (org-agenda-redo)
18419 (org-agenda-find-today-or-agenda))))
18421 (defun org-agenda-earlier (arg)
18422 "Go backward in time by the current span.
18423 With prefix ARG, go backward that many times the current span."
18424 (interactive "p")
18425 (org-agenda-later (- arg)))
18427 (defun org-agenda-day-view ()
18428 "Switch to daily view for agenda."
18429 (interactive)
18430 (setq org-agenda-ndays 1)
18431 (org-agenda-change-time-span 'day))
18432 (defun org-agenda-week-view ()
18433 "Switch to daily view for agenda."
18434 (interactive)
18435 (setq org-agenda-ndays 7)
18436 (org-agenda-change-time-span 'week))
18437 (defun org-agenda-month-view ()
18438 "Switch to daily view for agenda."
18439 (interactive)
18440 (org-agenda-change-time-span 'month))
18441 (defun org-agenda-year-view ()
18442 "Switch to daily view for agenda."
18443 (interactive)
18444 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
18445 (org-agenda-change-time-span 'year)
18446 (error "Abort")))
18448 (defun org-agenda-change-time-span (span)
18449 "Change the agenda view to SPAN.
18450 SPAN may be `day', `week', `month', `year'."
18451 (org-agenda-check-type t 'agenda)
18452 (if (equal org-agenda-span span)
18453 (error "Viewing span is already \"%s\"" span))
18454 (let* ((sd (or (get-text-property (point) 'day)
18455 org-starting-day))
18456 (computed (org-agenda-compute-time-span sd span))
18457 (org-agenda-overriding-arguments
18458 (list (car org-agenda-last-arguments)
18459 (car computed) (cdr computed) t)))
18460 (org-agenda-redo)
18461 (org-agenda-find-today-or-agenda))
18462 (org-agenda-set-mode-name)
18463 (message "Switched to %s view" span))
18465 (defun org-agenda-compute-time-span (sd span)
18466 "Compute starting date and number of days for agenda.
18467 SPAN may be `day', `week', `month', `year'. The return value
18468 is a cons cell with the starting date and the number of days,
18469 so that the date SD will be in that range."
18470 (let* ((greg (calendar-gregorian-from-absolute sd))
18472 (cond
18473 ((eq span 'day)
18474 (setq nd 1))
18475 ((eq span 'week)
18476 (let* ((nt (calendar-day-of-week
18477 (calendar-gregorian-from-absolute sd)))
18478 (d (if org-agenda-start-on-weekday
18479 (- nt org-agenda-start-on-weekday)
18480 0)))
18481 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
18482 (setq nd 7)))
18483 ((eq span 'month)
18484 (setq sd (calendar-absolute-from-gregorian
18485 (list (car greg) 1 (nth 2 greg)))
18486 nd (- (calendar-absolute-from-gregorian
18487 (list (1+ (car greg)) 1 (nth 2 greg)))
18488 sd)))
18489 ((eq span 'year)
18490 (setq sd (calendar-absolute-from-gregorian
18491 (list 1 1 (nth 2 greg)))
18492 nd (- (calendar-absolute-from-gregorian
18493 (list 1 1 (1+ (nth 2 greg))))
18494 sd))))
18495 (cons sd nd)))
18497 ;; FIXME: this no longer works if user make date format that starts with a blank
18498 (defun org-agenda-next-date-line (&optional arg)
18499 "Jump to the next line indicating a date in agenda buffer."
18500 (interactive "p")
18501 (org-agenda-check-type t 'agenda 'timeline)
18502 (beginning-of-line 1)
18503 (if (looking-at "^\\S-") (forward-char 1))
18504 (if (not (re-search-forward "^\\S-" nil t arg))
18505 (progn
18506 (backward-char 1)
18507 (error "No next date after this line in this buffer")))
18508 (goto-char (match-beginning 0)))
18510 (defun org-agenda-previous-date-line (&optional arg)
18511 "Jump to the previous line indicating a date in agenda buffer."
18512 (interactive "p")
18513 (org-agenda-check-type t 'agenda 'timeline)
18514 (beginning-of-line 1)
18515 (if (not (re-search-backward "^\\S-" nil t arg))
18516 (error "No previous date before this line in this buffer")))
18518 ;; Initialize the highlight
18519 (defvar org-hl (org-make-overlay 1 1))
18520 (org-overlay-put org-hl 'face 'highlight)
18522 (defun org-highlight (begin end &optional buffer)
18523 "Highlight a region with overlay."
18524 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
18525 org-hl begin end (or buffer (current-buffer))))
18527 (defun org-unhighlight ()
18528 "Detach overlay INDEX."
18529 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
18531 ;; FIXME this is currently not used.
18532 (defun org-highlight-until-next-command (beg end &optional buffer)
18533 (org-highlight beg end buffer)
18534 (add-hook 'pre-command-hook 'org-unhighlight-once))
18536 (defun org-unhighlight-once ()
18537 (remove-hook 'pre-command-hook 'org-unhighlight-once)
18538 (org-unhighlight))
18540 (defun org-agenda-follow-mode ()
18541 "Toggle follow mode in an agenda buffer."
18542 (interactive)
18543 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
18544 (org-agenda-set-mode-name)
18545 (message "Follow mode is %s"
18546 (if org-agenda-follow-mode "on" "off")))
18548 (defun org-agenda-log-mode ()
18549 "Toggle log mode in an agenda buffer."
18550 (interactive)
18551 (org-agenda-check-type t 'agenda 'timeline)
18552 (setq org-agenda-show-log (not org-agenda-show-log))
18553 (org-agenda-set-mode-name)
18554 (org-agenda-redo)
18555 (message "Log mode is %s"
18556 (if org-agenda-show-log "on" "off")))
18558 (defun org-agenda-toggle-diary ()
18559 "Toggle diary inclusion in an agenda buffer."
18560 (interactive)
18561 (org-agenda-check-type t 'agenda)
18562 (setq org-agenda-include-diary (not org-agenda-include-diary))
18563 (org-agenda-redo)
18564 (org-agenda-set-mode-name)
18565 (message "Diary inclusion turned %s"
18566 (if org-agenda-include-diary "on" "off")))
18568 (defun org-agenda-toggle-time-grid ()
18569 "Toggle time grid in an agenda buffer."
18570 (interactive)
18571 (org-agenda-check-type t 'agenda)
18572 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
18573 (org-agenda-redo)
18574 (org-agenda-set-mode-name)
18575 (message "Time-grid turned %s"
18576 (if org-agenda-use-time-grid "on" "off")))
18578 (defun org-agenda-set-mode-name ()
18579 "Set the mode name to indicate all the small mode settings."
18580 (setq mode-name
18581 (concat "Org-Agenda"
18582 (if (equal org-agenda-ndays 1) " Day" "")
18583 (if (equal org-agenda-ndays 7) " Week" "")
18584 (if org-agenda-follow-mode " Follow" "")
18585 (if org-agenda-include-diary " Diary" "")
18586 (if org-agenda-use-time-grid " Grid" "")
18587 (if org-agenda-show-log " Log" "")))
18588 (force-mode-line-update))
18590 (defun org-agenda-post-command-hook ()
18591 (and (eolp) (not (bolp)) (backward-char 1))
18592 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
18593 (if (and org-agenda-follow-mode
18594 (get-text-property (point) 'org-marker))
18595 (org-agenda-show)))
18597 (defun org-agenda-show-priority ()
18598 "Show the priority of the current item.
18599 This priority is composed of the main priority given with the [#A] cookies,
18600 and by additional input from the age of a schedules or deadline entry."
18601 (interactive)
18602 (let* ((pri (get-text-property (point-at-bol) 'priority)))
18603 (message "Priority is %d" (if pri pri -1000))))
18605 (defun org-agenda-show-tags ()
18606 "Show the tags applicable to the current item."
18607 (interactive)
18608 (let* ((tags (get-text-property (point-at-bol) 'tags)))
18609 (if tags
18610 (message "Tags are :%s:"
18611 (org-no-properties (mapconcat 'identity tags ":")))
18612 (message "No tags associated with this line"))))
18614 (defun org-agenda-goto (&optional highlight)
18615 "Go to the Org-mode file which contains the item at point."
18616 (interactive)
18617 (let* ((marker (or (get-text-property (point) 'org-marker)
18618 (org-agenda-error)))
18619 (buffer (marker-buffer marker))
18620 (pos (marker-position marker)))
18621 (switch-to-buffer-other-window buffer)
18622 (widen)
18623 (goto-char pos)
18624 (when (org-mode-p)
18625 (org-show-context 'agenda)
18626 (save-excursion
18627 (and (outline-next-heading)
18628 (org-flag-heading nil)))) ; show the next heading
18629 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
18631 (defun org-agenda-kill ()
18632 "Kill the entry or subtree belonging to the current agenda entry."
18633 (interactive)
18634 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
18635 (let* ((marker (or (get-text-property (point) 'org-marker)
18636 (org-agenda-error)))
18637 (buffer (marker-buffer marker))
18638 (pos (marker-position marker))
18639 (type (get-text-property (point) 'type))
18640 dbeg dend (n 0) conf)
18641 (org-with-remote-undo buffer
18642 (with-current-buffer buffer
18643 (save-excursion
18644 (goto-char pos)
18645 (if (and (org-mode-p) (not (member type '("sexp"))))
18646 (setq dbeg (progn (org-back-to-heading t) (point))
18647 dend (org-end-of-subtree t))
18648 (setq dbeg (point-at-bol)
18649 dend (min (point-max) (1+ (point-at-eol)))))
18650 (goto-char dbeg)
18651 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
18652 (setq conf (or (eq t org-agenda-confirm-kill)
18653 (and (numberp org-agenda-confirm-kill)
18654 (> n org-agenda-confirm-kill))))
18655 (and conf
18656 (not (y-or-n-p
18657 (format "Delete entry with %d lines in buffer \"%s\"? "
18658 n (buffer-name buffer))))
18659 (error "Abort"))
18660 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
18661 (with-current-buffer buffer (delete-region dbeg dend))
18662 (message "Agenda item and source killed"))))
18664 (defun org-agenda-archive ()
18665 "Kill the entry or subtree belonging to the current agenda entry."
18666 (interactive)
18667 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
18668 (let* ((marker (or (get-text-property (point) 'org-marker)
18669 (org-agenda-error)))
18670 (buffer (marker-buffer marker))
18671 (pos (marker-position marker)))
18672 (org-with-remote-undo buffer
18673 (with-current-buffer buffer
18674 (if (org-mode-p)
18675 (save-excursion
18676 (goto-char pos)
18677 (org-remove-subtree-entries-from-agenda)
18678 (org-back-to-heading t)
18679 (org-archive-subtree))
18680 (error "Archiving works only in Org-mode files"))))))
18682 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
18683 "Remove all lines in the agenda that correspond to a given subtree.
18684 The subtree is the one in buffer BUF, starting at BEG and ending at END.
18685 If this information is not given, the function uses the tree at point."
18686 (let ((buf (or buf (current-buffer))) m p)
18687 (save-excursion
18688 (unless (and beg end)
18689 (org-back-to-heading t)
18690 (setq beg (point))
18691 (org-end-of-subtree t)
18692 (setq end (point)))
18693 (set-buffer (get-buffer org-agenda-buffer-name))
18694 (save-excursion
18695 (goto-char (point-max))
18696 (beginning-of-line 1)
18697 (while (not (bobp))
18698 (when (and (setq m (get-text-property (point) 'org-marker))
18699 (equal buf (marker-buffer m))
18700 (setq p (marker-position m))
18701 (>= p beg)
18702 (<= p end))
18703 (let (buffer-read-only)
18704 (delete-region (point-at-bol) (1+ (point-at-eol)))))
18705 (beginning-of-line 0))))))
18707 (defun org-agenda-open-link ()
18708 "Follow the link in the current line, if any."
18709 (interactive)
18710 (let ((eol (point-at-eol)))
18711 (save-excursion
18712 (if (or (re-search-forward org-bracket-link-regexp eol t)
18713 (re-search-forward org-angle-link-re eol t)
18714 (re-search-forward org-plain-link-re eol t))
18715 (call-interactively 'org-open-at-point)
18716 (error "No link in current line")))))
18718 (defun org-agenda-switch-to (&optional delete-other-windows)
18719 "Go to the Org-mode file which contains the item at point."
18720 (interactive)
18721 (let* ((marker (or (get-text-property (point) 'org-marker)
18722 (org-agenda-error)))
18723 (buffer (marker-buffer marker))
18724 (pos (marker-position marker)))
18725 (switch-to-buffer buffer)
18726 (and delete-other-windows (delete-other-windows))
18727 (widen)
18728 (goto-char pos)
18729 (when (org-mode-p)
18730 (org-show-context 'agenda)
18731 (save-excursion
18732 (and (outline-next-heading)
18733 (org-flag-heading nil)))))) ; show the next heading
18735 (defun org-agenda-goto-mouse (ev)
18736 "Go to the Org-mode file which contains the item at the mouse click."
18737 (interactive "e")
18738 (mouse-set-point ev)
18739 (org-agenda-goto))
18741 (defun org-agenda-show ()
18742 "Display the Org-mode file which contains the item at point."
18743 (interactive)
18744 (let ((win (selected-window)))
18745 (org-agenda-goto t)
18746 (select-window win)))
18748 (defun org-agenda-recenter (arg)
18749 "Display the Org-mode file which contains the item at point and recenter."
18750 (interactive "P")
18751 (let ((win (selected-window)))
18752 (org-agenda-goto t)
18753 (recenter arg)
18754 (select-window win)))
18756 (defun org-agenda-show-mouse (ev)
18757 "Display the Org-mode file which contains the item at the mouse click."
18758 (interactive "e")
18759 (mouse-set-point ev)
18760 (org-agenda-show))
18762 (defun org-agenda-check-no-diary ()
18763 "Check if the entry is a diary link and abort if yes."
18764 (if (get-text-property (point) 'org-agenda-diary-link)
18765 (org-agenda-error)))
18767 (defun org-agenda-error ()
18768 (error "Command not allowed in this line"))
18770 (defun org-agenda-tree-to-indirect-buffer ()
18771 "Show the subtree corresponding to the current entry in an indirect buffer.
18772 This calls the command `org-tree-to-indirect-buffer' from the original
18773 Org-mode buffer.
18774 With numerical prefix arg ARG, go up to this level and then take that tree.
18775 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
18776 dedicated frame)."
18777 (interactive)
18778 (org-agenda-check-no-diary)
18779 (let* ((marker (or (get-text-property (point) 'org-marker)
18780 (org-agenda-error)))
18781 (buffer (marker-buffer marker))
18782 (pos (marker-position marker)))
18783 (with-current-buffer buffer
18784 (save-excursion
18785 (goto-char pos)
18786 (call-interactively 'org-tree-to-indirect-buffer)))))
18788 (defvar org-last-heading-marker (make-marker)
18789 "Marker pointing to the headline that last changed its TODO state
18790 by a remote command from the agenda.")
18792 (defun org-agenda-todo-nextset ()
18793 "Switch TODO entry to next sequence."
18794 (interactive)
18795 (org-agenda-todo 'nextset))
18797 (defun org-agenda-todo-previousset ()
18798 "Switch TODO entry to previous sequence."
18799 (interactive)
18800 (org-agenda-todo 'previousset))
18802 (defun org-agenda-todo (&optional arg)
18803 "Cycle TODO state of line at point, also in Org-mode file.
18804 This changes the line at point, all other lines in the agenda referring to
18805 the same tree node, and the headline of the tree node in the Org-mode file."
18806 (interactive "P")
18807 (org-agenda-check-no-diary)
18808 (let* ((col (current-column))
18809 (marker (or (get-text-property (point) 'org-marker)
18810 (org-agenda-error)))
18811 (buffer (marker-buffer marker))
18812 (pos (marker-position marker))
18813 (hdmarker (get-text-property (point) 'org-hd-marker))
18814 (buffer-read-only nil)
18815 newhead)
18816 (org-with-remote-undo buffer
18817 (with-current-buffer buffer
18818 (widen)
18819 (goto-char pos)
18820 (org-show-context 'agenda)
18821 (save-excursion
18822 (and (outline-next-heading)
18823 (org-flag-heading nil))) ; show the next heading
18824 (org-todo arg)
18825 (and (bolp) (forward-char 1))
18826 (setq newhead (org-get-heading))
18827 (save-excursion
18828 (org-back-to-heading)
18829 (move-marker org-last-heading-marker (point))))
18830 (beginning-of-line 1)
18831 (save-excursion
18832 (org-agenda-change-all-lines newhead hdmarker 'fixface))
18833 (move-to-column col))))
18835 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
18836 "Change all lines in the agenda buffer which match HDMARKER.
18837 The new content of the line will be NEWHEAD (as modified by
18838 `org-format-agenda-item'). HDMARKER is checked with
18839 `equal' against all `org-hd-marker' text properties in the file.
18840 If FIXFACE is non-nil, the face of each item is modified acording to
18841 the new TODO state."
18842 (let* ((buffer-read-only nil)
18843 props m pl undone-face done-face finish new dotime cat tags)
18844 (save-excursion
18845 (goto-char (point-max))
18846 (beginning-of-line 1)
18847 (while (not finish)
18848 (setq finish (bobp))
18849 (when (and (setq m (get-text-property (point) 'org-hd-marker))
18850 (equal m hdmarker))
18851 (setq props (text-properties-at (point))
18852 dotime (get-text-property (point) 'dotime)
18853 cat (get-text-property (point) 'org-category)
18854 tags (get-text-property (point) 'tags)
18855 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
18856 pl (get-text-property (point) 'prefix-length)
18857 undone-face (get-text-property (point) 'undone-face)
18858 done-face (get-text-property (point) 'done-face))
18859 (move-to-column pl)
18860 (cond
18861 ((equal new "")
18862 (beginning-of-line 1)
18863 (and (looking-at ".*\n?") (replace-match "")))
18864 ((looking-at ".*")
18865 (replace-match new t t)
18866 (beginning-of-line 1)
18867 (add-text-properties (point-at-bol) (point-at-eol) props)
18868 (when fixface
18869 (add-text-properties
18870 (point-at-bol) (point-at-eol)
18871 (list 'face
18872 (if org-last-todo-state-is-todo
18873 undone-face done-face))))
18874 (org-agenda-highlight-todo 'line)
18875 (beginning-of-line 1))
18876 (t (error "Line update did not work"))))
18877 (beginning-of-line 0)))
18878 (org-finalize-agenda)))
18880 ;; FIXME: allow negative value for org-agenda-align-tags-to-column
18881 ;; See the code in set-tags for the way to do this.
18882 (defun org-agenda-align-tags (&optional line)
18883 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
18884 (let ((buffer-read-only))
18885 (save-excursion
18886 (goto-char (if line (point-at-bol) (point-min)))
18887 (while (re-search-forward (org-re "\\([ \t]+\\):[[:alnum:]_@:]+:[ \t]*$")
18888 (if line (point-at-eol) nil) t)
18889 (delete-region (match-beginning 1) (match-end 1))
18890 (goto-char (match-beginning 1))
18891 (insert (org-add-props
18892 (make-string (max 1 (- org-agenda-align-tags-to-column
18893 (current-column))) ?\ )
18894 (text-properties-at (point))))))))
18896 (defun org-agenda-priority-up ()
18897 "Increase the priority of line at point, also in Org-mode file."
18898 (interactive)
18899 (org-agenda-priority 'up))
18901 (defun org-agenda-priority-down ()
18902 "Decrease the priority of line at point, also in Org-mode file."
18903 (interactive)
18904 (org-agenda-priority 'down))
18906 (defun org-agenda-priority (&optional force-direction)
18907 "Set the priority of line at point, also in Org-mode file.
18908 This changes the line at point, all other lines in the agenda referring to
18909 the same tree node, and the headline of the tree node in the Org-mode file."
18910 (interactive)
18911 (org-agenda-check-no-diary)
18912 (let* ((marker (or (get-text-property (point) 'org-marker)
18913 (org-agenda-error)))
18914 (buffer (marker-buffer marker))
18915 (pos (marker-position marker))
18916 (hdmarker (get-text-property (point) 'org-hd-marker))
18917 (buffer-read-only nil)
18918 newhead)
18919 (org-with-remote-undo buffer
18920 (with-current-buffer buffer
18921 (widen)
18922 (goto-char pos)
18923 (org-show-context 'agenda)
18924 (save-excursion
18925 (and (outline-next-heading)
18926 (org-flag-heading nil))) ; show the next heading
18927 (funcall 'org-priority force-direction)
18928 (end-of-line 1)
18929 (setq newhead (org-get-heading)))
18930 (org-agenda-change-all-lines newhead hdmarker)
18931 (beginning-of-line 1))))
18933 (defun org-get-tags-at (&optional pos)
18934 "Get a list of all headline tags applicable at POS.
18935 POS defaults to point. If tags are inherited, the list contains
18936 the targets in the same sequence as the headlines appear, i.e.
18937 the tags of the current headline come last."
18938 (interactive)
18939 (let (tags)
18940 (save-excursion
18941 (save-restriction
18942 (widen)
18943 (goto-char (or pos (point)))
18944 (save-match-data
18945 (org-back-to-heading t)
18946 (condition-case nil
18947 (while t
18948 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
18949 (setq tags (append (org-split-string
18950 (org-match-string-no-properties 1) ":")
18951 tags)))
18952 (or org-use-tag-inheritance (error ""))
18953 (org-up-heading-all 1))
18954 (error nil))))
18955 tags)))
18957 ;; FIXME: should fix the tags property of the agenda line.
18958 (defun org-agenda-set-tags ()
18959 "Set tags for the current headline."
18960 (interactive)
18961 (org-agenda-check-no-diary)
18962 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
18963 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
18964 (org-agenda-error)))
18965 (buffer (marker-buffer hdmarker))
18966 (pos (marker-position hdmarker))
18967 (buffer-read-only nil)
18968 newhead)
18969 (org-with-remote-undo buffer
18970 (with-current-buffer buffer
18971 (widen)
18972 (goto-char pos)
18973 (save-excursion
18974 (org-show-context 'agenda))
18975 (save-excursion
18976 (and (outline-next-heading)
18977 (org-flag-heading nil))) ; show the next heading
18978 (goto-char pos)
18979 (call-interactively 'org-set-tags)
18980 (end-of-line 1)
18981 (setq newhead (org-get-heading)))
18982 (org-agenda-change-all-lines newhead hdmarker)
18983 (beginning-of-line 1))))
18985 (defun org-agenda-toggle-archive-tag ()
18986 "Toggle the archive tag for the current entry."
18987 (interactive)
18988 (org-agenda-check-no-diary)
18989 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
18990 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
18991 (org-agenda-error)))
18992 (buffer (marker-buffer hdmarker))
18993 (pos (marker-position hdmarker))
18994 (buffer-read-only nil)
18995 newhead)
18996 (org-with-remote-undo buffer
18997 (with-current-buffer buffer
18998 (widen)
18999 (goto-char pos)
19000 (org-show-context 'agenda)
19001 (save-excursion
19002 (and (outline-next-heading)
19003 (org-flag-heading nil))) ; show the next heading
19004 (call-interactively 'org-toggle-archive-tag)
19005 (end-of-line 1)
19006 (setq newhead (org-get-heading)))
19007 (org-agenda-change-all-lines newhead hdmarker)
19008 (beginning-of-line 1))))
19010 (defun org-agenda-date-later (arg &optional what)
19011 "Change the date of this item to one day later."
19012 (interactive "p")
19013 (org-agenda-check-type t 'agenda 'timeline)
19014 (org-agenda-check-no-diary)
19015 (let* ((marker (or (get-text-property (point) 'org-marker)
19016 (org-agenda-error)))
19017 (buffer (marker-buffer marker))
19018 (pos (marker-position marker)))
19019 (org-with-remote-undo buffer
19020 (with-current-buffer buffer
19021 (widen)
19022 (goto-char pos)
19023 (if (not (org-at-timestamp-p))
19024 (error "Cannot find time stamp"))
19025 (org-timestamp-change arg (or what 'day)))
19026 (org-agenda-show-new-time marker org-last-changed-timestamp))
19027 (message "Time stamp changed to %s" org-last-changed-timestamp)))
19029 (defun org-agenda-date-earlier (arg &optional what)
19030 "Change the date of this item to one day earlier."
19031 (interactive "p")
19032 (org-agenda-date-later (- arg) what))
19034 (defun org-agenda-show-new-time (marker stamp)
19035 "Show new date stamp via text properties."
19036 ;; We use text properties to make this undoable
19037 (let ((buffer-read-only nil))
19038 (setq stamp (concat " => " stamp))
19039 (save-excursion
19040 (goto-char (point-max))
19041 (while (not (bobp))
19042 (when (equal marker (get-text-property (point) 'org-marker))
19043 (move-to-column (- (window-width) (length stamp)) t)
19044 (if (featurep 'xemacs)
19045 ;; Use `duplicable' property to trigger undo recording
19046 (let ((ex (make-extent nil nil))
19047 (gl (make-glyph stamp)))
19048 (set-glyph-face gl 'secondary-selection)
19049 (set-extent-properties
19050 ex (list 'invisible t 'end-glyph gl 'duplicable t))
19051 (insert-extent ex (1- (point)) (point-at-eol)))
19052 (add-text-properties
19053 (1- (point)) (point-at-eol)
19054 (list 'display (org-add-props stamp nil
19055 'face 'secondary-selection))))
19056 (beginning-of-line 1))
19057 (beginning-of-line 0)))))
19059 (defun org-agenda-date-prompt (arg)
19060 "Change the date of this item. Date is prompted for, with default today.
19061 The prefix ARG is passed to the `org-time-stamp' command and can therefore
19062 be used to request time specification in the time stamp."
19063 (interactive "P")
19064 (org-agenda-check-type t 'agenda 'timeline)
19065 (org-agenda-check-no-diary)
19066 (let* ((marker (or (get-text-property (point) 'org-marker)
19067 (org-agenda-error)))
19068 (buffer (marker-buffer marker))
19069 (pos (marker-position marker)))
19070 (org-with-remote-undo buffer
19071 (with-current-buffer buffer
19072 (widen)
19073 (goto-char pos)
19074 (if (not (org-at-timestamp-p))
19075 (error "Cannot find time stamp"))
19076 (org-time-stamp arg)
19077 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
19079 (defun org-agenda-schedule (arg)
19080 "Schedule the item at point."
19081 (interactive "P")
19082 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19083 (org-agenda-check-no-diary)
19084 (let* ((marker (or (get-text-property (point) 'org-marker)
19085 (org-agenda-error)))
19086 (buffer (marker-buffer marker))
19087 (pos (marker-position marker))
19088 (org-insert-labeled-timestamps-at-point nil)
19090 (org-with-remote-undo buffer
19091 (with-current-buffer buffer
19092 (widen)
19093 (goto-char pos)
19094 (setq ts (org-schedule))
19095 (message "Item scheduled for %s" ts)))))
19097 (defun org-agenda-deadline (arg)
19098 "Schedule the item at point."
19099 (interactive "P")
19100 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
19101 (org-agenda-check-no-diary)
19102 (let* ((marker (or (get-text-property (point) 'org-marker)
19103 (org-agenda-error)))
19104 (buffer (marker-buffer marker))
19105 (pos (marker-position marker))
19106 (org-insert-labeled-timestamps-at-point nil)
19108 (org-with-remote-undo buffer
19109 (with-current-buffer buffer
19110 (widen)
19111 (goto-char pos)
19112 (setq ts (org-deadline))
19113 (message "Deadline for this item set to %s" ts)))))
19115 (defun org-get-heading ()
19116 "Return the heading of the current entry, without the stars."
19117 (save-excursion
19118 (org-back-to-heading t)
19119 (if (looking-at "\\*+[ \t]+\\([^\r\n]*\\)") (match-string 1) "")))
19121 (defun org-agenda-clock-in (&optional arg)
19122 "Start the clock on the currently selected item."
19123 (interactive "P")
19124 (org-agenda-check-no-diary)
19125 (let* ((marker (or (get-text-property (point) 'org-marker)
19126 (org-agenda-error)))
19127 (pos (marker-position marker)))
19128 (org-with-remote-undo (marker-buffer marker)
19129 (with-current-buffer (marker-buffer marker)
19130 (widen)
19131 (goto-char pos)
19132 (org-clock-in)))))
19134 (defun org-agenda-clock-out (&optional arg)
19135 "Stop the currently running clock."
19136 (interactive "P")
19137 (unless (marker-buffer org-clock-marker)
19138 (error "No running clock"))
19139 (org-with-remote-undo (marker-buffer org-clock-marker)
19140 (org-clock-out)))
19142 (defun org-agenda-clock-cancel (&optional arg)
19143 "Cancel the currently running clock."
19144 (interactive "P")
19145 (unless (marker-buffer org-clock-marker)
19146 (error "No running clock"))
19147 (org-with-remote-undo (marker-buffer org-clock-marker)
19148 (org-clock-cancel)))
19150 (defun org-agenda-diary-entry ()
19151 "Make a diary entry, like the `i' command from the calendar.
19152 All the standard commands work: block, weekly etc."
19153 (interactive)
19154 (org-agenda-check-type t 'agenda 'timeline)
19155 (require 'diary-lib)
19156 (let* ((char (progn
19157 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
19158 (read-char-exclusive)))
19159 (cmd (cdr (assoc char
19160 '((?d . insert-diary-entry)
19161 (?w . insert-weekly-diary-entry)
19162 (?m . insert-monthly-diary-entry)
19163 (?y . insert-yearly-diary-entry)
19164 (?a . insert-anniversary-diary-entry)
19165 (?b . insert-block-diary-entry)
19166 (?c . insert-cyclic-diary-entry)))))
19167 (oldf (symbol-function 'calendar-cursor-to-date))
19168 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
19169 (point (point))
19170 (mark (or (mark t) (point))))
19171 (unless cmd
19172 (error "No command associated with <%c>" char))
19173 (unless (and (get-text-property point 'day)
19174 (or (not (equal ?b char))
19175 (get-text-property mark 'day)))
19176 (error "Don't know which date to use for diary entry"))
19177 ;; We implement this by hacking the `calendar-cursor-to-date' function
19178 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
19179 (let ((calendar-mark-ring
19180 (list (calendar-gregorian-from-absolute
19181 (or (get-text-property mark 'day)
19182 (get-text-property point 'day))))))
19183 (unwind-protect
19184 (progn
19185 (fset 'calendar-cursor-to-date
19186 (lambda (&optional error)
19187 (calendar-gregorian-from-absolute
19188 (get-text-property point 'day))))
19189 (call-interactively cmd))
19190 (fset 'calendar-cursor-to-date oldf)))))
19193 (defun org-agenda-execute-calendar-command (cmd)
19194 "Execute a calendar command from the agenda, with the date associated to
19195 the cursor position."
19196 (org-agenda-check-type t 'agenda 'timeline)
19197 (require 'diary-lib)
19198 (unless (get-text-property (point) 'day)
19199 (error "Don't know which date to use for calendar command"))
19200 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
19201 (point (point))
19202 (date (calendar-gregorian-from-absolute
19203 (get-text-property point 'day)))
19204 ;; the following 3 vars are needed in the calendar
19205 (displayed-day (extract-calendar-day date))
19206 (displayed-month (extract-calendar-month date))
19207 (displayed-year (extract-calendar-year date)))
19208 (unwind-protect
19209 (progn
19210 (fset 'calendar-cursor-to-date
19211 (lambda (&optional error)
19212 (calendar-gregorian-from-absolute
19213 (get-text-property point 'day))))
19214 (call-interactively cmd))
19215 (fset 'calendar-cursor-to-date oldf))))
19217 (defun org-agenda-phases-of-moon ()
19218 "Display the phases of the moon for the 3 months around the cursor date."
19219 (interactive)
19220 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
19222 (defun org-agenda-holidays ()
19223 "Display the holidays for the 3 months around the cursor date."
19224 (interactive)
19225 (org-agenda-execute-calendar-command 'list-calendar-holidays))
19227 (defun org-agenda-sunrise-sunset (arg)
19228 "Display sunrise and sunset for the cursor date.
19229 Latitude and longitude can be specified with the variables
19230 `calendar-latitude' and `calendar-longitude'. When called with prefix
19231 argument, latitude and longitude will be prompted for."
19232 (interactive "P")
19233 (let ((calendar-longitude (if arg nil calendar-longitude))
19234 (calendar-latitude (if arg nil calendar-latitude))
19235 (calendar-location-name
19236 (if arg "the given coordinates" calendar-location-name)))
19237 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
19239 (defun org-agenda-goto-calendar ()
19240 "Open the Emacs calendar with the date at the cursor."
19241 (interactive)
19242 (org-agenda-check-type t 'agenda 'timeline)
19243 (let* ((day (or (get-text-property (point) 'day)
19244 (error "Don't know which date to open in calendar")))
19245 (date (calendar-gregorian-from-absolute day))
19246 (calendar-move-hook nil)
19247 (view-calendar-holidays-initially nil)
19248 (view-diary-entries-initially nil))
19249 (calendar)
19250 (calendar-goto-date date)))
19252 (defun org-calendar-goto-agenda ()
19253 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
19254 This is a command that has to be installed in `calendar-mode-map'."
19255 (interactive)
19256 (org-agenda-list nil (calendar-absolute-from-gregorian
19257 (calendar-cursor-to-date))
19258 nil))
19260 (defun org-agenda-convert-date ()
19261 (interactive)
19262 (org-agenda-check-type t 'agenda 'timeline)
19263 (let ((day (get-text-property (point) 'day))
19264 date s)
19265 (unless day
19266 (error "Don't know which date to convert"))
19267 (setq date (calendar-gregorian-from-absolute day))
19268 (setq s (concat
19269 "Gregorian: " (calendar-date-string date) "\n"
19270 "ISO: " (calendar-iso-date-string date) "\n"
19271 "Day of Yr: " (calendar-day-of-year-string date) "\n"
19272 "Julian: " (calendar-julian-date-string date) "\n"
19273 "Astron. JD: " (calendar-astro-date-string date)
19274 " (Julian date number at noon UTC)\n"
19275 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
19276 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
19277 "French: " (calendar-french-date-string date) "\n"
19278 "Mayan: " (calendar-mayan-date-string date) "\n"
19279 "Coptic: " (calendar-coptic-date-string date) "\n"
19280 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
19281 "Persian: " (calendar-persian-date-string date) "\n"
19282 "Chinese: " (calendar-chinese-date-string date) "\n"))
19283 (with-output-to-temp-buffer "*Dates*"
19284 (princ s))
19285 (if (fboundp 'fit-window-to-buffer)
19286 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
19289 ;;;; Embedded LaTeX
19291 (defvar org-cdlatex-mode-map (make-sparse-keymap)
19292 "Keymap for the minor `org-cdlatex-mode'.")
19294 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
19295 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
19296 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
19297 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
19298 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
19300 (defvar org-cdlatex-texmathp-advice-is-done nil
19301 "Flag remembering if we have applied the advice to texmathp already.")
19303 (define-minor-mode org-cdlatex-mode
19304 "Toggle the minor `org-cdlatex-mode'.
19305 This mode supports entering LaTeX environment and math in LaTeX fragments
19306 in Org-mode.
19307 \\{org-cdlatex-mode-map}"
19308 nil " OCDL" nil
19309 (when org-cdlatex-mode (require 'cdlatex))
19310 (unless org-cdlatex-texmathp-advice-is-done
19311 (setq org-cdlatex-texmathp-advice-is-done t)
19312 (defadvice texmathp (around org-math-always-on activate)
19313 "Always return t in org-mode buffers.
19314 This is because we want to insert math symbols without dollars even outside
19315 the LaTeX math segments. If Orgmode thinks that point is actually inside
19316 en embedded LaTeX fragement, let texmathp do its job.
19317 \\[org-cdlatex-mode-map]"
19318 (interactive)
19319 (let (p)
19320 (cond
19321 ((not (org-mode-p)) ad-do-it)
19322 ((eq this-command 'cdlatex-math-symbol)
19323 (setq ad-return-value t
19324 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
19326 (let ((p (org-inside-LaTeX-fragment-p)))
19327 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
19328 (setq ad-return-value t
19329 texmathp-why '("Org-mode embedded math" . 0))
19330 (if p ad-do-it)))))))))
19332 (defun turn-on-org-cdlatex ()
19333 "Unconditionally turn on `org-cdlatex-mode'."
19334 (org-cdlatex-mode 1))
19336 (defun org-inside-LaTeX-fragment-p ()
19337 "Test if point is inside a LaTeX fragment.
19338 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19339 sequence appearing also before point.
19340 Even though the matchers for math are configurable, this function assumes
19341 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19342 delimiters are skipped when they have been removed by customization.
19343 The return value is nil, or a cons cell with the delimiter and
19344 and the position of this delimiter.
19346 This function does a reasonably good job, but can locally be fooled by
19347 for example currency specifications. For example it will assume being in
19348 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19349 fragments that are properly closed, but during editing, we have to live
19350 with the uncertainty caused by missing closing delimiters. This function
19351 looks only before point, not after."
19352 (catch 'exit
19353 (let ((pos (point))
19354 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19355 (lim (progn
19356 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19357 (point)))
19358 dd-on str (start 0) m re)
19359 (goto-char pos)
19360 (when dodollar
19361 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19362 re (nth 1 (assoc "$" org-latex-regexps)))
19363 (while (string-match re str start)
19364 (cond
19365 ((= (match-end 0) (length str))
19366 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19367 ((= (match-end 0) (- (length str) 5))
19368 (throw 'exit nil))
19369 (t (setq start (match-end 0))))))
19370 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19371 (goto-char pos)
19372 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19373 (and (match-beginning 2) (throw 'exit nil))
19374 ;; count $$
19375 (while (re-search-backward "\\$\\$" lim t)
19376 (setq dd-on (not dd-on)))
19377 (goto-char pos)
19378 (if dd-on (cons "$$" m))))))
19381 (defun org-try-cdlatex-tab ()
19382 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
19383 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
19384 - inside a LaTeX fragment, or
19385 - after the first word in a line, where an abbreviation expansion could
19386 insert a LaTeX environment."
19387 (when org-cdlatex-mode
19388 (cond
19389 ((save-excursion
19390 (skip-chars-backward "a-zA-Z0-9*")
19391 (skip-chars-backward " \t")
19392 (bolp))
19393 (cdlatex-tab) t)
19394 ((org-inside-LaTeX-fragment-p)
19395 (cdlatex-tab) t)
19396 (t nil))))
19398 (defun org-cdlatex-underscore-caret (&optional arg)
19399 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19400 Revert to the normal definition outside of these fragments."
19401 (interactive "P")
19402 (if (org-inside-LaTeX-fragment-p)
19403 (call-interactively 'cdlatex-sub-superscript)
19404 (let (org-cdlatex-mode)
19405 (call-interactively (key-binding (vector last-input-event))))))
19407 (defun org-cdlatex-math-modify (&optional arg)
19408 "Execute `cdlatex-math-modify' in LaTeX fragments.
19409 Revert to the normal definition outside of these fragments."
19410 (interactive "P")
19411 (if (org-inside-LaTeX-fragment-p)
19412 (call-interactively 'cdlatex-math-modify)
19413 (let (org-cdlatex-mode)
19414 (call-interactively (key-binding (vector last-input-event))))))
19416 (defvar org-latex-fragment-image-overlays nil
19417 "List of overlays carrying the images of latex fragments.")
19418 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
19420 (defun org-remove-latex-fragment-image-overlays ()
19421 "Remove all overlays with LaTeX fragment images in current buffer."
19422 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
19423 (setq org-latex-fragment-image-overlays nil))
19425 (defun org-preview-latex-fragment (&optional subtree)
19426 "Preview the LaTeX fragment at point, or all locally or globally.
19427 If the cursor is in a LaTeX fragment, create the image and overlay
19428 it over the source code. If there is no fragment at point, display
19429 all fragments in the current text, from one headline to the next. With
19430 prefix SUBTREE, display all fragments in the current subtree. With a
19431 double prefix `C-u C-u', or when the cursor is before the first headline,
19432 display all fragments in the buffer.
19433 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
19434 (interactive "P")
19435 (org-remove-latex-fragment-image-overlays)
19436 (save-excursion
19437 (save-restriction
19438 (let (beg end at msg)
19439 (cond
19440 ((or (equal subtree '(16))
19441 (not (save-excursion
19442 (re-search-backward (concat "^" outline-regexp) nil t))))
19443 (setq beg (point-min) end (point-max)
19444 msg "Creating images for buffer...%s"))
19445 ((equal subtree '(4))
19446 (org-back-to-heading)
19447 (setq beg (point) end (org-end-of-subtree t)
19448 msg "Creating images for subtree...%s"))
19450 (if (setq at (org-inside-LaTeX-fragment-p))
19451 (goto-char (max (point-min) (- (cdr at) 2)))
19452 (org-back-to-heading))
19453 (setq beg (point) end (progn (outline-next-heading) (point))
19454 msg (if at "Creating image...%s"
19455 "Creating images for entry...%s"))))
19456 (message msg "")
19457 (narrow-to-region beg end)
19458 (goto-char beg)
19459 (org-format-latex
19460 (concat "ltxpng/" (file-name-sans-extension
19461 (file-name-nondirectory
19462 buffer-file-name)))
19463 default-directory 'overlays msg at 'forbuffer)
19464 (message msg "done. Use `C-c C-c' to remove images.")))))
19466 (defvar org-latex-regexps
19467 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
19468 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
19469 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
19470 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
19471 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
19472 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
19473 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
19474 "Regular expressions for matching embedded LaTeX.")
19476 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
19477 "Replace LaTeX fragments with links to an image, and produce images."
19478 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19479 (let* ((prefixnodir (file-name-nondirectory prefix))
19480 (absprefix (expand-file-name prefix dir))
19481 (todir (file-name-directory absprefix))
19482 (opt org-format-latex-options)
19483 (matchers (plist-get opt :matchers))
19484 (re-list org-latex-regexps)
19485 (cnt 0) txt link beg end re e checkdir
19486 m n block linkfile movefile ov)
19487 ;; Check if there are old images files with this prefix, and remove them
19488 (when (file-directory-p todir)
19489 (mapc 'delete-file
19490 (directory-files
19491 todir 'full
19492 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
19493 ;; Check the different regular expressions
19494 (while (setq e (pop re-list))
19495 (setq m (car e) re (nth 1 e) n (nth 2 e)
19496 block (if (nth 3 e) "\n\n" ""))
19497 (when (member m matchers)
19498 (goto-char (point-min))
19499 (while (re-search-forward re nil t)
19500 (when (or (not at) (equal (cdr at) (match-beginning n)))
19501 (setq txt (match-string n)
19502 beg (match-beginning n) end (match-end n)
19503 cnt (1+ cnt)
19504 linkfile (format "%s_%04d.png" prefix cnt)
19505 movefile (format "%s_%04d.png" absprefix cnt)
19506 link (concat block "[[file:" linkfile "]]" block))
19507 (if msg (message msg cnt))
19508 (goto-char beg)
19509 (unless checkdir ; make sure the directory exists
19510 (setq checkdir t)
19511 (or (file-directory-p todir) (make-directory todir)))
19512 (org-create-formula-image
19513 txt movefile opt forbuffer)
19514 (if overlays
19515 (progn
19516 (setq ov (org-make-overlay beg end))
19517 (if (featurep 'xemacs)
19518 (progn
19519 (org-overlay-put ov 'invisible t)
19520 (org-overlay-put
19521 ov 'end-glyph
19522 (make-glyph (vector 'png :file movefile))))
19523 (org-overlay-put
19524 ov 'display
19525 (list 'image :type 'png :file movefile :ascent 'center)))
19526 (push ov org-latex-fragment-image-overlays)
19527 (goto-char end))
19528 (delete-region beg end)
19529 (insert link))))))))
19531 ;; This function borrows from Ganesh Swami's latex2png.el
19532 (defun org-create-formula-image (string tofile options buffer)
19533 (let* ((tmpdir (if (featurep 'xemacs)
19534 (temp-directory)
19535 temporary-file-directory))
19536 (texfilebase (make-temp-name
19537 (expand-file-name "orgtex" tmpdir)))
19538 (texfile (concat texfilebase ".tex"))
19539 (dvifile (concat texfilebase ".dvi"))
19540 (pngfile (concat texfilebase ".png"))
19541 (fnh (face-attribute 'default :height nil))
19542 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19543 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
19544 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19545 "Black"))
19546 (bg (or (plist-get options (if buffer :background :html-background))
19547 "Transparent")))
19548 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
19549 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
19550 (with-temp-file texfile
19551 (insert org-format-latex-header
19552 "\n\\begin{document}\n" string "\n\\end{document}\n"))
19553 (let ((dir default-directory))
19554 (condition-case nil
19555 (progn
19556 (cd tmpdir)
19557 (call-process "latex" nil nil nil texfile))
19558 (error nil))
19559 (cd dir))
19560 (if (not (file-exists-p dvifile))
19561 (progn (message "Failed to create dvi file from %s" texfile) nil)
19562 (call-process "dvipng" nil nil nil
19563 "-E" "-fg" fg "-bg" bg
19564 "-D" dpi
19565 ;;"-x" scale "-y" scale
19566 "-T" "tight"
19567 "-o" pngfile
19568 dvifile)
19569 (if (not (file-exists-p pngfile))
19570 (progn (message "Failed to create png file from %s" texfile) nil)
19571 ;; Use the requested file name and clean up
19572 (copy-file pngfile tofile 'replace)
19573 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
19574 (delete-file (concat texfilebase e)))
19575 pngfile))))
19577 (defun org-dvipng-color (attr)
19578 "Return an rgb color specification for dvipng."
19579 (apply 'format "rgb %s %s %s"
19580 (mapcar 'org-normalize-color
19581 (color-values (face-attribute 'default attr nil)))))
19583 (defun org-normalize-color (value)
19584 "Return string to be used as color value for an RGB component."
19585 (format "%g" (/ value 65535.0)))
19587 ;;;; Exporting
19589 ;;; Variables, constants, and parameter plists
19591 (defconst org-level-max 20)
19593 (defvar org-export-html-preamble nil
19594 "Preamble, to be inserted just after <body>. Set by publishing functions.")
19595 (defvar org-export-html-postamble nil
19596 "Preamble, to be inserted just before </body>. Set by publishing functions.")
19597 (defvar org-export-html-auto-preamble t
19598 "Should default preamble be inserted? Set by publishing functions.")
19599 (defvar org-export-html-auto-postamble t
19600 "Should default postamble be inserted? Set by publishing functions.")
19601 (defvar org-current-export-file nil) ; dynamically scoped parameter
19602 (defvar org-current-export-dir nil) ; dynamically scoped parameter
19605 (defconst org-export-plist-vars
19606 '((:language . org-export-default-language)
19607 (:customtime . org-display-custom-times)
19608 (:headline-levels . org-export-headline-levels)
19609 (:section-numbers . org-export-with-section-numbers)
19610 (:table-of-contents . org-export-with-toc)
19611 (:preserve-breaks . org-export-preserve-breaks)
19612 (:archived-trees . org-export-with-archived-trees)
19613 (:emphasize . org-export-with-emphasize)
19614 (:sub-superscript . org-export-with-sub-superscripts)
19615 (:footnotes . org-export-with-footnotes)
19616 (:property-drawer . org-export-with-property-drawer)
19617 (:TeX-macros . org-export-with-TeX-macros)
19618 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
19619 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
19620 (:fixed-width . org-export-with-fixed-width)
19621 (:timestamps . org-export-with-timestamps)
19622 (:tables . org-export-with-tables)
19623 (:table-auto-headline . org-export-highlight-first-table-line)
19624 (:style . org-export-html-style)
19625 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
19626 (:convert-org-links . org-export-html-link-org-files-as-html)
19627 (:inline-images . org-export-html-inline-images)
19628 (:expand-quoted-html . org-export-html-expand)
19629 (:timestamp . org-export-html-with-timestamp)
19630 (:publishing-directory . org-export-publishing-directory)
19631 (:preamble . org-export-html-preamble)
19632 (:postamble . org-export-html-postamble)
19633 (:auto-preamble . org-export-html-auto-preamble)
19634 (:auto-postamble . org-export-html-auto-postamble)
19635 (:author . user-full-name)
19636 (:email . user-mail-address)))
19638 (defun org-default-export-plist ()
19639 "Return the property list with default settings for the export variables."
19640 (let ((l org-export-plist-vars) rtn e)
19641 (while (setq e (pop l))
19642 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
19643 rtn))
19645 (defun org-infile-export-plist ()
19646 "Return the property list with file-local settings for export."
19647 (save-excursion
19648 (goto-char 0)
19649 (let ((re (org-make-options-regexp
19650 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
19651 p key val text options)
19652 (while (re-search-forward re nil t)
19653 (setq key (org-match-string-no-properties 1)
19654 val (org-match-string-no-properties 2))
19655 (cond
19656 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
19657 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
19658 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
19659 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
19660 ((string-equal key "TEXT")
19661 (setq text (if text (concat text "\n" val) val)))
19662 ((string-equal key "OPTIONS") (setq options val))))
19663 (setq p (plist-put p :text text))
19664 (when options
19665 (let ((op '(("H" . :headline-levels)
19666 ("num" . :section-numbers)
19667 ("toc" . :table-of-contents)
19668 ("\\n" . :preserve-breaks)
19669 ("@" . :expand-quoted-html)
19670 (":" . :fixed-width)
19671 ("|" . :tables)
19672 ("^" . :sub-superscript)
19673 ("f" . :footnotes)
19674 ("p" . :property-drawer)
19675 ("*" . :emphasize)
19676 ("TeX" . :TeX-macros)
19677 ("LaTeX" . :LaTeX-fragments)
19678 ("skip" . :skip-before-1st-heading)))
19680 (while (setq o (pop op))
19681 (if (string-match (concat (regexp-quote (car o))
19682 ":\\([^ \t\n\r;,.]*\\)")
19683 options)
19684 (setq p (plist-put p (cdr o)
19685 (car (read-from-string
19686 (match-string 1 options)))))))))
19687 p)))
19689 (defun org-export-directory (type plist)
19690 (let* ((val (plist-get plist :publishing-directory))
19691 (dir (if (listp val)
19692 (or (cdr (assoc type val)) ".")
19693 val)))
19694 dir))
19696 (defun org-skip-comments (lines)
19697 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
19698 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
19699 (re2 "^\\(\\*+\\)[ \t\n\r]")
19700 (case-fold-search nil)
19701 rtn line level)
19702 (while (setq line (pop lines))
19703 (cond
19704 ((and (string-match re1 line)
19705 (setq level (- (match-end 1) (match-beginning 1))))
19706 ;; Beginning of a COMMENT subtree. Skip it.
19707 (while (and (setq line (pop lines))
19708 (or (not (string-match re2 line))
19709 (> (- (match-end 1) (match-beginning 1)) level))))
19710 (setq lines (cons line lines)))
19711 ((string-match "^#" line)
19712 ;; an ordinary comment line
19714 ((and org-export-table-remove-special-lines
19715 (string-match "^[ \t]*|" line)
19716 (or (string-match "^[ \t]*| *[!_^] *|" line)
19717 (and (string-match "| *<[0-9]+> *|" line)
19718 (not (string-match "| *[^ <|]" line)))))
19719 ;; a special table line that should be removed
19721 (t (setq rtn (cons line rtn)))))
19722 (nreverse rtn)))
19724 (defun org-export (&optional arg)
19725 (interactive)
19726 (let ((help "[t] insert the export option template
19727 \[v] limit export to visible part of outline tree
19729 \[a] export as ASCII
19730 \[h] export as HTML
19731 \[H] export as HTML to temporary buffer
19732 \[b] export as HTML and browse immediately
19733 \[x] export as XOXO
19735 \[i] export current file as iCalendar file
19736 \[I] export all agenda files as iCalendar files
19737 \[c] export agenda files into combined iCalendar file
19739 \[F] publish current file
19740 \[P] publish current project
19741 \[X] publish... (project will be prompted for)
19742 \[A] publish all projects")
19743 (cmds
19744 '((?t . org-insert-export-options-template)
19745 (?v . org-export-visible)
19746 (?a . org-export-as-ascii)
19747 (?h . org-export-as-html)
19748 (?b . org-export-as-html-and-open)
19749 (?H . org-export-as-html-to-buffer)
19750 (?R . org-export-region-as-html)
19751 (?x . org-export-as-xoxo)
19752 (?i . org-export-icalendar-this-file)
19753 (?I . org-export-icalendar-all-agenda-files)
19754 (?c . org-export-icalendar-combine-agenda-files)
19755 (?F . org-publish-current-file)
19756 (?P . org-publish-current-project)
19757 (?X . org-publish)
19758 (?A . org-publish-all)))
19759 r1 r2 ass)
19760 (save-window-excursion
19761 (delete-other-windows)
19762 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
19763 (princ help))
19764 (message "Select command: ")
19765 (setq r1 (read-char-exclusive)))
19766 (setq r2 (if (< r1 27) (+ r1 96) r1))
19767 (if (setq ass (assq r2 cmds))
19768 (call-interactively (cdr ass))
19769 (error "No command associated with key %c" r1))))
19771 (defconst org-html-entities
19772 '(("nbsp")
19773 ("iexcl")
19774 ("cent")
19775 ("pound")
19776 ("curren")
19777 ("yen")
19778 ("brvbar")
19779 ("vert" . "&#124;")
19780 ("sect")
19781 ("uml")
19782 ("copy")
19783 ("ordf")
19784 ("laquo")
19785 ("not")
19786 ("shy")
19787 ("reg")
19788 ("macr")
19789 ("deg")
19790 ("plusmn")
19791 ("sup2")
19792 ("sup3")
19793 ("acute")
19794 ("micro")
19795 ("para")
19796 ("middot")
19797 ("odot"."o")
19798 ("star"."*")
19799 ("cedil")
19800 ("sup1")
19801 ("ordm")
19802 ("raquo")
19803 ("frac14")
19804 ("frac12")
19805 ("frac34")
19806 ("iquest")
19807 ("Agrave")
19808 ("Aacute")
19809 ("Acirc")
19810 ("Atilde")
19811 ("Auml")
19812 ("Aring") ("AA"."&Aring;")
19813 ("AElig")
19814 ("Ccedil")
19815 ("Egrave")
19816 ("Eacute")
19817 ("Ecirc")
19818 ("Euml")
19819 ("Igrave")
19820 ("Iacute")
19821 ("Icirc")
19822 ("Iuml")
19823 ("ETH")
19824 ("Ntilde")
19825 ("Ograve")
19826 ("Oacute")
19827 ("Ocirc")
19828 ("Otilde")
19829 ("Ouml")
19830 ("times")
19831 ("Oslash")
19832 ("Ugrave")
19833 ("Uacute")
19834 ("Ucirc")
19835 ("Uuml")
19836 ("Yacute")
19837 ("THORN")
19838 ("szlig")
19839 ("agrave")
19840 ("aacute")
19841 ("acirc")
19842 ("atilde")
19843 ("auml")
19844 ("aring")
19845 ("aelig")
19846 ("ccedil")
19847 ("egrave")
19848 ("eacute")
19849 ("ecirc")
19850 ("euml")
19851 ("igrave")
19852 ("iacute")
19853 ("icirc")
19854 ("iuml")
19855 ("eth")
19856 ("ntilde")
19857 ("ograve")
19858 ("oacute")
19859 ("ocirc")
19860 ("otilde")
19861 ("ouml")
19862 ("divide")
19863 ("oslash")
19864 ("ugrave")
19865 ("uacute")
19866 ("ucirc")
19867 ("uuml")
19868 ("yacute")
19869 ("thorn")
19870 ("yuml")
19871 ("fnof")
19872 ("Alpha")
19873 ("Beta")
19874 ("Gamma")
19875 ("Delta")
19876 ("Epsilon")
19877 ("Zeta")
19878 ("Eta")
19879 ("Theta")
19880 ("Iota")
19881 ("Kappa")
19882 ("Lambda")
19883 ("Mu")
19884 ("Nu")
19885 ("Xi")
19886 ("Omicron")
19887 ("Pi")
19888 ("Rho")
19889 ("Sigma")
19890 ("Tau")
19891 ("Upsilon")
19892 ("Phi")
19893 ("Chi")
19894 ("Psi")
19895 ("Omega")
19896 ("alpha")
19897 ("beta")
19898 ("gamma")
19899 ("delta")
19900 ("epsilon")
19901 ("varepsilon"."&epsilon;")
19902 ("zeta")
19903 ("eta")
19904 ("theta")
19905 ("iota")
19906 ("kappa")
19907 ("lambda")
19908 ("mu")
19909 ("nu")
19910 ("xi")
19911 ("omicron")
19912 ("pi")
19913 ("rho")
19914 ("sigmaf") ("varsigma"."&sigmaf;")
19915 ("sigma")
19916 ("tau")
19917 ("upsilon")
19918 ("phi")
19919 ("chi")
19920 ("psi")
19921 ("omega")
19922 ("thetasym") ("vartheta"."&thetasym;")
19923 ("upsih")
19924 ("piv")
19925 ("bull") ("bullet"."&bull;")
19926 ("hellip") ("dots"."&hellip;")
19927 ("prime")
19928 ("Prime")
19929 ("oline")
19930 ("frasl")
19931 ("weierp")
19932 ("image")
19933 ("real")
19934 ("trade")
19935 ("alefsym")
19936 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
19937 ("uarr") ("uparrow"."&uarr;")
19938 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
19939 ("darr")("downarrow"."&darr;")
19940 ("harr") ("leftrightarrow"."&harr;")
19941 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
19942 ("lArr") ("Leftarrow"."&lArr;")
19943 ("uArr") ("Uparrow"."&uArr;")
19944 ("rArr") ("Rightarrow"."&rArr;")
19945 ("dArr") ("Downarrow"."&dArr;")
19946 ("hArr") ("Leftrightarrow"."&hArr;")
19947 ("forall")
19948 ("part") ("partial"."&part;")
19949 ("exist") ("exists"."&exist;")
19950 ("empty") ("emptyset"."&empty;")
19951 ("nabla")
19952 ("isin") ("in"."&isin;")
19953 ("notin")
19954 ("ni")
19955 ("prod")
19956 ("sum")
19957 ("minus")
19958 ("lowast") ("ast"."&lowast;")
19959 ("radic")
19960 ("prop") ("proptp"."&prop;")
19961 ("infin") ("infty"."&infin;")
19962 ("ang") ("angle"."&ang;")
19963 ("and") ("vee"."&and;")
19964 ("or") ("wedge"."&or;")
19965 ("cap")
19966 ("cup")
19967 ("int")
19968 ("there4")
19969 ("sim")
19970 ("cong") ("simeq"."&cong;")
19971 ("asymp")("approx"."&asymp;")
19972 ("ne") ("neq"."&ne;")
19973 ("equiv")
19974 ("le")
19975 ("ge")
19976 ("sub") ("subset"."&sub;")
19977 ("sup") ("supset"."&sup;")
19978 ("nsub")
19979 ("sube")
19980 ("supe")
19981 ("oplus")
19982 ("otimes")
19983 ("perp")
19984 ("sdot") ("cdot"."&sdot;")
19985 ("lceil")
19986 ("rceil")
19987 ("lfloor")
19988 ("rfloor")
19989 ("lang")
19990 ("rang")
19991 ("loz") ("Diamond"."&loz;")
19992 ("spades") ("spadesuit"."&spades;")
19993 ("clubs") ("clubsuit"."&clubs;")
19994 ("hearts") ("diamondsuit"."&hearts;")
19995 ("diams") ("diamondsuit"."&diams;")
19996 ("quot")
19997 ("amp")
19998 ("lt")
19999 ("gt")
20000 ("OElig")
20001 ("oelig")
20002 ("Scaron")
20003 ("scaron")
20004 ("Yuml")
20005 ("circ")
20006 ("tilde")
20007 ("ensp")
20008 ("emsp")
20009 ("thinsp")
20010 ("zwnj")
20011 ("zwj")
20012 ("lrm")
20013 ("rlm")
20014 ("ndash")
20015 ("mdash")
20016 ("lsquo")
20017 ("rsquo")
20018 ("sbquo")
20019 ("ldquo")
20020 ("rdquo")
20021 ("bdquo")
20022 ("dagger")
20023 ("Dagger")
20024 ("permil")
20025 ("lsaquo")
20026 ("rsaquo")
20027 ("euro")
20029 ("arccos"."arccos")
20030 ("arcsin"."arcsin")
20031 ("arctan"."arctan")
20032 ("arg"."arg")
20033 ("cos"."cos")
20034 ("cosh"."cosh")
20035 ("cot"."cot")
20036 ("coth"."coth")
20037 ("csc"."csc")
20038 ("deg"."deg")
20039 ("det"."det")
20040 ("dim"."dim")
20041 ("exp"."exp")
20042 ("gcd"."gcd")
20043 ("hom"."hom")
20044 ("inf"."inf")
20045 ("ker"."ker")
20046 ("lg"."lg")
20047 ("lim"."lim")
20048 ("liminf"."liminf")
20049 ("limsup"."limsup")
20050 ("ln"."ln")
20051 ("log"."log")
20052 ("max"."max")
20053 ("min"."min")
20054 ("Pr"."Pr")
20055 ("sec"."sec")
20056 ("sin"."sin")
20057 ("sinh"."sinh")
20058 ("sup"."sup")
20059 ("tan"."tan")
20060 ("tanh"."tanh")
20062 "Entities for TeX->HTML translation.
20063 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
20064 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
20065 In that case, \"\\ent\" will be translated to \"&other;\".
20066 The list contains HTML entities for Latin-1, Greek and other symbols.
20067 It is supplemented by a number of commonly used TeX macros with appropriate
20068 translations. There is currently no way for users to extend this.")
20070 ;;; General functions for all backends
20072 (defun org-cleaned-string-for-export (string &rest parameters)
20073 "Cleanup a buffer substring so that links can be created safely."
20074 (interactive)
20075 (let* ((re-radio (and org-target-link-regexp
20076 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
20077 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
20078 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
20079 (re-archive (concat ":" org-archive-tag ":"))
20080 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
20081 (htmlp (plist-get parameters :for-html))
20082 (inhibit-read-only t)
20083 (outline-regexp "\\*+ ")
20085 rtn p)
20086 (save-excursion
20087 (set-buffer (get-buffer-create " org-mode-tmp"))
20088 (erase-buffer)
20089 (insert string)
20090 ;; Remove license-to-kill stuff
20091 (while (setq p (text-property-any (point-min) (point-max)
20092 :org-license-to-kill t))
20093 (delete-region p (next-single-property-change p :org-license-to-kill)))
20095 (let ((org-inhibit-startup t)) (org-mode))
20096 (untabify (point-min) (point-max))
20098 ;; Get the correct stuff before the first headline
20099 (when (plist-get parameters :skip-before-1st-heading)
20100 (goto-char (point-min))
20101 (when (re-search-forward "^\\*+[ \t]" nil t)
20102 (delete-region (point-min) (match-beginning 0))
20103 (goto-char (point-min))
20104 (insert "\n")))
20105 (when (plist-get parameters :add-text)
20106 (goto-char (point-min))
20107 (insert (plist-get parameters :add-text) "\n"))
20109 ;; Get rid of archived trees
20110 (when (not (eq org-export-with-archived-trees t))
20111 (goto-char (point-min))
20112 (while (re-search-forward re-archive nil t)
20113 (if (not (org-on-heading-p t))
20114 (org-end-of-subtree t)
20115 (beginning-of-line 1)
20116 (setq a (if org-export-with-archived-trees
20117 (1+ (point-at-eol)) (point))
20118 b (org-end-of-subtree t))
20119 (if (> b a) (delete-region a b)))))
20121 ;; Get rid of property drawers
20122 (unless org-export-with-property-drawer
20123 (goto-char (point-min))
20124 (while (re-search-forward "^[ \t]*:PROPERTIES:[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n" nil t)
20125 (replace-match "")))
20127 ;; Protect stuff from HTML processing
20128 (goto-char (point-min))
20129 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
20130 (add-text-properties (match-beginning 0) (match-end 0)
20131 '(org-protected t)))
20132 (when htmlp
20133 (goto-char (point-min))
20134 (while (re-search-forward "^#\\+HTML:[ \t]*\\(.*\\)" nil t)
20135 (replace-match "\\1" t)
20136 (add-text-properties
20137 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
20138 '(org-protected t))))
20139 (goto-char (point-min))
20140 (while (re-search-forward
20141 "^#\\+BEGIN_HTML\\>.*\\(\\(\n.*\\)*?\n\\)#\\+END_HTML\\>.*\n?" nil t)
20142 (if htmlp
20143 (add-text-properties (match-beginning 1) (1+ (match-end 1))
20144 '(org-protected t))
20145 (delete-region (match-beginning 0) (match-end 0))))
20146 (goto-char (point-min))
20147 (while (re-search-forward re-quote nil t)
20148 (goto-char (match-beginning 0))
20149 (end-of-line 1)
20150 (add-text-properties (point) (org-end-of-subtree t)
20151 '(org-protected t)))
20153 ;; Find targets in comments and move them out of comments,
20154 ;; but mark them as targets that should be invisible
20155 (goto-char (point-min))
20156 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
20157 (replace-match "\\1(INVISIBLE)"))
20159 ;; Remove comments
20160 (goto-char (point-min))
20161 (while (re-search-forward "^#.*\n?" nil t)
20162 (replace-match ""))
20164 ;; Find matches for radio targets and turn them into internal links
20165 (goto-char (point-min))
20166 (when re-radio
20167 (while (re-search-forward re-radio nil t)
20168 (org-if-unprotected
20169 (replace-match "\\1[[\\2]]"))))
20171 ;; Find all links that contain a newline and put them into a single line
20172 (goto-char (point-min))
20173 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
20174 (org-if-unprotected
20175 (replace-match "\\1 \\3")
20176 (goto-char (match-beginning 0))))
20178 ;; Convert LaTeX fragments to images
20179 (when (plist-get parameters :LaTeX-fragments)
20180 (org-format-latex
20181 (concat "ltxpng/" (file-name-sans-extension
20182 (file-name-nondirectory
20183 org-current-export-file)))
20184 org-current-export-dir nil "Creating LaTeX image %s"))
20185 (message "Exporting...")
20187 ;; Normalize links: Convert angle and plain links into bracket links
20188 ;; Expand link abbreviations
20189 (goto-char (point-min))
20190 (while (re-search-forward re-plain-link nil t)
20191 (goto-char (1- (match-end 0)))
20192 (org-if-unprotected
20193 (replace-match
20194 (concat
20195 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
20196 t t)))
20197 (goto-char (point-min))
20198 (while (re-search-forward re-angle-link nil t)
20199 (goto-char (1- (match-end 0)))
20200 (org-if-unprotected
20201 (replace-match
20202 (concat
20203 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
20204 t t)))
20205 (goto-char (point-min))
20206 (while (re-search-forward org-bracket-link-regexp nil t)
20207 (org-if-unprotected
20208 (replace-match
20209 (concat "[[" (save-match-data
20210 (org-link-expand-abbrev (match-string 1)))
20212 (if (match-end 3)
20213 (match-string 2)
20214 (concat "[" (match-string 1) "]"))
20215 "]")
20216 t t)))
20218 ;; Find multiline emphasis and put them into single line
20219 (when (plist-get parameters :emph-multiline)
20220 (goto-char (point-min))
20221 (while (re-search-forward org-emph-re nil t)
20222 (if (not (= (char-after (match-beginning 3))
20223 (char-after (match-beginning 4))))
20224 (org-if-unprotected
20225 (subst-char-in-region (match-beginning 0) (match-end 0)
20226 ?\n ?\ t)
20227 (goto-char (1- (match-end 0))))
20228 (goto-char (1+ (match-beginning 0))))))
20230 (setq rtn (buffer-string)))
20231 (kill-buffer " org-mode-tmp")
20232 rtn))
20234 (defun org-export-grab-title-from-buffer ()
20235 "Get a title for the current document, from looking at the buffer."
20236 (let (buffer-read-only)
20237 (save-excursion
20238 (goto-char (point-min))
20239 (let ((end (save-excursion (outline-next-heading) (point))))
20240 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
20241 ;; Mark the line so that it will not be exported as normal text.
20242 (org-unmodified
20243 (add-text-properties (match-beginning 0) (match-end 0)
20244 (list :org-license-to-kill t)))
20245 ;; Return the title string
20246 (org-trim (match-string 0)))))))
20248 (defun org-solidify-link-text (s &optional alist)
20249 "Take link text and make a safe target out of it."
20250 (save-match-data
20251 (let* ((rtn
20252 (mapconcat
20253 'identity
20254 (org-split-string s "[ \t\r\n]+") "--"))
20255 (a (assoc rtn alist)))
20256 (or (cdr a) rtn))))
20258 ;; Variable holding the vector with section numbers
20259 (defvar org-section-numbers (make-vector org-level-max 0))
20261 (defun org-init-section-numbers ()
20262 "Initialize the vector for the section numbers."
20263 (let* ((level -1)
20264 (numbers (nreverse (org-split-string "" "\\.")))
20265 (depth (1- (length org-section-numbers)))
20266 (i depth) number-string)
20267 (while (>= i 0)
20268 (if (> i level)
20269 (aset org-section-numbers i 0)
20270 (setq number-string (or (car numbers) "0"))
20271 (if (string-match "\\`[A-Z]\\'" number-string)
20272 (aset org-section-numbers i
20273 (- (string-to-char number-string) ?A -1))
20274 (aset org-section-numbers i (string-to-number number-string)))
20275 (pop numbers))
20276 (setq i (1- i)))))
20278 (defun org-section-number (&optional level)
20279 "Return a string with the current section number.
20280 When LEVEL is non-nil, increase section numbers on that level."
20281 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
20282 (when level
20283 (when (> level -1)
20284 (aset org-section-numbers
20285 level (1+ (aref org-section-numbers level))))
20286 (setq idx (1+ level))
20287 (while (<= idx depth)
20288 (if (not (= idx 1))
20289 (aset org-section-numbers idx 0))
20290 (setq idx (1+ idx))))
20291 (setq idx 0)
20292 (while (<= idx depth)
20293 (setq n (aref org-section-numbers idx))
20294 (setq string (concat string (if (not (string= string "")) "." "")
20295 (int-to-string n)))
20296 (setq idx (1+ idx)))
20297 (save-match-data
20298 (if (string-match "\\`\\([@0]\\.\\)+" string)
20299 (setq string (replace-match "" t nil string)))
20300 (if (string-match "\\(\\.0\\)+\\'" string)
20301 (setq string (replace-match "" t nil string))))
20302 string))
20304 ;;; ASCII export
20306 (defvar org-last-level nil) ; dynamically scoped variable
20307 (defvar org-levels-open nil) ; dynamically scoped parameter
20308 (defvar org-ascii-current-indentation nil) ; For communication
20310 (defun org-export-as-ascii (arg)
20311 "Export the outline as a pretty ASCII file.
20312 If there is an active region, export only the region.
20313 The prefix ARG specifies how many levels of the outline should become
20314 underlined headlines. The default is 3."
20315 (interactive "P")
20316 (setq-default org-todo-line-regexp org-todo-line-regexp)
20317 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20318 (org-infile-export-plist)))
20319 (custom-times org-display-custom-times)
20320 (org-ascii-current-indentation '(0 . 0))
20321 (level 0) line txt
20322 (umax nil)
20323 (umax-toc nil)
20324 (case-fold-search nil)
20325 (filename (concat (file-name-as-directory
20326 (org-export-directory :ascii opt-plist))
20327 (file-name-sans-extension
20328 (file-name-nondirectory buffer-file-name))
20329 ".txt"))
20330 (buffer (find-file-noselect filename))
20331 (org-levels-open (make-vector org-level-max nil))
20332 (odd org-odd-levels-only)
20333 (date (format-time-string "%Y/%m/%d" (current-time)))
20334 (time (format-time-string "%X" (org-current-time)))
20335 (author (plist-get opt-plist :author))
20336 (title (or (plist-get opt-plist :title)
20337 (and (not
20338 (plist-get opt-plist :skip-before-1st-heading))
20339 (org-export-grab-title-from-buffer))
20340 (file-name-sans-extension
20341 (file-name-nondirectory buffer-file-name))))
20342 (email (plist-get opt-plist :email))
20343 (language (plist-get opt-plist :language))
20344 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
20345 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
20346 (todo nil)
20347 (lang-words nil)
20348 (region
20349 (buffer-substring
20350 (if (org-region-active-p) (region-beginning) (point-min))
20351 (if (org-region-active-p) (region-end) (point-max))))
20352 (lines (org-skip-comments
20353 (org-split-string
20354 (org-cleaned-string-for-export
20355 region
20356 :skip-before-1st-heading
20357 (plist-get opt-plist :skip-before-1st-heading)
20358 :add-text (plist-get opt-plist :text))
20359 "[\r\n]"))) ;; FIXME: why \r here???/
20360 thetoc have-headings first-heading-pos
20361 table-open table-buffer)
20363 (let (buffer-read-only)
20364 (org-unmodified
20365 (remove-text-properties (point-min) (point-max)
20366 '(:org-license-to-kill t))))
20368 (setq org-last-level 1)
20369 (org-init-section-numbers)
20371 (find-file-noselect filename)
20373 (setq lang-words (or (assoc language org-export-language-setup)
20374 (assoc "en" org-export-language-setup)))
20375 (switch-to-buffer-other-window buffer)
20376 (erase-buffer)
20377 (fundamental-mode)
20378 ;; create local variables for all options, to make sure all called
20379 ;; functions get the correct information
20380 (mapcar (lambda (x)
20381 (set (make-local-variable (cdr x))
20382 (plist-get opt-plist (car x))))
20383 org-export-plist-vars)
20384 (org-set-local 'org-odd-levels-only odd)
20385 (setq umax (if arg (prefix-numeric-value arg)
20386 org-export-headline-levels))
20387 (setq umax-toc (if (integerp org-export-with-toc)
20388 (min org-export-with-toc umax)
20389 umax))
20391 ;; File header
20392 (if title (org-insert-centered title ?=))
20393 (insert "\n")
20394 (if (or author email)
20395 (insert (concat (nth 1 lang-words) ": " (or author "")
20396 (if email (concat " <" email ">") "")
20397 "\n")))
20398 (if (and date time)
20399 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
20401 (insert "\n\n")
20403 (if org-export-with-toc
20404 (progn
20405 (push (concat (nth 3 lang-words) "\n") thetoc)
20406 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
20407 (mapcar '(lambda (line)
20408 (if (string-match org-todo-line-regexp
20409 line)
20410 ;; This is a headline
20411 (progn
20412 (setq have-headings t)
20413 (setq level (- (match-end 1) (match-beginning 1))
20414 level (org-tr-level level)
20415 txt (match-string 3 line)
20416 todo
20417 (or (and org-export-mark-todo-in-toc
20418 (match-beginning 2)
20419 (not (member (match-string 2 line)
20420 org-done-keywords)))
20421 ; TODO, not DONE
20422 (and org-export-mark-todo-in-toc
20423 (= level umax-toc)
20424 (org-search-todo-below
20425 line lines level))))
20426 (setq txt (org-html-expand-for-ascii txt))
20428 (if (and (memq org-export-with-tags '(not-in-toc nil))
20429 (string-match
20430 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
20431 txt))
20432 (setq txt (replace-match "" t t txt)))
20433 (if (string-match quote-re0 txt)
20434 (setq txt (replace-match "" t t txt)))
20436 (if org-export-with-section-numbers
20437 (setq txt (concat (org-section-number level)
20438 " " txt)))
20439 (if (<= level umax-toc)
20440 (progn
20441 (push
20442 (concat
20443 (make-string (* (1- level) 4) ?\ )
20444 (format (if todo "%s (*)\n" "%s\n") txt))
20445 thetoc)
20446 (setq org-last-level level))
20447 ))))
20448 lines)
20449 (setq thetoc (if have-headings (nreverse thetoc) nil))))
20451 (org-init-section-numbers)
20452 (while (setq line (pop lines))
20453 ;; Remove the quoted HTML tags.
20454 (setq line (org-html-expand-for-ascii line))
20455 ;; Remove targets
20456 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
20457 (setq line (replace-match "" t t line)))
20458 ;; Replace internal links
20459 (while (string-match org-bracket-link-regexp line)
20460 (setq line (replace-match
20461 (if (match-end 3) "[\\3]" "[\\1]")
20462 t nil line)))
20463 (when custom-times
20464 (setq line (org-translate-time line)))
20465 (cond
20466 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
20467 ;; a Headline
20468 (setq first-heading-pos (or first-heading-pos (point)))
20469 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
20470 txt (match-string 2 line))
20471 (org-ascii-level-start level txt umax lines))
20473 ((and org-export-with-tables
20474 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
20475 (if (not table-open)
20476 ;; New table starts
20477 (setq table-open t table-buffer nil))
20478 ;; Accumulate lines
20479 (setq table-buffer (cons line table-buffer))
20480 (when (or (not lines)
20481 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
20482 (car lines))))
20483 (setq table-open nil
20484 table-buffer (nreverse table-buffer))
20485 (insert (mapconcat
20486 (lambda (x)
20487 (org-fix-indentation x org-ascii-current-indentation))
20488 (org-format-table-ascii table-buffer)
20489 "\n") "\n")))
20491 (setq line (org-fix-indentation line org-ascii-current-indentation))
20492 (if (and org-export-with-fixed-width
20493 (string-match "^\\([ \t]*\\)\\(:\\)" line))
20494 (setq line (replace-match "\\1" nil nil line)))
20495 (insert line "\n"))))
20497 (normal-mode)
20499 ;; insert the table of contents
20500 (when thetoc
20501 (goto-char (point-min))
20502 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
20503 (progn
20504 (goto-char (match-beginning 0))
20505 (replace-match ""))
20506 (goto-char first-heading-pos))
20507 (mapc 'insert thetoc)
20508 (or (looking-at "[ \t]*\n[ \t]*\n")
20509 (insert "\n\n")))
20511 (save-buffer)
20512 ;; remove display and invisible chars
20513 (let (beg end)
20514 (goto-char (point-min))
20515 (while (setq beg (next-single-property-change (point) 'display))
20516 (setq end (next-single-property-change beg 'display))
20517 (delete-region beg end)
20518 (goto-char beg)
20519 (insert "=>"))
20520 (goto-char (point-min))
20521 (while (setq beg (next-single-property-change (point) 'org-cwidth))
20522 (setq end (next-single-property-change beg 'org-cwidth))
20523 (delete-region beg end)
20524 (goto-char beg)))
20525 (goto-char (point-min))))
20527 (defun org-search-todo-below (line lines level)
20528 "Search the subtree below LINE for any TODO entries."
20529 (let ((rest (cdr (memq line lines)))
20530 (re org-todo-line-regexp)
20531 line lv todo)
20532 (catch 'exit
20533 (while (setq line (pop rest))
20534 (if (string-match re line)
20535 (progn
20536 (setq lv (- (match-end 1) (match-beginning 1))
20537 todo (and (match-beginning 2)
20538 (not (member (match-string 2 line)
20539 org-done-keywords))))
20540 ; TODO, not DONE
20541 (if (<= lv level) (throw 'exit nil))
20542 (if todo (throw 'exit t))))))))
20544 (defun org-html-expand-for-ascii (line)
20545 "Handle quoted HTML for ASCII export."
20546 (if org-export-html-expand
20547 (while (string-match "@<[^<>\n]*>" line)
20548 ;; We just remove the tags for now.
20549 (setq line (replace-match "" nil nil line))))
20550 line)
20552 (defun org-insert-centered (s &optional underline)
20553 "Insert the string S centered and underline it with character UNDERLINE."
20554 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
20555 (insert (make-string ind ?\ ) s "\n")
20556 (if underline
20557 (insert (make-string ind ?\ )
20558 (make-string (string-width s) underline)
20559 "\n"))))
20561 (defun org-ascii-level-start (level title umax &optional lines)
20562 "Insert a new level in ASCII export."
20563 (let (char (n (- level umax 1)) (ind 0))
20564 (if (> level umax)
20565 (progn
20566 (insert (make-string (* 2 n) ?\ )
20567 (char-to-string (nth (% n (length org-export-ascii-bullets))
20568 org-export-ascii-bullets))
20569 " " title "\n")
20570 ;; find the indentation of the next non-empty line
20571 (catch 'stop
20572 (while lines
20573 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
20574 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
20575 (throw 'stop (setq ind (org-get-indentation (car lines)))))
20576 (pop lines)))
20577 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
20578 (if (or (not (equal (char-before) ?\n))
20579 (not (equal (char-before (1- (point))) ?\n)))
20580 (insert "\n"))
20581 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
20582 (unless org-export-with-tags
20583 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
20584 (setq title (replace-match "" t t title))))
20585 (if org-export-with-section-numbers
20586 (setq title (concat (org-section-number level) " " title)))
20587 (insert title "\n" (make-string (string-width title) char) "\n")
20588 (setq org-ascii-current-indentation '(0 . 0)))))
20590 (defun org-export-visible (type arg)
20591 "Create a copy of the visible part of the current buffer, and export it.
20592 The copy is created in a temporary buffer and removed after use.
20593 TYPE is the final key (as a string) that also select the export command in
20594 the `C-c C-e' export dispatcher.
20595 As a special case, if the you type SPC at the prompt, the temporary
20596 org-mode file will not be removed but presented to you so that you can
20597 continue to use it. The prefix arg ARG is passed through to the exporting
20598 command."
20599 (interactive
20600 (list (progn
20601 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
20602 (read-char-exclusive))
20603 current-prefix-arg))
20604 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
20605 (error "Invalid export key"))
20606 (let* ((binding (cdr (assoc type
20607 '((?a . org-export-as-ascii)
20608 (?\C-a . org-export-as-ascii)
20609 (?b . org-export-as-html-and-open)
20610 (?\C-b . org-export-as-html-and-open)
20611 (?h . org-export-as-html)
20612 (?H . org-export-as-html-to-buffer)
20613 (?R . org-export-region-as-html)
20614 (?x . org-export-as-xoxo)))))
20615 (keepp (equal type ?\ ))
20616 (file buffer-file-name)
20617 (buffer (get-buffer-create "*Org Export Visible*"))
20618 s e)
20619 (with-current-buffer buffer (erase-buffer))
20620 (save-excursion
20621 (setq s (goto-char (point-min)))
20622 (while (not (= (point) (point-max)))
20623 (goto-char (org-find-invisible))
20624 (append-to-buffer buffer s (point))
20625 (setq s (goto-char (org-find-visible))))
20626 (goto-char (point-min))
20627 (unless keepp
20628 ;; Copy all comment lines to the end, to make sure #+ settings are
20629 ;; still available for the second export step. Kind of a hack, but
20630 ;; does do the trick.
20631 (if (looking-at "#[^\r\n]*")
20632 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
20633 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
20634 (append-to-buffer buffer (1+ (match-beginning 0))
20635 (min (point-max) (1+ (match-end 0))))))
20636 (set-buffer buffer)
20637 (let ((buffer-file-name file)
20638 (org-inhibit-startup t))
20639 (org-mode)
20640 (show-all)
20641 (unless keepp (funcall binding arg))))
20642 (if (not keepp)
20643 (kill-buffer buffer)
20644 (switch-to-buffer-other-window buffer)
20645 (goto-char (point-min)))))
20647 (defun org-find-visible ()
20648 (let ((s (point)))
20649 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20650 (get-char-property s 'invisible)))
20652 (defun org-find-invisible ()
20653 (let ((s (point)))
20654 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20655 (not (get-char-property s 'invisible))))
20658 ;;; HTML export
20660 (defun org-get-current-options ()
20661 "Return a string with current options as keyword options.
20662 Does include HTML export options as well as TODO and CATEGORY stuff."
20663 (format
20664 "#+TITLE: %s
20665 #+AUTHOR: %s
20666 #+EMAIL: %s
20667 #+LANGUAGE: %s
20668 #+TEXT: Some descriptive text to be emitted. Several lines OK.
20669 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s p:%s
20670 #+CATEGORY: %s
20671 #+SEQ_TODO: %s
20672 #+TYP_TODO: %s
20673 #+PRIORITIES: %c %c %c
20674 #+STARTUP: %s %s %s %s %s
20675 #+TAGS: %s
20676 #+ARCHIVE: %s
20677 #+LINK: %s
20679 (buffer-name) (user-full-name) user-mail-address org-export-default-language
20680 org-export-headline-levels
20681 org-export-with-section-numbers
20682 org-export-with-toc
20683 org-export-preserve-breaks
20684 org-export-html-expand
20685 org-export-with-fixed-width
20686 org-export-with-tables
20687 org-export-with-sub-superscripts
20688 org-export-with-footnotes
20689 org-export-with-emphasize
20690 org-export-with-TeX-macros
20691 org-export-with-LaTeX-fragments
20692 org-export-skip-text-before-1st-heading
20693 org-export-with-property-drawer
20694 (file-name-nondirectory buffer-file-name)
20695 "TODO FEEDBACK VERIFY DONE"
20696 "Me Jason Marie DONE"
20697 org-highest-priority org-lowest-priority org-default-priority
20698 (cdr (assoc org-startup-folded
20699 '((nil . "showall") (t . "overview") (content . "content"))))
20700 (if org-odd-levels-only "odd" "oddeven")
20701 (if org-hide-leading-stars "hidestars" "showstars")
20702 (if org-startup-align-all-tables "align" "noalign")
20703 (cond ((eq t org-log-done) "logdone")
20704 ((not org-log-done) "nologging")
20705 ((listp org-log-done)
20706 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
20707 org-log-done " ")))
20708 (or (mapconcat (lambda (x)
20709 (cond
20710 ((equal '(:startgroup) x) "{")
20711 ((equal '(:endgroup) x) "}")
20712 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
20713 (t (car x))))
20714 (or org-tag-alist (org-get-buffer-tags)) " ") "")
20715 org-archive-location
20716 "org file:~/org/%s.org"
20719 (defun org-insert-export-options-template ()
20720 "Insert into the buffer a template with information for exporting."
20721 (interactive)
20722 (if (not (bolp)) (newline))
20723 (let ((s (org-get-current-options)))
20724 (and (string-match "#\\+CATEGORY" s)
20725 (setq s (substring s 0 (match-beginning 0))))
20726 (insert s)))
20728 (defun org-toggle-fixed-width-section (arg)
20729 "Toggle the fixed-width export.
20730 If there is no active region, the QUOTE keyword at the current headline is
20731 inserted or removed. When present, it causes the text between this headline
20732 and the next to be exported as fixed-width text, and unmodified.
20733 If there is an active region, this command adds or removes a colon as the
20734 first character of this line. If the first character of a line is a colon,
20735 this line is also exported in fixed-width font."
20736 (interactive "P")
20737 (let* ((cc 0)
20738 (regionp (org-region-active-p))
20739 (beg (if regionp (region-beginning) (point)))
20740 (end (if regionp (region-end)))
20741 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
20742 (re "[ \t]*\\(:\\)")
20743 off)
20744 (if regionp
20745 (save-excursion
20746 (goto-char beg)
20747 (setq cc (current-column))
20748 (beginning-of-line 1)
20749 (setq off (looking-at re))
20750 (while (> nlines 0)
20751 (setq nlines (1- nlines))
20752 (beginning-of-line 1)
20753 (cond
20754 (arg
20755 (move-to-column cc t)
20756 (insert ":\n")
20757 (forward-line -1))
20758 ((and off (looking-at re))
20759 (replace-match "" t t nil 1))
20760 ((not off) (move-to-column cc t) (insert ":")))
20761 (forward-line 1)))
20762 (save-excursion
20763 (org-back-to-heading)
20764 (if (looking-at (concat outline-regexp
20765 "\\( *\\<" org-quote-string "\\>\\)"))
20766 (replace-match "" t t nil 1)
20767 (if (looking-at outline-regexp)
20768 (progn
20769 (goto-char (match-end 0))
20770 (insert org-quote-string " "))))))))
20772 (defun org-export-as-html-and-open (arg)
20773 "Export the outline as HTML and immediately open it with a browser.
20774 If there is an active region, export only the region.
20775 The prefix ARG specifies how many levels of the outline should become
20776 headlines. The default is 3. Lower levels will become bulleted lists."
20777 (interactive "P")
20778 (org-export-as-html arg 'hidden)
20779 (org-open-file buffer-file-name))
20781 (defun org-export-as-html-batch ()
20782 "Call `org-export-as-html', may be used in batch processing as
20783 emacs --batch
20784 --load=$HOME/lib/emacs/org.el
20785 --eval \"(setq org-export-headline-levels 2)\"
20786 --visit=MyFile --funcall org-export-as-html-batch"
20787 (org-export-as-html org-export-headline-levels 'hidden))
20789 (defun org-export-as-html-to-buffer (arg)
20790 "Call `org-exort-as-html` with output to a temporary buffer.
20791 No file is created. The prefix ARG is passed through to `org-export-as-html'."
20792 (interactive "P")
20793 (org-export-as-html arg nil nil "*Org HTML Export*")
20794 (switch-to-buffer-other-window "*Org HTML Export*"))
20796 (defun org-replace-region-by-html (beg end)
20797 "Assume the current region has org-mode syntax, and convert it to HTML.
20798 This can be used in any buffer. For example, you could write an
20799 itemized list in org-mode syntax in an HTML buffer and then use this
20800 command to convert it."
20801 (interactive "r")
20802 (let (reg html buf)
20803 (if (org-mode-p)
20804 (setq html (org-export-region-as-html
20805 beg end t 'string))
20806 (setq reg (buffer-substring beg end)
20807 buf (get-buffer-create "*Org tmp*"))
20808 (save-excursion
20809 (set-buffer buf)
20810 (erase-buffer)
20811 (insert reg)
20812 (org-mode)
20813 (setq html (org-export-region-as-html
20814 (point-min) (point-max) t 'string)))
20815 (kill-buffer buf))
20816 (delete-region beg end)
20817 (insert html)))
20819 (defun org-export-region-as-html (beg end &optional body-only buffer)
20820 "Convert region from BEG to END in org-mode buffer to HTML.
20821 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
20822 contents, and only produce the region of converted text, useful for
20823 cut-and-paste operations.
20824 If BUFFER is a buffer or a string, use/create that buffer as a target
20825 of the converted HTML. If BUFFER is the symbol `string', return the
20826 produced HTML as a string and leave not buffer behind. For example,
20827 a Lisp program could call this function in the following way:
20829 (setq html (org-export-region-as-html beg end t 'string))
20831 When called interactively, the output buffer is selected, and shown
20832 in a window. A non-interactive call will only retunr the buffer."
20833 (interactive "r\nP")
20834 (when (interactive-p)
20835 (setq buffer "*Org HTML EXPORT*"))
20836 (let ((transient-mark-mode t) (zmacs-regions t)
20837 rtn)
20838 (goto-char end)
20839 (set-mark (point)) ;; to activate the region
20840 (goto-char beg)
20841 (setq rtn (org-export-as-html
20842 nil nil nil
20843 buffer body-only))
20844 (if (fboundp 'deactivate-mark) (deactivate-mark))
20845 (if (and (interactive-p) (bufferp rtn))
20846 (switch-to-buffer-other-window rtn)
20847 rtn)))
20849 (defun org-export-as-html (arg &optional hidden ext-plist
20850 to-buffer body-only)
20851 "Export the outline as a pretty HTML file.
20852 If there is an active region, export only the region. The prefix
20853 ARG specifies how many levels of the outline should become
20854 headlines. The default is 3. Lower levels will become bulleted
20855 lists. When HIDDEN is non-nil, don't display the HTML buffer.
20856 EXT-PLIST is a property list with external parameters overriding
20857 org-mode's default settings, but still inferior to file-local
20858 settings. When TO-BUFFER is non-nil, create a buffer with that
20859 name and export to that buffer. If TO-BUFFER is the symbol `string',
20860 don't leave any buffer behind but just return the resulting HTML as
20861 a string. When BODY-ONLY is set, don't produce the file header and footer,
20862 simply return the content of <body>...</body>, without even
20863 the body tags themselves."
20864 (interactive "P")
20866 ;; Make sure we have a file name when we need it.
20867 (when (and (not (or to-buffer body-only))
20868 (not buffer-file-name))
20869 (if (buffer-base-buffer)
20870 (org-set-local 'buffer-file-name
20871 (with-current-buffer (buffer-base-buffer)
20872 buffer-file-name))
20873 (error "Need a file name to be able to export.")))
20875 (message "Exporting...")
20876 (setq-default org-todo-line-regexp org-todo-line-regexp)
20877 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
20878 (setq-default org-done-keywords org-done-keywords)
20879 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
20880 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
20881 ext-plist
20882 (org-infile-export-plist)))
20884 (style (plist-get opt-plist :style))
20885 (link-validate (plist-get opt-plist :link-validation-function))
20886 valid thetoc have-headings first-heading-pos
20887 (odd org-odd-levels-only)
20888 (region-p (org-region-active-p))
20889 ;; The following two are dynamically scoped into other
20890 ;; routines below.
20891 (org-current-export-dir (org-export-directory :html opt-plist))
20892 (org-current-export-file buffer-file-name)
20893 (level 0) (line "") (origline "") txt todo
20894 (umax nil)
20895 (umax-toc nil)
20896 (filename (if to-buffer nil
20897 (concat (file-name-as-directory
20898 (org-export-directory :html opt-plist))
20899 (file-name-sans-extension
20900 (file-name-nondirectory buffer-file-name))
20901 ".html")))
20902 (current-dir (if buffer-file-name
20903 (file-name-directory buffer-file-name)
20904 default-directory))
20905 (buffer (if to-buffer
20906 (cond
20907 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
20908 (t (get-buffer-create to-buffer)))
20909 (find-file-noselect filename)))
20910 (org-levels-open (make-vector org-level-max nil))
20911 (date (format-time-string "%Y/%m/%d" (current-time)))
20912 (time (format-time-string "%X" (org-current-time)))
20913 (author (plist-get opt-plist :author))
20914 (title (or (plist-get opt-plist :title)
20915 (and (not
20916 (plist-get opt-plist :skip-before-1st-heading))
20917 (org-export-grab-title-from-buffer))
20918 (and buffer-file-name
20919 (file-name-sans-extension
20920 (file-name-nondirectory buffer-file-name)))
20921 "UNTITLED"))
20922 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
20923 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
20924 (inquote nil)
20925 (infixed nil)
20926 (in-local-list nil)
20927 (local-list-num nil)
20928 (local-list-indent nil)
20929 (llt org-plain-list-ordered-item-terminator)
20930 (email (plist-get opt-plist :email))
20931 (language (plist-get opt-plist :language))
20932 (lang-words nil)
20933 (target-alist nil) tg
20934 (head-count 0) cnt
20935 (start 0)
20936 (coding-system (and (boundp 'buffer-file-coding-system)
20937 buffer-file-coding-system))
20938 (coding-system-for-write (or org-export-html-coding-system
20939 coding-system))
20940 (save-buffer-coding-system (or org-export-html-coding-system
20941 coding-system))
20942 (charset (and coding-system-for-write
20943 (fboundp 'coding-system-get)
20944 (coding-system-get coding-system-for-write
20945 'mime-charset)))
20946 (region
20947 (buffer-substring
20948 (if region-p (region-beginning) (point-min))
20949 (if region-p (region-end) (point-max))))
20950 (lines
20951 (org-skip-comments (org-split-string
20952 (org-cleaned-string-for-export
20953 region
20954 :emph-multiline t
20955 :for-html t
20956 :skip-before-1st-heading
20957 (plist-get opt-plist :skip-before-1st-heading)
20958 :add-text
20959 (plist-get opt-plist :text)
20960 :LaTeX-fragments
20961 (plist-get opt-plist :LaTeX-fragments))
20962 "[\r\n]")))
20963 table-open type
20964 table-buffer table-orig-buffer
20965 ind start-is-num starter didclose
20966 rpl path desc descp desc1 desc2 link
20969 (let (buffer-read-only)
20970 (org-unmodified
20971 (remove-text-properties (point-min) (point-max)
20972 '(:org-license-to-kill t))))
20974 (message "Exporting...")
20976 (setq org-last-level 1)
20977 (org-init-section-numbers)
20979 ;; Get the language-dependent settings
20980 (setq lang-words (or (assoc language org-export-language-setup)
20981 (assoc "en" org-export-language-setup)))
20983 ;; Switch to the output buffer
20984 (set-buffer buffer)
20985 (erase-buffer)
20986 (fundamental-mode)
20987 (let ((case-fold-search nil)
20988 (org-odd-levels-only odd))
20989 ;; create local variables for all options, to make sure all called
20990 ;; functions get the correct information
20991 (mapcar (lambda (x)
20992 (set (make-local-variable (cdr x))
20993 (plist-get opt-plist (car x))))
20994 org-export-plist-vars)
20995 (setq umax (if arg (prefix-numeric-value arg)
20996 org-export-headline-levels))
20997 (setq umax-toc (if (integerp org-export-with-toc)
20998 (min org-export-with-toc umax)
20999 umax))
21000 (unless body-only
21001 ;; File header
21002 (insert (format
21003 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
21004 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
21005 <html xmlns=\"http://www.w3.org/1999/xhtml\"
21006 lang=\"%s\" xml:lang=\"%s\">
21007 <head>
21008 <title>%s</title>
21009 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
21010 <meta name=\"generator\" content=\"Org-mode\"/>
21011 <meta name=\"generated\" content=\"%s %s\"/>
21012 <meta name=\"author\" content=\"%s\"/>
21014 </head><body>
21016 language language (org-html-expand title)
21017 (or charset "iso-8859-1") date time author style))
21019 (insert (or (plist-get opt-plist :preamble) ""))
21021 (when (plist-get opt-plist :auto-preamble)
21022 (if title (insert (format org-export-html-title-format
21023 (org-html-expand title))))))
21025 (if (and org-export-with-toc (not body-only))
21026 (progn
21027 (push (format "<h%d>%s</h%d>\n"
21028 org-export-html-toplevel-hlevel
21029 (nth 3 lang-words)
21030 org-export-html-toplevel-hlevel)
21031 thetoc)
21032 (push "<ul>\n<li>" thetoc)
21033 (setq lines
21034 (mapcar '(lambda (line)
21035 (if (string-match org-todo-line-regexp line)
21036 ;; This is a headline
21037 (progn
21038 (setq have-headings t)
21039 (setq level (- (match-end 1) (match-beginning 1))
21040 level (org-tr-level level)
21041 txt (save-match-data
21042 (org-html-expand
21043 (org-export-cleanup-toc-line
21044 (match-string 3 line))))
21045 todo
21046 (or (and org-export-mark-todo-in-toc
21047 (match-beginning 2)
21048 (not (member (match-string 2 line)
21049 org-done-keywords)))
21050 ; TODO, not DONE
21051 (and org-export-mark-todo-in-toc
21052 (= level umax-toc)
21053 (org-search-todo-below
21054 line lines level))))
21055 (if (and (memq org-export-with-tags '(not-in-toc nil))
21056 (string-match
21057 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
21058 txt))
21059 (setq txt (replace-match "" t t txt)))
21060 (if (string-match quote-re0 txt)
21061 (setq txt (replace-match "" t t txt)))
21062 (if org-export-with-section-numbers
21063 (setq txt (concat (org-section-number level)
21064 " " txt)))
21065 (if (<= level (max umax umax-toc))
21066 (setq head-count (+ head-count 1)))
21067 (if (<= level umax-toc)
21068 (progn
21069 (if (> level org-last-level)
21070 (progn
21071 (setq cnt (- level org-last-level))
21072 (while (>= (setq cnt (1- cnt)) 0)
21073 (push "\n<ul>\n<li>" thetoc))
21074 (push "\n" thetoc)))
21075 (if (< level org-last-level)
21076 (progn
21077 (setq cnt (- org-last-level level))
21078 (while (>= (setq cnt (1- cnt)) 0)
21079 (push "</li>\n</ul>" thetoc))
21080 (push "\n" thetoc)))
21081 ;; Check for targets
21082 (while (string-match org-target-regexp line)
21083 (setq tg (match-string 1 line)
21084 line (replace-match
21085 (concat "@<span class=\"target\">" tg "@</span> ")
21086 t t line))
21087 (push (cons (org-solidify-link-text tg)
21088 (format "sec-%d" head-count))
21089 target-alist))
21090 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
21091 (setq txt (replace-match "" t t txt)))
21092 (push
21093 (format
21094 (if todo
21095 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
21096 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
21097 head-count txt) thetoc)
21099 (setq org-last-level level))
21101 line)
21102 lines))
21103 (while (> org-last-level 0)
21104 (setq org-last-level (1- org-last-level))
21105 (push "</li>\n</ul>\n" thetoc))
21106 (setq thetoc (if have-headings (nreverse thetoc) nil))))
21108 (setq head-count 0)
21109 (org-init-section-numbers)
21111 (while (setq line (pop lines) origline line)
21112 (catch 'nextline
21114 ;; end of quote section?
21115 (when (and inquote (string-match "^\\*+ " line))
21116 (insert "</pre>\n")
21117 (setq inquote nil))
21118 ;; inside a quote section?
21119 (when inquote
21120 (insert (org-html-protect line) "\n")
21121 (throw 'nextline nil))
21123 ;; verbatim lines
21124 (when (and org-export-with-fixed-width
21125 (string-match "^[ \t]*:\\(.*\\)" line))
21126 (when (not infixed)
21127 (setq infixed t)
21128 (insert "<pre>\n"))
21129 (insert (org-html-protect (match-string 1 line)) "\n")
21130 (when (and lines
21131 (not (string-match "^[ \t]*\\(:.*\\)"
21132 (car lines))))
21133 (setq infixed nil)
21134 (insert "</pre>\n"))
21135 (throw 'nextline nil))
21137 ;; Protected HTML
21138 (when (get-text-property 0 'org-protected line)
21139 (let (par)
21140 (when (re-search-backward
21141 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
21142 (setq par (match-string 1))
21143 (replace-match "\\2\n"))
21144 (insert line "\n")
21145 (while (and lines
21146 (get-text-property 0 'org-protected (car lines)))
21147 (insert (pop lines) "\n"))
21148 (and par (insert "<p>\n")))
21149 (throw 'nextline nil))
21151 ;; Horizontal line
21152 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
21153 (insert "\n<hr/>\n")
21154 (throw 'nextline nil))
21156 ;; make targets to anchors
21157 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
21158 (cond
21159 ((match-end 2)
21160 (setq line (replace-match
21161 (concat "@<a name=\""
21162 (org-solidify-link-text (match-string 1 line))
21163 "\">\\nbsp@</a>")
21164 t t line)))
21165 ((and org-export-with-toc (equal (string-to-char line) ?*))
21166 (setq line (replace-match
21167 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
21168 ; (concat "@<i>" (match-string 1 line) "@</i> ")
21169 t t line)))
21171 (setq line (replace-match
21172 (concat "@<a name=\""
21173 (org-solidify-link-text (match-string 1 line))
21174 "\" class=\"target\">" (match-string 1 line) "@</a> ")
21175 t t line)))))
21177 (setq line (org-html-handle-time-stamps line))
21179 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
21180 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
21181 ;; Also handle sub_superscripts and checkboxes
21182 (setq line (org-html-expand line))
21184 ;; Format the links
21185 (setq start 0)
21186 (while (string-match org-bracket-link-analytic-regexp line start)
21187 (setq start (match-beginning 0))
21188 (setq type (if (match-end 2) (match-string 2 line) "internal"))
21189 (setq path (match-string 3 line))
21190 (setq desc1 (if (match-end 5) (match-string 5 line))
21191 desc2 (if (match-end 2) (concat type ":" path) path)
21192 descp (and desc1 (not (equal desc1 desc2)))
21193 desc (or desc1 desc2))
21194 ;; Make an image out of the description if that is so wanted
21195 (when (and descp (org-file-image-p desc))
21196 (save-match-data
21197 (if (string-match "^file:" desc)
21198 (setq desc (substring desc (match-end 0)))))
21199 (setq desc (concat "<img src=\"" desc "\"/>")))
21200 ;; FIXME: do we need to unescape here somewhere?
21201 (cond
21202 ((equal type "internal")
21203 (setq rpl
21204 (concat
21205 "<a href=\"#"
21206 (org-solidify-link-text
21207 (save-match-data (org-link-unescape path)) target-alist)
21208 "\">" desc "</a>")))
21209 ((member type '("http" "https")) ; FIXME: need to test this.
21210 ;; standard URL, just check if we need to inline an image
21211 (if (and (or (eq t org-export-html-inline-images)
21212 (and org-export-html-inline-images (not descp)))
21213 (org-file-image-p path))
21214 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
21215 (setq link (concat type ":" path))
21216 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
21217 ((member type '("ftp" "mailto" "news"))
21218 ;; standard URL
21219 (setq link (concat type ":" path))
21220 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
21221 ((string= type "file")
21222 ;; FILE link
21223 (let* ((filename path)
21224 (abs-p (file-name-absolute-p filename))
21225 thefile file-is-image-p search)
21226 (save-match-data
21227 (if (string-match "::\\(.*\\)" filename)
21228 (setq search (match-string 1 filename)
21229 filename (replace-match "" t nil filename)))
21230 (setq valid
21231 (if (functionp link-validate)
21232 (funcall link-validate filename current-dir)
21234 (setq file-is-image-p (org-file-image-p filename))
21235 (setq thefile (if abs-p (expand-file-name filename) filename))
21236 (when (and org-export-html-link-org-files-as-html
21237 (string-match "\\.org$" thefile))
21238 (setq thefile (concat (substring thefile 0
21239 (match-beginning 0))
21240 ".html"))
21241 (if (and search
21242 ;; make sure this is can be used as target search
21243 (not (string-match "^[0-9]*$" search))
21244 (not (string-match "^\\*" search))
21245 (not (string-match "^/.*/$" search)))
21246 (setq thefile (concat thefile "#"
21247 (org-solidify-link-text
21248 (org-link-unescape search)))))
21249 (when (string-match "^file:" desc)
21250 (setq desc (replace-match "" t t desc))
21251 (if (string-match "\\.org$" desc)
21252 (setq desc (replace-match "" t t desc))))))
21253 (setq rpl (if (and file-is-image-p
21254 (or (eq t org-export-html-inline-images)
21255 (and org-export-html-inline-images
21256 (not descp))))
21257 (concat "<img src=\"" thefile "\"/>")
21258 (concat "<a href=\"" thefile "\">" desc "</a>")))
21259 (if (not valid) (setq rpl desc))))
21260 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
21261 (setq rpl (concat "<i>&lt;" type ":"
21262 (save-match-data (org-link-unescape path))
21263 "&gt;</i>"))))
21264 (setq line (replace-match rpl t t line)
21265 start (+ start (length rpl))))
21267 ;; TODO items
21268 (if (and (string-match org-todo-line-regexp line)
21269 (match-beginning 2))
21271 (setq line
21272 (concat (substring line 0 (match-beginning 2))
21273 "<span class=\""
21274 (if (member (match-string 2 line)
21275 org-done-keywords)
21276 "done" "todo")
21277 "\">" (match-string 2 line)
21278 "</span>" (substring line (match-end 2)))))
21280 ;; Does this contain a reference to a footnote?
21281 (when org-export-with-footnotes
21282 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
21283 (let ((n (match-string 2 line)))
21284 (setq line
21285 (replace-match
21286 (format
21287 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
21288 (match-string 1 line) n n n)
21289 t t line)))))
21291 (cond
21292 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
21293 ;; This is a headline
21294 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
21295 txt (match-string 2 line))
21296 (if (string-match quote-re0 txt)
21297 (setq txt (replace-match "" t t txt)))
21298 (if (<= level (max umax umax-toc))
21299 (setq head-count (+ head-count 1)))
21300 (when in-local-list
21301 ;; Close any local lists before inserting a new header line
21302 (while local-list-num
21303 (org-close-li)
21304 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21305 (pop local-list-num))
21306 (setq local-list-indent nil
21307 in-local-list nil))
21308 (setq first-heading-pos (or first-heading-pos (point)))
21309 (org-html-level-start level txt umax
21310 (and org-export-with-toc (<= level umax))
21311 head-count)
21312 ;; QUOTES
21313 (when (string-match quote-re line)
21314 (insert "<pre>")
21315 (setq inquote t)))
21317 ((and org-export-with-tables
21318 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
21319 (if (not table-open)
21320 ;; New table starts
21321 (setq table-open t table-buffer nil table-orig-buffer nil))
21322 ;; Accumulate lines
21323 (setq table-buffer (cons line table-buffer)
21324 table-orig-buffer (cons origline table-orig-buffer))
21325 (when (or (not lines)
21326 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
21327 (car lines))))
21328 (setq table-open nil
21329 table-buffer (nreverse table-buffer)
21330 table-orig-buffer (nreverse table-orig-buffer))
21331 (org-close-par-maybe)
21332 (insert (org-format-table-html table-buffer table-orig-buffer))))
21334 ;; Normal lines
21335 (when (string-match
21336 (cond
21337 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21338 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21339 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
21340 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
21341 line)
21342 (setq ind (org-get-string-indentation line)
21343 start-is-num (match-beginning 4)
21344 starter (if (match-beginning 2)
21345 (substring (match-string 2 line) 0 -1))
21346 line (substring line (match-beginning 5)))
21347 (unless (string-match "[^ \t]" line)
21348 ;; empty line. Pretend indentation is large.
21349 (setq ind (if org-empty-line-terminates-plain-lists
21351 (1+ (or (car local-list-indent) 1)))))
21352 (setq didclose nil)
21353 (while (and in-local-list
21354 (or (and (= ind (car local-list-indent))
21355 (not starter))
21356 (< ind (car local-list-indent))))
21357 (setq didclose t)
21358 (org-close-li)
21359 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
21360 (pop local-list-num) (pop local-list-indent)
21361 (setq in-local-list local-list-indent))
21362 (cond
21363 ((and starter
21364 (or (not in-local-list)
21365 (> ind (car local-list-indent))))
21366 ;; Start new (level of) list
21367 (org-close-par-maybe)
21368 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
21369 (push start-is-num local-list-num)
21370 (push ind local-list-indent)
21371 (setq in-local-list t))
21372 (starter
21373 ;; continue current list
21374 (org-close-li)
21375 (insert "<li>\n"))
21376 (didclose
21377 ;; we did close a list, normal text follows: need <p>
21378 (org-open-par)))
21379 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
21380 (setq line
21381 (replace-match
21382 (if (equal (match-string 1 line) "X")
21383 "<b>[X]</b>"
21384 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
21385 t t line))))
21387 ;; Empty lines start a new paragraph. If hand-formatted lists
21388 ;; are not fully interpreted, lines starting with "-", "+", "*"
21389 ;; also start a new paragraph.
21390 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
21392 ;; Is this the start of a footnote?
21393 (when org-export-with-footnotes
21394 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
21395 (org-close-par-maybe)
21396 (let ((n (match-string 1 line)))
21397 (setq line (replace-match
21398 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
21400 ;; Check if the line break needs to be conserved
21401 (cond
21402 ((string-match "\\\\\\\\[ \t]*$" line)
21403 (setq line (replace-match "<br/>" t t line)))
21404 (org-export-preserve-breaks
21405 (setq line (concat line "<br/>"))))
21407 (insert line "\n")))))
21409 ;; Properly close all local lists and other lists
21410 (when inquote (insert "</pre>\n"))
21411 (when in-local-list
21412 ;; Close any local lists before inserting a new header line
21413 (while local-list-num
21414 (org-close-li)
21415 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
21416 (pop local-list-num))
21417 (setq local-list-indent nil
21418 in-local-list nil))
21419 (org-html-level-start 1 nil umax
21420 (and org-export-with-toc (<= level umax))
21421 head-count)
21423 (unless body-only
21424 (when (plist-get opt-plist :auto-postamble)
21425 (when author
21426 (insert "<p class=\"author\"> "
21427 (nth 1 lang-words) ": " author "\n")
21428 (when email
21429 (insert "<a href=\"mailto:" email "\">&lt;"
21430 email "&gt;</a>\n"))
21431 (insert "</p>\n"))
21432 (when (and date time)
21433 (insert "<p class=\"date\"> "
21434 (nth 2 lang-words) ": "
21435 date " " time "</p>\n")))
21437 (if org-export-html-with-timestamp
21438 (insert org-export-html-html-helper-timestamp))
21439 (insert (or (plist-get opt-plist :postamble) ""))
21440 (insert "</body>\n</html>\n"))
21442 (normal-mode)
21443 (if (eq major-mode default-major-mode) (html-mode))
21445 ;; insert the table of contents
21446 (goto-char (point-min))
21447 (when thetoc
21448 (if (or (re-search-forward
21449 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
21450 (re-search-forward
21451 "\\[TABLE-OF-CONTENTS\\]" nil t))
21452 (progn
21453 (goto-char (match-beginning 0))
21454 (replace-match ""))
21455 (goto-char first-heading-pos)
21456 (when (looking-at "\\s-*</p>")
21457 (goto-char (match-end 0))
21458 (insert "\n")))
21459 (mapc 'insert thetoc))
21460 ;; remove empty paragraphs and lists
21461 (goto-char (point-min))
21462 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
21463 (replace-match ""))
21464 (goto-char (point-min))
21465 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
21466 (replace-match ""))
21467 (or to-buffer (save-buffer))
21468 (goto-char (point-min))
21469 (message "Exporting... done")
21470 (if (eq to-buffer 'string)
21471 (prog1 (buffer-substring (point-min) (point-max))
21472 (kill-buffer (current-buffer)))
21473 (current-buffer)))))
21475 (defvar org-table-colgroup-info nil) ;; FIXME: mode to a better place
21476 (defun org-format-table-ascii (lines)
21477 "Format a table for ascii export."
21478 (if (stringp lines)
21479 (setq lines (org-split-string lines "\n")))
21480 (if (not (string-match "^[ \t]*|" (car lines)))
21481 ;; Table made by table.el - test for spanning
21482 lines
21484 ;; A normal org table
21485 ;; Get rid of hlines at beginning and end
21486 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21487 (setq lines (nreverse lines))
21488 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21489 (setq lines (nreverse lines))
21490 (when org-export-table-remove-special-lines
21491 ;; Check if the table has a marking column. If yes remove the
21492 ;; column and the special lines
21493 (setq lines (org-table-clean-before-export lines)))
21494 ;; Get rid of the vertical lines except for grouping
21495 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
21496 rtn line vl1 start)
21497 (while (setq line (pop lines))
21498 (if (string-match org-table-hline-regexp line)
21499 (and (string-match "|\\(.*\\)|" line)
21500 (setq line (replace-match " \\1" t nil line)))
21501 (setq start 0 vl1 vl)
21502 (while (string-match "|" line start)
21503 (setq start (match-end 0))
21504 (or (pop vl1) (setq line (replace-match " " t t line)))))
21505 (push line rtn))
21506 (nreverse rtn))))
21508 (defun org-colgroup-info-to-vline-list (info)
21509 (let (vl new last)
21510 (while info
21511 (setq last new new (pop info))
21512 (if (or (memq last '(:end :startend))
21513 (memq new '(:start :startend)))
21514 (push t vl)
21515 (push nil vl)))
21516 (setq vl (cons nil (nreverse vl)))))
21519 (defun org-format-table-html (lines olines)
21520 "Find out which HTML converter to use and return the HTML code."
21521 (if (stringp lines)
21522 (setq lines (org-split-string lines "\n")))
21523 (if (string-match "^[ \t]*|" (car lines))
21524 ;; A normal org table
21525 (org-format-org-table-html lines)
21526 ;; Table made by table.el - test for spanning
21527 (let* ((hlines (delq nil (mapcar
21528 (lambda (x)
21529 (if (string-match "^[ \t]*\\+-" x) x
21530 nil))
21531 lines)))
21532 (first (car hlines))
21533 (ll (and (string-match "\\S-+" first)
21534 (match-string 0 first)))
21535 (re (concat "^[ \t]*" (regexp-quote ll)))
21536 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
21537 hlines))))
21538 (if (and (not spanning)
21539 (not org-export-prefer-native-exporter-for-tables))
21540 ;; We can use my own converter with HTML conversions
21541 (org-format-table-table-html lines)
21542 ;; Need to use the code generator in table.el, with the original text.
21543 (org-format-table-table-html-using-table-generate-source olines)))))
21545 (defun org-format-org-table-html (lines &optional splice)
21546 "Format a table into HTML."
21547 ;; Get rid of hlines at beginning and end
21548 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21549 (setq lines (nreverse lines))
21550 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
21551 (setq lines (nreverse lines))
21552 (when org-export-table-remove-special-lines
21553 ;; Check if the table has a marking column. If yes remove the
21554 ;; column and the special lines
21555 (setq lines (org-table-clean-before-export lines)))
21557 (let ((head (and org-export-highlight-first-table-line
21558 (delq nil (mapcar
21559 (lambda (x) (string-match "^[ \t]*|-" x))
21560 (cdr lines)))))
21561 (nlines 0) fnum i
21562 tbopen line fields html gr colgropen)
21563 (if splice (setq head nil))
21564 (unless splice (push (if head "<thead>" "<tbody>") html))
21565 (setq tbopen t)
21566 (while (setq line (pop lines))
21567 (catch 'next-line
21568 (if (string-match "^[ \t]*|-" line)
21569 (progn
21570 (unless splice
21571 (push (if head "</thead>" "</tbody>") html)
21572 (if lines (push "<tbody>" html) (setq tbopen nil)))
21573 (setq head nil) ;; head ends here, first time around
21574 ;; ignore this line
21575 (throw 'next-line t)))
21576 ;; Break the line into fields
21577 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
21578 (unless fnum (setq fnum (make-vector (length fields) 0)))
21579 (setq nlines (1+ nlines) i -1)
21580 (push (concat "<tr>"
21581 (mapconcat
21582 (lambda (x)
21583 (setq i (1+ i))
21584 (if (and (< i nlines)
21585 (string-match org-table-number-regexp x))
21586 (incf (aref fnum i)))
21587 (if head
21588 (concat (car org-export-table-header-tags) x
21589 (cdr org-export-table-header-tags))
21590 (concat (car org-export-table-data-tags) x
21591 (cdr org-export-table-data-tags))))
21592 fields "")
21593 "</tr>")
21594 html)))
21595 (unless splice (if tbopen (push "</tbody>" html)))
21596 (unless splice (push "</table>\n" html))
21597 (setq html (nreverse html))
21598 (unless splice
21599 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
21600 (push (mapconcat
21601 (lambda (x)
21602 (setq gr (pop org-table-colgroup-info))
21603 (format "%s<COL align=\"%s\"></COL>%s"
21604 (if (memq gr '(:start :startend))
21605 (prog1
21606 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
21607 (setq colgropen t))
21609 (if (> (/ (float x) nlines) org-table-number-fraction)
21610 "right" "left")
21611 (if (memq gr '(:end :startend))
21612 (progn (setq colgropen nil) "</colgroup>")
21613 "")))
21614 fnum "")
21615 html)
21616 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
21617 (push org-export-html-table-tag html))
21618 (concat (mapconcat 'identity html "\n") "\n")))
21620 (defun org-table-clean-before-export (lines)
21621 "Check if the table has a marking column.
21622 If yes remove the column and the special lines."
21623 (setq org-table-colgroup-info nil)
21624 (if (memq nil
21625 (mapcar
21626 (lambda (x) (or (string-match "^[ \t]*|-" x)
21627 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
21628 lines))
21629 (progn
21630 (setq org-table-clean-did-remove-column nil)
21631 (delq nil
21632 (mapcar
21633 (lambda (x)
21634 (cond
21635 ((string-match "^[ \t]*| */ *|" x)
21636 (setq org-table-colgroup-info
21637 (mapcar (lambda (x)
21638 (cond ((member x '("<" "&lt;")) :start)
21639 ((member x '(">" "&gt;")) :end)
21640 ((member x '("<>" "&lt;&gt;")) :startend)
21641 (t nil)))
21642 (org-split-string x "[ \t]*|[ \t]*")))
21643 nil)
21644 (t x)))
21645 lines)))
21646 (setq org-table-clean-did-remove-column t)
21647 (delq nil
21648 (mapcar
21649 (lambda (x)
21650 (cond
21651 ((string-match "^[ \t]*| */ *|" x)
21652 (setq org-table-colgroup-info
21653 (mapcar (lambda (x)
21654 (cond ((member x '("<" "&lt;")) :start)
21655 ((member x '(">" "&gt;")) :end)
21656 ((member x '("<>" "&lt;&gt;")) :startend)
21657 (t nil)))
21658 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
21659 nil)
21660 ((string-match "^[ \t]*| *[!_^/] *|" x)
21661 nil) ; ignore this line
21662 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
21663 (string-match "^\\([ \t]*\\)|[^|]*|" x))
21664 ;; remove the first column
21665 (replace-match "\\1|" t nil x))
21666 (t (error "This should not happen"))))
21667 lines))))
21669 (defun org-format-table-table-html (lines)
21670 "Format a table generated by table.el into HTML.
21671 This conversion does *not* use `table-generate-source' from table.el.
21672 This has the advantage that Org-mode's HTML conversions can be used.
21673 But it has the disadvantage, that no cell- or row-spanning is allowed."
21674 (let (line field-buffer
21675 (head org-export-highlight-first-table-line)
21676 fields html empty)
21677 (setq html (concat org-export-html-table-tag "\n"))
21678 (while (setq line (pop lines))
21679 (setq empty "&nbsp;")
21680 (catch 'next-line
21681 (if (string-match "^[ \t]*\\+-" line)
21682 (progn
21683 (if field-buffer
21684 (progn
21685 (setq
21686 html
21687 (concat
21688 html
21689 "<tr>"
21690 (mapconcat
21691 (lambda (x)
21692 (if (equal x "") (setq x empty))
21693 (if head
21694 (concat (car org-export-table-header-tags) x
21695 (cdr org-export-table-header-tags))
21696 (concat (car org-export-table-data-tags) x
21697 (cdr org-export-table-data-tags))))
21698 field-buffer "\n")
21699 "</tr>\n"))
21700 (setq head nil)
21701 (setq field-buffer nil)))
21702 ;; Ignore this line
21703 (throw 'next-line t)))
21704 ;; Break the line into fields and store the fields
21705 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
21706 (if field-buffer
21707 (setq field-buffer (mapcar
21708 (lambda (x)
21709 (concat x "<br/>" (pop fields)))
21710 field-buffer))
21711 (setq field-buffer fields))))
21712 (setq html (concat html "</table>\n"))
21713 html))
21715 (defun org-format-table-table-html-using-table-generate-source (lines)
21716 "Format a table into html, using `table-generate-source' from table.el.
21717 This has the advantage that cell- or row-spanning is allowed.
21718 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
21719 (require 'table)
21720 (with-current-buffer (get-buffer-create " org-tmp1 ")
21721 (erase-buffer)
21722 (insert (mapconcat 'identity lines "\n"))
21723 (goto-char (point-min))
21724 (if (not (re-search-forward "|[^+]" nil t))
21725 (error "Error processing table"))
21726 (table-recognize-table)
21727 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
21728 (table-generate-source 'html " org-tmp2 ")
21729 (set-buffer " org-tmp2 ")
21730 (buffer-substring (point-min) (point-max))))
21732 (defun org-html-handle-time-stamps (s)
21733 "Format time stamps in string S, or remove them."
21734 (catch 'exit
21735 (let (r b)
21736 (while (string-match org-maybe-keyword-time-regexp s)
21737 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
21738 ;; never export CLOCK
21739 (throw 'exit ""))
21740 (or b (setq b (substring s 0 (match-beginning 0))))
21741 (if (not org-export-with-timestamps)
21742 (setq r (concat r (substring s 0 (match-beginning 0)))
21743 s (substring s (match-end 0)))
21744 (setq r (concat
21745 r (substring s 0 (match-beginning 0))
21746 (if (match-end 1)
21747 (format "@<span class=\"timestamp-kwd\">%s @</span>"
21748 (match-string 1 s)))
21749 (format " @<span class=\"timestamp\">%s@</span>"
21750 (substring
21751 (org-translate-time (match-string 3 s)) 1 -1)))
21752 s (substring s (match-end 0)))))
21753 ;; Line break if line started and ended with time stamp stuff
21754 (if (not r)
21756 (setq r (concat r s))
21757 (unless (string-match "\\S-" (concat b s))
21758 (setq r (concat r "@<br/>")))
21759 r))))
21761 (defun org-html-protect (s)
21762 ;; convert & to &amp;, < to &lt; and > to &gt;
21763 (let ((start 0))
21764 (while (string-match "&" s start)
21765 (setq s (replace-match "&amp;" t t s)
21766 start (1+ (match-beginning 0))))
21767 (while (string-match "<" s)
21768 (setq s (replace-match "&lt;" t t s)))
21769 (while (string-match ">" s)
21770 (setq s (replace-match "&gt;" t t s))))
21773 (defun org-export-cleanup-toc-line (s)
21774 "Remove tags and time staps from lines going into the toc."
21775 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
21776 (setq s (replace-match "" t t s)))
21777 (when org-export-remove-timestamps-from-toc
21778 (while (string-match org-maybe-keyword-time-regexp s)
21779 (setq s (replace-match "" t t s))))
21780 (while (string-match org-bracket-link-regexp s)
21781 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
21782 t t s)))
21785 (defun org-html-expand (string)
21786 "Prepare STRING for HTML export. Applies all active conversions.
21787 If there are links in the string, don't modify these."
21788 (let* (m s l res)
21789 (while (setq m (string-match org-bracket-link-regexp string))
21790 (setq s (substring string 0 m)
21791 l (match-string 0 string)
21792 string (substring string (match-end 0)))
21793 (push (org-html-do-expand s) res)
21794 (push l res))
21795 (push (org-html-do-expand string) res)
21796 (apply 'concat (nreverse res))))
21798 (defun org-html-do-expand (s)
21799 "Apply all active conversions to translate special ASCII to HTML."
21800 (setq s (org-html-protect s))
21801 (if org-export-html-expand
21802 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
21803 (setq s (replace-match "<\\1>" t nil s))))
21804 (if org-export-with-emphasize
21805 (setq s (org-export-html-convert-emphasize s)))
21806 (if org-export-with-sub-superscripts
21807 (setq s (org-export-html-convert-sub-super s)))
21808 (if org-export-with-TeX-macros
21809 (let ((start 0) wd ass)
21810 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
21811 (setq wd (match-string 1 s))
21812 (if (setq ass (assoc wd org-html-entities))
21813 (setq s (replace-match (or (cdr ass)
21814 (concat "&" (car ass) ";"))
21815 t t s))
21816 (setq start (+ start (length wd)))))))
21819 (defun org-create-multibrace-regexp (left right n)
21820 "Create a regular expression which will match a balanced sexp.
21821 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
21822 as single character strings.
21823 The regexp returned will match the entire expression including the
21824 delimiters. It will also define a single group which contains the
21825 match except for the outermost delimiters. The maximum depth of
21826 stacked delimiters is N. Escaping delimiters is not possible."
21827 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
21828 (or "\\|")
21829 (re nothing)
21830 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
21831 (while (> n 1)
21832 (setq n (1- n)
21833 re (concat re or next)
21834 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
21835 (concat left "\\(" re "\\)" right)))
21837 (defvar org-match-substring-regexp
21838 (concat
21839 "\\([^\\]\\)\\([_^]\\)\\("
21840 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
21841 "\\|"
21842 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
21843 "\\|"
21844 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
21845 "The regular expression matching a sub- or superscript.")
21847 ;(let ((s "a\\_b"))
21848 ; (and (string-match org-match-substring-regexp s)
21849 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
21851 (defun org-export-html-convert-sub-super (string)
21852 "Convert sub- and superscripts in STRING to HTML."
21853 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
21854 (while (string-match org-match-substring-regexp string s)
21855 (if (and requireb (match-end 8))
21856 (setq s (match-end 2))
21857 (setq s (match-end 1)
21858 key (if (string= (match-string 2 string) "_") "sub" "sup")
21859 c (or (match-string 8 string)
21860 (match-string 6 string)
21861 (match-string 5 string))
21862 string (replace-match
21863 (concat (match-string 1 string)
21864 "<" key ">" c "</" key ">")
21865 t t string))))
21866 (while (string-match "\\\\\\([_^]\\)" string)
21867 (setq string (replace-match (match-string 1 string) t t string)))
21868 string))
21870 (defun org-export-html-convert-emphasize (string)
21871 "Apply emphasis."
21872 (let ((s 0))
21873 (while (string-match org-emph-re string s)
21874 (if (not (equal
21875 (substring string (match-beginning 3) (1+ (match-beginning 3)))
21876 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
21877 (setq string (replace-match
21878 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
21879 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
21880 "\\5") t nil string))
21881 (setq s (1+ s))))
21882 string))
21884 (defvar org-par-open nil)
21885 (defun org-open-par ()
21886 "Insert <p>, but first close previous paragraph if any."
21887 (org-close-par-maybe)
21888 (insert "\n<p>")
21889 (setq org-par-open t))
21890 (defun org-close-par-maybe ()
21891 "Close paragraph if there is one open."
21892 (when org-par-open
21893 (insert "</p>")
21894 (setq org-par-open nil)))
21895 (defun org-close-li ()
21896 "Close <li> if necessary."
21897 (org-close-par-maybe)
21898 (insert "</li>\n"))
21900 (defvar body-only) ; dynamically scoped into this.
21901 (defun org-html-level-start (level title umax with-toc head-count)
21902 "Insert a new level in HTML export.
21903 When TITLE is nil, just close all open levels."
21904 (org-close-par-maybe)
21905 (let ((l (1+ (max level umax))))
21906 (while (<= l org-level-max)
21907 (if (aref org-levels-open (1- l))
21908 (progn
21909 (org-html-level-close l)
21910 (aset org-levels-open (1- l) nil)))
21911 (setq l (1+ l)))
21912 (when title
21913 ;; If title is nil, this means this function is called to close
21914 ;; all levels, so the rest is done only if title is given
21915 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
21916 (setq title (replace-match
21917 (if org-export-with-tags
21918 (save-match-data
21919 (concat
21920 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
21921 (mapconcat 'identity (org-split-string
21922 (match-string 1 title) ":")
21923 "&nbsp;")
21924 "</span>"))
21926 t t title)))
21927 (if (> level umax)
21928 (progn
21929 (if (aref org-levels-open (1- level))
21930 (progn
21931 (org-close-li)
21932 (insert "<li>" title "<br/>\n"))
21933 (aset org-levels-open (1- level) t)
21934 (org-close-par-maybe)
21935 (insert "<ul>\n<li>" title "<br/>\n")))
21936 (if (and org-export-with-section-numbers (not body-only))
21937 (setq title (concat (org-section-number level) " " title)))
21938 (setq level (+ level org-export-html-toplevel-hlevel -1))
21939 (if with-toc
21940 (insert (format "\n<h%d id=\"sec-%d\">%s</h%d>\n"
21941 level head-count title level))
21942 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
21943 (org-open-par)))))
21945 (defun org-html-level-close (&rest args)
21946 "Terminate one level in HTML export."
21947 (org-close-li)
21948 (insert "</ul>\n"))
21950 ;;; iCalendar export
21952 ;;;###autoload
21953 (defun org-export-icalendar-this-file ()
21954 "Export current file as an iCalendar file.
21955 The iCalendar file will be located in the same directory as the Org-mode
21956 file, but with extension `.ics'."
21957 (interactive)
21958 (org-export-icalendar nil buffer-file-name))
21960 ;;;###autoload
21961 (defun org-export-icalendar-all-agenda-files ()
21962 "Export all files in `org-agenda-files' to iCalendar .ics files.
21963 Each iCalendar file will be located in the same directory as the Org-mode
21964 file, but with extension `.ics'."
21965 (interactive)
21966 (apply 'org-export-icalendar nil (org-agenda-files t)))
21968 ;;;###autoload
21969 (defun org-export-icalendar-combine-agenda-files ()
21970 "Export all files in `org-agenda-files' to a single combined iCalendar file.
21971 The file is stored under the name `org-combined-agenda-icalendar-file'."
21972 (interactive)
21973 (apply 'org-export-icalendar t (org-agenda-files t)))
21975 (defun org-export-icalendar (combine &rest files)
21976 "Create iCalendar files for all elements of FILES.
21977 If COMBINE is non-nil, combine all calendar entries into a single large
21978 file and store it under the name `org-combined-agenda-icalendar-file'."
21979 (save-excursion
21980 (org-prepare-agenda-buffers files)
21981 (let* ((dir (org-export-directory
21982 :ical (list :publishing-directory
21983 org-export-publishing-directory)))
21984 file ical-file ical-buffer category started org-agenda-new-buffers)
21986 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
21987 (when combine
21988 (setq ical-file
21989 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
21990 org-combined-agenda-icalendar-file
21991 (expand-file-name org-combined-agenda-icalendar-file dir))
21992 ical-buffer (org-get-agenda-file-buffer ical-file))
21993 (set-buffer ical-buffer) (erase-buffer))
21994 (while (setq file (pop files))
21995 (catch 'nextfile
21996 (org-check-agenda-file file)
21997 (set-buffer (org-get-agenda-file-buffer file))
21998 (unless combine
21999 (setq ical-file (concat (file-name-as-directory dir)
22000 (file-name-sans-extension
22001 (file-name-nondirectory buffer-file-name))
22002 ".ics"))
22003 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
22004 (with-current-buffer ical-buffer (erase-buffer)))
22005 (setq category (or org-category
22006 (file-name-sans-extension
22007 (file-name-nondirectory buffer-file-name))))
22008 (if (symbolp category) (setq category (symbol-name category)))
22009 (let ((standard-output ical-buffer))
22010 (if combine
22011 (and (not started) (setq started t)
22012 (org-start-icalendar-file org-icalendar-combined-name))
22013 (org-start-icalendar-file category))
22014 (org-print-icalendar-entries combine)
22015 (when (or (and combine (not files)) (not combine))
22016 (org-finish-icalendar-file)
22017 (set-buffer ical-buffer)
22018 (save-buffer)
22019 (run-hooks 'org-after-save-iCalendar-file-hook)))))
22020 (org-release-buffers org-agenda-new-buffers))))
22022 (defvar org-after-save-iCalendar-file-hook nil
22023 "Hook run after an iCalendar file has been saved.
22024 The iCalendar buffer is still current when this hook is run.
22025 A good way to use this is to tell a desktop calenndar application to re-read
22026 the iCalendar file.")
22028 (defun org-print-icalendar-entries (&optional combine)
22029 "Print iCalendar entries for the current Org-mode file to `standard-output'.
22030 When COMBINE is non nil, add the category to each line."
22031 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
22032 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
22033 (org-category-table (org-get-category-table))
22034 (dts (org-ical-ts-to-string
22035 (format-time-string (cdr org-time-stamp-formats) (current-time))
22036 "DTSTART"))
22037 hd ts ts2 state status (inc t) pos b sexp rrule
22038 scheduledp deadlinep tmp pri category
22039 (sexp-buffer (get-buffer-create "*ical-tmp*")))
22040 (save-excursion
22041 (goto-char (point-min))
22042 (while (re-search-forward re1 nil t)
22043 (catch :skip
22044 (org-agenda-skip)
22045 (setq pos (match-beginning 0)
22046 ts (match-string 0)
22047 inc t
22048 hd (org-get-heading)
22049 category (org-get-category))
22050 (if (looking-at re2)
22051 (progn
22052 (goto-char (match-end 0))
22053 (setq ts2 (match-string 1) inc nil))
22054 (setq tmp (buffer-substring (max (point-min)
22055 (- pos org-ds-keyword-length))
22056 pos)
22057 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
22058 (progn
22059 (setq inc nil)
22060 (replace-match "\\1" t nil ts))
22062 deadlinep (string-match org-deadline-regexp tmp)
22063 scheduledp (string-match org-scheduled-regexp tmp)
22064 ;; donep (org-entry-is-done-p)
22066 (if (or (string-match org-tr-regexp hd)
22067 (string-match org-ts-regexp hd))
22068 (setq hd (replace-match "" t t hd)))
22069 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
22070 (setq rrule
22071 (concat "\nRRULE:FREQ="
22072 (cdr (assoc
22073 (match-string 2 ts)
22074 '(("d" . "DAILY")("w" . "WEEKLY")
22075 ("m" . "MONTHLY")("y" . "YEARLY"))))
22076 ";INTERVAL=" (match-string 1 ts)))
22077 (setq rrule ""))
22078 (if (string-match org-bracket-link-regexp hd)
22079 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22080 (match-string 1 hd))
22081 t t hd)))
22082 (if deadlinep (setq hd (concat "DL: " hd)))
22083 (if scheduledp (setq hd (concat "S: " hd)))
22084 (if (string-match "\\`<%%" ts)
22085 (with-current-buffer sexp-buffer
22086 (insert (substring ts 1 -1) " " hd "\n"))
22087 (princ (format "BEGIN:VEVENT
22089 %s%s
22090 SUMMARY:%s
22091 CATEGORIES:%s
22092 END:VEVENT\n"
22093 (org-ical-ts-to-string ts "DTSTART")
22094 (org-ical-ts-to-string ts2 "DTEND" inc)
22095 rrule hd category)))))
22097 (when (and org-icalendar-include-sexps
22098 (condition-case nil (require 'icalendar) (error nil))
22099 (fboundp 'icalendar-export-region))
22100 ;; Get all the literal sexps
22101 (goto-char (point-min))
22102 (while (re-search-forward "^&?%%(" nil t)
22103 (catch :skip
22104 (org-agenda-skip)
22105 (setq b (match-beginning 0))
22106 (goto-char (1- (match-end 0)))
22107 (forward-sexp 1)
22108 (end-of-line 1)
22109 (setq sexp (buffer-substring b (point)))
22110 (with-current-buffer sexp-buffer
22111 (insert sexp "\n"))
22112 (princ (org-diary-to-ical-string sexp-buffer)))))
22114 (when org-icalendar-include-todo
22115 (goto-char (point-min))
22116 (while (re-search-forward org-todo-line-regexp nil t)
22117 (catch :skip
22118 (org-agenda-skip)
22119 (setq state (match-string 2))
22120 (setq status (if (member state org-done-keywords)
22121 "COMPLETED" "NEEDS-ACTION"))
22122 (when (and state
22123 (or (not (member state org-done-keywords))
22124 (eq org-icalendar-include-todo 'all))
22125 (not (member org-archive-tag (org-get-tags-at)))
22127 (setq hd (match-string 3))
22128 (if (string-match org-bracket-link-regexp hd)
22129 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
22130 (match-string 1 hd))
22131 t t hd)))
22132 (if (string-match org-priority-regexp hd)
22133 (setq pri (string-to-char (match-string 2 hd))
22134 hd (concat (substring hd 0 (match-beginning 1))
22135 (substring hd (match-end 1))))
22136 (setq pri org-default-priority))
22137 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
22138 (- org-lowest-priority org-highest-priority))))))
22140 (princ (format "BEGIN:VTODO
22142 SUMMARY:%s
22143 CATEGORIES:%s
22144 SEQUENCE:1
22145 PRIORITY:%d
22146 STATUS:%s
22147 END:VTODO\n"
22148 dts hd category pri status)))))))))
22150 (defun org-start-icalendar-file (name)
22151 "Start an iCalendar file by inserting the header."
22152 (let ((user user-full-name)
22153 (name (or name "unknown"))
22154 (timezone (cadr (current-time-zone))))
22155 (princ
22156 (format "BEGIN:VCALENDAR
22157 VERSION:2.0
22158 X-WR-CALNAME:%s
22159 PRODID:-//%s//Emacs with Org-mode//EN
22160 X-WR-TIMEZONE:%s
22161 CALSCALE:GREGORIAN\n" name user timezone))))
22163 (defun org-finish-icalendar-file ()
22164 "Finish an iCalendar file by inserting the END statement."
22165 (princ "END:VCALENDAR\n"))
22167 (defun org-ical-ts-to-string (s keyword &optional inc)
22168 "Take a time string S and convert it to iCalendar format.
22169 KEYWORD is added in front, to make a complete line like DTSTART....
22170 When INC is non-nil, increase the hour by two (if time string contains
22171 a time), or the day by one (if it does not contain a time)."
22172 (let ((t1 (org-parse-time-string s 'nodefault))
22173 t2 fmt have-time time)
22174 (if (and (car t1) (nth 1 t1) (nth 2 t1))
22175 (setq t2 t1 have-time t)
22176 (setq t2 (org-parse-time-string s)))
22177 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
22178 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
22179 (when inc
22180 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
22181 (setq time (encode-time s mi h d m y)))
22182 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
22183 (concat keyword (format-time-string fmt time))))
22185 ;;; XOXO export
22187 (defun org-export-as-xoxo-insert-into (buffer &rest output)
22188 (with-current-buffer buffer
22189 (apply 'insert output)))
22190 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
22192 (defun org-export-as-xoxo (&optional buffer)
22193 "Export the org buffer as XOXO.
22194 The XOXO buffer is named *xoxo-<source buffer name>*"
22195 (interactive (list (current-buffer)))
22196 ;; A quickie abstraction
22198 ;; Output everything as XOXO
22199 (with-current-buffer (get-buffer buffer)
22200 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
22201 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22202 (org-infile-export-plist)))
22203 (filename (concat (file-name-as-directory
22204 (org-export-directory :xoxo opt-plist))
22205 (file-name-sans-extension
22206 (file-name-nondirectory buffer-file-name))
22207 ".html"))
22208 (out (find-file-noselect filename))
22209 (last-level 1)
22210 (hanging-li nil))
22211 ;; Check the output buffer is empty.
22212 (with-current-buffer out (erase-buffer))
22213 ;; Kick off the output
22214 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
22215 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
22216 (let* ((hd (match-string-no-properties 1))
22217 (level (length hd))
22218 (text (concat
22219 (match-string-no-properties 2)
22220 (save-excursion
22221 (goto-char (match-end 0))
22222 (let ((str ""))
22223 (catch 'loop
22224 (while 't
22225 (forward-line)
22226 (if (looking-at "^[ \t]\\(.*\\)")
22227 (setq str (concat str (match-string-no-properties 1)))
22228 (throw 'loop str)))))))))
22230 ;; Handle level rendering
22231 (cond
22232 ((> level last-level)
22233 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
22235 ((< level last-level)
22236 (dotimes (- (- last-level level) 1)
22237 (if hanging-li
22238 (org-export-as-xoxo-insert-into out "</li>\n"))
22239 (org-export-as-xoxo-insert-into out "</ol>\n"))
22240 (when hanging-li
22241 (org-export-as-xoxo-insert-into out "</li>\n")
22242 (setq hanging-li nil)))
22244 ((equal level last-level)
22245 (if hanging-li
22246 (org-export-as-xoxo-insert-into out "</li>\n")))
22249 (setq last-level level)
22251 ;; And output the new li
22252 (setq hanging-li 't)
22253 (if (equal ?+ (elt text 0))
22254 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
22255 (org-export-as-xoxo-insert-into out "<li>" text))))
22257 ;; Finally finish off the ol
22258 (dotimes (- last-level 1)
22259 (if hanging-li
22260 (org-export-as-xoxo-insert-into out "</li>\n"))
22261 (org-export-as-xoxo-insert-into out "</ol>\n"))
22263 ;; Finish the buffer off and clean it up.
22264 (switch-to-buffer-other-window out)
22265 (indent-region (point-min) (point-max) nil)
22266 (save-buffer)
22267 (goto-char (point-min))
22271 ;;;; Key bindings
22273 ;; Make `C-c C-x' a prefix key
22274 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
22276 ;; TAB key with modifiers
22277 (org-defkey org-mode-map "\C-i" 'org-cycle)
22278 (org-defkey org-mode-map [(tab)] 'org-cycle)
22279 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
22280 (org-defkey org-mode-map [(meta tab)] 'org-complete)
22281 (org-defkey org-mode-map "\M-\t" 'org-complete)
22282 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
22283 ;; The following line is necessary under Suse GNU/Linux
22284 (unless (featurep 'xemacs)
22285 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
22286 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
22287 (define-key org-mode-map (kbd "<backtab>") 'org-shifttab)
22289 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
22290 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
22291 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
22293 ;; Cursor keys with modifiers
22294 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
22295 (org-defkey org-mode-map [(meta right)] 'org-metaright)
22296 (org-defkey org-mode-map [(meta up)] 'org-metaup)
22297 (org-defkey org-mode-map [(meta down)] 'org-metadown)
22299 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
22300 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
22301 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
22302 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
22304 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
22305 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
22306 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
22307 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
22309 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
22310 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
22312 ;;; Extra keys for tty access.
22313 ;; We only set them when really needed because otherwise the
22314 ;; menus don't show the simple keys
22316 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
22317 (not window-system))
22318 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
22319 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
22320 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
22321 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
22322 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
22323 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
22324 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
22325 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
22326 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
22327 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
22328 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
22329 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
22330 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
22331 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
22332 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
22333 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
22334 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
22335 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
22336 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
22337 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
22338 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
22339 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
22341 ;; All the other keys
22343 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
22344 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
22345 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
22346 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
22347 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
22348 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
22349 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
22350 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
22351 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
22352 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
22353 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
22354 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
22355 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
22356 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
22357 (org-defkey org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
22358 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
22359 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
22360 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
22361 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
22362 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
22363 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
22364 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
22365 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
22366 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
22367 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
22368 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
22369 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
22370 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
22371 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
22372 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
22373 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
22374 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
22375 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
22376 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
22377 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
22378 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
22379 (org-defkey org-mode-map "\C-c^" 'org-sort)
22380 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
22381 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
22382 (org-defkey org-mode-map "\C-m" 'org-return)
22383 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
22384 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
22385 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
22386 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
22387 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
22388 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
22389 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
22390 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
22391 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
22392 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
22393 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
22394 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
22395 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
22396 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
22397 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
22398 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
22400 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
22401 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
22402 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
22403 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
22405 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
22406 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
22407 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
22408 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
22409 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
22410 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
22411 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
22412 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
22413 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
22415 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
22417 (when (featurep 'xemacs)
22418 (org-defkey org-mode-map 'button3 'popup-mode-menu))
22420 (defsubst org-table-p () (org-at-table-p))
22422 (defun org-self-insert-command (N)
22423 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
22424 If the cursor is in a table looking at whitespace, the whitespace is
22425 overwritten, and the table is not marked as requiring realignment."
22426 (interactive "p")
22427 (if (and (org-table-p)
22428 (progn
22429 ;; check if we blank the field, and if that triggers align
22430 (and org-table-auto-blank-field
22431 (member last-command
22432 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
22433 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
22434 ;; got extra space, this field does not determine column width
22435 (let (org-table-may-need-update) (org-table-blank-field))
22436 ;; no extra space, this field may determine column width
22437 (org-table-blank-field)))
22439 (eq N 1)
22440 (looking-at "[^|\n]* |"))
22441 (let (org-table-may-need-update)
22442 (goto-char (1- (match-end 0)))
22443 (delete-backward-char 1)
22444 (goto-char (match-beginning 0))
22445 (self-insert-command N))
22446 (setq org-table-may-need-update t)
22447 (self-insert-command N)
22448 (org-fix-tags-on-the-fly)))
22450 (defun org-fix-tags-on-the-fly ()
22451 (when (and (equal (char-after (point-at-bol)) ?*)
22452 (org-on-heading-p))
22453 (org-align-tags-here org-tags-column)))
22455 (defun org-delete-backward-char (N)
22456 "Like `delete-backward-char', insert whitespace at field end in tables.
22457 When deleting backwards, in tables this function will insert whitespace in
22458 front of the next \"|\" separator, to keep the table aligned. The table will
22459 still be marked for re-alignment if the field did fill the entire column,
22460 because, in this case the deletion might narrow the column."
22461 (interactive "p")
22462 (if (and (org-table-p)
22463 (eq N 1)
22464 (string-match "|" (buffer-substring (point-at-bol) (point)))
22465 (looking-at ".*?|"))
22466 (let ((pos (point))
22467 (noalign (looking-at "[^|\n\r]* |"))
22468 (c org-table-may-need-update))
22469 (backward-delete-char N)
22470 (skip-chars-forward "^|")
22471 (insert " ")
22472 (goto-char (1- pos))
22473 ;; noalign: if there were two spaces at the end, this field
22474 ;; does not determine the width of the column.
22475 (if noalign (setq org-table-may-need-update c)))
22476 (backward-delete-char N)
22477 (org-fix-tags-on-the-fly)))
22479 (defun org-delete-char (N)
22480 "Like `delete-char', but insert whitespace at field end in tables.
22481 When deleting characters, in tables this function will insert whitespace in
22482 front of the next \"|\" separator, to keep the table aligned. The table will
22483 still be marked for re-alignment if the field did fill the entire column,
22484 because, in this case the deletion might narrow the column."
22485 (interactive "p")
22486 (if (and (org-table-p)
22487 (not (bolp))
22488 (not (= (char-after) ?|))
22489 (eq N 1))
22490 (if (looking-at ".*?|")
22491 (let ((pos (point))
22492 (noalign (looking-at "[^|\n\r]* |"))
22493 (c org-table-may-need-update))
22494 (replace-match (concat
22495 (substring (match-string 0) 1 -1)
22496 " |"))
22497 (goto-char pos)
22498 ;; noalign: if there were two spaces at the end, this field
22499 ;; does not determine the width of the column.
22500 (if noalign (setq org-table-may-need-update c)))
22501 (delete-char N))
22502 (delete-char N)
22503 (org-fix-tags-on-the-fly)))
22505 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
22506 (put 'org-self-insert-command 'delete-selection t)
22507 (put 'orgtbl-self-insert-command 'delete-selection t)
22508 (put 'org-delete-char 'delete-selection 'supersede)
22509 (put 'org-delete-backward-char 'delete-selection 'supersede)
22511 ;; Make `flyspell-mode' delay after some commands
22512 (put 'org-self-insert-command 'flyspell-delayed t)
22513 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
22514 (put 'org-delete-char 'flyspell-delayed t)
22515 (put 'org-delete-backward-char 'flyspell-delayed t)
22517 ;; How to do this: Measure non-white length of current string
22518 ;; If equal to column width, we should realign.
22520 (defun org-remap (map &rest commands)
22521 "In MAP, remap the functions given in COMMANDS.
22522 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
22523 (let (new old)
22524 (while commands
22525 (setq old (pop commands) new (pop commands))
22526 (if (fboundp 'command-remapping)
22527 (org-defkey map (vector 'remap old) new)
22528 (substitute-key-definition old new map global-map)))))
22530 (when (eq org-enable-table-editor 'optimized)
22531 ;; If the user wants maximum table support, we need to hijack
22532 ;; some standard editing functions
22533 (org-remap org-mode-map
22534 'self-insert-command 'org-self-insert-command
22535 'delete-char 'org-delete-char
22536 'delete-backward-char 'org-delete-backward-char)
22537 (org-defkey org-mode-map "|" 'org-force-self-insert))
22539 (defun org-shiftcursor-error ()
22540 "Throw an error because Shift-Cursor command was applied in wrong context."
22541 (error "This command is active in special context like tables, headlines or timestamps"))
22543 (defun org-shifttab (&optional arg)
22544 "Global visibility cycling or move to previous table field.
22545 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
22546 on context.
22547 See the individual commands for more information."
22548 (interactive "P")
22549 (cond
22550 ((org-at-table-p) (call-interactively 'org-table-previous-field))
22551 (arg (message "Content view to level: ")
22552 (org-content (prefix-numeric-value arg))
22553 (setq org-cycle-global-status 'overview))
22554 (t (call-interactively 'org-global-cycle))))
22556 (defun org-shiftmetaleft ()
22557 "Promote subtree or delete table column.
22558 Calls `org-promote-subtree', `org-outdent-item',
22559 or `org-table-delete-column', depending on context.
22560 See the individual commands for more information."
22561 (interactive)
22562 (cond
22563 ((org-at-table-p) (call-interactively 'org-table-delete-column))
22564 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
22565 ((org-at-item-p) (call-interactively 'org-outdent-item))
22566 (t (org-shiftcursor-error))))
22568 (defun org-shiftmetaright ()
22569 "Demote subtree or insert table column.
22570 Calls `org-demote-subtree', `org-indent-item',
22571 or `org-table-insert-column', depending on context.
22572 See the individual commands for more information."
22573 (interactive)
22574 (cond
22575 ((org-at-table-p) (call-interactively 'org-table-insert-column))
22576 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
22577 ((org-at-item-p) (call-interactively 'org-indent-item))
22578 (t (org-shiftcursor-error))))
22580 (defun org-shiftmetaup (&optional arg)
22581 "Move subtree up or kill table row.
22582 Calls `org-move-subtree-up' or `org-table-kill-row' or
22583 `org-move-item-up' depending on context. See the individual commands
22584 for more information."
22585 (interactive "P")
22586 (cond
22587 ((org-at-table-p) (call-interactively 'org-table-kill-row))
22588 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
22589 ((org-at-item-p) (call-interactively 'org-move-item-up))
22590 (t (org-shiftcursor-error))))
22591 (defun org-shiftmetadown (&optional arg)
22592 "Move subtree down or insert table row.
22593 Calls `org-move-subtree-down' or `org-table-insert-row' or
22594 `org-move-item-down', depending on context. See the individual
22595 commands for more information."
22596 (interactive "P")
22597 (cond
22598 ((org-at-table-p) (call-interactively 'org-table-insert-row))
22599 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
22600 ((org-at-item-p) (call-interactively 'org-move-item-down))
22601 (t (org-shiftcursor-error))))
22603 (defun org-metaleft (&optional arg)
22604 "Promote heading or move table column to left.
22605 Calls `org-do-promote' or `org-table-move-column', depending on context.
22606 With no specific context, calls the Emacs default `backward-word'.
22607 See the individual commands for more information."
22608 (interactive "P")
22609 (cond
22610 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
22611 ((or (org-on-heading-p) (org-region-active-p))
22612 (call-interactively 'org-do-promote))
22613 ((org-at-item-p) (call-interactively 'org-outdent-item))
22614 (t (call-interactively 'backward-word))))
22616 (defun org-metaright (&optional arg)
22617 "Demote subtree or move table column to right.
22618 Calls `org-do-demote' or `org-table-move-column', depending on context.
22619 With no specific context, calls the Emacs default `forward-word'.
22620 See the individual commands for more information."
22621 (interactive "P")
22622 (cond
22623 ((org-at-table-p) (call-interactively 'org-table-move-column))
22624 ((or (org-on-heading-p) (org-region-active-p))
22625 (call-interactively 'org-do-demote))
22626 ((org-at-item-p) (call-interactively 'org-indent-item))
22627 (t (call-interactively 'forward-word))))
22629 (defun org-metaup (&optional arg)
22630 "Move subtree up or move table row up.
22631 Calls `org-move-subtree-up' or `org-table-move-row' or
22632 `org-move-item-up', depending on context. See the individual commands
22633 for more information."
22634 (interactive "P")
22635 (cond
22636 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
22637 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
22638 ((org-at-item-p) (call-interactively 'org-move-item-up))
22639 (t (org-shiftcursor-error))))
22641 (defun org-metadown (&optional arg)
22642 "Move subtree down or move table row down.
22643 Calls `org-move-subtree-down' or `org-table-move-row' or
22644 `org-move-item-down', depending on context. See the individual
22645 commands for more information."
22646 (interactive "P")
22647 (cond
22648 ((org-at-table-p) (call-interactively 'org-table-move-row))
22649 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
22650 ((org-at-item-p) (call-interactively 'org-move-item-down))
22651 (t (org-shiftcursor-error))))
22653 (defun org-shiftup (&optional arg)
22654 "Increase item in timestamp or increase priority of current headline.
22655 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
22656 depending on context. See the individual commands for more information."
22657 (interactive "P")
22658 (cond
22659 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
22660 ((org-on-heading-p) (call-interactively 'org-priority-up))
22661 ((org-at-item-p) (call-interactively 'org-previous-item))
22662 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
22664 (defun org-shiftdown (&optional arg)
22665 "Decrease item in timestamp or decrease priority of current headline.
22666 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
22667 depending on context. See the individual commands for more information."
22668 (interactive "P")
22669 (cond
22670 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
22671 ((org-on-heading-p) (call-interactively 'org-priority-down))
22672 (t (call-interactively 'org-next-item))))
22674 (defun org-shiftright ()
22675 "Next TODO keyword or timestamp one day later, depending on context."
22676 (interactive)
22677 (cond
22678 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
22679 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
22680 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
22681 (t (org-shiftcursor-error))))
22683 (defun org-shiftleft ()
22684 "Previous TODO keyword or timestamp one day earlier, depending on context."
22685 (interactive)
22686 (cond
22687 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
22688 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
22689 ((org-at-property-p)
22690 (call-interactively 'org-property-previous-allowed-value))
22691 (t (org-shiftcursor-error))))
22693 (defun org-shiftcontrolright ()
22694 "Switch to next TODO set."
22695 (interactive)
22696 (cond
22697 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
22698 (t (org-shiftcursor-error))))
22700 (defun org-shiftcontrolleft ()
22701 "Switch to previous TODO set."
22702 (interactive)
22703 (cond
22704 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
22705 (t (org-shiftcursor-error))))
22707 (defun org-ctrl-c-ret ()
22708 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
22709 (interactive)
22710 (cond
22711 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
22712 (t (call-interactively 'org-insert-heading))))
22714 (defun org-copy-special ()
22715 "Copy region in table or copy current subtree.
22716 Calls `org-table-copy' or `org-copy-subtree', depending on context.
22717 See the individual commands for more information."
22718 (interactive)
22719 (call-interactively
22720 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
22722 (defun org-cut-special ()
22723 "Cut region in table or cut current subtree.
22724 Calls `org-table-copy' or `org-cut-subtree', depending on context.
22725 See the individual commands for more information."
22726 (interactive)
22727 (call-interactively
22728 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
22730 (defun org-paste-special (arg)
22731 "Paste rectangular region into table, or past subtree relative to level.
22732 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
22733 See the individual commands for more information."
22734 (interactive "P")
22735 (if (org-at-table-p)
22736 (org-table-paste-rectangle)
22737 (org-paste-subtree arg)))
22739 (defun org-ctrl-c-ctrl-c (&optional arg)
22740 "Set tags in headline, or update according to changed information at point.
22742 This command does many different things, depending on context:
22744 - If the cursor is in a headline, prompt for tags and insert them
22745 into the current line, aligned to `org-tags-column'. When called
22746 with prefix arg, realign all tags in the current buffer.
22748 - If the cursor is in one of the special #+KEYWORD lines, this
22749 triggers scanning the buffer for these lines and updating the
22750 information.
22752 - If the cursor is inside a table, realign the table. This command
22753 works even if the automatic table editor has been turned off.
22755 - If the cursor is on a #+TBLFM line, re-apply the formulas to
22756 the entire table.
22758 - If the cursor is inside a table created by the table.el package,
22759 activate that table.
22761 - If the current buffer is a remember buffer, close note and file it.
22762 with a prefix argument, file it without further interaction to the default
22763 location.
22765 - If the cursor is on a <<<target>>>, update radio targets and corresponding
22766 links in this buffer.
22768 - If the cursor is on a numbered item in a plain list, renumber the
22769 ordered list."
22770 (interactive "P")
22771 (let ((org-enable-table-editor t))
22772 (cond
22773 ((or org-clock-overlays
22774 org-occur-highlights
22775 org-latex-fragment-image-overlays)
22776 (org-remove-clock-overlays)
22777 (org-remove-occur-highlights)
22778 (org-remove-latex-fragment-image-overlays)
22779 (message "Temporary highlights/overlays removed from current buffer"))
22780 ((and (local-variable-p 'org-finish-function (current-buffer))
22781 (fboundp org-finish-function))
22782 (funcall org-finish-function))
22783 ((org-at-property-p)
22784 (call-interactively 'org-property-action))
22785 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
22786 ((org-on-heading-p) (call-interactively 'org-set-tags))
22787 ((org-at-table.el-p)
22788 (require 'table)
22789 (beginning-of-line 1)
22790 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
22791 (call-interactively 'table-recognize-table))
22792 ((org-at-table-p)
22793 (org-table-maybe-eval-formula)
22794 (if arg
22795 (call-interactively 'org-table-recalculate)
22796 (org-table-maybe-recalculate-line))
22797 (call-interactively 'org-table-align))
22798 ((org-at-item-checkbox-p)
22799 (call-interactively 'org-toggle-checkbox))
22800 ((org-at-item-p)
22801 (call-interactively 'org-maybe-renumber-ordered-list))
22802 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
22803 (cond
22804 ((equal (match-string 1) "TBLFM")
22805 ;; Recalculate the table before this line
22806 (save-excursion
22807 (beginning-of-line 1)
22808 (skip-chars-backward " \r\n\t")
22809 (if (org-at-table-p)
22810 (org-call-with-arg 'org-table-recalculate t))))
22812 (call-interactively 'org-mode-restart))))
22813 (t (error "C-c C-c can do nothing useful at this location.")))))
22815 (defun org-mode-restart ()
22816 "Restart Org-mode, to scan again for special lines.
22817 Also updates the keyword regular expressions."
22818 (interactive)
22819 (let ((org-inhibit-startup t)) (org-mode))
22820 (message "Org-mode restarted to refresh keyword and special line setup"))
22822 (defun org-return ()
22823 "Goto next table row or insert a newline.
22824 Calls `org-table-next-row' or `newline', depending on context.
22825 See the individual commands for more information."
22826 (interactive)
22827 (cond
22828 ((bobp) (newline))
22829 ((org-at-table-p)
22830 (org-table-justify-field-maybe)
22831 (call-interactively 'org-table-next-row))
22832 (t (newline))))
22834 (defun org-ctrl-c-minus ()
22835 "Insert separator line in table or modify bullet type in list.
22836 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
22837 depending on context."
22838 (interactive)
22839 (cond
22840 ((org-at-table-p)
22841 (call-interactively 'org-table-insert-hline))
22842 ((org-in-item-p)
22843 (call-interactively 'org-cycle-list-bullet))
22844 (t (error "`C-c -' does have no function here."))))
22846 (defun org-meta-return (&optional arg)
22847 "Insert a new heading or wrap a region in a table.
22848 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
22849 See the individual commands for more information."
22850 (interactive "P")
22851 (cond
22852 ((org-at-table-p)
22853 (call-interactively 'org-table-wrap-region))
22854 (t (call-interactively 'org-insert-heading))))
22856 ;;; Menu entries
22858 ;; Define the Org-mode menus
22859 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
22860 '("Tbl"
22861 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
22862 ["Next Field" org-cycle (org-at-table-p)]
22863 ["Previous Field" org-shifttab (org-at-table-p)]
22864 ["Next Row" org-return (org-at-table-p)]
22865 "--"
22866 ["Blank Field" org-table-blank-field (org-at-table-p)]
22867 ["Edit Field" org-table-edit-field (org-at-table-p)]
22868 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
22869 "--"
22870 ("Column"
22871 ["Move Column Left" org-metaleft (org-at-table-p)]
22872 ["Move Column Right" org-metaright (org-at-table-p)]
22873 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
22874 ["Insert Column" org-shiftmetaright (org-at-table-p)])
22875 ("Row"
22876 ["Move Row Up" org-metaup (org-at-table-p)]
22877 ["Move Row Down" org-metadown (org-at-table-p)]
22878 ["Delete Row" org-shiftmetaup (org-at-table-p)]
22879 ["Insert Row" org-shiftmetadown (org-at-table-p)]
22880 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
22881 "--"
22882 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
22883 ("Rectangle"
22884 ["Copy Rectangle" org-copy-special (org-at-table-p)]
22885 ["Cut Rectangle" org-cut-special (org-at-table-p)]
22886 ["Paste Rectangle" org-paste-special (org-at-table-p)]
22887 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
22888 "--"
22889 ("Calculate"
22890 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
22891 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
22892 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
22893 "--"
22894 ["Recalculate line" org-table-recalculate (org-at-table-p)]
22895 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
22896 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
22897 "--"
22898 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
22899 "--"
22900 ["Sum Column/Rectangle" org-table-sum
22901 (or (org-at-table-p) (org-region-active-p))]
22902 ["Which Column?" org-table-current-column (org-at-table-p)])
22903 ["Debug Formulas"
22904 org-table-toggle-formula-debugger
22905 :style toggle :selected org-table-formula-debug]
22906 ["Show Col/Row Numbers"
22907 org-table-toggle-coordinate-overlays
22908 :style toggle :selected org-table-overlay-coordinates]
22909 "--"
22910 ["Create" org-table-create (and (not (org-at-table-p))
22911 org-enable-table-editor)]
22912 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
22913 ["Import from File" org-table-import (not (org-at-table-p))]
22914 ["Export to File" org-table-export (org-at-table-p)]
22915 "--"
22916 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
22918 (easy-menu-define org-org-menu org-mode-map "Org menu"
22919 '("Org"
22920 ("Show/Hide"
22921 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
22922 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
22923 ["Sparse Tree" org-occur t]
22924 ["Reveal Context" org-reveal t]
22925 ["Show All" show-all t]
22926 "--"
22927 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
22928 "--"
22929 ["New Heading" org-insert-heading t]
22930 ("Navigate Headings"
22931 ["Up" outline-up-heading t]
22932 ["Next" outline-next-visible-heading t]
22933 ["Previous" outline-previous-visible-heading t]
22934 ["Next Same Level" outline-forward-same-level t]
22935 ["Previous Same Level" outline-backward-same-level t]
22936 "--"
22937 ["Jump" org-goto t]
22938 "--"
22939 ["C-a/e find headline start/end"
22940 (setq org-special-ctrl-a/e (not org-special-ctrl-a/e))
22941 :style toggle :selected org-special-ctrl-a/e])
22942 ("Edit Structure"
22943 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
22944 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
22945 "--"
22946 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
22947 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
22948 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
22949 "--"
22950 ["Promote Heading" org-metaleft (not (org-at-table-p))]
22951 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
22952 ["Demote Heading" org-metaright (not (org-at-table-p))]
22953 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
22954 "--"
22955 ["Sort Region/Children" org-sort (not (org-at-table-p))]
22956 "--"
22957 ["Convert to odd levels" org-convert-to-odd-levels t]
22958 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
22959 ("Editing"
22960 ["Emphasis..." org-emphasize t])
22961 ("Archive"
22962 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
22963 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
22964 ; :active t :keys "C-u C-c C-x C-a"]
22965 ["Sparse trees open ARCHIVE trees"
22966 (setq org-sparse-tree-open-archived-trees
22967 (not org-sparse-tree-open-archived-trees))
22968 :style toggle :selected org-sparse-tree-open-archived-trees]
22969 ["Cycling opens ARCHIVE trees"
22970 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
22971 :style toggle :selected org-cycle-open-archived-trees]
22972 ["Agenda includes ARCHIVE trees"
22973 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
22974 :style toggle :selected (not org-agenda-skip-archived-trees)]
22975 "--"
22976 ["Move Subtree to Archive" org-advertized-archive-subtree t]
22977 ; ["Check and Move Children" (org-archive-subtree '(4))
22978 ; :active t :keys "C-u C-c C-x C-s"]
22980 "--"
22981 ("TODO Lists"
22982 ["TODO/DONE/-" org-todo t]
22983 ("Select keyword"
22984 ["Next keyword" org-shiftright (org-on-heading-p)]
22985 ["Previous keyword" org-shiftleft (org-on-heading-p)]
22986 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
22987 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
22988 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
22989 ["Show TODO Tree" org-show-todo-tree t]
22990 ["Global TODO list" org-todo-list t]
22991 "--"
22992 ["Set Priority" org-priority t]
22993 ["Priority Up" org-shiftup t]
22994 ["Priority Down" org-shiftdown t])
22995 ("TAGS and Properties"
22996 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
22997 ["Column view of properties" org-columns t])
22998 ("Dates and Scheduling"
22999 ["Timestamp" org-time-stamp t]
23000 ["Timestamp (inactive)" org-time-stamp-inactive t]
23001 ("Change Date"
23002 ["1 Day Later" org-shiftright t]
23003 ["1 Day Earlier" org-shiftleft t]
23004 ["1 ... Later" org-shiftup t]
23005 ["1 ... Earlier" org-shiftdown t])
23006 ["Compute Time Range" org-evaluate-time-range t]
23007 ["Schedule Item" org-schedule t]
23008 ["Deadline" org-deadline t]
23009 "--"
23010 ["Custom time format" org-toggle-time-stamp-overlays
23011 :style radio :selected org-display-custom-times]
23012 "--"
23013 ["Goto Calendar" org-goto-calendar t]
23014 ["Date from Calendar" org-date-from-calendar t])
23015 ("Logging work"
23016 ["Clock in" org-clock-in t]
23017 ["Clock out" org-clock-out t]
23018 ["Clock cancel" org-clock-cancel t]
23019 ["Display times" org-clock-display t]
23020 ["Create clock table" org-clock-report t]
23021 "--"
23022 ["Record DONE time"
23023 (progn (setq org-log-done (not org-log-done))
23024 (message "Switching to %s will %s record a timestamp"
23025 (car org-done-keywords)
23026 (if org-log-done "automatically" "not")))
23027 :style toggle :selected org-log-done])
23028 "--"
23029 ["Agenda Command..." org-agenda t]
23030 ("File List for Agenda")
23031 ("Special views current file"
23032 ["TODO Tree" org-show-todo-tree t]
23033 ["Check Deadlines" org-check-deadlines t]
23034 ["Timeline" org-timeline t]
23035 ["Tags Tree" org-tags-sparse-tree t])
23036 "--"
23037 ("Hyperlinks"
23038 ["Store Link (Global)" org-store-link t]
23039 ["Insert Link" org-insert-link t]
23040 ["Follow Link" org-open-at-point t]
23041 "--"
23042 ["Next link" org-next-link t]
23043 ["Previous link" org-previous-link t]
23044 "--"
23045 ["Descriptive Links"
23046 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
23047 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
23048 ["Literal Links"
23049 (progn
23050 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
23051 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
23052 "--"
23053 ["Export/Publish..." org-export t]
23054 ("LaTeX"
23055 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
23056 :selected org-cdlatex-mode]
23057 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
23058 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
23059 ["Modify math symbol" org-cdlatex-math-modify
23060 (org-inside-LaTeX-fragment-p)]
23061 ["Export LaTeX fragments as images"
23062 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
23063 :style toggle :selected org-export-with-LaTeX-fragments])
23064 "--"
23065 ("Documentation"
23066 ["Show Version" org-version t]
23067 ["Info Documentation" org-info t])
23068 ("Customize"
23069 ["Browse Org Group" org-customize t]
23070 "--"
23071 ["Expand This Menu" org-create-customize-menu
23072 (fboundp 'customize-menu-create)])
23073 "--"
23074 ["Refresh setup" org-mode-restart t]
23077 (defun org-info (&optional node)
23078 "Read documentation for Org-mode in the info system.
23079 With optional NODE, go directly to that node."
23080 (interactive)
23081 (require 'info)
23082 (Info-goto-node (format "(org)%s" (or node ""))))
23084 (defun org-install-agenda-files-menu ()
23085 (let ((bl (buffer-list)))
23086 (save-excursion
23087 (while bl
23088 (set-buffer (pop bl))
23089 (if (org-mode-p) (setq bl nil)))
23090 (when (org-mode-p)
23091 (easy-menu-change
23092 '("Org") "File List for Agenda"
23093 (append
23094 (list
23095 ["Edit File List" (org-edit-agenda-file-list) t]
23096 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
23097 ["Remove Current File from List" org-remove-file t]
23098 ["Cycle through agenda files" org-cycle-agenda-files t]
23099 "--")
23100 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
23102 ;;;; Documentation
23104 (defun org-customize ()
23105 "Call the customize function with org as argument."
23106 (interactive)
23107 (customize-browse 'org))
23109 (defun org-create-customize-menu ()
23110 "Create a full customization menu for Org-mode, insert it into the menu."
23111 (interactive)
23112 (if (fboundp 'customize-menu-create)
23113 (progn
23114 (easy-menu-change
23115 '("Org") "Customize"
23116 `(["Browse Org group" org-customize t]
23117 "--"
23118 ,(customize-menu-create 'org)
23119 ["Set" Custom-set t]
23120 ["Save" Custom-save t]
23121 ["Reset to Current" Custom-reset-current t]
23122 ["Reset to Saved" Custom-reset-saved t]
23123 ["Reset to Standard Settings" Custom-reset-standard t]))
23124 (message "\"Org\"-menu now contains full customization menu"))
23125 (error "Cannot expand menu (outdated version of cus-edit.el)")))
23127 ;;;; Miscellaneous stuff
23130 ;;; Generally useful functions
23132 (defun org-context ()
23133 "Return a list of contexts of the current cursor position.
23134 If several contexts apply, all are returned.
23135 Each context entry is a list with a symbol naming the context, and
23136 two positions indicating start and end of the context. Possible
23137 contexts are:
23139 :headline anywhere in a headline
23140 :headline-stars on the leading stars in a headline
23141 :todo-keyword on a TODO keyword (including DONE) in a headline
23142 :tags on the TAGS in a headline
23143 :priority on the priority cookie in a headline
23144 :item on the first line of a plain list item
23145 :item-bullet on the bullet/number of a plain list item
23146 :checkbox on the checkbox in a plain list item
23147 :table in an org-mode table
23148 :table-special on a special filed in a table
23149 :table-table in a table.el table
23150 :link on a hyperlink
23151 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
23152 :target on a <<target>>
23153 :radio-target on a <<<radio-target>>>
23154 :latex-fragment on a LaTeX fragment
23155 :latex-preview on a LaTeX fragment with overlayed preview image
23157 This function expects the position to be visible because it uses font-lock
23158 faces as a help to recognize the following contexts: :table-special, :link,
23159 and :keyword."
23160 (let* ((f (get-text-property (point) 'face))
23161 (faces (if (listp f) f (list f)))
23162 (p (point)) clist o)
23163 ;; First the large context
23164 (cond
23165 ((org-on-heading-p t)
23166 (push (list :headline (point-at-bol) (point-at-eol)) clist)
23167 (when (progn
23168 (beginning-of-line 1)
23169 (looking-at org-todo-line-tags-regexp))
23170 (push (org-point-in-group p 1 :headline-stars) clist)
23171 (push (org-point-in-group p 2 :todo-keyword) clist)
23172 (push (org-point-in-group p 4 :tags) clist))
23173 (goto-char p)
23174 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
23175 (if (looking-at "\\[#[A-Z0-9]\\]")
23176 (push (org-point-in-group p 0 :priority) clist)))
23178 ((org-at-item-p)
23179 (push (org-point-in-group p 2 :item-bullet) clist)
23180 (push (list :item (point-at-bol)
23181 (save-excursion (org-end-of-item) (point)))
23182 clist)
23183 (and (org-at-item-checkbox-p)
23184 (push (org-point-in-group p 0 :checkbox) clist)))
23186 ((org-at-table-p)
23187 (push (list :table (org-table-begin) (org-table-end)) clist)
23188 (if (memq 'org-formula faces)
23189 (push (list :table-special
23190 (previous-single-property-change p 'face)
23191 (next-single-property-change p 'face)) clist)))
23192 ((org-at-table-p 'any)
23193 (push (list :table-table) clist)))
23194 (goto-char p)
23196 ;; Now the small context
23197 (cond
23198 ((org-at-timestamp-p)
23199 (push (org-point-in-group p 0 :timestamp) clist))
23200 ((memq 'org-link faces)
23201 (push (list :link
23202 (previous-single-property-change p 'face)
23203 (next-single-property-change p 'face)) clist))
23204 ((memq 'org-special-keyword faces)
23205 (push (list :keyword
23206 (previous-single-property-change p 'face)
23207 (next-single-property-change p 'face)) clist))
23208 ((org-on-target-p)
23209 (push (org-point-in-group p 0 :target) clist)
23210 (goto-char (1- (match-beginning 0)))
23211 (if (looking-at org-radio-target-regexp)
23212 (push (org-point-in-group p 0 :radio-target) clist))
23213 (goto-char p))
23214 ((setq o (car (delq nil
23215 (mapcar
23216 (lambda (x)
23217 (if (memq x org-latex-fragment-image-overlays) x))
23218 (org-overlays-at (point))))))
23219 (push (list :latex-fragment
23220 (org-overlay-start o) (org-overlay-end o)) clist)
23221 (push (list :latex-preview
23222 (org-overlay-start o) (org-overlay-end o)) clist))
23223 ((org-inside-LaTeX-fragment-p)
23224 ;; FIXME: positions wrong.
23225 (push (list :latex-fragment (point) (point)) clist)))
23227 (setq clist (nreverse (delq nil clist)))
23228 clist))
23230 ;; FIXME Compare with at-regexp-p
23231 (defun org-in-regexp (re &optional nlines visually)
23232 "Check if point is inside a match of regexp.
23233 Normally only the current line is checked, but you can include NLINES extra
23234 lines both before and after point into the search.
23235 If VISUALLY is set, require that the cursor is not after the match but
23236 really on, so that the block visually is on the match."
23237 (catch 'exit
23238 (let ((pos (point))
23239 (eol (point-at-eol (+ 1 (or nlines 0))))
23240 (inc (if visually 1 0)))
23241 (save-excursion
23242 (beginning-of-line (- 1 (or nlines 0)))
23243 (while (re-search-forward re eol t)
23244 (if (and (<= (match-beginning 0) pos)
23245 (>= (+ inc (match-end 0)) pos))
23246 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
23248 (defun org-at-regexp-p (regexp)
23249 "Is point inside a match of REGEXP in the current line?"
23250 (catch 'exit
23251 (save-excursion
23252 (let ((pos (point)) (end (point-at-eol)))
23253 (beginning-of-line 1)
23254 (while (re-search-forward regexp end t)
23255 (if (and (<= (match-beginning 0) pos)
23256 (>= (match-end 0) pos))
23257 (throw 'exit t)))
23258 nil))))
23260 (defun org-uniquify (list)
23261 "Remove duplicate elements from LIST."
23262 (let (res)
23263 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
23264 res))
23266 (defun org-delete-all (elts list)
23267 "Remove all elements in ELTS from LIST."
23268 (while elts
23269 (setq list (delete (pop elts) list)))
23270 list)
23272 (defun org-point-in-group (point group &optional context)
23273 "Check if POINT is in match-group GROUP.
23274 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
23275 match. If the match group does ot exist or point is not inside it,
23276 return nil."
23277 (and (match-beginning group)
23278 (>= point (match-beginning group))
23279 (<= point (match-end group))
23280 (if context
23281 (list context (match-beginning group) (match-end group))
23282 t)))
23284 (defun org-combine-plists (&rest plists)
23285 "Create a single property list from all plists in PLISTS.
23286 The process starts by copying the first list, and then setting properties
23287 from the other lists. Settings in the last list are the most significant
23288 ones and overrule settings in the other lists."
23289 (let ((rtn (copy-sequence (pop plists)))
23290 p v ls)
23291 (while plists
23292 (setq ls (pop plists))
23293 (while ls
23294 (setq p (pop ls) v (pop ls))
23295 (setq rtn (plist-put rtn p v))))
23296 rtn))
23298 (defun org-move-line-down (arg)
23299 "Move the current line down. With prefix argument, move it past ARG lines."
23300 (interactive "p")
23301 (let ((col (current-column))
23302 beg end pos)
23303 (beginning-of-line 1) (setq beg (point))
23304 (beginning-of-line 2) (setq end (point))
23305 (beginning-of-line (+ 1 arg))
23306 (setq pos (move-marker (make-marker) (point)))
23307 (insert (delete-and-extract-region beg end))
23308 (goto-char pos)
23309 (move-to-column col)))
23311 (defun org-move-line-up (arg)
23312 "Move the current line up. With prefix argument, move it past ARG lines."
23313 (interactive "p")
23314 (let ((col (current-column))
23315 beg end pos)
23316 (beginning-of-line 1) (setq beg (point))
23317 (beginning-of-line 2) (setq end (point))
23318 (beginning-of-line (- arg))
23319 (setq pos (move-marker (make-marker) (point)))
23320 (insert (delete-and-extract-region beg end))
23321 (goto-char pos)
23322 (move-to-column col)))
23324 (defun org-replace-escapes (string table)
23325 "Replace %-escapes in STRING with values in TABLE.
23326 TABLE is an association list with keys line \"%a\" and string values.
23327 The sequences in STRING may contain normal field width and padding information,
23328 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
23329 so values can contain further %-escapes if they are define later in TABLE."
23330 (let ((case-fold-search nil)
23331 e re rpl)
23332 (while (setq e (pop table))
23333 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
23334 (while (string-match re string)
23335 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
23336 (cdr e)))
23337 (setq string (replace-match rpl t t string))))
23338 string))
23341 (defun org-sublist (list start end)
23342 "Return a section of LIST, from START to END.
23343 Counting starts at 1."
23344 (let (rtn (c start))
23345 (setq list (nthcdr (1- start) list))
23346 (while (and list (<= c end))
23347 (push (pop list) rtn)
23348 (setq c (1+ c)))
23349 (nreverse rtn)))
23351 (defun org-find-base-buffer-visiting (file)
23352 "Like `find-buffer-visiting' but alway return the base buffer and
23353 not an indirect buffer"
23354 (let ((buf (find-buffer-visiting file)))
23355 (or (buffer-base-buffer buf) buf)))
23357 (defun org-image-file-name-regexp ()
23358 "Return regexp matching the file names of images."
23359 (if (fboundp 'image-file-name-regexp)
23360 (image-file-name-regexp)
23361 (let ((image-file-name-extensions
23362 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
23363 "xbm" "xpm" "pbm" "pgm" "ppm")))
23364 (concat "\\."
23365 (regexp-opt (nconc (mapcar 'upcase
23366 image-file-name-extensions)
23367 image-file-name-extensions)
23369 "\\'"))))
23371 (defun org-file-image-p (file)
23372 "Return non-nil if FILE is an image."
23373 (save-match-data
23374 (string-match (org-image-file-name-regexp) file)))
23376 ;;; Paragraph filling stuff.
23377 ;; We want this to be just right, so use the full arsenal.
23379 (defun org-indent-line-function ()
23380 "Indent line like previous, but further if previous was headline or item."
23381 (interactive)
23382 (let* ((pos (point))
23383 (itemp (org-at-item-p))
23384 column bpos bcol tpos tcol bullet btype bullet-type)
23385 ;; Find the previous relevant line
23386 (beginning-of-line 1)
23387 (cond
23388 ((looking-at "#") (setq column 0))
23389 ((looking-at "\\*+ ") (setq column 0))
23391 (beginning-of-line 0)
23392 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
23393 (beginning-of-line 0))
23394 (cond
23395 ((looking-at "\\*+[ \t]+")
23396 (goto-char (match-end 0))
23397 (setq column (current-column)))
23398 ((org-in-item-p)
23399 (org-beginning-of-item)
23400 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
23401 (setq bpos (match-beginning 1) tpos (match-end 0)
23402 bcol (progn (goto-char bpos) (current-column))
23403 tcol (progn (goto-char tpos) (current-column))
23404 bullet (match-string 1)
23405 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
23406 (if (not itemp)
23407 (setq column tcol)
23408 (goto-char pos)
23409 (beginning-of-line 1)
23410 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
23411 (setq bullet (match-string 1)
23412 btype (if (string-match "[0-9]" bullet) "n" bullet))
23413 (setq column (if (equal btype bullet-type) bcol tcol))))
23414 (t (setq column (org-get-indentation))))))
23415 (goto-char pos)
23416 (if (<= (current-column) (current-indentation))
23417 (indent-line-to column)
23418 (save-excursion (indent-line-to column)))
23419 (setq column (current-column))
23420 (beginning-of-line 1)
23421 (if (looking-at
23422 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
23423 (replace-match (concat "\\1" (format org-property-format
23424 (match-string 2) (match-string 3)))
23425 t nil))
23426 (move-to-column column)))
23428 (defun org-set-autofill-regexps ()
23429 (interactive)
23430 ;; In the paragraph separator we include headlines, because filling
23431 ;; text in a line directly attached to a headline would otherwise
23432 ;; fill the headline as well.
23433 (org-set-local 'comment-start-skip "^#+[ \t]*")
23434 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
23435 ;; FIXME!!!!!!! (org-set-local 'paragraph-separate "\f\\|[ ]*$")
23436 ;; The paragraph starter includes hand-formatted lists.
23437 (org-set-local 'paragraph-start
23438 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
23439 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
23440 ;; But only if the user has not turned off tables or fixed-width regions
23441 (org-set-local
23442 'auto-fill-inhibit-regexp
23443 (concat "\\*+ \\|#\\+"
23444 "\\|[ \t]*" org-keyword-time-regexp
23445 (if (or org-enable-table-editor org-enable-fixed-width-editor)
23446 (concat
23447 "\\|[ \t]*["
23448 (if org-enable-table-editor "|" "")
23449 (if org-enable-fixed-width-editor ":" "")
23450 "]"))))
23451 ;; We use our own fill-paragraph function, to make sure that tables
23452 ;; and fixed-width regions are not wrapped. That function will pass
23453 ;; through to `fill-paragraph' when appropriate.
23454 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
23455 ; Adaptive filling: To get full control, first make sure that
23456 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
23457 (org-set-local 'adaptive-fill-regexp "\000")
23458 (org-set-local 'adaptive-fill-function
23459 'org-adaptive-fill-function))
23461 (defun org-fill-paragraph (&optional justify)
23462 "Re-align a table, pass through to fill-paragraph if no table."
23463 (let ((table-p (org-at-table-p))
23464 (table.el-p (org-at-table.el-p)))
23465 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
23466 (table.el-p t) ; skip table.el tables
23467 (table-p (org-table-align) t) ; align org-mode tables
23468 (t nil)))) ; call paragraph-fill
23470 ;; For reference, this is the default value of adaptive-fill-regexp
23471 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
23473 (defun org-adaptive-fill-function ()
23474 "Return a fill prefix for org-mode files.
23475 In particular, this makes sure hanging paragraphs for hand-formatted lists
23476 work correctly."
23477 (cond ((looking-at "#[ \t]+")
23478 (match-string 0))
23479 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
23480 (save-excursion
23481 (goto-char (match-end 0))
23482 (make-string (current-column) ?\ )))
23483 (t nil)))
23485 ;;;; Functions extending outline functionality
23487 ;; C-a should go to the beginning of a *visible* line, also in the
23488 ;; new outline.el. I guess this should be patched into Emacs?
23489 (defun org-beginning-of-line (&optional arg)
23490 "Go to the beginning of the current line. If that is invisible, continue
23491 to a visible line beginning. This makes the function of C-a more intuitive.
23492 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23493 first attempt, and only move to after the tags when the cursor is already
23494 beyond the end of the headline."
23495 (interactive "P")
23496 (let ((pos (point)))
23497 (beginning-of-line 1)
23498 (if (bobp)
23500 (backward-char 1)
23501 (if (org-invisible-p)
23502 (while (and (not (bobp)) (org-invisible-p))
23503 (backward-char 1)
23504 (beginning-of-line 1))
23505 (forward-char 1)))
23506 (when (and org-special-ctrl-a/e (looking-at org-todo-line-regexp)
23507 (= (char-after (match-end 1)) ?\ ))
23508 (goto-char
23509 (cond ((> pos (match-beginning 3)) (match-beginning 3))
23510 ((= pos (point)) (match-beginning 3))
23511 (t (point)))))))
23513 (defun org-end-of-line (&optional arg)
23514 "Go to the end of the line.
23515 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23516 first attempt, and only move to after the tags when the cursor is already
23517 beyond the end of the headline."
23518 (interactive "P")
23519 (if (or (not org-special-ctrl-a/e)
23520 (not (org-on-heading-p)))
23521 (end-of-line arg)
23522 (let ((pos (point)))
23523 (beginning-of-line 1)
23524 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
23525 (if (or (< pos (match-beginning 1))
23526 (= pos (match-end 0)))
23527 (goto-char (match-beginning 1))
23528 (goto-char (match-end 0)))
23529 (end-of-line arg)))))
23531 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23532 (define-key org-mode-map "\C-e" 'org-end-of-line)
23534 (defun org-invisible-p ()
23535 "Check if point is at a character currently not visible."
23536 ;; Early versions of noutline don't have `outline-invisible-p'.
23537 (if (fboundp 'outline-invisible-p)
23538 (outline-invisible-p)
23539 (get-char-property (point) 'invisible)))
23541 (defun org-invisible-p2 ()
23542 "Check if point is at a character currently not visible."
23543 (save-excursion
23544 (if (and (eolp) (not (bobp))) (backward-char 1))
23545 ;; Early versions of noutline don't have `outline-invisible-p'.
23546 (if (fboundp 'outline-invisible-p)
23547 (outline-invisible-p)
23548 (get-char-property (point) 'invisible))))
23550 (defalias 'org-back-to-heading 'outline-back-to-heading)
23551 (defalias 'org-on-heading-p 'outline-on-heading-p)
23552 (defalias 'org-at-heading-p 'outline-on-heading-p)
23553 (defun org-at-heading-or-item-p ()
23554 (or (org-on-heading-p) (org-at-item-p)))
23556 (defun org-on-target-p ()
23557 (or (org-in-regexp org-radio-target-regexp)
23558 (org-in-regexp org-target-regexp)))
23560 (defun org-up-heading-all (arg)
23561 "Move to the heading line of which the present line is a subheading.
23562 This function considers both visible and invisible heading lines.
23563 With argument, move up ARG levels."
23564 (if (fboundp 'outline-up-heading-all)
23565 (outline-up-heading-all arg) ; emacs 21 version of outline.el
23566 (outline-up-heading arg t))) ; emacs 22 version of outline.el
23568 (defun org-goto-sibling (&optional previous)
23569 "Goto the next sibling, even if it is invisible.
23570 When PREVIOUS is set, go to the previous sibling instead. Returns t
23571 when a sibling was found. When none is found, return nil and don't
23572 move point."
23573 (let ((fun (if previous 're-search-backward 're-search-forward))
23574 (pos (point))
23575 (re (concat "^" outline-regexp))
23576 level l)
23577 (when (condition-case nil (org-back-to-heading t) (error nil))
23578 (setq level (funcall outline-level))
23579 (catch 'exit
23580 (or previous (forward-char 1))
23581 (while (funcall fun re nil t)
23582 (setq l (funcall outline-level))
23583 (when (< l level) (goto-char pos) (throw 'exit nil))
23584 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23585 (goto-char pos)
23586 nil))))
23588 (defun org-show-siblings ()
23589 "Show all siblings of the current headline."
23590 (save-excursion
23591 (while (org-goto-sibling) (org-flag-heading nil)))
23592 (save-excursion
23593 (while (org-goto-sibling 'previous)
23594 (org-flag-heading nil))))
23596 (defun org-show-hidden-entry ()
23597 "Show an entry where even the heading is hidden."
23598 (save-excursion
23599 (org-show-entry)))
23601 (defun org-flag-heading (flag &optional entry)
23602 "Flag the current heading. FLAG non-nil means make invisible.
23603 When ENTRY is non-nil, show the entire entry."
23604 (save-excursion
23605 (org-back-to-heading t)
23606 ;; Check if we should show the entire entry
23607 (if entry
23608 (progn
23609 (org-show-entry)
23610 (save-excursion
23611 (and (outline-next-heading)
23612 (org-flag-heading nil))))
23613 (outline-flag-region (max 1 (1- (point)))
23614 (save-excursion (outline-end-of-heading) (point))
23615 flag))))
23617 (defun org-end-of-subtree (&optional invisible-OK to-heading)
23618 ;; This is an exact copy of the original function, but it uses
23619 ;; `org-back-to-heading', to make it work also in invisible
23620 ;; trees. And is uses an invisible-OK argument.
23621 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23622 (org-back-to-heading invisible-OK)
23623 (let ((first t)
23624 (level (funcall outline-level)))
23625 (while (and (not (eobp))
23626 (or first (> (funcall outline-level) level)))
23627 (setq first nil)
23628 (outline-next-heading))
23629 (unless to-heading
23630 (if (memq (preceding-char) '(?\n ?\^M))
23631 (progn
23632 ;; Go to end of line before heading
23633 (forward-char -1)
23634 (if (memq (preceding-char) '(?\n ?\^M))
23635 ;; leave blank line before heading
23636 (forward-char -1))))))
23637 (point))
23639 (defun org-show-subtree ()
23640 "Show everything after this heading at deeper levels."
23641 (outline-flag-region
23642 (point)
23643 (save-excursion
23644 (outline-end-of-subtree) (outline-next-heading) (point))
23645 nil))
23647 (defun org-show-entry ()
23648 "Show the body directly following this heading.
23649 Show the heading too, if it is currently invisible."
23650 (interactive)
23651 (save-excursion
23652 (org-back-to-heading t)
23653 (outline-flag-region
23654 (max 1 (1- (point)))
23655 (save-excursion
23656 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
23657 (or (match-beginning 1) (point-max)))
23658 nil)))
23660 (defun org-make-options-regexp (kwds)
23661 "Make a regular expression for keyword lines."
23662 (concat
23664 "#?[ \t]*\\+\\("
23665 (mapconcat 'regexp-quote kwds "\\|")
23666 "\\):[ \t]*"
23667 "\\(.+\\)"))
23669 ;; Make isearch reveal the necessary context
23670 (defun org-isearch-end ()
23671 "Reveal context after isearch exits."
23672 (when isearch-success ; only if search was successful
23673 (if (featurep 'xemacs)
23674 ;; Under XEmacs, the hook is run in the correct place,
23675 ;; we directly show the context.
23676 (org-show-context 'isearch)
23677 ;; In Emacs the hook runs *before* restoring the overlays.
23678 ;; So we have to use a one-time post-command-hook to do this.
23679 ;; (Emacs 22 has a special variable, see function `org-mode')
23680 (unless (and (boundp 'isearch-mode-end-hook-quit)
23681 isearch-mode-end-hook-quit)
23682 ;; Only when the isearch was not quitted.
23683 (org-add-hook 'post-command-hook 'org-isearch-post-command
23684 'append 'local)))))
23686 (defun org-isearch-post-command ()
23687 "Remove self from hook, and show context."
23688 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
23689 (org-show-context 'isearch))
23692 ;;;; Address problems with some other packages
23694 ;; Make flyspell not check words in links, to not mess up our keymap
23695 (defun org-mode-flyspell-verify ()
23696 "Don't let flyspell put overlays at active buttons."
23697 (not (get-text-property (point) 'keymap)))
23699 ;; Make `bookmark-jump' show the jump location if it was hidden.
23700 (eval-after-load "bookmark"
23701 '(if (boundp 'bookmark-after-jump-hook)
23702 ;; We can use the hook
23703 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
23704 ;; Hook not available, use advice
23705 (defadvice bookmark-jump (after org-make-visible activate)
23706 "Make the position visible."
23707 (org-bookmark-jump-unhide))))
23709 (defun org-bookmark-jump-unhide ()
23710 "Unhide the current position, to show the bookmark location."
23711 (and (org-mode-p)
23712 (or (org-invisible-p)
23713 (save-excursion (goto-char (max (point-min) (1- (point))))
23714 (org-invisible-p)))
23715 (org-show-context 'bookmark-jump)))
23717 ;; Make session.el ignore our circular variable
23718 (eval-after-load "session"
23719 '(add-to-list 'session-globals-exclude 'org-mark-ring))
23721 ;;;; Experimental code
23723 (defun org-closed-in-range ()
23724 "Sparse tree of items closed in a certain time range.
23725 Still experimental, may disappear in the furture."
23726 (interactive)
23727 ;; Get the time interval from the user.
23728 (let* ((time1 (time-to-seconds
23729 (org-read-date nil 'to-time nil "Starting date: ")))
23730 (time2 (time-to-seconds
23731 (org-read-date nil 'to-time nil "End date:")))
23732 ;; callback function
23733 (callback (lambda ()
23734 (let ((time
23735 (time-to-seconds
23736 (apply 'encode-time
23737 (org-parse-time-string
23738 (match-string 1))))))
23739 ;; check if time in interval
23740 (and (>= time time1) (<= time time2))))))
23741 ;; make tree, check each match with the callback
23742 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
23744 (defun org-fill-paragraph-experimental (&optional justify)
23745 "Re-align a table, pass through to fill-paragraph if no table."
23746 (let ((table-p (org-at-table-p))
23747 (table.el-p (org-at-table.el-p)))
23748 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
23749 (table.el-p t) ; skip table.el tables
23750 (table-p (org-table-align) t) ; align org-mode tables
23751 ((save-excursion
23752 (let ((pos (1+ (point-at-eol))))
23753 (backward-paragraph 1)
23754 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
23755 (save-excursion
23756 (save-restriction
23757 (narrow-to-region (1+ (match-end 0)) (point-max))
23758 (fill-paragraph nil)
23759 t)))
23760 (t nil)))) ; call paragraph-fill
23762 (defun org-property-previous-allowed-value (&optional previous)
23763 "Switch to the next allowed value for this property."
23764 (interactive)
23765 (org-property-next-allowed-value t))
23767 (defun org-property-next-allowed-value (&optional previous)
23768 "Switch to the next allowed value for this property."
23769 (interactive)
23770 (unless (org-at-property-p)
23771 (error "Not at a property"))
23772 (let* ((key (match-string 2))
23773 (value (match-string 3))
23774 (allowed (or (org-property-get-allowed-values (point) key)
23775 (and (member value '("[ ]" "[-]" "[X]"))
23776 '("[ ]" "[X]"))))
23777 nval)
23778 (unless allowed
23779 (error "Allowed values for this property have not been defined"))
23780 (if previous (setq allowed (reverse allowed)))
23781 (if (member value allowed)
23782 (setq nval (car (cdr (member value allowed)))))
23783 (setq nval (or nval (car allowed)))
23784 (if (equal nval value)
23785 (error "Only one allowed value for this property"))
23786 (org-at-property-p)
23787 (replace-match (concat " :" key ": " nval))
23788 (org-indent-line-function)
23789 (beginning-of-line 1)
23790 (skip-chars-forward " \t")))
23792 ;;;; Finish up
23794 (provide 'org)
23796 (run-hooks 'org-load-hook)
23798 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
23799 ;;; org.el ends here