Release 5.13
[org-mode.git] / org.el
blob07fd76406cf47137a196e8105db2fb705dacf42f
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.13
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.13"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 (defmacro org-unmodified (&rest body)
101 "Execute body without changing buffer-modified-p."
102 `(set-buffer-modified-p
103 (prog1 (buffer-modified-p) ,@body)))
105 (defmacro org-re (s)
106 "Replace posix classes in regular expression."
107 (if (featurep 'xemacs)
108 (let ((ss s))
109 (save-match-data
110 (while (string-match "\\[:alnum:\\]" ss)
111 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
112 (while (string-match "\\[:alpha:\\]" ss)
113 (setq ss (replace-match "a-zA-Z" t t ss)))
114 ss))
117 (defmacro org-preserve-lc (&rest body)
118 `(let ((_line (org-current-line))
119 (_col (current-column)))
120 (unwind-protect
121 (progn ,@body)
122 (goto-line _line)
123 (move-to-column _col))))
125 (defmacro org-without-partial-completion (&rest body)
126 `(let ((pc-mode (and (boundp 'partial-completion-mode)
127 partial-completion-mode)))
128 (unwind-protect
129 (progn
130 (if pc-mode (partial-completion-mode -1))
131 ,@body)
132 (if pc-mode (partial-completion-mode 1)))))
134 ;;; The custom variables
136 (defgroup org nil
137 "Outline-based notes management and organizer."
138 :tag "Org"
139 :group 'outlines
140 :group 'hypermedia
141 :group 'calendar)
143 ;; FIXME: Needs a separate group...
144 (defcustom org-completion-fallback-command 'hippie-expand
145 "The expansion command called by \\[org-complete] in normal context.
146 Normal means, no org-mode-specific context."
147 :group 'org
148 :type 'function)
150 (defgroup org-startup nil
151 "Options concerning startup of Org-mode."
152 :tag "Org Startup"
153 :group 'org)
155 (defcustom org-startup-folded t
156 "Non-nil means, entering Org-mode will switch to OVERVIEW.
157 This can also be configured on a per-file basis by adding one of
158 the following lines anywhere in the buffer:
160 #+STARTUP: fold
161 #+STARTUP: nofold
162 #+STARTUP: content"
163 :group 'org-startup
164 :type '(choice
165 (const :tag "nofold: show all" nil)
166 (const :tag "fold: overview" t)
167 (const :tag "content: all headlines" content)))
169 (defcustom org-startup-truncated t
170 "Non-nil means, entering Org-mode will set `truncate-lines'.
171 This is useful since some lines containing links can be very long and
172 uninteresting. Also tables look terrible when wrapped."
173 :group 'org-startup
174 :type 'boolean)
176 (defcustom org-startup-align-all-tables nil
177 "Non-nil means, align all tables when visiting a file.
178 This is useful when the column width in tables is forced with <N> cookies
179 in table fields. Such tables will look correct only after the first re-align.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182 #+STARTUP: align
183 #+STARTUP: noalign"
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-insert-mode-line-in-empty-file nil
188 "Non-nil means insert the first line setting Org-mode in empty files.
189 When the function `org-mode' is called interactively in an empty file, this
190 normally means that the file name does not automatically trigger Org-mode.
191 To ensure that the file will always be in Org-mode in the future, a
192 line enforcing Org-mode will be inserted into the buffer, if this option
193 has been set."
194 :group 'org-startup
195 :type 'boolean)
197 (defcustom org-replace-disputed-keys nil
198 "Non-nil means use alternative key bindings for some keys.
199 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
200 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
201 If you want to use Org-mode together with one of these other modes,
202 or more generally if you would like to move some Org-mode commands to
203 other keys, set this variable and configure the keys with the variable
204 `org-disputed-keys'.
206 This option is only relevant at load-time of Org-mode, and must be set
207 *before* org.el is loaded. Changing it requires a restart of Emacs to
208 become effective."
209 :group 'org-startup
210 :type 'boolean)
212 (if (fboundp 'defvaralias)
213 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
215 (defcustom org-disputed-keys
216 '(([(shift up)] . [(meta p)])
217 ([(shift down)] . [(meta n)])
218 ([(shift left)] . [(meta -)])
219 ([(shift right)] . [(meta +)])
220 ([(control shift right)] . [(meta shift +)])
221 ([(control shift left)] . [(meta shift -)]))
222 "Keys for which Org-mode and other modes compete.
223 This is an alist, cars are the default keys, second element specifies
224 the alternative to use when `org-replace-disputed-keys' is t.
226 Keys can be specified in any syntax supported by `define-key'.
227 The value of this option takes effect only at Org-mode's startup,
228 therefore you'll have to restart Emacs to apply it after changing."
229 :group 'org-startup
230 :type 'alist)
232 (defun org-key (key)
233 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
234 Or return the original if not disputed."
235 (if org-replace-disputed-keys
236 (let* ((nkey (key-description key))
237 (x (org-find-if (lambda (x)
238 (equal (key-description (car x)) nkey))
239 org-disputed-keys)))
240 (if x (cdr x) key))
241 key))
243 (defun org-find-if (predicate seq)
244 (catch 'exit
245 (while seq
246 (if (funcall predicate (car seq))
247 (throw 'exit (car seq))
248 (pop seq)))))
250 (defun org-defkey (keymap key def)
251 "Define a key, possibly translated, as returned by `org-key'."
252 (define-key keymap (org-key key) def))
254 (defcustom org-ellipsis 'org-ellipsis
255 "The ellipsis to use in the Org-mode outline.
256 When nil, just use the standard three dots. When a string, use that instead,
257 When a face, use the standart 3 dots, but with the specified face.
258 The change affects only Org-mode (which will then use its own display table).
259 Changing this requires executing `M-x org-mode' in a buffer to become
260 effective."
261 :group 'org-startup
262 :type '(choice (const :tag "Default" nil)
263 (face :tag "Face" :value org-warning)
264 (string :tag "String" :value "...#")))
266 (defvar org-display-table nil
267 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
269 (defgroup org-keywords nil
270 "Keywords in Org-mode."
271 :tag "Org Keywords"
272 :group 'org)
274 (defcustom org-deadline-string "DEADLINE:"
275 "String to mark deadline entries.
276 A deadline is this string, followed by a time stamp. Should be a word,
277 terminated by a colon. You can insert a schedule keyword and
278 a timestamp with \\[org-deadline].
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type 'string)
283 (defcustom org-scheduled-string "SCHEDULED:"
284 "String to mark scheduled TODO entries.
285 A schedule is this string, followed by a time stamp. Should be a word,
286 terminated by a colon. You can insert a schedule keyword and
287 a timestamp with \\[org-schedule].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
292 (defcustom org-closed-string "CLOSED:"
293 "String used as the prefix for timestamps logging closing a TODO entry."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-clock-string "CLOCK:"
298 "String used as prefix for timestamps clocking work hours on an item."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-comment-string "COMMENT"
303 "Entries starting with this keyword will never be exported.
304 An entry can be toggled between COMMENT and normal with
305 \\[org-toggle-comment].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
310 (defcustom org-quote-string "QUOTE"
311 "Entries starting with this keyword will be exported in fixed-width font.
312 Quoting applies only to the text in the entry following the headline, and does
313 not extend beyond the next headline, even if that is lower level.
314 An entry can be toggled between QUOTE and normal with
315 \\[org-toggle-fixed-width-section]."
316 :group 'org-keywords
317 :type 'string)
319 (defconst org-repeat-re
320 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
321 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
322 "Regular expression for specifying repeated events.
323 After a match, group 1 contains the repeat expression.")
325 (defgroup org-structure nil
326 "Options concerning the general structure of Org-mode files."
327 :tag "Org Structure"
328 :group 'org)
330 (defgroup org-reveal-location nil
331 "Options about how to make context of a location visible."
332 :tag "Org Reveal Location"
333 :group 'org-structure)
335 (defcustom org-show-hierarchy-above '((default . t))
336 "Non-nil means, show full hierarchy when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the hierarchy of headings
339 above the exposed location is shown.
340 Turning this off for example for sparse trees makes them very compact.
341 Instead of t, this can also be an alist specifying this option for different
342 contexts. Valid contexts are
343 agenda when exposing an entry from the agenda
344 org-goto when using the command `org-goto' on key C-c C-j
345 occur-tree when using the command `org-occur' on key C-c /
346 tags-tree when constructing a sparse tree based on tags matches
347 link-search when exposing search matches associated with a link
348 mark-goto when exposing the jump goal of a mark
349 bookmark-jump when exposing a bookmark location
350 isearch when exiting from an incremental search
351 default default for all contexts not set explicitly"
352 :group 'org-reveal-location
353 :type '(choice
354 (const :tag "Always" t)
355 (const :tag "Never" nil)
356 (repeat :greedy t :tag "Individual contexts"
357 (cons
358 (choice :tag "Context"
359 (const agenda)
360 (const org-goto)
361 (const occur-tree)
362 (const tags-tree)
363 (const link-search)
364 (const mark-goto)
365 (const bookmark-jump)
366 (const isearch)
367 (const default))
368 (boolean)))))
370 (defcustom org-show-following-heading '((default . nil))
371 "Non-nil means, show following heading when revealing a location.
372 Org-mode often shows locations in an org-mode file which might have
373 been invisible before. When this is set, the heading following the
374 match is shown.
375 Turning this off for example for sparse trees makes them very compact,
376 but makes it harder to edit the location of the match. In such a case,
377 use the command \\[org-reveal] to show more context.
378 Instead of t, this can also be an alist specifying this option for different
379 contexts. See `org-show-hierarchy-above' for valid contexts."
380 :group 'org-reveal-location
381 :type '(choice
382 (const :tag "Always" t)
383 (const :tag "Never" nil)
384 (repeat :greedy t :tag "Individual contexts"
385 (cons
386 (choice :tag "Context"
387 (const agenda)
388 (const org-goto)
389 (const occur-tree)
390 (const tags-tree)
391 (const link-search)
392 (const mark-goto)
393 (const bookmark-jump)
394 (const isearch)
395 (const default))
396 (boolean)))))
398 (defcustom org-show-siblings '((default . nil) (isearch t))
399 "Non-nil means, show all sibling heading when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the sibling of the current entry
402 heading are all made visible. If `org-show-hierarchy-above' is t,
403 the same happens on each level of the hierarchy above the current entry.
405 By default this is on for the isearch context, off for all other contexts.
406 Turning this off for example for sparse trees makes them very compact,
407 but makes it harder to edit the location of the match. In such a case,
408 use the command \\[org-reveal] to show more context.
409 Instead of t, this can also be an alist specifying this option for different
410 contexts. See `org-show-hierarchy-above' for valid contexts."
411 :group 'org-reveal-location
412 :type '(choice
413 (const :tag "Always" t)
414 (const :tag "Never" nil)
415 (repeat :greedy t :tag "Individual contexts"
416 (cons
417 (choice :tag "Context"
418 (const agenda)
419 (const org-goto)
420 (const occur-tree)
421 (const tags-tree)
422 (const link-search)
423 (const mark-goto)
424 (const bookmark-jump)
425 (const isearch)
426 (const default))
427 (boolean)))))
429 (defgroup org-cycle nil
430 "Options concerning visibility cycling in Org-mode."
431 :tag "Org Cycle"
432 :group 'org-structure)
434 (defcustom org-drawers '("PROPERTIES" "CLOCK")
435 "Names of drawers. Drawers are not opened by cycling on the headline above.
436 Drawers only open with a TAB on the drawer line itself. A drawer looks like
437 this:
438 :DRAWERNAME:
439 .....
440 :END:
441 The drawer \"PROPERTIES\" is special for capturing properties through
442 the property API.
444 Drawers can be defined on the per-file basis with a line like:
446 #+DRAWERS: HIDDEN STATE PROPERTIES"
447 :group 'org-structure
448 :type '(repeat (string :tag "Drawer Name")))
450 (defcustom org-cycle-global-at-bob nil
451 "Cycle globally if cursor is at beginning of buffer and not at a headline.
452 This makes it possible to do global cycling without having to use S-TAB or
453 C-u TAB. For this special case to work, the first line of the buffer
454 must not be a headline - it may be empty ot some other text. When used in
455 this way, `org-cycle-hook' is disables temporarily, to make sure the
456 cursor stays at the beginning of the buffer.
457 When this option is nil, don't do anything special at the beginning
458 of the buffer."
459 :group 'org-cycle
460 :type 'boolean)
462 (defcustom org-cycle-emulate-tab t
463 "Where should `org-cycle' emulate TAB.
464 nil Never
465 white Only in completely white lines
466 whitestart Only at the beginning of lines, before the first non-white char.
467 t Everywhere except in headlines
468 exc-hl-bol Everywhere except at the start of a headline
469 If TAB is used in a place where it does not emulate TAB, the current subtree
470 visibility is cycled."
471 :group 'org-cycle
472 :type '(choice (const :tag "Never" nil)
473 (const :tag "Only in completely white lines" white)
474 (const :tag "Before first char in a line" whitestart)
475 (const :tag "Everywhere except in headlines" t)
476 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
479 (defcustom org-cycle-separator-lines 2
480 "Number of empty lines needed to keep an empty line between collapsed trees.
481 If you leave an empty line between the end of a subtree and the following
482 headline, this empty line is hidden when the subtree is folded.
483 Org-mode will leave (exactly) one empty line visible if the number of
484 empty lines is equal or larger to the number given in this variable.
485 So the default 2 means, at least 2 empty lines after the end of a subtree
486 are needed to produce free space between a collapsed subtree and the
487 following headline.
489 Special case: when 0, never leave empty lines in collapsed view."
490 :group 'org-cycle
491 :type 'integer)
493 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
494 org-cycle-hide-drawers
495 org-cycle-show-empty-lines
496 org-optimize-window-after-visibility-change)
497 "Hook that is run after `org-cycle' has changed the buffer visibility.
498 The function(s) in this hook must accept a single argument which indicates
499 the new state that was set by the most recent `org-cycle' command. The
500 argument is a symbol. After a global state change, it can have the values
501 `overview', `content', or `all'. After a local state change, it can have
502 the values `folded', `children', or `subtree'."
503 :group 'org-cycle
504 :type 'hook)
506 (defgroup org-edit-structure nil
507 "Options concerning structure editing in Org-mode."
508 :tag "Org Edit Structure"
509 :group 'org-structure)
511 (defcustom org-special-ctrl-a/e nil
512 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
513 When t, `C-a' will bring back the cursor to the beginning of the
514 headline text, i.e. after the stars and after a possible TODO keyword.
515 In an item, this will be the position after the bullet.
516 When the cursor is already at that position, another `C-a' will bring
517 it to the beginning of the line.
518 `C-e' will jump to the end of the headline, ignoring the presence of tags
519 in the headline. A second `C-e' will then jump to the true end of the
520 line, after any tags.
521 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
522 and only a directly following, identical keypress will bring the cursor
523 to the special positions."
524 :group 'org-edit-structure
525 :type '(choice
526 (const :tag "off" nil)
527 (const :tag "after bullet first" t)
528 (const :tag "border first" reversed)))
530 (if (fboundp 'defvaralias)
531 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
558 (defcustom org-blank-before-new-entry '((heading . nil)
559 (plain-list-item . nil))
560 "Should `org-insert-heading' leave a blank line before new heading/item?
561 The value is an alist, with `heading' and `plain-list-item' as car,
562 and a boolean flag as cdr."
563 :group 'org-edit-structure
564 :type '(list
565 (cons (const heading) (boolean))
566 (cons (const plain-list-item) (boolean))))
568 (defcustom org-insert-heading-hook nil
569 "Hook being run after inserting a new heading."
570 :group 'org-edit-structure
571 :type 'boolean)
573 (defcustom org-enable-fixed-width-editor t
574 "Non-nil means, lines starting with \":\" are treated as fixed-width.
575 This currently only means, they are never auto-wrapped.
576 When nil, such lines will be treated like ordinary lines.
577 See also the QUOTE keyword."
578 :group 'org-edit-structure
579 :type 'boolean)
581 (defgroup org-sparse-trees nil
582 "Options concerning sparse trees in Org-mode."
583 :tag "Org Sparse Trees"
584 :group 'org-structure)
586 (defcustom org-highlight-sparse-tree-matches t
587 "Non-nil means, highlight all matches that define a sparse tree.
588 The highlights will automatically disappear the next time the buffer is
589 changed by an edit command."
590 :group 'org-sparse-trees
591 :type 'boolean)
593 (defcustom org-remove-highlights-with-change t
594 "Non-nil means, any change to the buffer will remove temporary highlights.
595 Such highlights are created by `org-occur' and `org-clock-display'.
596 When nil, `C-c C-c needs to be used to get rid of the highlights.
597 The highlights created by `org-preview-latex-fragment' always need
598 `C-c C-c' to be removed."
599 :group 'org-sparse-trees
600 :group 'org-time
601 :type 'boolean)
604 (defcustom org-occur-hook '(org-first-headline-recenter)
605 "Hook that is run after `org-occur' has constructed a sparse tree.
606 This can be used to recenter the window to show as much of the structure
607 as possible."
608 :group 'org-sparse-trees
609 :type 'hook)
611 (defgroup org-plain-lists nil
612 "Options concerning plain lists in Org-mode."
613 :tag "Org Plain lists"
614 :group 'org-structure)
616 (defcustom org-cycle-include-plain-lists nil
617 "Non-nil means, include plain lists into visibility cycling.
618 This means that during cycling, plain list items will *temporarily* be
619 interpreted as outline headlines with a level given by 1000+i where i is the
620 indentation of the bullet. In all other operations, plain list items are
621 not seen as headlines. For example, you cannot assign a TODO keyword to
622 such an item."
623 :group 'org-plain-lists
624 :type 'boolean)
626 (defcustom org-plain-list-ordered-item-terminator t
627 "The character that makes a line with leading number an ordered list item.
628 Valid values are ?. and ?\). To get both terminators, use t. While
629 ?. may look nicer, it creates the danger that a line with leading
630 number may be incorrectly interpreted as an item. ?\) therefore is
631 the safe choice."
632 :group 'org-plain-lists
633 :type '(choice (const :tag "dot like in \"2.\"" ?.)
634 (const :tag "paren like in \"2)\"" ?\))
635 (const :tab "both" t)))
637 (defcustom org-auto-renumber-ordered-lists t
638 "Non-nil means, automatically renumber ordered plain lists.
639 Renumbering happens when the sequence have been changed with
640 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
641 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
642 :group 'org-plain-lists
643 :type 'boolean)
645 (defcustom org-provide-checkbox-statistics t
646 "Non-nil means, update checkbox statistics after insert and toggle.
647 When this is set, checkbox statistics is updated each time you either insert
648 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
649 with \\[org-ctrl-c-ctrl-c\\]."
650 :group 'org-plain-lists
651 :type 'boolean)
653 (defgroup org-archive nil
654 "Options concerning archiving in Org-mode."
655 :tag "Org Archive"
656 :group 'org-structure)
658 (defcustom org-archive-tag "ARCHIVE"
659 "The tag that marks a subtree as archived.
660 An archived subtree does not open during visibility cycling, and does
661 not contribute to the agenda listings."
662 :group 'org-archive
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-agenda-skip-archived-trees t
667 "Non-nil means, the agenda will skip any items located in archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE."
669 :group 'org-archive
670 :group 'org-agenda-skip
671 :type 'boolean)
673 (defcustom org-cycle-open-archived-trees nil
674 "Non-nil means, `org-cycle' will open archived trees.
675 An archived tree is a tree marked with the tag ARCHIVE.
676 When nil, archived trees will stay folded. You can still open them with
677 normal outline commands like `show-all', but not with the cycling commands."
678 :group 'org-archive
679 :group 'org-cycle
680 :type 'boolean)
682 (defcustom org-sparse-tree-open-archived-trees nil
683 "Non-nil means sparse tree construction shows matches in archived trees.
684 When nil, matches in these trees are highlighted, but the trees are kept in
685 collapsed state."
686 :group 'org-archive
687 :group 'org-sparse-trees
688 :type 'boolean)
690 (defcustom org-archive-location "%s_archive::"
691 "The location where subtrees should be archived.
692 This string consists of two parts, separated by a double-colon.
694 The first part is a file name - when omitted, archiving happens in the same
695 file. %s will be replaced by the current file name (without directory part).
696 Archiving to a different file is useful to keep archived entries from
697 contributing to the Org-mode Agenda.
699 The part after the double colon is a headline. The archived entries will be
700 filed under that headline. When omitted, the subtrees are simply filed away
701 at the end of the file, as top-level entries.
703 Here are a few examples:
704 \"%s_archive::\"
705 If the current file is Projects.org, archive in file
706 Projects.org_archive, as top-level trees. This is the default.
708 \"::* Archived Tasks\"
709 Archive in the current file, under the top-level headline
710 \"* Archived Tasks\".
712 \"~/org/archive.org::\"
713 Archive in file ~/org/archive.org (absolute path), as top-level trees.
715 \"basement::** Finished Tasks\"
716 Archive in file ./basement (relative path), as level 3 trees
717 below the level 2 heading \"** Finished Tasks\".
719 You may set this option on a per-file basis by adding to the buffer a
720 line like
722 #+ARCHIVE: basement::** Finished Tasks"
723 :group 'org-archive
724 :type 'string)
726 (defcustom org-archive-mark-done t
727 "Non-nil means, mark entries as DONE when they are moved to the archive file.
728 This can be a string to set the keyword to use. When t, Org-mode will
729 use the first keyword in its list that means done."
730 :group 'org-archive
731 :type '(choice
732 (const :tag "No" nil)
733 (const :tag "Yes" t)
734 (string :tag "Use this keyword")))
736 (defcustom org-archive-stamp-time t
737 "Non-nil means, add a time stamp to entries moved to an archive file.
738 This variable is obsolete and has no effect anymore, instead add ot remove
739 `time' from the variablle `org-archive-save-context-info'."
740 :group 'org-archive
741 :type 'boolean)
743 (defcustom org-archive-save-context-info '(time file category todo itags)
744 "Parts of context info that should be stored as properties when archiving.
745 When a subtree is moved to an archive file, it looses information given by
746 context, like inherited tags, the category, and possibly also the TODO
747 state (depending on the variable `org-archive-mark-done').
748 This variable can be a list of any of the following symbols:
750 time The time of archiving.
751 file The file where the entry originates.
752 itags The local tags, in the headline of the subtree.
753 ltags The tags the subtree inherits from further up the hierarchy.
754 todo The pre-archive TODO state.
755 category The category, taken from file name or #+CATEGORY lines.
757 For each symbol present in the list, a property will be created in
758 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
759 information."
760 :group 'org-archive
761 :type '(set :greedy t
762 (const :tag "Time" time)
763 (const :tag "File" file)
764 (const :tag "Category" category)
765 (const :tag "TODO state" todo)
766 (const :tag "TODO state" priority)
767 (const :tag "Inherited tags" itags)
768 (const :tag "Local tags" ltags)))
770 (defgroup org-table nil
771 "Options concerning tables in Org-mode."
772 :tag "Org Table"
773 :group 'org)
775 (defcustom org-enable-table-editor 'optimized
776 "Non-nil means, lines starting with \"|\" are handled by the table editor.
777 When nil, such lines will be treated like ordinary lines.
779 When equal to the symbol `optimized', the table editor will be optimized to
780 do the following:
781 - Automatic overwrite mode in front of whitespace in table fields.
782 This makes the structure of the table stay in tact as long as the edited
783 field does not exceed the column width.
784 - Minimize the number of realigns. Normally, the table is aligned each time
785 TAB or RET are pressed to move to another field. With optimization this
786 happens only if changes to a field might have changed the column width.
787 Optimization requires replacing the functions `self-insert-command',
788 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
789 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
790 very good at guessing when a re-align will be necessary, but you can always
791 force one with \\[org-ctrl-c-ctrl-c].
793 If you would like to use the optimized version in Org-mode, but the
794 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
796 This variable can be used to turn on and off the table editor during a session,
797 but in order to toggle optimization, a restart is required.
799 See also the variable `org-table-auto-blank-field'."
800 :group 'org-table
801 :type '(choice
802 (const :tag "off" nil)
803 (const :tag "on" t)
804 (const :tag "on, optimized" optimized)))
806 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
807 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
808 In the optimized version, the table editor takes over all simple keys that
809 normally just insert a character. In tables, the characters are inserted
810 in a way to minimize disturbing the table structure (i.e. in overwrite mode
811 for empty fields). Outside tables, the correct binding of the keys is
812 restored.
814 The default for this option is t if the optimized version is also used in
815 Org-mode. See the variable `org-enable-table-editor' for details. Changing
816 this variable requires a restart of Emacs to become effective."
817 :group 'org-table
818 :type 'boolean)
820 (defcustom orgtbl-radio-table-templates
821 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
822 % END RECEIVE ORGTBL %n
823 \\begin{comment}
824 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
825 | | |
826 \\end{comment}\n")
827 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
828 @c END RECEIVE ORGTBL %n
829 @ignore
830 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
831 | | |
832 @end ignore\n")
833 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
834 <!-- END RECEIVE ORGTBL %n -->
835 <!--
836 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
837 | | |
838 -->\n"))
839 "Templates for radio tables in different major modes.
840 All occurrences of %n in a template will be replaced with the name of the
841 table, obtained by prompting the user."
842 :group 'org-table
843 :type '(repeat
844 (list (symbol :tag "Major mode")
845 (string :tag "Format"))))
847 (defgroup org-table-settings nil
848 "Settings for tables in Org-mode."
849 :tag "Org Table Settings"
850 :group 'org-table)
852 (defcustom org-table-default-size "5x2"
853 "The default size for newly created tables, Columns x Rows."
854 :group 'org-table-settings
855 :type 'string)
857 (defcustom org-table-number-regexp
858 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
859 "Regular expression for recognizing numbers in table columns.
860 If a table column contains mostly numbers, it will be aligned to the
861 right. If not, it will be aligned to the left.
863 The default value of this option is a regular expression which allows
864 anything which looks remotely like a number as used in scientific
865 context. For example, all of the following will be considered a
866 number:
867 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
869 Other options offered by the customize interface are more restrictive."
870 :group 'org-table-settings
871 :type '(choice
872 (const :tag "Positive Integers"
873 "^[0-9]+$")
874 (const :tag "Integers"
875 "^[-+]?[0-9]+$")
876 (const :tag "Floating Point Numbers"
877 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
878 (const :tag "Floating Point Number or Integer"
879 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
880 (const :tag "Exponential, Floating point, Integer"
881 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
882 (const :tag "Very General Number-Like, including hex"
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
884 (string :tag "Regexp:")))
886 (defcustom org-table-number-fraction 0.5
887 "Fraction of numbers in a column required to make the column align right.
888 In a column all non-white fields are considered. If at least this
889 fraction of fields is matched by `org-table-number-fraction',
890 alignment to the right border applies."
891 :group 'org-table-settings
892 :type 'number)
894 (defgroup org-table-editing nil
895 "Bahavior of tables during editing in Org-mode."
896 :tag "Org Table Editing"
897 :group 'org-table)
899 (defcustom org-table-automatic-realign t
900 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
901 When nil, aligning is only done with \\[org-table-align], or after column
902 removal/insertion."
903 :group 'org-table-editing
904 :type 'boolean)
906 (defcustom org-table-auto-blank-field t
907 "Non-nil means, automatically blank table field when starting to type into it.
908 This only happens when typing immediately after a field motion
909 command (TAB, S-TAB or RET).
910 Only relevant when `org-enable-table-editor' is equal to `optimized'."
911 :group 'org-table-editing
912 :type 'boolean)
914 (defcustom org-table-tab-jumps-over-hlines t
915 "Non-nil means, tab in the last column of a table with jump over a hline.
916 If a horizontal separator line is following the current line,
917 `org-table-next-field' can either create a new row before that line, or jump
918 over the line. When this option is nil, a new line will be created before
919 this line."
920 :group 'org-table-editing
921 :type 'boolean)
923 (defcustom org-table-tab-recognizes-table.el t
924 "Non-nil means, TAB will automatically notice a table.el table.
925 When it sees such a table, it moves point into it and - if necessary -
926 calls `table-recognize-table'."
927 :group 'org-table-editing
928 :type 'boolean)
930 (defgroup org-table-calculation nil
931 "Options concerning tables in Org-mode."
932 :tag "Org Table Calculation"
933 :group 'org-table)
935 (defcustom org-table-use-standard-references t
936 "Should org-mode work with table refrences like B3 instead of @3$2?
937 Possible values are:
938 nil never use them
939 from accept as input, do not present for editing
940 t: accept as input and present for editing"
941 :group 'org-table-calculation
942 :type '(choice
943 (const :tag "Never, don't even check unser input for them" nil)
944 (const :tag "Always, both as user input, and when editing" t)
945 (const :tag "Convert user input, don't offer during editing" 'from)))
947 (defcustom org-table-copy-increment t
948 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
949 :group 'org-table-calculation
950 :type 'boolean)
952 (defcustom org-calc-default-modes
953 '(calc-internal-prec 12
954 calc-float-format (float 5)
955 calc-angle-mode deg
956 calc-prefer-frac nil
957 calc-symbolic-mode nil
958 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
959 calc-display-working-message t
961 "List with Calc mode settings for use in calc-eval for table formulas.
962 The list must contain alternating symbols (Calc modes variables and values).
963 Don't remove any of the default settings, just change the values. Org-mode
964 relies on the variables to be present in the list."
965 :group 'org-table-calculation
966 :type 'plist)
968 (defcustom org-table-formula-evaluate-inline t
969 "Non-nil means, TAB and RET evaluate a formula in current table field.
970 If the current field starts with an equal sign, it is assumed to be a formula
971 which should be evaluated as described in the manual and in the documentation
972 string of the command `org-table-eval-formula'. This feature requires the
973 Emacs calc package.
974 When this variable is nil, formula calculation is only available through
975 the command \\[org-table-eval-formula]."
976 :group 'org-table-calculation
977 :type 'boolean)
979 (defcustom org-table-formula-use-constants t
980 "Non-nil means, interpret constants in formulas in tables.
981 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
982 by the value given in `org-table-formula-constants', or by a value obtained
983 from the `constants.el' package."
984 :group 'org-table-calculation
985 :type 'boolean)
987 (defcustom org-table-formula-constants nil
988 "Alist with constant names and values, for use in table formulas.
989 The car of each element is a name of a constant, without the `$' before it.
990 The cdr is the value as a string. For example, if you'd like to use the
991 speed of light in a formula, you would configure
993 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
995 and then use it in an equation like `$1*$c'.
997 Constants can also be defined on a per-file basis using a line like
999 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1000 :group 'org-table-calculation
1001 :type '(repeat
1002 (cons (string :tag "name")
1003 (string :tag "value"))))
1005 (defvar org-table-formula-constants-local nil
1006 "Local version of `org-table-formula-constants'.")
1007 (make-variable-buffer-local 'org-table-formula-constants-local)
1009 (defcustom org-table-allow-automatic-line-recalculation t
1010 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1011 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1012 :group 'org-table-calculation
1013 :type 'boolean)
1015 (defgroup org-link nil
1016 "Options concerning links in Org-mode."
1017 :tag "Org Link"
1018 :group 'org)
1020 (defvar org-link-abbrev-alist-local nil
1021 "Buffer-local version of `org-link-abbrev-alist', which see.
1022 The value of this is taken from the #+LINK lines.")
1023 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1025 (defcustom org-link-abbrev-alist nil
1026 "Alist of link abbreviations.
1027 The car of each element is a string, to be replaced at the start of a link.
1028 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1029 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1031 [[linkkey:tag][description]]
1033 If REPLACE is a string, the tag will simply be appended to create the link.
1034 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1035 also be a function that will be called with the tag as the only argument to
1036 create the link. See the manual for examples."
1037 :group 'org-link
1038 :type 'alist)
1040 (defcustom org-descriptive-links t
1041 "Non-nil means, hide link part and only show description of bracket links.
1042 Bracket links are like [[link][descritpion]]. This variable sets the initial
1043 state in new org-mode buffers. The setting can then be toggled on a
1044 per-buffer basis from the Org->Hyperlinks menu."
1045 :group 'org-link
1046 :type 'boolean)
1048 (defcustom org-link-file-path-type 'adaptive
1049 "How the path name in file links should be stored.
1050 Valid values are:
1052 relative relative to the current directory, i.e. the directory of the file
1053 into which the link is being inserted.
1054 absolute absolute path, if possible with ~ for home directory.
1055 noabbrev absolute path, no abbreviation of home directory.
1056 adaptive Use relative path for files in the current directory and sub-
1057 directories of it. For other files, use an absolute path."
1058 :group 'org-link
1059 :type '(choice
1060 (const relative)
1061 (const absolute)
1062 (const noabbrev)
1063 (const adaptive)))
1065 (defcustom org-activate-links '(bracket angle plain radio tag date)
1066 "Types of links that should be activated in Org-mode files.
1067 This is a list of symbols, each leading to the activation of a certain link
1068 type. In principle, it does not hurt to turn on most link types - there may
1069 be a small gain when turning off unused link types. The types are:
1071 bracket The recommended [[link][description]] or [[link]] links with hiding.
1072 angular Links in angular brackes that may contain whitespace like
1073 <bbdb:Carsten Dominik>.
1074 plain Plain links in normal text, no whitespace, like http://google.com.
1075 radio Text that is matched by a radio target, see manual for details.
1076 tag Tag settings in a headline (link to tag search).
1077 date Time stamps (link to calendar).
1079 Changing this variable requires a restart of Emacs to become effective."
1080 :group 'org-link
1081 :type '(set (const :tag "Double bracket links (new style)" bracket)
1082 (const :tag "Angular bracket links (old style)" angular)
1083 (const :tag "plain text links" plain)
1084 (const :tag "Radio target matches" radio)
1085 (const :tag "Tags" tag)
1086 (const :tag "Tags" target)
1087 (const :tag "Timestamps" date)))
1089 (defgroup org-link-store nil
1090 "Options concerning storing links in Org-mode"
1091 :tag "Org Store Link"
1092 :group 'org-link)
1094 (defcustom org-email-link-description-format "Email %c: %.30s"
1095 "Format of the description part of a link to an email or usenet message.
1096 The following %-excapes will be replaced by corresponding information:
1098 %F full \"From\" field
1099 %f name, taken from \"From\" field, address if no name
1100 %T full \"To\" field
1101 %t first name in \"To\" field, address if no name
1102 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1103 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1104 %s subject
1105 %m message-id.
1107 You may use normal field width specification between the % and the letter.
1108 This is for example useful to limit the length of the subject.
1110 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1111 :group 'org-link-store
1112 :type 'string)
1114 (defcustom org-from-is-user-regexp
1115 (let (r1 r2)
1116 (when (and user-mail-address (not (string= user-mail-address "")))
1117 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1118 (when (and user-full-name (not (string= user-full-name "")))
1119 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1120 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1121 "Regexp mached against the \"From:\" header of an email or usenet message.
1122 It should match if the message is from the user him/herself."
1123 :group 'org-link-store
1124 :type 'regexp)
1126 (defcustom org-context-in-file-links t
1127 "Non-nil means, file links from `org-store-link' contain context.
1128 A search string will be added to the file name with :: as separator and
1129 used to find the context when the link is activated by the command
1130 `org-open-at-point'.
1131 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1132 negates this setting for the duration of the command."
1133 :group 'org-link-store
1134 :type 'boolean)
1136 (defcustom org-keep-stored-link-after-insertion nil
1137 "Non-nil means, keep link in list for entire session.
1139 The command `org-store-link' adds a link pointing to the current
1140 location to an internal list. These links accumulate during a session.
1141 The command `org-insert-link' can be used to insert links into any
1142 Org-mode file (offering completion for all stored links). When this
1143 option is nil, every link which has been inserted once using \\[org-insert-link]
1144 will be removed from the list, to make completing the unused links
1145 more efficient."
1146 :group 'org-link-store
1147 :type 'boolean)
1149 (defcustom org-usenet-links-prefer-google nil
1150 "Non-nil means, `org-store-link' will create web links to Google groups.
1151 When nil, Gnus will be used for such links.
1152 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1153 negates this setting for the duration of the command."
1154 :group 'org-link-store
1155 :type 'boolean)
1157 (defgroup org-link-follow nil
1158 "Options concerning following links in Org-mode"
1159 :tag "Org Follow Link"
1160 :group 'org-link)
1162 (defcustom org-tab-follows-link nil
1163 "Non-nil means, on links TAB will follow the link.
1164 Needs to be set before org.el is loaded."
1165 :group 'org-link-follow
1166 :type 'boolean)
1168 (defcustom org-return-follows-link nil
1169 "Non-nil means, on links RET will follow the link.
1170 Needs to be set before org.el is loaded."
1171 :group 'org-link-follow
1172 :type 'boolean)
1174 (defcustom org-mouse-1-follows-link t
1175 "Non-nil means, mouse-1 on a link will follow the link.
1176 A longer mouse click will still set point. Does not wortk on XEmacs.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mark-ring-length 4
1182 "Number of different positions to be recorded in the ring
1183 Changing this requires a restart of Emacs to work correctly."
1184 :group 'org-link-follow
1185 :type 'interger)
1187 (defcustom org-link-frame-setup
1188 '((vm . vm-visit-folder-other-frame)
1189 (gnus . gnus-other-frame)
1190 (file . find-file-other-window))
1191 "Setup the frame configuration for following links.
1192 When following a link with Emacs, it may often be useful to display
1193 this link in another window or frame. This variable can be used to
1194 set this up for the different types of links.
1195 For VM, use any of
1196 `vm-visit-folder'
1197 `vm-visit-folder-other-frame'
1198 For Gnus, use any of
1199 `gnus'
1200 `gnus-other-frame'
1201 For FILE, use any of
1202 `find-file'
1203 `find-file-other-window'
1204 `find-file-other-frame'
1205 For the calendar, use the variable `calendar-setup'.
1206 For BBDB, it is currently only possible to display the matches in
1207 another window."
1208 :group 'org-link-follow
1209 :type '(list
1210 (cons (const vm)
1211 (choice
1212 (const vm-visit-folder)
1213 (const vm-visit-folder-other-window)
1214 (const vm-visit-folder-other-frame)))
1215 (cons (const gnus)
1216 (choice
1217 (const gnus)
1218 (const gnus-other-frame)))
1219 (cons (const file)
1220 (choice
1221 (const find-file)
1222 (const find-file-other-window)
1223 (const find-file-other-frame)))))
1225 (defcustom org-display-internal-link-with-indirect-buffer nil
1226 "Non-nil means, use indirect buffer to display infile links.
1227 Activating internal links (from one location in a file to another location
1228 in the same file) normally just jumps to the location. When the link is
1229 activated with a C-u prefix (or with mouse-3), the link is displayed in
1230 another window. When this option is set, the other window actually displays
1231 an indirect buffer clone of the current buffer, to avoid any visibility
1232 changes to the current buffer."
1233 :group 'org-link-follow
1234 :type 'boolean)
1236 (defcustom org-open-non-existing-files nil
1237 "Non-nil means, `org-open-file' will open non-existing files.
1238 When nil, an error will be generated."
1239 :group 'org-link-follow
1240 :type 'boolean)
1242 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1243 "Function and arguments to call for following mailto links.
1244 This is a list with the first element being a lisp function, and the
1245 remaining elements being arguments to the function. In string arguments,
1246 %a will be replaced by the address, and %s will be replaced by the subject
1247 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1248 :group 'org-link-follow
1249 :type '(choice
1250 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1251 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1252 (const :tag "message-mail" (message-mail "%a" "%s"))
1253 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1255 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1256 "Non-nil means, ask for confirmation before executing shell links.
1257 Shell links can be dangerous: just think about a link
1259 [[shell:rm -rf ~/*][Google Search]]
1261 This link would show up in your Org-mode document as \"Google Search\",
1262 but really it would remove your entire home directory.
1263 Therefore we advise against setting this variable to nil.
1264 Just change it to `y-or-n-p' of you want to confirm with a
1265 single keystroke rather than having to type \"yes\"."
1266 :group 'org-link-follow
1267 :type '(choice
1268 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1269 (const :tag "with y-or-n (faster)" y-or-n-p)
1270 (const :tag "no confirmation (dangerous)" nil)))
1272 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1273 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1274 Elisp links can be dangerous: just think about a link
1276 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1278 This link would show up in your Org-mode document as \"Google Search\",
1279 but really it would remove your entire home directory.
1280 Therefore we advise against setting this variable to nil.
1281 Just change it to `y-or-n-p' of you want to confirm with a
1282 single keystroke rather than having to type \"yes\"."
1283 :group 'org-link-follow
1284 :type '(choice
1285 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1286 (const :tag "with y-or-n (faster)" y-or-n-p)
1287 (const :tag "no confirmation (dangerous)" nil)))
1289 (defconst org-file-apps-defaults-gnu
1290 '((remote . emacs)
1291 (t . mailcap))
1292 "Default file applications on a UNIX or GNU/Linux system.
1293 See `org-file-apps'.")
1295 (defconst org-file-apps-defaults-macosx
1296 '((remote . emacs)
1297 (t . "open %s")
1298 ("ps" . "gv %s")
1299 ("ps.gz" . "gv %s")
1300 ("eps" . "gv %s")
1301 ("eps.gz" . "gv %s")
1302 ("dvi" . "xdvi %s")
1303 ("fig" . "xfig %s"))
1304 "Default file applications on a MacOS X system.
1305 The system \"open\" is known as a default, but we use X11 applications
1306 for some files for which the OS does not have a good default.
1307 See `org-file-apps'.")
1309 (defconst org-file-apps-defaults-windowsnt
1310 (list
1311 '(remote . emacs)
1312 (cons t
1313 (list (if (featurep 'xemacs)
1314 'mswindows-shell-execute
1315 'w32-shell-execute)
1316 "open" 'file)))
1317 "Default file applications on a Windows NT system.
1318 The system \"open\" is used for most files.
1319 See `org-file-apps'.")
1321 (defcustom org-file-apps
1323 ("txt" . emacs)
1324 ("tex" . emacs)
1325 ("ltx" . emacs)
1326 ("org" . emacs)
1327 ("el" . emacs)
1328 ("bib" . emacs)
1330 "External applications for opening `file:path' items in a document.
1331 Org-mode uses system defaults for different file types, but
1332 you can use this variable to set the application for a given file
1333 extension. The entries in this list are cons cells where the car identifies
1334 files and the cdr the corresponding command. Possible values for the
1335 file identifier are
1336 \"ext\" A string identifying an extension
1337 `directory' Matches a directory
1338 `remote' Matches a remote file, accessible through tramp or efs.
1339 Remote files most likely should be visited through Emacs
1340 because external applications cannot handle such paths.
1341 t Default for all remaining files
1343 Possible values for the command are:
1344 `emacs' The file will be visited by the current Emacs process.
1345 `default' Use the default application for this file type.
1346 string A command to be executed by a shell; %s will be replaced
1347 by the path to the file.
1348 sexp A Lisp form which will be evaluated. The file path will
1349 be available in the Lisp variable `file'.
1350 For more examples, see the system specific constants
1351 `org-file-apps-defaults-macosx'
1352 `org-file-apps-defaults-windowsnt'
1353 `org-file-apps-defaults-gnu'."
1354 :group 'org-link-follow
1355 :type '(repeat
1356 (cons (choice :value ""
1357 (string :tag "Extension")
1358 (const :tag "Default for unrecognized files" t)
1359 (const :tag "Remote file" remote)
1360 (const :tag "Links to a directory" directory))
1361 (choice :value ""
1362 (const :tag "Visit with Emacs" emacs)
1363 (const :tag "Use system default" default)
1364 (string :tag "Command")
1365 (sexp :tag "Lisp form")))))
1367 (defcustom org-mhe-search-all-folders nil
1368 "Non-nil means, that the search for the mh-message will be extended to
1369 all folders if the message cannot be found in the folder given in the link.
1370 Searching all folders is very efficient with one of the search engines
1371 supported by MH-E, but will be slow with pick."
1372 :group 'org-link-follow
1373 :type 'boolean)
1375 (defgroup org-remember nil
1376 "Options concerning interaction with remember.el."
1377 :tag "Org Remember"
1378 :group 'org)
1380 (defcustom org-directory "~/org"
1381 "Directory with org files.
1382 This directory will be used as default to prompt for org files.
1383 Used by the hooks for remember.el."
1384 :group 'org-remember
1385 :type 'directory)
1387 (defcustom org-default-notes-file "~/.notes"
1388 "Default target for storing notes.
1389 Used by the hooks for remember.el. This can be a string, or nil to mean
1390 the value of `remember-data-file'.
1391 You can set this on a per-template basis with the variable
1392 `org-remember-templates'."
1393 :group 'org-remember
1394 :type '(choice
1395 (const :tag "Default from remember-data-file" nil)
1396 file))
1398 (defcustom org-remember-store-without-prompt t
1399 "Non-nil means, `C-c C-c' stores remember note without further promts.
1400 In this case, you need `C-u C-c C-c' to get the prompts for
1401 note file and headline.
1402 When this variable is nil, `C-c C-c' give you the prompts, and
1403 `C-u C-c C-c' trigger the fasttrack."
1404 :group 'org-remember
1405 :type 'boolean)
1407 (defcustom org-remember-default-headline ""
1408 "The headline that should be the default location in the notes file.
1409 When filing remember notes, the cursor will start at that position.
1410 You can set this on a per-template basis with the variable
1411 `org-remember-templates'."
1412 :group 'org-remember
1413 :type 'string)
1415 (defcustom org-remember-templates nil
1416 "Templates for the creation of remember buffers.
1417 When nil, just let remember make the buffer.
1418 When not nil, this is a list of 5-element lists. In each entry, the first
1419 element is a the name of the template, It should be a single short word.
1420 The second element is a character, a unique key to select this template.
1421 The third element is the template. The forth element is optional and can
1422 specify a destination file for remember items created with this template.
1423 The default file is given by `org-default-notes-file'. An optional fifth
1424 element can specify the headline in that file that should be offered
1425 first when the user is asked to file the entry. The default headline is
1426 given in the variable `org-remember-default-headline'.
1428 The template specifies the structure of the remember buffer. It should have
1429 a first line starting with a star, to act as the org-mode headline.
1430 Furthermore, the following %-escapes will be replaced with content:
1432 %^{prompt} prompt the user for a string and replace this sequence with it.
1433 %t time stamp, date only
1434 %T time stamp with date and time
1435 %u, %U like the above, but inactive time stamps
1436 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1437 You may define a prompt like %^{Please specify birthday}t
1438 %n user name (taken from `user-full-name')
1439 %a annotation, normally the link created with org-store-link
1440 %i initial content, the region when remember is called with C-u.
1441 If %i is indented, the entire inserted text will be indented
1442 as well.
1444 %? After completing the template, position cursor here.
1446 Apart from these general escapes, you can access information specific to the
1447 link type that is created. For example, calling `remember' in emails or gnus
1448 will record the author and the subject of the message, which you can access
1449 with %:author and %:subject, respectively. Here is a complete list of what
1450 is recorded for each link type.
1452 Link type | Available information
1453 -------------------+------------------------------------------------------
1454 bbdb | %:type %:name %:company
1455 vm, wl, mh, rmail | %:type %:subject %:message-id
1456 | %:from %:fromname %:fromaddress
1457 | %:to %:toname %:toaddress
1458 | %:fromto (either \"to NAME\" or \"from NAME\")
1459 gnus | %:group, for messages also all email fields
1460 w3, w3m | %:type %:url
1461 info | %:type %:file %:node
1462 calendar | %:type %:date"
1463 :group 'org-remember
1464 :get (lambda (var) ; Make sure all entries have 5 elements
1465 (mapcar (lambda (x)
1466 (if (not (stringp (car x))) (setq x (cons "" x)))
1467 (cond ((= (length x) 4) (append x '("")))
1468 ((= (length x) 3) (append x '("" "")))
1469 (t x)))
1470 (default-value var)))
1471 :type '(repeat
1472 :tag "enabled"
1473 (list :value ("" ?a "\n" nil nil)
1474 (string :tag "Name")
1475 (character :tag "Selection Key")
1476 (string :tag "Template")
1477 (choice
1478 (file :tag "Destination file")
1479 (const :tag "Prompt for file" nil))
1480 (choice
1481 (string :tag "Destination headline")
1482 (const :tag "Selection interface for heading")))))
1484 (defcustom org-reverse-note-order nil
1485 "Non-nil means, store new notes at the beginning of a file or entry.
1486 When nil, new notes will be filed to the end of a file or entry."
1487 :group 'org-remember
1488 :type '(choice
1489 (const :tag "Reverse always" t)
1490 (const :tag "Reverse never" nil)
1491 (repeat :tag "By file name regexp"
1492 (cons regexp boolean))))
1494 (defgroup org-todo nil
1495 "Options concerning TODO items in Org-mode."
1496 :tag "Org TODO"
1497 :group 'org)
1499 (defgroup org-progress nil
1500 "Options concerning Progress logging in Org-mode."
1501 :tag "Org Progress"
1502 :group 'org-time)
1504 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1505 "List of TODO entry keyword sequences and their interpretation.
1506 \\<org-mode-map>This is a list of sequences.
1508 Each sequence starts with a symbol, either `sequence' or `type',
1509 indicating if the keywords should be interpreted as a sequence of
1510 action steps, or as different types of TODO items. The first
1511 keywords are states requiring action - these states will select a headline
1512 for inclusion into the global TODO list Org-mode produces. If one of
1513 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1514 signify that no further action is necessary. If \"|\" is not found,
1515 the last keyword is treated as the only DONE state of the sequence.
1517 The command \\[org-todo] cycles an entry through these states, and one
1518 additional state where no keyword is present. For details about this
1519 cycling, see the manual.
1521 TODO keywords and interpretation can also be set on a per-file basis with
1522 the special #+SEQ_TODO and #+TYP_TODO lines.
1524 For backward compatibility, this variable may also be just a list
1525 of keywords - in this case the interptetation (sequence or type) will be
1526 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1527 :group 'org-todo
1528 :group 'org-keywords
1529 :type '(choice
1530 (repeat :tag "Old syntax, just keywords"
1531 (string :tag "Keyword"))
1532 (repeat :tag "New syntax"
1533 (cons
1534 (choice
1535 :tag "Interpretation"
1536 (const :tag "Sequence (cycling hits every state)" sequence)
1537 (const :tag "Type (cycling directly to DONE)" type))
1538 (repeat
1539 (string :tag "Keyword"))))))
1541 (defvar org-todo-keywords-1 nil)
1542 (make-variable-buffer-local 'org-todo-keywords-1)
1543 (defvar org-todo-keywords-for-agenda nil)
1544 (defvar org-done-keywords-for-agenda nil)
1545 (defvar org-not-done-keywords nil)
1546 (make-variable-buffer-local 'org-not-done-keywords)
1547 (defvar org-done-keywords nil)
1548 (make-variable-buffer-local 'org-done-keywords)
1549 (defvar org-todo-heads nil)
1550 (make-variable-buffer-local 'org-todo-heads)
1551 (defvar org-todo-sets nil)
1552 (make-variable-buffer-local 'org-todo-sets)
1553 (defvar org-todo-log-states nil)
1554 (make-variable-buffer-local 'org-todo-log-states)
1555 (defvar org-todo-kwd-alist nil)
1556 (make-variable-buffer-local 'org-todo-kwd-alist)
1557 (defvar org-todo-key-alist nil)
1558 (make-variable-buffer-local 'org-todo-key-alist)
1559 (defvar org-todo-key-trigger nil)
1560 (make-variable-buffer-local 'org-todo-key-trigger)
1562 (defcustom org-todo-interpretation 'sequence
1563 "Controls how TODO keywords are interpreted.
1564 This variable is in principle obsolete and is only used for
1565 backward compatibility, if the interpretation of todo keywords is
1566 not given already in `org-todo-keywords'. See that variable for
1567 more information."
1568 :group 'org-todo
1569 :group 'org-keywords
1570 :type '(choice (const sequence)
1571 (const type)))
1573 (defcustom org-use-fast-todo-selection 'prefix
1574 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1575 This variable describes if and under what circumstances the cycling
1576 mechanism for TODO keywords will be replaced by a single-key, direct
1577 selection scheme.
1579 When nil, fast selection is never used.
1581 When the symbol `prefix', it will be used when `org-todo' is called with
1582 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1583 in an agenda buffer.
1585 When t, fast selection is used by default. In this case, the prefix
1586 argument forces cycling instead.
1588 In all cases, the special interface is only used if access keys have actually
1589 been assigned by the user, i.e. if keywords in the configuration are followed
1590 by a letter in parenthesis, like TODO(t)."
1591 :group 'org-todo
1592 :type '(choice
1593 (const :tag "Never" nil)
1594 (const :tag "By default" t)
1595 (const :tag "Only with C-u C-c C-t" prefix)))
1597 (defcustom org-after-todo-state-change-hook nil
1598 "Hook which is run after the state of a TODO item was changed.
1599 The new state (a string with a TODO keyword, or nil) is available in the
1600 Lisp variable `state'."
1601 :group 'org-todo
1602 :type 'hook)
1604 (defcustom org-log-done nil
1605 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1606 When the state of an entry is changed from nothing or a DONE state to
1607 a not-done TODO state, remove a previous closing date.
1609 This can also be a list of symbols indicating under which conditions
1610 the time stamp recording the action should be annotated with a short note.
1611 Valid members of this list are
1613 done Offer to record a note when marking entries done
1614 state Offer to record a note whenever changing the TODO state
1615 of an item. This is only relevant if TODO keywords are
1616 interpreted as sequence, see variable `org-todo-interpretation'.
1617 When `state' is set, this includes tracking `done'.
1618 clock-out Offer to record a note when clocking out of an item.
1620 A separate window will then pop up and allow you to type a note.
1621 After finishing with C-c C-c, the note will be added directly after the
1622 timestamp, as a plain list item. See also the variable
1623 `org-log-note-headings'.
1625 Logging can also be configured on a per-file basis by adding one of
1626 the following lines anywhere in the buffer:
1628 #+STARTUP: logdone
1629 #+STARTUP: nologging
1630 #+STARTUP: lognotedone
1631 #+STARTUP: lognotestate
1632 #+STARTUP: lognoteclock-out
1634 You can have local logging settings for a subtree by setting the LOGGING
1635 property to one or more of these keywords."
1636 :group 'org-todo
1637 :group 'org-progress
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1642 (const :tag "when item is marked DONE" done)
1643 (const :tag "when TODO state changes" state)
1644 (const :tag "when clocking out" clock-out))))
1646 (defcustom org-log-done-with-time t
1647 "Non-nil means, the CLOSED time stamp will contain date and time.
1648 When nil, only the date will be recorded."
1649 :group 'org-progress
1650 :type 'boolean)
1652 (defcustom org-log-note-headings
1653 '((done . "CLOSING NOTE %t")
1654 (state . "State %-12s %t")
1655 (clock-out . ""))
1656 "Headings for notes added when clocking out or closing TODO items.
1657 The value is an alist, with the car being a symbol indicating the note
1658 context, and the cdr is the heading to be used. The heading may also be the
1659 empty string.
1660 %t in the heading will be replaced by a time stamp.
1661 %s will be replaced by the new TODO state, in double quotes.
1662 %u will be replaced by the user name.
1663 %U will be replaced by the full user name."
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type '(list :greedy t
1667 (cons (const :tag "Heading when closing an item" done) string)
1668 (cons (const :tag
1669 "Heading when changing todo state (todo sequence only)"
1670 state) string)
1671 (cons (const :tag "Heading when clocking out" clock-out) string)))
1673 (defcustom org-log-states-order-reversed t
1674 "Non-nil means, the latest state change note will be directly after heading.
1675 When nil, the notes will be orderer according to time."
1676 :group 'org-todo
1677 :group 'org-progress
1678 :type 'boolean)
1680 (defcustom org-log-repeat t
1681 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1682 When nil, no note will be taken.
1683 This option can also be set with on a per-file-basis with
1685 #+STARTUP: logrepeat
1686 #+STARTUP: nologrepeat
1688 You can have local logging settings for a subtree by setting the LOGGING
1689 property to one or more of these keywords."
1690 :group 'org-todo
1691 :group 'org-progress
1692 :type 'boolean)
1694 (defcustom org-clock-into-drawer 2
1695 "Should clocking info be wrapped into a drawer?
1696 When t, clocking info will always be inserted into a :CLOCK: drawer.
1697 If necessary, the drawer will be created.
1698 When nil, the drawer will not be created, but used when present.
1699 When an integer and the number of clocking entries in an item
1700 reaches or exceeds this number, a drawer will be created."
1701 :group 'org-todo
1702 :group 'org-progress
1703 :type '(choice
1704 (const :tag "Always" t)
1705 (const :tag "Only when drawer exists" nil)
1706 (integer :tag "When at least N clock entries")))
1708 (defcustom org-clock-out-when-done t
1709 "When t, the clock will be stopped when the relevant entry is marked DONE.
1710 Nil means, clock will keep running until stopped explicitly with
1711 `C-c C-x C-o', or until the clock is started in a different item."
1712 :group 'org-progress
1713 :type 'boolean)
1715 (defgroup org-priorities nil
1716 "Priorities in Org-mode."
1717 :tag "Org Priorities"
1718 :group 'org-todo)
1720 (defcustom org-highest-priority ?A
1721 "The highest priority of TODO items. A character like ?A, ?B etc.
1722 Must have a smaller ASCII number than `org-lowest-priority'."
1723 :group 'org-priorities
1724 :type 'character)
1726 (defcustom org-lowest-priority ?C
1727 "The lowest priority of TODO items. A character like ?A, ?B etc.
1728 Must have a larger ASCII number than `org-highest-priority'."
1729 :group 'org-priorities
1730 :type 'character)
1732 (defcustom org-default-priority ?B
1733 "The default priority of TODO items.
1734 This is the priority an item get if no explicit priority is given."
1735 :group 'org-priorities
1736 :type 'character)
1738 (defcustom org-priority-start-cycle-with-default t
1739 "Non-nil means, start with default priority when starting to cycle.
1740 When this is nil, the first step in the cycle will be (depending on the
1741 command used) one higher or lower that the default priority."
1742 :group 'org-priorities
1743 :type 'boolean)
1745 (defgroup org-time nil
1746 "Options concerning time stamps and deadlines in Org-mode."
1747 :tag "Org Time"
1748 :group 'org)
1750 (defcustom org-insert-labeled-timestamps-at-point nil
1751 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1752 When nil, these labeled time stamps are forces into the second line of an
1753 entry, just after the headline. When scheduling from the global TODO list,
1754 the time stamp will always be forced into the second line."
1755 :group 'org-time
1756 :type 'boolean)
1758 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1759 "Formats for `format-time-string' which are used for time stamps.
1760 It is not recommended to change this constant.")
1762 (defcustom org-time-stamp-rounding-minutes 0
1763 "Number of minutes to round time stamps to upon insertion.
1764 When zero, insert the time unmodified. Useful rounding numbers
1765 should be factors of 60, so for example 5, 10, 15.
1766 When this is not zero, you can still force an exact time-stamp by using
1767 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1768 :group 'org-time
1769 :type 'integer)
1771 (defcustom org-display-custom-times nil
1772 "Non-nil means, overlay custom formats over all time stamps.
1773 The formats are defined through the variable `org-time-stamp-custom-formats'.
1774 To turn this on on a per-file basis, insert anywhere in the file:
1775 #+STARTUP: customtime"
1776 :group 'org-time
1777 :set 'set-default
1778 :type 'sexp)
1779 (make-variable-buffer-local 'org-display-custom-times)
1781 (defcustom org-time-stamp-custom-formats
1782 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1783 "Custom formats for time stamps. See `format-time-string' for the syntax.
1784 These are overlayed over the default ISO format if the variable
1785 `org-display-custom-times' is set. Time like %H:%M should be at the
1786 end of the second format."
1787 :group 'org-time
1788 :type 'sexp)
1790 (defun org-time-stamp-format (&optional long inactive)
1791 "Get the right format for a time string."
1792 (let ((f (if long (cdr org-time-stamp-formats)
1793 (car org-time-stamp-formats))))
1794 (if inactive
1795 (concat "[" (substring f 1 -1) "]")
1796 f)))
1798 (defcustom org-popup-calendar-for-date-prompt t
1799 "Non-nil means, pop up a calendar when prompting for a date.
1800 In the calendar, the date can be selected with mouse-1. However, the
1801 minibuffer will also be active, and you can simply enter the date as well.
1802 When nil, only the minibuffer will be available."
1803 :group 'org-time
1804 :type 'boolean)
1806 (defcustom org-edit-timestamp-down-means-later nil
1807 "Non-nil means, S-down will increase the time in a time stamp.
1808 When nil, S-up will increase."
1809 :group 'org-time
1810 :type 'boolean)
1812 (defcustom org-calendar-follow-timestamp-change t
1813 "Non-nil means, make the calendar window follow timestamp changes.
1814 When a timestamp is modified and the calendar window is visible, it will be
1815 moved to the new date."
1816 :group 'org-time
1817 :type 'boolean)
1819 (defgroup org-tags nil
1820 "Options concerning tags in Org-mode."
1821 :tag "Org Tags"
1822 :group 'org)
1824 (defcustom org-tag-alist nil
1825 "List of tags allowed in Org-mode files.
1826 When this list is nil, Org-mode will base TAG input on what is already in the
1827 buffer.
1828 The value of this variable is an alist, the car of each entry must be a
1829 keyword as a string, the cdr may be a character that is used to select
1830 that tag through the fast-tag-selection interface.
1831 See the manual for details."
1832 :group 'org-tags
1833 :type '(repeat
1834 (choice
1835 (cons (string :tag "Tag name")
1836 (character :tag "Access char"))
1837 (const :tag "Start radio group" (:startgroup))
1838 (const :tag "End radio group" (:endgroup)))))
1840 (defcustom org-use-fast-tag-selection 'auto
1841 "Non-nil means, use fast tag selection scheme.
1842 This is a special interface to select and deselect tags with single keys.
1843 When nil, fast selection is never used.
1844 When the symbol `auto', fast selection is used if and only if selection
1845 characters for tags have been configured, either through the variable
1846 `org-tag-alist' or through a #+TAGS line in the buffer.
1847 When t, fast selection is always used and selection keys are assigned
1848 automatically if necessary."
1849 :group 'org-tags
1850 :type '(choice
1851 (const :tag "Always" t)
1852 (const :tag "Never" nil)
1853 (const :tag "When selection characters are configured" 'auto)))
1855 (defcustom org-fast-tag-selection-single-key nil
1856 "Non-nil means, fast tag selection exits after first change.
1857 When nil, you have to press RET to exit it.
1858 During fast tag selection, you can toggle this flag with `C-c'.
1859 This variable can also have the value `expert'. In this case, the window
1860 displaying the tags menu is not even shown, until you press C-c again."
1861 :group 'org-tags
1862 :type '(choice
1863 (const :tag "No" nil)
1864 (const :tag "Yes" t)
1865 (const :tag "Expert" expert)))
1867 (defvar org-fast-tag-selection-include-todo nil
1868 "Non-nil means, fast tags selection interface will also offer TODO states.
1869 This is an undocumented feature, you should not rely on it.")
1871 (defcustom org-tags-column -80
1872 "The column to which tags should be indented in a headline.
1873 If this number is positive, it specifies the column. If it is negative,
1874 it means that the tags should be flushright to that column. For example,
1875 -80 works well for a normal 80 character screen."
1876 :group 'org-tags
1877 :type 'integer)
1879 (defcustom org-auto-align-tags t
1880 "Non-nil means, realign tags after pro/demotion of TODO state change.
1881 These operations change the length of a headline and therefore shift
1882 the tags around. With this options turned on, after each such operation
1883 the tags are again aligned to `org-tags-column'."
1884 :group 'org-tags
1885 :type 'boolean)
1887 (defcustom org-use-tag-inheritance t
1888 "Non-nil means, tags in levels apply also for sublevels.
1889 When nil, only the tags directly given in a specific line apply there.
1890 If you turn off this option, you very likely want to turn on the
1891 companion option `org-tags-match-list-sublevels'."
1892 :group 'org-tags
1893 :type 'boolean)
1895 (defcustom org-tags-match-list-sublevels nil
1896 "Non-nil means list also sublevels of headlines matching tag search.
1897 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1898 the sublevels of a headline matching a tag search often also match
1899 the same search. Listing all of them can create very long lists.
1900 Setting this variable to nil causes subtrees of a match to be skipped.
1901 This option is off by default, because inheritance in on. If you turn
1902 inheritance off, you very likely want to turn this option on.
1904 As a special case, if the tag search is restricted to TODO items, the
1905 value of this variable is ignored and sublevels are always checked, to
1906 make sure all corresponding TODO items find their way into the list."
1907 :group 'org-tags
1908 :type 'boolean)
1910 (defvar org-tags-history nil
1911 "History of minibuffer reads for tags.")
1912 (defvar org-last-tags-completion-table nil
1913 "The last used completion table for tags.")
1914 (defvar org-after-tags-change-hook nil
1915 "Hook that is run after the tags in a line have changed.")
1917 (defgroup org-properties nil
1918 "Options concerning properties in Org-mode."
1919 :tag "Org Properties"
1920 :group 'org)
1922 (defcustom org-property-format "%-10s %s"
1923 "How property key/value pairs should be formatted by `indent-line'.
1924 When `indent-line' hits a property definition, it will format the line
1925 according to this format, mainly to make sure that the values are
1926 lined-up with respect to each other."
1927 :group 'org-properties
1928 :type 'string)
1930 (defcustom org-use-property-inheritance nil
1931 "Non-nil means, properties apply also for sublevels.
1932 This can cause significant overhead when doing a search, so this is turned
1933 off by default.
1934 When nil, only the properties directly given in the current entry count.
1936 However, note that some special properties use inheritance under special
1937 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1938 and the properties ending in \"_ALL\" when they are used as descriptor
1939 for valid values of a property."
1940 :group 'org-properties
1941 :type 'boolean)
1943 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1944 "The default column format, if no other format has been defined.
1945 This variable can be set on the per-file basis by inserting a line
1947 #+COLUMNS: %25ITEM ....."
1948 :group 'org-properties
1949 :type 'string)
1951 (defcustom org-global-properties nil
1952 "List of property/value pairs that can be inherited by any entry.
1953 You can set buffer-local values for this by adding lines like
1955 #+PROPERTY: NAME VALUE"
1956 :group 'org-properties
1957 :type '(repeat
1958 (cons (string :tag "Property")
1959 (string :tag "Value"))))
1961 (defvar org-local-properties nil
1962 "List of property/value pairs that can be inherited by any entry.
1963 Valid for the current buffer.
1964 This variable is populated from #+PROPERTY lines.")
1966 (defgroup org-agenda nil
1967 "Options concerning agenda views in Org-mode."
1968 :tag "Org Agenda"
1969 :group 'org)
1971 (defvar org-category nil
1972 "Variable used by org files to set a category for agenda display.
1973 Such files should use a file variable to set it, for example
1975 # -*- mode: org; org-category: \"ELisp\"
1977 or contain a special line
1979 #+CATEGORY: ELisp
1981 If the file does not specify a category, then file's base name
1982 is used instead.")
1983 (make-variable-buffer-local 'org-category)
1985 (defcustom org-agenda-files nil
1986 "The files to be used for agenda display.
1987 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1988 \\[org-remove-file]. You can also use customize to edit the list.
1990 If the value of the variable is not a list but a single file name, then
1991 the list of agenda files is actually stored and maintained in that file, one
1992 agenda file per line."
1993 :group 'org-agenda
1994 :type '(choice
1995 (repeat :tag "List of files" file)
1996 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1998 (defcustom org-agenda-skip-unavailable-files nil
1999 "t means to just skip non-reachable files in `org-agenda-files'.
2000 Nil means to remove them, after a query, from the list."
2001 :group 'org-agenda
2002 :type 'boolean)
2004 (defcustom org-agenda-multi-occur-extra-files nil
2005 "List of extra files to be searched by `org-occur-in-agenda-files'.
2006 The files in `org-agenda-files' are always searched."
2007 :group 'org-agenda
2008 :type '(repeat file))
2010 (defcustom org-agenda-confirm-kill 1
2011 "When set, remote killing from the agenda buffer needs confirmation.
2012 When t, a confirmation is always needed. When a number N, confirmation is
2013 only needed when the text to be killed contains more than N non-white lines."
2014 :group 'org-agenda
2015 :type '(choice
2016 (const :tag "Never" nil)
2017 (const :tag "Always" t)
2018 (number :tag "When more than N lines")))
2020 (defcustom org-calendar-to-agenda-key [?c]
2021 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2022 The command `org-calendar-goto-agenda' will be bound to this key. The
2023 default is the character `c' because then `c' can be used to switch back and
2024 forth between agenda and calendar."
2025 :group 'org-agenda
2026 :type 'sexp)
2028 (defcustom org-agenda-compact-blocks nil
2029 "Non-nil means, make the block agenda more compact.
2030 This is done by leaving out unnecessary lines."
2031 :group 'org-agenda
2032 :type nil)
2034 (defgroup org-agenda-export nil
2035 "Options concerning exporting agenda views in Org-mode."
2036 :tag "Org Agenda Export"
2037 :group 'org-agenda)
2039 (defcustom org-agenda-with-colors t
2040 "Non-nil means, use colors in agenda views."
2041 :group 'org-agenda-export
2042 :type 'boolean)
2044 (defcustom org-agenda-exporter-settings nil
2045 "Alist of variable/value pairs that should be active during agenda export.
2046 This is a good place to set uptions for ps-print and for htmlize."
2047 :group 'org-agenda-export
2048 :type '(repeat
2049 (list
2050 (variable)
2051 (sexp :tag "Value"))))
2053 (defcustom org-agenda-export-html-style ""
2054 "The style specification for exported HTML Agenda files.
2055 If this variable contains a string, it will replace the default <style>
2056 section as produced by `htmlize'.
2057 Since there are different ways of setting style information, this variable
2058 needs to contain the full HTML structure to provide a style, including the
2059 surrounding HTML tags. The style specifications should include definitions
2060 the fonts used by the agenda, here is an example:
2062 <style type=\"text/css\">
2063 p { font-weight: normal; color: gray; }
2064 .org-agenda-structure {
2065 font-size: 110%;
2066 color: #003399;
2067 font-weight: 600;
2069 .org-todo {
2070 color: #cc6666;Week-agenda:
2071 font-weight: bold;
2073 .org-done {
2074 color: #339933;
2076 .title { text-align: center; }
2077 .todo, .deadline { color: red; }
2078 .done { color: green; }
2079 </style>
2081 or, if you want to keep the style in a file,
2083 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2085 As the value of this option simply gets inserted into the HTML <head> header,
2086 you can \"misuse\" it to also add other text to the header. However,
2087 <style>...</style> is required, if not present the variable will be ignored."
2088 :group 'org-agenda-export
2089 :group 'org-export-html
2090 :type 'string)
2092 (defgroup org-agenda-custom-commands nil
2093 "Options concerning agenda views in Org-mode."
2094 :tag "Org Agenda Custom Commands"
2095 :group 'org-agenda)
2097 (defcustom org-agenda-custom-commands nil
2098 "Custom commands for the agenda.
2099 These commands will be offered on the splash screen displayed by the
2100 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2102 (key desc type match options files)
2104 key The key (one or more characters as a string) to be associated
2105 with the command.
2106 desc A description of the commend, when omitted or nil, a default
2107 description is built using MATCH.
2108 type The command type, any of the following symbols:
2109 todo Entries with a specific TODO keyword, in all agenda files.
2110 tags Tags match in all agenda files.
2111 tags-todo Tags match in all agenda files, TODO entries only.
2112 todo-tree Sparse tree of specific TODO keyword in *current* file.
2113 tags-tree Sparse tree with all tags matches in *current* file.
2114 occur-tree Occur sparse tree for *current* file.
2115 ... A user-defined function.
2116 match What to search for:
2117 - a single keyword for TODO keyword searches
2118 - a tags match expression for tags searches
2119 - a regular expression for occur searches
2120 options A list of option settings, similar to that in a let form, so like
2121 this: ((opt1 val1) (opt2 val2) ...)
2122 files A list of files file to write the produced agenda buffer to
2123 with the command `org-store-agenda-views'.
2124 If a file name ends in \".html\", an HTML version of the buffer
2125 is written out. If it ends in \".ps\", a postscript version is
2126 produced. Otherwide, only the plain text is written to the file.
2128 You can also define a set of commands, to create a composite agenda buffer.
2129 In this case, an entry looks like this:
2131 (key desc (cmd1 cmd2 ...) general-options file)
2133 where
2135 desc A description string to be displayed in the dispatcher menu.
2136 cmd An agenda command, similar to the above. However, tree commands
2137 are no allowed, but instead you can get agenda and global todo list.
2138 So valid commands for a set are:
2139 (agenda)
2140 (alltodo)
2141 (stuck)
2142 (todo \"match\" options files)
2143 (tags \"match\" options files)
2144 (tags-todo \"match\" options files)
2146 Each command can carry a list of options, and another set of options can be
2147 given for the whole set of commands. Individual command options take
2148 precedence over the general options.
2150 When using several characters as key to a command, the first characters
2151 are prefix commands. For the dispatcher to display useful information, you
2152 should provide a description for the prefix, like
2154 (setq org-agenda-custom-commands
2155 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2156 (\"hl\" tags \"+HOME+Lisa\")
2157 (\"hp\" tags \"+HOME+Peter\")
2158 (\"hk\" tags \"+HOME+Kim\")))"
2159 :group 'org-agenda-custom-commands
2160 :type '(repeat
2161 (choice :value ("a" "" tags "" nil)
2162 (list :tag "Single command"
2163 (string :tag "Access Key(s) ")
2164 (option (string :tag "Description"))
2165 (choice
2166 (const :tag "Agenda" agenda)
2167 (const :tag "TODO list" alltodo)
2168 (const :tag "Stuck projects" stuck)
2169 (const :tag "Tags search (all agenda files)" tags)
2170 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2171 (const :tag "TODO keyword search (all agenda files)" todo)
2172 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2173 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2174 (const :tag "Occur tree (current buffer)" occur-tree)
2175 (sexp :tag "Other, user-defined function"))
2176 (string :tag "Match")
2177 (repeat :tag "Local options"
2178 (list (variable :tag "Option") (sexp :tag "Value")))
2179 (option (repeat :tag "Export" (file :tag "Export to"))))
2180 (list :tag "Command series, all agenda files"
2181 (string :tag "Access Key(s)")
2182 (string :tag "Description ")
2183 (repeat
2184 (choice
2185 (const :tag "Agenda" (agenda))
2186 (const :tag "TODO list" (alltodo))
2187 (const :tag "Stuck projects" (stuck))
2188 (list :tag "Tags search"
2189 (const :format "" tags)
2190 (string :tag "Match")
2191 (repeat :tag "Local options"
2192 (list (variable :tag "Option")
2193 (sexp :tag "Value"))))
2195 (list :tag "Tags search, TODO entries only"
2196 (const :format "" tags-todo)
2197 (string :tag "Match")
2198 (repeat :tag "Local options"
2199 (list (variable :tag "Option")
2200 (sexp :tag "Value"))))
2202 (list :tag "TODO keyword search"
2203 (const :format "" todo)
2204 (string :tag "Match")
2205 (repeat :tag "Local options"
2206 (list (variable :tag "Option")
2207 (sexp :tag "Value"))))
2209 (list :tag "Other, user-defined function"
2210 (symbol :tag "function")
2211 (string :tag "Match")
2212 (repeat :tag "Local options"
2213 (list (variable :tag "Option")
2214 (sexp :tag "Value"))))))
2216 (repeat :tag "General options"
2217 (list (variable :tag "Option")
2218 (sexp :tag "Value")))
2219 (option (repeat :tag "Export" (file :tag "Export to"))))
2220 (cons :tag "Prefix key documentation"
2221 (string :tag "Access Key(s)")
2222 (string :tag "Description ")))))
2224 (defcustom org-stuck-projects
2225 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2226 "How to identify stuck projects.
2227 This is a list of four items:
2228 1. A tags/todo matcher string that is used to identify a project.
2229 The entire tree below a headline matched by this is considered one project.
2230 2. A list of TODO keywords identifying non-stuck projects.
2231 If the project subtree contains any headline with one of these todo
2232 keywords, the project is considered to be not stuck. If you specify
2233 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2234 3. A list of tags identifying non-stuck projects.
2235 If the project subtree contains any headline with one of these tags,
2236 the project is considered to be not stuck. If you specify \"*\" as
2237 a tag, any tag will mark the project unstuck.
2238 4. An arbitrary regular expression matching non-stuck projects.
2240 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2241 or `C-c a #' to produce the list."
2242 :group 'org-agenda-custom-commands
2243 :type '(list
2244 (string :tag "Tags/TODO match to identify a project")
2245 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2246 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2247 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2250 (defgroup org-agenda-skip nil
2251 "Options concerning skipping parts of agenda files."
2252 :tag "Org Agenda Skip"
2253 :group 'org-agenda)
2255 (defcustom org-agenda-todo-list-sublevels t
2256 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2257 When nil, the sublevels of a TODO entry are not checked, resulting in
2258 potentially much shorter TODO lists."
2259 :group 'org-agenda-skip
2260 :group 'org-todo
2261 :type 'boolean)
2263 (defcustom org-agenda-todo-ignore-with-date nil
2264 "Non-nil means, don't show entries with a date in the global todo list.
2265 You can use this if you prefer to mark mere appointments with a TODO keyword,
2266 but don't want them to show up in the TODO list.
2267 When this is set, it also covers deadlines and scheduled items, the settings
2268 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2269 will be ignored."
2270 :group 'org-agenda-skip
2271 :group 'org-todo
2272 :type 'boolean)
2274 (defcustom org-agenda-todo-ignore-scheduled nil
2275 "Non-nil means, don't show scheduled entries in the global todo list.
2276 The idea behind this is that by scheduling it, you have already taken care
2277 of this item.
2278 See also `org-agenda-todo-ignore-with-date'."
2279 :group 'org-agenda-skip
2280 :group 'org-todo
2281 :type 'boolean)
2283 (defcustom org-agenda-todo-ignore-deadlines nil
2284 "Non-nil means, don't show near deadline entries in the global todo list.
2285 Near means closer than `org-deadline-warning-days' days.
2286 The idea behind this is that such items will appear in the agenda anyway.
2287 See also `org-agenda-todo-ignore-with-date'."
2288 :group 'org-agenda-skip
2289 :group 'org-todo
2290 :type 'boolean)
2292 (defcustom org-agenda-skip-scheduled-if-done nil
2293 "Non-nil means don't show scheduled items in agenda when they are done.
2294 This is relevant for the daily/weekly agenda, not for the TODO list. And
2295 it applies only to the actual date of the scheduling. Warnings about
2296 an item with a past scheduling dates are always turned off when the item
2297 is DONE."
2298 :group 'org-agenda-skip
2299 :type 'boolean)
2301 (defcustom org-agenda-skip-deadline-if-done nil
2302 "Non-nil means don't show deadines when the corresponding item is done.
2303 When nil, the deadline is still shown and should give you a happy feeling.
2304 This is relevant for the daily/weekly agenda. And it applied only to the
2305 actualy date of the deadline. Warnings about approching and past-due
2306 deadlines are always turned off when the item is DONE."
2307 :group 'org-agenda-skip
2308 :type 'boolean)
2310 (defcustom org-timeline-show-empty-dates 3
2311 "Non-nil means, `org-timeline' also shows dates without an entry.
2312 When nil, only the days which actually have entries are shown.
2313 When t, all days between the first and the last date are shown.
2314 When an integer, show also empty dates, but if there is a gap of more than
2315 N days, just insert a special line indicating the size of the gap."
2316 :group 'org-agenda-skip
2317 :type '(choice
2318 (const :tag "None" nil)
2319 (const :tag "All" t)
2320 (number :tag "at most")))
2323 (defgroup org-agenda-startup nil
2324 "Options concerning initial settings in the Agenda in Org Mode."
2325 :tag "Org Agenda Startup"
2326 :group 'org-agenda)
2328 (defcustom org-finalize-agenda-hook nil
2329 "Hook run just before displaying an agenda buffer."
2330 :group 'org-agenda-startup
2331 :type 'hook)
2333 (defcustom org-agenda-mouse-1-follows-link nil
2334 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2335 A longer mouse click will still set point. Does not wortk on XEmacs.
2336 Needs to be set before org.el is loaded."
2337 :group 'org-agenda-startup
2338 :type 'boolean)
2340 (defcustom org-agenda-start-with-follow-mode nil
2341 "The initial value of follow-mode in a newly created agenda window."
2342 :group 'org-agenda-startup
2343 :type 'boolean)
2345 (defgroup org-agenda-windows nil
2346 "Options concerning the windows used by the Agenda in Org Mode."
2347 :tag "Org Agenda Windows"
2348 :group 'org-agenda)
2350 (defcustom org-agenda-window-setup 'reorganize-frame
2351 "How the agenda buffer should be displayed.
2352 Possible values for this option are:
2354 current-window Show agenda in the current window, keeping all other windows.
2355 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2356 other-window Use `switch-to-buffer-other-window' to display agenda.
2357 reorganize-frame Show only two windows on the current frame, the current
2358 window and the agenda.
2359 See also the variable `org-agenda-restore-windows-after-quit'."
2360 :group 'org-agenda-windows
2361 :type '(choice
2362 (const current-window)
2363 (const other-frame)
2364 (const other-window)
2365 (const reorganize-frame)))
2367 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2368 "The min and max height of the agenda window as a fraction of frame height.
2369 The value of the variable is a cons cell with two numbers between 0 and 1.
2370 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2371 :group 'org-agenda-windows
2372 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2374 (defcustom org-agenda-restore-windows-after-quit nil
2375 "Non-nil means, restore window configuration open exiting agenda.
2376 Before the window configuration is changed for displaying the agenda,
2377 the current status is recorded. When the agenda is exited with
2378 `q' or `x' and this option is set, the old state is restored. If
2379 `org-agenda-window-setup' is `other-frame', the value of this
2380 option will be ignored.."
2381 :group 'org-agenda-windows
2382 :type 'boolean)
2384 (defcustom org-indirect-buffer-display 'other-window
2385 "How should indirect tree buffers be displayed?
2386 This applies to indirect buffers created with the commands
2387 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2388 Valid values are:
2389 current-window Display in the current window
2390 other-window Just display in another window.
2391 dedicated-frame Create one new frame, and re-use it each time.
2392 new-frame Make a new frame each time."
2393 :group 'org-structure
2394 :group 'org-agenda-windows
2395 :type '(choice
2396 (const :tag "In current window" current-window)
2397 (const :tag "In current frame, other window" other-window)
2398 (const :tag "Each time a new frame" new-frame)
2399 (const :tag "One dedicated frame" dedicated-frame)))
2401 (defgroup org-agenda-daily/weekly nil
2402 "Options concerning the daily/weekly agenda."
2403 :tag "Org Agenda Daily/Weekly"
2404 :group 'org-agenda)
2406 (defcustom org-agenda-ndays 7
2407 "Number of days to include in overview display.
2408 Should be 1 or 7."
2409 :group 'org-agenda-daily/weekly
2410 :type 'number)
2412 (defcustom org-agenda-start-on-weekday 1
2413 "Non-nil means, start the overview always on the specified weekday.
2414 0 denotes Sunday, 1 denotes Monday etc.
2415 When nil, always start on the current day."
2416 :group 'org-agenda-daily/weekly
2417 :type '(choice (const :tag "Today" nil)
2418 (number :tag "Weekday No.")))
2420 (defcustom org-agenda-show-all-dates t
2421 "Non-nil means, `org-agenda' shows every day in the selected range.
2422 When nil, only the days which actually have entries are shown."
2423 :group 'org-agenda-daily/weekly
2424 :type 'boolean)
2426 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2427 "Format string for displaying dates in the agenda.
2428 Used by the daily/weekly agenda and by the timeline. This should be
2429 a format string understood by `format-time-string', or a function returning
2430 the formatted date as a string. The function must take a single argument,
2431 a calendar-style date list like (month day year)."
2432 :group 'org-agenda-daily/weekly
2433 :type '(choice
2434 (string :tag "Format string")
2435 (function :tag "Function")))
2437 (defun org-agenda-format-date-aligned (date)
2438 "Format a date string for display in the daily/weekly agenda, or timeline.
2439 This function makes sure that dates are aligned for easy reading."
2440 (format "%-9s %2d %s %4d"
2441 (calendar-day-name date)
2442 (extract-calendar-day date)
2443 (calendar-month-name (extract-calendar-month date))
2444 (extract-calendar-year date)))
2446 (defcustom org-agenda-include-diary nil
2447 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2448 :group 'org-agenda-daily/weekly
2449 :type 'boolean)
2451 (defcustom org-agenda-include-all-todo nil
2452 "Set means weekly/daily agenda will always contain all TODO entries.
2453 The TODO entries will be listed at the top of the agenda, before
2454 the entries for specific days."
2455 :group 'org-agenda-daily/weekly
2456 :type 'boolean)
2458 (defcustom org-agenda-repeating-timestamp-show-all t
2459 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2460 When nil, only one occurence is shown, either today or the
2461 nearest into the future."
2462 :group 'org-agenda-daily/weekly
2463 :type 'boolean)
2465 (defcustom org-deadline-warning-days 14
2466 "No. of days before expiration during which a deadline becomes active.
2467 This variable governs the display in sparse trees and in the agenda.
2468 When negative, it means use this number (the absolute value of it)
2469 even if a deadline has a different individual lead time specified."
2470 :group 'org-time
2471 :group 'org-agenda-daily/weekly
2472 :type 'number)
2474 (defcustom org-scheduled-past-days 10000
2475 "No. of days to continue listing scheduled items that are not marked DONE.
2476 When an item is scheduled on a date, it shows up in the agenda on this
2477 day and will be listed until it is marked done for the number of days
2478 given here."
2479 :group 'org-agenda-daily/weekly
2480 :type 'number)
2482 (defgroup org-agenda-time-grid nil
2483 "Options concerning the time grid in the Org-mode Agenda."
2484 :tag "Org Agenda Time Grid"
2485 :group 'org-agenda)
2487 (defcustom org-agenda-use-time-grid t
2488 "Non-nil means, show a time grid in the agenda schedule.
2489 A time grid is a set of lines for specific times (like every two hours between
2490 8:00 and 20:00). The items scheduled for a day at specific times are
2491 sorted in between these lines.
2492 For details about when the grid will be shown, and what it will look like, see
2493 the variable `org-agenda-time-grid'."
2494 :group 'org-agenda-time-grid
2495 :type 'boolean)
2497 (defcustom org-agenda-time-grid
2498 '((daily today require-timed)
2499 "----------------"
2500 (800 1000 1200 1400 1600 1800 2000))
2502 "The settings for time grid for agenda display.
2503 This is a list of three items. The first item is again a list. It contains
2504 symbols specifying conditions when the grid should be displayed:
2506 daily if the agenda shows a single day
2507 weekly if the agenda shows an entire week
2508 today show grid on current date, independent of daily/weekly display
2509 require-timed show grid only if at least one item has a time specification
2511 The second item is a string which will be places behing the grid time.
2513 The third item is a list of integers, indicating the times that should have
2514 a grid line."
2515 :group 'org-agenda-time-grid
2516 :type
2517 '(list
2518 (set :greedy t :tag "Grid Display Options"
2519 (const :tag "Show grid in single day agenda display" daily)
2520 (const :tag "Show grid in weekly agenda display" weekly)
2521 (const :tag "Always show grid for today" today)
2522 (const :tag "Show grid only if any timed entries are present"
2523 require-timed)
2524 (const :tag "Skip grid times already present in an entry"
2525 remove-match))
2526 (string :tag "Grid String")
2527 (repeat :tag "Grid Times" (integer :tag "Time"))))
2529 (defgroup org-agenda-sorting nil
2530 "Options concerning sorting in the Org-mode Agenda."
2531 :tag "Org Agenda Sorting"
2532 :group 'org-agenda)
2534 (let ((sorting-choice
2535 '(choice
2536 (const time-up) (const time-down)
2537 (const category-keep) (const category-up) (const category-down)
2538 (const tag-down) (const tag-up)
2539 (const priority-up) (const priority-down))))
2541 (defcustom org-agenda-sorting-strategy
2542 '((agenda time-up category-keep priority-down)
2543 (todo category-keep priority-down)
2544 (tags category-keep priority-down))
2545 "Sorting structure for the agenda items of a single day.
2546 This is a list of symbols which will be used in sequence to determine
2547 if an entry should be listed before another entry. The following
2548 symbols are recognized:
2550 time-up Put entries with time-of-day indications first, early first
2551 time-down Put entries with time-of-day indications first, late first
2552 category-keep Keep the default order of categories, corresponding to the
2553 sequence in `org-agenda-files'.
2554 category-up Sort alphabetically by category, A-Z.
2555 category-down Sort alphabetically by category, Z-A.
2556 tag-up Sort alphabetically by last tag, A-Z.
2557 tag-down Sort alphabetically by last tag, Z-A.
2558 priority-up Sort numerically by priority, high priority last.
2559 priority-down Sort numerically by priority, high priority first.
2561 The different possibilities will be tried in sequence, and testing stops
2562 if one comparison returns a \"not-equal\". For example, the default
2563 '(time-up category-keep priority-down)
2564 means: Pull out all entries having a specified time of day and sort them,
2565 in order to make a time schedule for the current day the first thing in the
2566 agenda listing for the day. Of the entries without a time indication, keep
2567 the grouped in categories, don't sort the categories, but keep them in
2568 the sequence given in `org-agenda-files'. Within each category sort by
2569 priority.
2571 Leaving out `category-keep' would mean that items will be sorted across
2572 categories by priority."
2573 :group 'org-agenda-sorting
2574 :type `(choice
2575 (repeat :tag "General" ,sorting-choice)
2576 (list :tag "Individually"
2577 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2578 (repeat ,sorting-choice))
2579 (cons (const :tag "Strategy for TODO lists" todo)
2580 (repeat ,sorting-choice))
2581 (cons (const :tag "Strategy for Tags matches" tags)
2582 (repeat ,sorting-choice))))))
2584 (defcustom org-sort-agenda-notime-is-late t
2585 "Non-nil means, items without time are considered late.
2586 This is only relevant for sorting. When t, items which have no explicit
2587 time like 15:30 will be considered as 99:01, i.e. later than any items which
2588 do have a time. When nil, the default time is before 0:00. You can use this
2589 option to decide if the schedule for today should come before or after timeless
2590 agenda entries."
2591 :group 'org-agenda-sorting
2592 :type 'boolean)
2594 (defgroup org-agenda-line-format nil
2595 "Options concerning the entry prefix in the Org-mode agenda display."
2596 :tag "Org Agenda Line Format"
2597 :group 'org-agenda)
2599 (defcustom org-agenda-prefix-format
2600 '((agenda . " %-12:c%?-12t% s")
2601 (timeline . " % s")
2602 (todo . " %-12:c")
2603 (tags . " %-12:c"))
2604 "Format specifications for the prefix of items in the agenda views.
2605 An alist with four entries, for the different agenda types. The keys to the
2606 sublists are `agenda', `timeline', `todo', and `tags'. The values
2607 are format strings.
2608 This format works similar to a printf format, with the following meaning:
2610 %c the category of the item, \"Diary\" for entries from the diary, or
2611 as given by the CATEGORY keyword or derived from the file name.
2612 %T the *last* tag of the item. Last because inherited tags come
2613 first in the list.
2614 %t the time-of-day specification if one applies to the entry, in the
2615 format HH:MM
2616 %s Scheduling/Deadline information, a short string
2618 All specifiers work basically like the standard `%s' of printf, but may
2619 contain two additional characters: A question mark just after the `%' and
2620 a whitespace/punctuation character just before the final letter.
2622 If the first character after `%' is a question mark, the entire field
2623 will only be included if the corresponding value applies to the
2624 current entry. This is useful for fields which should have fixed
2625 width when present, but zero width when absent. For example,
2626 \"%?-12t\" will result in a 12 character time field if a time of the
2627 day is specified, but will completely disappear in entries which do
2628 not contain a time.
2630 If there is punctuation or whitespace character just before the final
2631 format letter, this character will be appended to the field value if
2632 the value is not empty. For example, the format \"%-12:c\" leads to
2633 \"Diary: \" if the category is \"Diary\". If the category were be
2634 empty, no additional colon would be interted.
2636 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2637 - Indent the line with two space characters
2638 - Give the category in a 12 chars wide field, padded with whitespace on
2639 the right (because of `-'). Append a colon if there is a category
2640 (because of `:').
2641 - If there is a time-of-day, put it into a 12 chars wide field. If no
2642 time, don't put in an empty field, just skip it (because of '?').
2643 - Finally, put the scheduling information and append a whitespace.
2645 As another example, if you don't want the time-of-day of entries in
2646 the prefix, you could use:
2648 (setq org-agenda-prefix-format \" %-11:c% s\")
2650 See also the variables `org-agenda-remove-times-when-in-prefix' and
2651 `org-agenda-remove-tags'."
2652 :type '(choice
2653 (string :tag "General format")
2654 (list :greedy t :tag "View dependent"
2655 (cons (const agenda) (string :tag "Format"))
2656 (cons (const timeline) (string :tag "Format"))
2657 (cons (const todo) (string :tag "Format"))
2658 (cons (const tags) (string :tag "Format"))))
2659 :group 'org-agenda-line-format)
2661 (defvar org-prefix-format-compiled nil
2662 "The compiled version of the most recently used prefix format.
2663 See the variable `org-agenda-prefix-format'.")
2665 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2666 "Text preceeding scheduled items in the agenda view.
2667 THis is a list with two strings. The first applies when the item is
2668 scheduled on the current day. The second applies when it has been scheduled
2669 previously, it may contain a %d to capture how many days ago the item was
2670 scheduled."
2671 :group 'org-agenda-line-format
2672 :type '(list
2673 (string :tag "Scheduled today ")
2674 (string :tag "Scheduled previously")))
2676 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2677 "Text preceeding deadline items in the agenda view.
2678 This is a list with two strings. The first applies when the item has its
2679 deadline on the current day. The second applies when it is in the past or
2680 in the future, it may contain %d to capture how many days away the deadline
2681 is (was)."
2682 :group 'org-agenda-line-format
2683 :type '(list
2684 (string :tag "Deadline today ")
2685 (string :tag "Deadline relative")))
2687 (defcustom org-agenda-remove-times-when-in-prefix t
2688 "Non-nil means, remove duplicate time specifications in agenda items.
2689 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2690 time-of-day specification in a headline or diary entry is extracted and
2691 placed into the prefix. If this option is non-nil, the original specification
2692 \(a timestamp or -range, or just a plain time(range) specification like
2693 11:30-4pm) will be removed for agenda display. This makes the agenda less
2694 cluttered.
2695 The option can be t or nil. It may also be the symbol `beg', indicating
2696 that the time should only be removed what it is located at the beginning of
2697 the headline/diary entry."
2698 :group 'org-agenda-line-format
2699 :type '(choice
2700 (const :tag "Always" t)
2701 (const :tag "Never" nil)
2702 (const :tag "When at beginning of entry" beg)))
2705 (defcustom org-agenda-default-appointment-duration nil
2706 "Default duration for appointments that only have a starting time.
2707 When nil, no duration is specified in such cases.
2708 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2709 :group 'org-agenda-line-format
2710 :type '(choice
2711 (integer :tag "Minutes")
2712 (const :tag "No default duration")))
2715 (defcustom org-agenda-remove-tags nil
2716 "Non-nil means, remove the tags from the headline copy in the agenda.
2717 When this is the symbol `prefix', only remove tags when
2718 `org-agenda-prefix-format' contains a `%T' specifier."
2719 :group 'org-agenda-line-format
2720 :type '(choice
2721 (const :tag "Always" t)
2722 (const :tag "Never" nil)
2723 (const :tag "When prefix format contains %T" prefix)))
2725 (if (fboundp 'defvaralias)
2726 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2727 'org-agenda-remove-tags))
2729 (defcustom org-agenda-tags-column -80
2730 "Shift tags in agenda items to this column.
2731 If this number is positive, it specifies the column. If it is negative,
2732 it means that the tags should be flushright to that column. For example,
2733 -80 works well for a normal 80 character screen."
2734 :group 'org-agenda-line-format
2735 :type 'integer)
2737 (if (fboundp 'defvaralias)
2738 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2740 (defcustom org-agenda-fontify-priorities t
2741 "Non-nil means, highlight low and high priorities in agenda.
2742 When t, the highest priority entries are bold, lowest priority italic.
2743 This may also be an association list of priority faces. The face may be
2744 a names face, or a list like `(:background \"Red\")'."
2745 :group 'org-agenda-line-format
2746 :type '(choice
2747 (const :tag "Never" nil)
2748 (const :tag "Defaults" t)
2749 (repeat :tag "Specify"
2750 (list (character :tag "Priority" :value ?A)
2751 (sexp :tag "face")))))
2753 (defgroup org-latex nil
2754 "Options for embedding LaTeX code into Org-mode"
2755 :tag "Org LaTeX"
2756 :group 'org)
2758 (defcustom org-format-latex-options
2759 '(:foreground default :background default :scale 1.0
2760 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2761 :matchers ("begin" "$" "$$" "\\(" "\\["))
2762 "Options for creating images from LaTeX fragments.
2763 This is a property list with the following properties:
2764 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2765 `default' means use the forground of the default face.
2766 :background the background color, or \"Transparent\".
2767 `default' means use the background of the default face.
2768 :scale a scaling factor for the size of the images
2769 :html-foreground, :html-background, :html-scale
2770 The same numbers for HTML export.
2771 :matchers a list indicating which matchers should be used to
2772 find LaTeX fragments. Valid members of this list are:
2773 \"begin\" find environments
2774 \"$\" find math expressions surrounded by $...$
2775 \"$$\" find math expressions surrounded by $$....$$
2776 \"\\(\" find math expressions surrounded by \\(...\\)
2777 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2778 :group 'org-latex
2779 :type 'plist)
2781 (defcustom org-format-latex-header "\\documentclass{article}
2782 \\usepackage{fullpage} % do not remove
2783 \\usepackage{amssymb}
2784 \\usepackage[usenames]{color}
2785 \\usepackage{amsmath}
2786 \\usepackage{latexsym}
2787 \\usepackage[mathscr]{eucal}
2788 \\pagestyle{empty} % do not remove"
2789 "The document header used for processing LaTeX fragments."
2790 :group 'org-latex
2791 :type 'string)
2793 (defgroup org-export nil
2794 "Options for exporting org-listings."
2795 :tag "Org Export"
2796 :group 'org)
2798 (defgroup org-export-general nil
2799 "General options for exporting Org-mode files."
2800 :tag "Org Export General"
2801 :group 'org-export)
2803 (defcustom org-export-publishing-directory "."
2804 "Path to the location where exported files should be located.
2805 This path may be relative to the directory where the Org-mode file lives.
2806 The default is to put them into the same directory as the Org-mode file.
2807 The variable may also be an alist with export types `:html', `:ascii',
2808 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2809 If a directory path is relative, it is interpreted relative to the
2810 directory where the exported Org-mode files lives."
2811 :group 'org-export-general
2812 :type '(choice
2813 (directory)
2814 (repeat
2815 (cons
2816 (choice :tag "Type"
2817 (const :html) (const :LaTeX)
2818 (const :ascii) (const :ical) (const :xoxo))
2819 (directory)))))
2821 (defcustom org-export-language-setup
2822 '(("en" "Author" "Date" "Table of Contents")
2823 ("cs" "Autor" "Datum" "Obsah")
2824 ("da" "Ophavsmand" "Dato" "Indhold")
2825 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2826 ("es" "Autor" "Fecha" "\xcdndice")
2827 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2828 ("it" "Autore" "Data" "Indice")
2829 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2830 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2831 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2832 "Terms used in export text, translated to different languages.
2833 Use the variable `org-export-default-language' to set the language,
2834 or use the +OPTION lines for a per-file setting."
2835 :group 'org-export-general
2836 :type '(repeat
2837 (list
2838 (string :tag "HTML language tag")
2839 (string :tag "Author")
2840 (string :tag "Date")
2841 (string :tag "Table of Contents"))))
2843 (defcustom org-export-default-language "en"
2844 "The default language of HTML export, as a string.
2845 This should have an association in `org-export-language-setup'."
2846 :group 'org-export-general
2847 :type 'string)
2849 (defcustom org-export-skip-text-before-1st-heading t
2850 "Non-nil means, skip all text before the first headline when exporting.
2851 When nil, that text is exported as well."
2852 :group 'org-export-general
2853 :type 'boolean)
2855 (defcustom org-export-headline-levels 3
2856 "The last level which is still exported as a headline.
2857 Inferior levels will produce itemize lists when exported.
2858 Note that a numeric prefix argument to an exporter function overrides
2859 this setting.
2861 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2862 :group 'org-export-general
2863 :type 'number)
2865 (defcustom org-export-with-section-numbers t
2866 "Non-nil means, add section numbers to headlines when exporting.
2868 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2869 :group 'org-export-general
2870 :type 'boolean)
2872 (defcustom org-export-with-toc t
2873 "Non-nil means, create a table of contents in exported files.
2874 The TOC contains headlines with levels up to`org-export-headline-levels'.
2875 When an integer, include levels up to N in the toc, this may then be
2876 different from `org-export-headline-levels', but it will not be allowed
2877 to be larger than the number of headline levels.
2878 When nil, no table of contents is made.
2880 Headlines which contain any TODO items will be marked with \"(*)\" in
2881 ASCII export, and with red color in HTML output, if the option
2882 `org-export-mark-todo-in-toc' is set.
2884 In HTML output, the TOC will be clickable.
2886 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2887 or \"toc:3\"."
2888 :group 'org-export-general
2889 :type '(choice
2890 (const :tag "No Table of Contents" nil)
2891 (const :tag "Full Table of Contents" t)
2892 (integer :tag "TOC to level")))
2894 (defcustom org-export-mark-todo-in-toc nil
2895 "Non-nil means, mark TOC lines that contain any open TODO items."
2896 :group 'org-export-general
2897 :type 'boolean)
2899 (defcustom org-export-preserve-breaks nil
2900 "Non-nil means, preserve all line breaks when exporting.
2901 Normally, in HTML output paragraphs will be reformatted. In ASCII
2902 export, line breaks will always be preserved, regardless of this variable.
2904 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2905 :group 'org-export-general
2906 :type 'boolean)
2908 (defcustom org-export-with-archived-trees 'headline
2909 "Whether subtrees with the ARCHIVE tag should be exported.
2910 This can have three different values
2911 nil Do not export, pretend this tree is not present
2912 t Do export the entire tree
2913 headline Only export the headline, but skip the tree below it."
2914 :group 'org-export-general
2915 :group 'org-archive
2916 :type '(choice
2917 (const :tag "not at all" nil)
2918 (const :tag "headline only" 'headline)
2919 (const :tag "entirely" t)))
2921 (defcustom org-export-author-info t
2922 "Non-nil means, insert author name and email into the exported file.
2924 This option can also be set with the +OPTIONS line,
2925 e.g. \"author-info:nil\"."
2926 :group 'org-export-general
2927 :type 'boolean)
2929 (defcustom org-export-time-stamp-file t
2930 "Non-nil means, insert a time stamp into the exported file.
2931 The time stamp shows when the file was created.
2933 This option can also be set with the +OPTIONS line,
2934 e.g. \"timestamp:nil\"."
2935 :group 'org-export-general
2936 :type 'boolean)
2938 (defcustom org-export-with-timestamps t
2939 "If nil, do not export time stamps and associated keywords."
2940 :group 'org-export-general
2941 :type 'boolean)
2943 (defcustom org-export-remove-timestamps-from-toc t
2944 "If nil, remove timestamps from the table of contents entries."
2945 :group 'org-export-general
2946 :type 'boolean)
2948 (defcustom org-export-with-tags 'not-in-toc
2949 "If nil, do not export tags, just remove them from headlines.
2950 If this is the symbol `not-in-toc', tags will be removed from table of
2951 contents entries, but still be shown in the headlines of the document.
2953 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
2954 :group 'org-export-general
2955 :type '(choice
2956 (const :tag "Off" nil)
2957 (const :tag "Not in TOC" not-in-toc)
2958 (const :tag "On" t)))
2960 (defcustom org-export-with-drawers nil
2961 "Non-nil means, export with drawers like the property drawer.
2962 When t, all drawers are exported. This may also be a list of
2963 drawer names to export."
2964 :group 'org-export-general
2965 :type '(choice
2966 (const :tag "All drawers" t)
2967 (const :tag "None" nil)
2968 (repeat :tag "Selected drawers"
2969 (string :tag "Drawer name"))))
2971 (defgroup org-export-translation nil
2972 "Options for translating special ascii sequences for the export backends."
2973 :tag "Org Export Translation"
2974 :group 'org-export)
2976 (defcustom org-export-with-emphasize t
2977 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2978 If the export target supports emphasizing text, the word will be
2979 typeset in bold, italic, or underlined, respectively. Works only for
2980 single words, but you can say: I *really* *mean* *this*.
2981 Not all export backends support this.
2983 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2984 :group 'org-export-translation
2985 :type 'boolean)
2987 (defcustom org-export-with-footnotes t
2988 "If nil, export [1] as a footnote marker.
2989 Lines starting with [1] will be formatted as footnotes.
2991 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
2992 :group 'org-export-translation
2993 :type 'boolean)
2995 (defcustom org-export-with-sub-superscripts t
2996 "Non-nil means, interpret \"_\" and \"^\" for export.
2997 When this option is turned on, you can use TeX-like syntax for sub- and
2998 superscripts. Several characters after \"_\" or \"^\" will be
2999 considered as a single item - so grouping with {} is normally not
3000 needed. For example, the following things will be parsed as single
3001 sub- or superscripts.
3003 10^24 or 10^tau several digits will be considered 1 item.
3004 10^-12 or 10^-tau a leading sign with digits or a word
3005 x^2-y^3 will be read as x^2 - y^3, because items are
3006 terminated by almost any nonword/nondigit char.
3007 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3009 Still, ambiguity is possible - so when in doubt use {} to enclose the
3010 sub/superscript. If you set this variable to the symbol `{}',
3011 the braces are *required* in order to trigger interpretations as
3012 sub/superscript. This can be helpful in documents that need \"_\"
3013 frequently in plain text.
3015 Not all export backends support this, but HTML does.
3017 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3018 :group 'org-export-translation
3019 :type '(choice
3020 (const :tag "Always interpret" t)
3021 (const :tag "Only with braces" {})
3022 (const :tag "Never interpret" nil)))
3024 (defcustom org-export-with-TeX-macros t
3025 "Non-nil means, interpret simple TeX-like macros when exporting.
3026 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3027 No only real TeX macros will work here, but the standard HTML entities
3028 for math can be used as macro names as well. For a list of supported
3029 names in HTML export, see the constant `org-html-entities'.
3030 Not all export backends support this.
3032 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3033 :group 'org-export-translation
3034 :group 'org-export-latex
3035 :type 'boolean)
3037 (defcustom org-export-with-LaTeX-fragments nil
3038 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3039 When set, the exporter will find LaTeX environments if the \\begin line is
3040 the first non-white thing on a line. It will also find the math delimiters
3041 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3042 display math.
3044 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3045 :group 'org-export-translation
3046 :group 'org-export-latex
3047 :type 'boolean)
3049 (defcustom org-export-with-fixed-width t
3050 "Non-nil means, lines starting with \":\" will be in fixed width font.
3051 This can be used to have pre-formatted text, fragments of code etc. For
3052 example:
3053 : ;; Some Lisp examples
3054 : (while (defc cnt)
3055 : (ding))
3056 will be looking just like this in also HTML. See also the QUOTE keyword.
3057 Not all export backends support this.
3059 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3060 :group 'org-export-translation
3061 :type 'boolean)
3063 (defcustom org-match-sexp-depth 3
3064 "Number of stacked braces for sub/superscript matching.
3065 This has to be set before loading org.el to be effective."
3066 :group 'org-export-translation
3067 :type 'integer)
3069 (defgroup org-export-tables nil
3070 "Options for exporting tables in Org-mode."
3071 :tag "Org Export Tables"
3072 :group 'org-export)
3074 (defcustom org-export-with-tables t
3075 "If non-nil, lines starting with \"|\" define a table.
3076 For example:
3078 | Name | Address | Birthday |
3079 |-------------+----------+-----------|
3080 | Arthur Dent | England | 29.2.2100 |
3082 Not all export backends support this.
3084 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3085 :group 'org-export-tables
3086 :type 'boolean)
3088 (defcustom org-export-highlight-first-table-line t
3089 "Non-nil means, highlight the first table line.
3090 In HTML export, this means use <th> instead of <td>.
3091 In tables created with table.el, this applies to the first table line.
3092 In Org-mode tables, all lines before the first horizontal separator
3093 line will be formatted with <th> tags."
3094 :group 'org-export-tables
3095 :type 'boolean)
3097 (defcustom org-export-table-remove-special-lines t
3098 "Remove special lines and marking characters in calculating tables.
3099 This removes the special marking character column from tables that are set
3100 up for spreadsheet calculations. It also removes the entire lines
3101 marked with `!', `_', or `^'. The lines with `$' are kept, because
3102 the values of constants may be useful to have."
3103 :group 'org-export-tables
3104 :type 'boolean)
3106 (defcustom org-export-prefer-native-exporter-for-tables nil
3107 "Non-nil means, always export tables created with table.el natively.
3108 Natively means, use the HTML code generator in table.el.
3109 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3110 the table does not use row- or column-spanning). This has the
3111 advantage, that the automatic HTML conversions for math symbols and
3112 sub/superscripts can be applied. Org-mode's HTML generator is also
3113 much faster."
3114 :group 'org-export-tables
3115 :type 'boolean)
3117 (defgroup org-export-ascii nil
3118 "Options specific for ASCII export of Org-mode files."
3119 :tag "Org Export ASCII"
3120 :group 'org-export)
3122 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3123 "Characters for underlining headings in ASCII export.
3124 In the given sequence, these characters will be used for level 1, 2, ..."
3125 :group 'org-export-ascii
3126 :type '(repeat character))
3128 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3129 "Bullet characters for headlines converted to lists in ASCII export.
3130 The first character is is used for the first lest level generated in this
3131 way, and so on. If there are more levels than characters given here,
3132 the list will be repeated.
3133 Note that plain lists will keep the same bullets as the have in the
3134 Org-mode file."
3135 :group 'org-export-ascii
3136 :type '(repeat character))
3138 (defgroup org-export-xml nil
3139 "Options specific for XML export of Org-mode files."
3140 :tag "Org Export XML"
3141 :group 'org-export)
3143 (defgroup org-export-html nil
3144 "Options specific for HTML export of Org-mode files."
3145 :tag "Org Export HTML"
3146 :group 'org-export)
3148 (defcustom org-export-html-coding-system nil
3150 :group 'org-export-html
3151 :type 'coding-system)
3153 (defcustom org-export-html-extension "html"
3154 "The extension for exported HTML files."
3155 :group 'org-export-html
3156 :type 'string)
3158 (defcustom org-export-html-style
3159 "<style type=\"text/css\">
3160 html {
3161 font-family: Times, serif;
3162 font-size: 12pt;
3164 .title { text-align: center; }
3165 .todo { color: red; }
3166 .done { color: green; }
3167 .timestamp { color: grey }
3168 .timestamp-kwd { color: CadetBlue }
3169 .tag { background-color:lightblue; font-weight:normal }
3170 .target { background-color: lavender; }
3171 pre {
3172 border: 1pt solid #AEBDCC;
3173 background-color: #F3F5F7;
3174 padding: 5pt;
3175 font-family: courier, monospace;
3177 table { border-collapse: collapse; }
3178 td, th {
3179 vertical-align: top;
3180 <!--border: 1pt solid #ADB9CC;-->
3182 </style>"
3183 "The default style specification for exported HTML files.
3184 Since there are different ways of setting style information, this variable
3185 needs to contain the full HTML structure to provide a style, including the
3186 surrounding HTML tags. The style specifications should include definitions
3187 for new classes todo, done, title, and deadline. For example, legal values
3188 would be:
3190 <style type=\"text/css\">
3191 p { font-weight: normal; color: gray; }
3192 h1 { color: black; }
3193 .title { text-align: center; }
3194 .todo, .deadline { color: red; }
3195 .done { color: green; }
3196 </style>
3198 or, if you want to keep the style in a file,
3200 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3202 As the value of this option simply gets inserted into the HTML <head> header,
3203 you can \"misuse\" it to add arbitrary text to the header."
3204 :group 'org-export-html
3205 :type 'string)
3208 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3209 "Format for typesetting the document title in HTML export."
3210 :group 'org-export-html
3211 :type 'string)
3213 (defcustom org-export-html-toplevel-hlevel 2
3214 "The <H> level for level 1 headings in HTML export."
3215 :group 'org-export-html
3216 :type 'string)
3218 (defcustom org-export-html-link-org-files-as-html t
3219 "Non-nil means, make file links to `file.org' point to `file.html'.
3220 When org-mode is exporting an org-mode file to HTML, links to
3221 non-html files are directly put into a href tag in HTML.
3222 However, links to other Org-mode files (recognized by the
3223 extension `.org.) should become links to the corresponding html
3224 file, assuming that the linked org-mode file will also be
3225 converted to HTML.
3226 When nil, the links still point to the plain `.org' file."
3227 :group 'org-export-html
3228 :type 'boolean)
3230 (defcustom org-export-html-inline-images 'maybe
3231 "Non-nil means, inline images into exported HTML pages.
3232 This is done using an <img> tag. When nil, an anchor with href is used to
3233 link to the image. If this option is `maybe', then images in links with
3234 an empty description will be inlined, while images with a description will
3235 be linked only."
3236 :group 'org-export-html
3237 :type '(choice (const :tag "Never" nil)
3238 (const :tag "Always" t)
3239 (const :tag "When there is no description" maybe)))
3241 ;; FIXME: rename
3242 (defcustom org-export-html-expand t
3243 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3244 When nil, these tags will be exported as plain text and therefore
3245 not be interpreted by a browser.
3247 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3248 :group 'org-export-html
3249 :type 'boolean)
3251 (defcustom org-export-html-table-tag
3252 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3253 "The HTML tag that is used to start a table.
3254 This must be a <table> tag, but you may change the options like
3255 borders and spacing."
3256 :group 'org-export-html
3257 :type 'string)
3259 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3260 "The opening tag for table header fields.
3261 This is customizable so that alignment options can be specified."
3262 :group 'org-export-tables
3263 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3265 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3266 "The opening tag for table data fields.
3267 This is customizable so that alignment options can be specified."
3268 :group 'org-export-tables
3269 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3271 (defcustom org-export-html-with-timestamp nil
3272 "If non-nil, write `org-export-html-html-helper-timestamp'
3273 into the exported HTML text. Otherwise, the buffer will just be saved
3274 to a file."
3275 :group 'org-export-html
3276 :type 'boolean)
3278 (defcustom org-export-html-html-helper-timestamp
3279 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3280 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3281 :group 'org-export-html
3282 :type 'string)
3284 (defgroup org-export-icalendar nil
3285 "Options specific for iCalendar export of Org-mode files."
3286 :tag "Org Export iCalendar"
3287 :group 'org-export)
3289 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3290 "The file name for the iCalendar file covering all agenda files.
3291 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3292 The file name should be absolute, the file will be overwritten without warning."
3293 :group 'org-export-icalendar
3294 :type 'file)
3296 (defcustom org-icalendar-include-todo nil
3297 "Non-nil means, export to iCalendar files should also cover TODO items."
3298 :group 'org-export-icalendar
3299 :type '(choice
3300 (const :tag "None" nil)
3301 (const :tag "Unfinished" t)
3302 (const :tag "All" all)))
3304 (defcustom org-icalendar-include-sexps t
3305 "Non-nil means, export to iCalendar files should also cover sexp entries.
3306 These are entries like in the diary, but directly in an Org-mode file."
3307 :group 'org-export-icalendar
3308 :type 'boolean)
3310 (defcustom org-icalendar-include-body 100
3311 "Amount of text below headline to be included in iCalendar export.
3312 This is a number of characters that should maximally be included.
3313 Properties, scheduling and clocking lines will always be removed.
3314 The text will be inserted into the DESCRIPTION field."
3315 :group 'org-export-icalendar
3316 :type '(choice
3317 (const :tag "Nothing" nil)
3318 (const :tag "Everything" t)
3319 (integer :tag "Max characters")))
3321 (defcustom org-icalendar-combined-name "OrgMode"
3322 "Calendar name for the combined iCalendar representing all agenda files."
3323 :group 'org-export-icalendar
3324 :type 'string)
3326 (defgroup org-font-lock nil
3327 "Font-lock settings for highlighting in Org-mode."
3328 :tag "Org Font Lock"
3329 :group 'org)
3331 (defcustom org-level-color-stars-only nil
3332 "Non-nil means fontify only the stars in each headline.
3333 When nil, the entire headline is fontified.
3334 Changing it requires restart of `font-lock-mode' to become effective
3335 also in regions already fontified."
3336 :group 'org-font-lock
3337 :type 'boolean)
3339 (defcustom org-hide-leading-stars nil
3340 "Non-nil means, hide the first N-1 stars in a headline.
3341 This works by using the face `org-hide' for these stars. This
3342 face is white for a light background, and black for a dark
3343 background. You may have to customize the face `org-hide' to
3344 make this work.
3345 Changing it requires restart of `font-lock-mode' to become effective
3346 also in regions already fontified.
3347 You may also set this on a per-file basis by adding one of the following
3348 lines to the buffer:
3350 #+STARTUP: hidestars
3351 #+STARTUP: showstars"
3352 :group 'org-font-lock
3353 :type 'boolean)
3355 (defcustom org-fontify-done-headline nil
3356 "Non-nil means, change the face of a headline if it is marked DONE.
3357 Normally, only the TODO/DONE keyword indicates the state of a headline.
3358 When this is non-nil, the headline after the keyword is set to the
3359 `org-headline-done' as an additional indication."
3360 :group 'org-font-lock
3361 :type 'boolean)
3363 (defcustom org-fontify-emphasized-text t
3364 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3365 Changing this variable requires a restart of Emacs to take effect."
3366 :group 'org-font-lock
3367 :type 'boolean)
3369 (defvar org-emph-re nil
3370 "Regular expression for matching emphasis.")
3371 (defvar org-emphasis-regexp-components) ; defined just below
3372 (defvar org-emphasis-alist) ; defined just below
3373 (defun org-set-emph-re (var val)
3374 "Set variable and compute the emphasis regular expression."
3375 (set var val)
3376 (when (and (boundp 'org-emphasis-alist)
3377 (boundp 'org-emphasis-regexp-components)
3378 org-emphasis-alist org-emphasis-regexp-components)
3379 (let* ((e org-emphasis-regexp-components)
3380 (pre (car e))
3381 (post (nth 1 e))
3382 (border (nth 2 e))
3383 (body (nth 3 e))
3384 (nl (nth 4 e))
3385 (stacked (nth 5 e))
3386 (body1 (concat body "*?"))
3387 (markers (mapconcat 'car org-emphasis-alist "")))
3388 ;; make sure special characters appear at the right position in the class
3389 (if (string-match "\\^" markers)
3390 (setq markers (concat (replace-match "" t t markers) "^")))
3391 (if (string-match "-" markers)
3392 (setq markers (concat (replace-match "" t t markers) "-")))
3393 (if (> nl 0)
3394 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3395 (int-to-string nl) "\\}")))
3396 ;; Make the regexp
3397 (setq org-emph-re
3398 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3399 "\\("
3400 "\\([" markers "]\\)"
3401 "\\("
3402 "[^" border (if (and nil stacked) markers) "]"
3403 body1
3404 "[^" border (if (and nil stacked) markers) "]"
3405 "\\)"
3406 "\\3\\)"
3407 "\\([" post (if stacked markers) "]\\|$\\)")))))
3409 (defcustom org-emphasis-regexp-components
3410 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3411 "Components used to build the reqular expression for emphasis.
3412 This is a list with 6 entries. Terminology: In an emphasis string
3413 like \" *strong word* \", we call the initial space PREMATCH, the final
3414 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3415 and \"trong wor\" is the body. The different components in this variable
3416 specify what is allowed/forbidden in each part:
3418 pre Chars allowed as prematch. Beginning of line will be allowed too.
3419 post Chars allowed as postmatch. End of line will be allowed too.
3420 border The chars *forbidden* as border characters.
3421 body-regexp A regexp like \".\" to match a body character. Don't use
3422 non-shy groups here, and don't allow newline here.
3423 newline The maximum number of newlines allowed in an emphasis exp.
3424 stacked Non-nil means, allow stacked styles. This works only in HTML
3425 export. When this is set, all marker characters (as given in
3426 `org-emphasis-alist') will be allowed as pre/post, aiding
3427 inside-out matching.
3428 Use customize to modify this, or restart Emacs after changing it."
3429 :group 'org-font-lock
3430 :set 'org-set-emph-re
3431 :type '(list
3432 (sexp :tag "Allowed chars in pre ")
3433 (sexp :tag "Allowed chars in post ")
3434 (sexp :tag "Forbidden chars in border ")
3435 (sexp :tag "Regexp for body ")
3436 (integer :tag "number of newlines allowed")
3437 (boolean :tag "Stacking allowed ")))
3439 (defcustom org-emphasis-alist
3440 '(("*" bold "<b>" "</b>")
3441 ("/" italic "<i>" "</i>")
3442 ("_" underline "<u>" "</u>")
3443 ("=" org-code "<code>" "</code>")
3444 ("+" (:strike-through t) "<del>" "</del>")
3446 "Special syntax for emphasized text.
3447 Text starting and ending with a special character will be emphasized, for
3448 example *bold*, _underlined_ and /italic/. This variable sets the marker
3449 characters, the face to be used by font-lock for highlighting in Org-mode
3450 Emacs buffers, and the HTML tags to be used for this.
3451 Use customize to modify this, or restart Emacs after changing it."
3452 :group 'org-font-lock
3453 :set 'org-set-emph-re
3454 :type '(repeat
3455 (list
3456 (string :tag "Marker character")
3457 (choice
3458 (face :tag "Font-lock-face")
3459 (plist :tag "Face property list"))
3460 (string :tag "HTML start tag")
3461 (string :tag "HTML end tag"))))
3463 ;;; The faces
3465 (defgroup org-faces nil
3466 "Faces in Org-mode."
3467 :tag "Org Faces"
3468 :group 'org-font-lock)
3470 (defun org-compatible-face (inherits specs)
3471 "Make a compatible face specification.
3472 If INHERITS is an existing face and if the Emacs version supports it,
3473 just inherit the face. If not, use SPECS to define the face.
3474 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3475 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3476 to the top of the list. The `min-colors' attribute will be removed from
3477 any other entries, and any resulting duplicates will be removed entirely."
3478 (cond
3479 ((and inherits (facep inherits)
3480 (not (featurep 'xemacs)) (> emacs-major-version 22))
3481 ;; In Emacs 23, we use inheritance where possible.
3482 ;; We only do this in Emacs 23, because only there the outline
3483 ;; faces have been changed to the original org-mode-level-faces.
3484 (list (list t :inherit inherits)))
3485 ((or (featurep 'xemacs) (< emacs-major-version 22))
3486 ;; These do not understand the `min-colors' attribute.
3487 (let (r e a)
3488 (while (setq e (pop specs))
3489 (cond
3490 ((memq (car e) '(t default)) (push e r))
3491 ((setq a (member '(min-colors 8) (car e)))
3492 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3493 (cdr e)))))
3494 ((setq a (assq 'min-colors (car e)))
3495 (setq e (cons (delq a (car e)) (cdr e)))
3496 (or (assoc (car e) r) (push e r)))
3497 (t (or (assoc (car e) r) (push e r)))))
3498 (nreverse r)))
3499 (t specs)))
3501 (defface org-hide
3502 '((((background light)) (:foreground "white"))
3503 (((background dark)) (:foreground "black")))
3504 "Face used to hide leading stars in headlines.
3505 The forground color of this face should be equal to the background
3506 color of the frame."
3507 :group 'org-faces)
3509 (defface org-level-1 ;; font-lock-function-name-face
3510 (org-compatible-face
3511 'outline-1
3512 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3513 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3514 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3515 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3516 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3517 (t (:bold t))))
3518 "Face used for level 1 headlines."
3519 :group 'org-faces)
3521 (defface org-level-2 ;; font-lock-variable-name-face
3522 (org-compatible-face
3523 'outline-2
3524 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3525 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3526 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3527 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3528 (t (:bold t))))
3529 "Face used for level 2 headlines."
3530 :group 'org-faces)
3532 (defface org-level-3 ;; font-lock-keyword-face
3533 (org-compatible-face
3534 'outline-3
3535 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3536 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3537 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3538 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3539 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3540 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3541 (t (:bold t))))
3542 "Face used for level 3 headlines."
3543 :group 'org-faces)
3545 (defface org-level-4 ;; font-lock-comment-face
3546 (org-compatible-face
3547 'outline-4
3548 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3549 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3550 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3551 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3552 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3553 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3554 (t (:bold t))))
3555 "Face used for level 4 headlines."
3556 :group 'org-faces)
3558 (defface org-level-5 ;; font-lock-type-face
3559 (org-compatible-face
3560 'outline-5
3561 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3562 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3563 (((class color) (min-colors 8)) (:foreground "green"))))
3564 "Face used for level 5 headlines."
3565 :group 'org-faces)
3567 (defface org-level-6 ;; font-lock-constant-face
3568 (org-compatible-face
3569 'outline-6
3570 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3571 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3572 (((class color) (min-colors 8)) (:foreground "magenta"))))
3573 "Face used for level 6 headlines."
3574 :group 'org-faces)
3576 (defface org-level-7 ;; font-lock-builtin-face
3577 (org-compatible-face
3578 'outline-7
3579 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3580 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3581 (((class color) (min-colors 8)) (:foreground "blue"))))
3582 "Face used for level 7 headlines."
3583 :group 'org-faces)
3585 (defface org-level-8 ;; font-lock-string-face
3586 (org-compatible-face
3587 'outline-8
3588 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3589 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3590 (((class color) (min-colors 8)) (:foreground "green"))))
3591 "Face used for level 8 headlines."
3592 :group 'org-faces)
3594 (defface org-special-keyword ;; font-lock-string-face
3595 (org-compatible-face
3597 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3598 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3599 (t (:italic t))))
3600 "Face used for special keywords."
3601 :group 'org-faces)
3603 (defface org-drawer ;; font-lock-function-name-face
3604 (org-compatible-face
3606 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3607 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3608 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3609 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3610 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3611 (t (:bold t))))
3612 "Face used for drawers."
3613 :group 'org-faces)
3615 (defface org-property-value nil
3616 "Face used for the value of a property."
3617 :group 'org-faces)
3619 (defface org-column
3620 (org-compatible-face
3622 '((((class color) (min-colors 16) (background light))
3623 (:background "grey90"))
3624 (((class color) (min-colors 16) (background dark))
3625 (:background "grey30"))
3626 (((class color) (min-colors 8))
3627 (:background "cyan" :foreground "black"))
3628 (t (:inverse-video t))))
3629 "Face for column display of entry properties."
3630 :group 'org-faces)
3632 (when (fboundp 'set-face-attribute)
3633 ;; Make sure that a fixed-width face is used when we have a column table.
3634 (set-face-attribute 'org-column nil
3635 :height (face-attribute 'default :height)
3636 :family (face-attribute 'default :family)))
3638 (defface org-warning
3639 (org-compatible-face
3640 'font-lock-warning-face
3641 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3642 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3643 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3644 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3645 (t (:bold t))))
3646 "Face for deadlines and TODO keywords."
3647 :group 'org-faces)
3649 (defface org-archived ; similar to shadow
3650 (org-compatible-face
3651 'shadow
3652 '((((class color grayscale) (min-colors 88) (background light))
3653 (:foreground "grey50"))
3654 (((class color grayscale) (min-colors 88) (background dark))
3655 (:foreground "grey70"))
3656 (((class color) (min-colors 8) (background light))
3657 (:foreground "green"))
3658 (((class color) (min-colors 8) (background dark))
3659 (:foreground "yellow"))))
3660 "Face for headline with the ARCHIVE tag."
3661 :group 'org-faces)
3663 (defface org-link
3664 '((((class color) (background light)) (:foreground "Purple" :underline t))
3665 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3666 (t (:underline t)))
3667 "Face for links."
3668 :group 'org-faces)
3670 (defface org-ellipsis
3671 '((((class color) (background light)) (:foreground "DarkGoldenrod" :strike-through t))
3672 (((class color) (background dark)) (:foreground "LightGoldenrod" :strike-through t))
3673 (t (:strike-through t)))
3674 "Face for the ellipsis in folded text."
3675 :group 'org-faces)
3677 (defface org-target
3678 '((((class color) (background light)) (:underline t))
3679 (((class color) (background dark)) (:underline t))
3680 (t (:underline t)))
3681 "Face for links."
3682 :group 'org-faces)
3684 (defface org-date
3685 '((((class color) (background light)) (:foreground "Purple" :underline t))
3686 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3687 (t (:underline t)))
3688 "Face for links."
3689 :group 'org-faces)
3691 (defface org-sexp-date
3692 '((((class color) (background light)) (:foreground "Purple"))
3693 (((class color) (background dark)) (:foreground "Cyan"))
3694 (t (:underline t)))
3695 "Face for links."
3696 :group 'org-faces)
3698 (defface org-tag
3699 '((t (:bold t)))
3700 "Face for tags."
3701 :group 'org-faces)
3703 (defface org-todo ; font-lock-warning-face
3704 (org-compatible-face
3706 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3707 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3708 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3709 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3710 (t (:inverse-video t :bold t))))
3711 "Face for TODO keywords."
3712 :group 'org-faces)
3714 (defface org-done ;; font-lock-type-face
3715 (org-compatible-face
3717 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3718 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3719 (((class color) (min-colors 8)) (:foreground "green"))
3720 (t (:bold t))))
3721 "Face used for todo keywords that indicate DONE items."
3722 :group 'org-faces)
3724 (defface org-headline-done ;; font-lock-string-face
3725 (org-compatible-face
3727 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3728 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3729 (((class color) (min-colors 8) (background light)) (:bold nil))))
3730 "Face used to indicate that a headline is DONE.
3731 This face is only used if `org-fontify-done-headline' is set. If applies
3732 to the part of the headline after the DONE keyword."
3733 :group 'org-faces)
3735 (defcustom org-todo-keyword-faces nil
3736 "Faces for specific TODO keywords.
3737 This is a list of cons cells, with TODO keywords in the car
3738 and faces in the cdr. The face can be a symbol, or a property
3739 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3740 :group 'org-faces
3741 :group 'org-todo
3742 :type '(repeat
3743 (cons
3744 (string :tag "keyword")
3745 (sexp :tag "face"))))
3747 (defface org-table ;; font-lock-function-name-face
3748 (org-compatible-face
3750 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3751 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3752 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3753 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3754 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3755 (((class color) (min-colors 8) (background dark)))))
3756 "Face used for tables."
3757 :group 'org-faces)
3759 (defface org-formula
3760 (org-compatible-face
3762 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3763 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3764 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3765 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3766 (t (:bold t :italic t))))
3767 "Face for formulas."
3768 :group 'org-faces)
3770 (defface org-code
3771 (org-compatible-face
3773 '((((class color grayscale) (min-colors 88) (background light))
3774 (:foreground "grey50"))
3775 (((class color grayscale) (min-colors 88) (background dark))
3776 (:foreground "grey70"))
3777 (((class color) (min-colors 8) (background light))
3778 (:foreground "green"))
3779 (((class color) (min-colors 8) (background dark))
3780 (:foreground "yellow"))))
3781 "Face for fixed-with text like code snippets."
3782 :group 'org-faces
3783 :version "22.1")
3785 (defface org-agenda-structure ;; font-lock-function-name-face
3786 (org-compatible-face
3788 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3789 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3790 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3791 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3792 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3793 (t (:bold t))))
3794 "Face used in agenda for captions and dates."
3795 :group 'org-faces)
3797 (defface org-scheduled-today
3798 (org-compatible-face
3800 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3801 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3802 (((class color) (min-colors 8)) (:foreground "green"))
3803 (t (:bold t :italic t))))
3804 "Face for items scheduled for a certain day."
3805 :group 'org-faces)
3807 (defface org-scheduled-previously
3808 (org-compatible-face
3810 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3811 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3812 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3813 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3814 (t (:bold t))))
3815 "Face for items scheduled previously, and not yet done."
3816 :group 'org-faces)
3818 (defface org-upcoming-deadline
3819 (org-compatible-face
3821 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3822 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3823 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3824 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3825 (t (:bold t))))
3826 "Face for items scheduled previously, and not yet done."
3827 :group 'org-faces)
3829 (defcustom org-agenda-deadline-faces
3830 '((1.0 . org-warning)
3831 (0.5 . org-upcoming-deadline)
3832 (0.0 . default))
3833 "Faces for showing deadlines in the agenda.
3834 This is a list of cons cells. The cdr of each cess is a face to be used,
3835 and it can also just be a like like '(:foreground \"yellow\").
3836 Each car is a fraction of the head-warning time that must have passed for
3837 this the face in the cdr to be used for display. The numbers must be
3838 given in descending order. The head-warning time is normally taken
3839 from `org-deadline-warning-days', but can also be specified in the deadline
3840 timestamp itself, like this:
3842 DEADLINE: <2007-08-13 Mon -8d>
3844 You may use d for days, w for weeks, m for months and y for years. Months
3845 and years will only be treated in an approximate fashion (30.4 days for a
3846 month and 365.24 days for a year)."
3847 :group 'org-faces
3848 :group 'org-agenda-daily/weekly
3849 :type '(repeat
3850 (cons
3851 (number :tag "Fraction of head-warning time passed")
3852 (sexp :tag "Face"))))
3854 (defface org-time-grid ;; font-lock-variable-name-face
3855 (org-compatible-face
3857 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3858 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3859 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3860 "Face used for time grids."
3861 :group 'org-faces)
3863 (defconst org-level-faces
3864 '(org-level-1 org-level-2 org-level-3 org-level-4
3865 org-level-5 org-level-6 org-level-7 org-level-8
3868 (defcustom org-n-level-faces (length org-level-faces)
3869 "The number different faces to be used for headlines.
3870 Org-mode defines 8 different headline faces, so this can be at most 8.
3871 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3872 :type 'number
3873 :group 'org-faces)
3875 ;;; Variables for pre-computed regular expressions, all buffer local
3877 (defvar org-drawer-regexp nil
3878 "Matches first line of a hidden block.")
3879 (make-variable-buffer-local 'org-drawer-regexp)
3880 (defvar org-todo-regexp nil
3881 "Matches any of the TODO state keywords.")
3882 (make-variable-buffer-local 'org-todo-regexp)
3883 (defvar org-not-done-regexp nil
3884 "Matches any of the TODO state keywords except the last one.")
3885 (make-variable-buffer-local 'org-not-done-regexp)
3886 (defvar org-todo-line-regexp nil
3887 "Matches a headline and puts TODO state into group 2 if present.")
3888 (make-variable-buffer-local 'org-todo-line-regexp)
3889 (defvar org-complex-heading-regexp nil
3890 "Matches a headline and puts everything into groups:
3891 group 1: the stars
3892 group 2: The todo keyword, maybe
3893 group 3: Priority cookie
3894 group 4: True headline
3895 group 5: Tags")
3896 (make-variable-buffer-local 'org-complex-heading-regexp)
3897 (defvar org-todo-line-tags-regexp nil
3898 "Matches a headline and puts TODO state into group 2 if present.
3899 Also put tags into group 4 if tags are present.")
3900 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3901 (defvar org-nl-done-regexp nil
3902 "Matches newline followed by a headline with the DONE keyword.")
3903 (make-variable-buffer-local 'org-nl-done-regexp)
3904 (defvar org-looking-at-done-regexp nil
3905 "Matches the DONE keyword a point.")
3906 (make-variable-buffer-local 'org-looking-at-done-regexp)
3907 (defvar org-ds-keyword-length 12
3908 "Maximum length of the Deadline and SCHEDULED keywords.")
3909 (make-variable-buffer-local 'org-ds-keyword-length)
3910 (defvar org-deadline-regexp nil
3911 "Matches the DEADLINE keyword.")
3912 (make-variable-buffer-local 'org-deadline-regexp)
3913 (defvar org-deadline-time-regexp nil
3914 "Matches the DEADLINE keyword together with a time stamp.")
3915 (make-variable-buffer-local 'org-deadline-time-regexp)
3916 (defvar org-deadline-line-regexp nil
3917 "Matches the DEADLINE keyword and the rest of the line.")
3918 (make-variable-buffer-local 'org-deadline-line-regexp)
3919 (defvar org-scheduled-regexp nil
3920 "Matches the SCHEDULED keyword.")
3921 (make-variable-buffer-local 'org-scheduled-regexp)
3922 (defvar org-scheduled-time-regexp nil
3923 "Matches the SCHEDULED keyword together with a time stamp.")
3924 (make-variable-buffer-local 'org-scheduled-time-regexp)
3925 (defvar org-closed-time-regexp nil
3926 "Matches the CLOSED keyword together with a time stamp.")
3927 (make-variable-buffer-local 'org-closed-time-regexp)
3929 (defvar org-keyword-time-regexp nil
3930 "Matches any of the 4 keywords, together with the time stamp.")
3931 (make-variable-buffer-local 'org-keyword-time-regexp)
3932 (defvar org-keyword-time-not-clock-regexp nil
3933 "Matches any of the 3 keywords, together with the time stamp.")
3934 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3935 (defvar org-maybe-keyword-time-regexp nil
3936 "Matches a timestamp, possibly preceeded by a keyword.")
3937 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3938 (defvar org-planning-or-clock-line-re nil
3939 "Matches a line with planning or clock info.")
3940 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3942 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3943 rear-nonsticky t mouse-map t fontified t)
3944 "Properties to remove when a string without properties is wanted.")
3946 (defsubst org-match-string-no-properties (num &optional string)
3947 (if (featurep 'xemacs)
3948 (let ((s (match-string num string)))
3949 (remove-text-properties 0 (length s) org-rm-props s)
3951 (match-string-no-properties num string)))
3953 (defsubst org-no-properties (s)
3954 (if (fboundp 'set-text-properties)
3955 (set-text-properties 0 (length s) nil s)
3956 (remove-text-properties 0 (length s) org-rm-props s))
3959 (defsubst org-get-alist-option (option key)
3960 (cond ((eq key t) t)
3961 ((eq option t) t)
3962 ((assoc key option) (cdr (assoc key option)))
3963 (t (cdr (assq 'default option)))))
3965 (defsubst org-inhibit-invisibility ()
3966 "Modified `buffer-invisibility-spec' for Emacs 21.
3967 Some ops with invisible text do not work correctly on Emacs 21. For these
3968 we turn off invisibility temporarily. Use this in a `let' form."
3969 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3971 (defsubst org-set-local (var value)
3972 "Make VAR local in current buffer and set it to VALUE."
3973 (set (make-variable-buffer-local var) value))
3975 (defsubst org-mode-p ()
3976 "Check if the current buffer is in Org-mode."
3977 (eq major-mode 'org-mode))
3979 (defsubst org-last (list)
3980 "Return the last element of LIST."
3981 (car (last list)))
3983 (defun org-let (list &rest body)
3984 (eval (cons 'let (cons list body))))
3985 (put 'org-let 'lisp-indent-function 1)
3987 (defun org-let2 (list1 list2 &rest body)
3988 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
3989 (put 'org-let2 'lisp-indent-function 2)
3990 (defconst org-startup-options
3991 '(("fold" org-startup-folded t)
3992 ("overview" org-startup-folded t)
3993 ("nofold" org-startup-folded nil)
3994 ("showall" org-startup-folded nil)
3995 ("content" org-startup-folded content)
3996 ("hidestars" org-hide-leading-stars t)
3997 ("showstars" org-hide-leading-stars nil)
3998 ("odd" org-odd-levels-only t)
3999 ("oddeven" org-odd-levels-only nil)
4000 ("align" org-startup-align-all-tables t)
4001 ("noalign" org-startup-align-all-tables nil)
4002 ("customtime" org-display-custom-times t)
4003 ("logging" org-log-done t)
4004 ("logdone" org-log-done t)
4005 ("nologging" org-log-done nil)
4006 ("lognotedone" org-log-done done push)
4007 ("lognotestate" org-log-done state push)
4008 ("lognoteclock-out" org-log-done clock-out push)
4009 ("logrepeat" org-log-repeat t)
4010 ("nologrepeat" org-log-repeat nil)
4011 ("constcgs" constants-unit-system cgs)
4012 ("constSI" constants-unit-system SI))
4013 "Variable associated with STARTUP options for org-mode.
4014 Each element is a list of three items: The startup options as written
4015 in the #+STARTUP line, the corresponding variable, and the value to
4016 set this variable to if the option is found. An optional forth element PUSH
4017 means to push this value onto the list in the variable.")
4019 (defun org-set-regexps-and-options ()
4020 "Precompute regular expressions for current buffer."
4021 (when (org-mode-p)
4022 (org-set-local 'org-todo-kwd-alist nil)
4023 (org-set-local 'org-todo-key-alist nil)
4024 (org-set-local 'org-todo-key-trigger nil)
4025 (org-set-local 'org-todo-keywords-1 nil)
4026 (org-set-local 'org-done-keywords nil)
4027 (org-set-local 'org-todo-heads nil)
4028 (org-set-local 'org-todo-sets nil)
4029 (org-set-local 'org-todo-log-states nil)
4030 (let ((re (org-make-options-regexp
4031 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4032 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4033 "CONSTANTS" "PROPERTY" "DRAWERS")))
4034 (splitre "[ \t]+")
4035 kwds kws0 kwsa key value cat arch tags const links hw dws
4036 tail sep kws1 prio props drawers
4037 ex log)
4038 (save-excursion
4039 (save-restriction
4040 (widen)
4041 (goto-char (point-min))
4042 (while (re-search-forward re nil t)
4043 (setq key (match-string 1) value (org-match-string-no-properties 2))
4044 (cond
4045 ((equal key "CATEGORY")
4046 (if (string-match "[ \t]+$" value)
4047 (setq value (replace-match "" t t value)))
4048 (setq cat (intern value)))
4049 ((member key '("SEQ_TODO" "TODO"))
4050 (push (cons 'sequence (org-split-string value splitre)) kwds))
4051 ((equal key "TYP_TODO")
4052 (push (cons 'type (org-split-string value splitre)) kwds))
4053 ((equal key "TAGS")
4054 (setq tags (append tags (org-split-string value splitre))))
4055 ((equal key "COLUMNS")
4056 (org-set-local 'org-columns-default-format value))
4057 ((equal key "LINK")
4058 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4059 (push (cons (match-string 1 value)
4060 (org-trim (match-string 2 value)))
4061 links)))
4062 ((equal key "PRIORITIES")
4063 (setq prio (org-split-string value " +")))
4064 ((equal key "PROPERTY")
4065 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4066 (push (cons (match-string 1 value) (match-string 2 value))
4067 props)))
4068 ((equal key "DRAWERS")
4069 (setq drawers (org-split-string value splitre)))
4070 ((equal key "CONSTANTS")
4071 (setq const (append const (org-split-string value splitre))))
4072 ((equal key "STARTUP")
4073 (let ((opts (org-split-string value splitre))
4074 l var val)
4075 (while (setq l (pop opts))
4076 (when (setq l (assoc l org-startup-options))
4077 (setq var (nth 1 l) val (nth 2 l))
4078 (if (not (nth 3 l))
4079 (set (make-local-variable var) val)
4080 (if (not (listp (symbol-value var)))
4081 (set (make-local-variable var) nil))
4082 (set (make-local-variable var) (symbol-value var))
4083 (add-to-list var val))))))
4084 ((equal key "ARCHIVE")
4085 (string-match " *$" value)
4086 (setq arch (replace-match "" t t value))
4087 (remove-text-properties 0 (length arch)
4088 '(face t fontified t) arch)))
4090 (and cat (org-set-local 'org-category cat))
4091 (when prio
4092 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4093 (setq prio (mapcar 'string-to-char prio))
4094 (org-set-local 'org-highest-priority (nth 0 prio))
4095 (org-set-local 'org-lowest-priority (nth 1 prio))
4096 (org-set-local 'org-default-priority (nth 2 prio)))
4097 (and props (org-set-local 'org-local-properties (nreverse props)))
4098 (and drawers (org-set-local 'org-drawers drawers))
4099 (and arch (org-set-local 'org-archive-location arch))
4100 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4101 ;; Process the TODO keywords
4102 (unless kwds
4103 ;; Use the global values as if they had been given locally.
4104 (setq kwds (default-value 'org-todo-keywords))
4105 (if (stringp (car kwds))
4106 (setq kwds (list (cons org-todo-interpretation
4107 (default-value 'org-todo-keywords)))))
4108 (setq kwds (reverse kwds)))
4109 (setq kwds (nreverse kwds))
4110 (let (inter kws kw)
4111 (while (setq kws (pop kwds))
4112 (setq inter (pop kws) sep (member "|" kws)
4113 kws0 (delete "|" (copy-sequence kws))
4114 kwsa nil
4115 kws1 (mapcar
4116 (lambda (x)
4117 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4118 (progn
4119 (setq kw (match-string 1 x)
4120 ex (and (match-end 2) (match-string 2 x))
4121 log (and ex (string-match "@" ex))
4122 key (and ex (substring ex 0 1)))
4123 (if (equal key "@") (setq key nil))
4124 (push (cons kw (and key (string-to-char key))) kwsa)
4125 (and log (push kw org-todo-log-states))
4127 (error "Invalid TODO keyword %s" x)))
4128 kws0)
4129 kwsa (if kwsa (append '((:startgroup))
4130 (nreverse kwsa)
4131 '((:endgroup))))
4132 hw (car kws1)
4133 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4134 tail (list inter hw (car dws) (org-last dws)))
4135 (add-to-list 'org-todo-heads hw 'append)
4136 (push kws1 org-todo-sets)
4137 (setq org-done-keywords (append org-done-keywords dws nil))
4138 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4139 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4140 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4141 (setq org-todo-sets (nreverse org-todo-sets)
4142 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4143 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4144 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4145 ;; Process the constants
4146 (when const
4147 (let (e cst)
4148 (while (setq e (pop const))
4149 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4150 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4151 (setq org-table-formula-constants-local cst)))
4153 ;; Process the tags.
4154 (when tags
4155 (let (e tgs)
4156 (while (setq e (pop tags))
4157 (cond
4158 ((equal e "{") (push '(:startgroup) tgs))
4159 ((equal e "}") (push '(:endgroup) tgs))
4160 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4161 (push (cons (match-string 1 e)
4162 (string-to-char (match-string 2 e)))
4163 tgs))
4164 (t (push (list e) tgs))))
4165 (org-set-local 'org-tag-alist nil)
4166 (while (setq e (pop tgs))
4167 (or (and (stringp (car e))
4168 (assoc (car e) org-tag-alist))
4169 (push e org-tag-alist))))))
4171 ;; Compute the regular expressions and other local variables
4172 (if (not org-done-keywords)
4173 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4174 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4175 (length org-scheduled-string)))
4176 org-drawer-regexp
4177 (concat "^[ \t]*:\\("
4178 (mapconcat 'regexp-quote org-drawers "\\|")
4179 "\\):[ \t]*$")
4180 org-not-done-keywords
4181 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4182 org-todo-regexp
4183 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4184 "\\|") "\\)\\>")
4185 org-not-done-regexp
4186 (concat "\\<\\("
4187 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4188 "\\)\\>")
4189 org-todo-line-regexp
4190 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4191 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4192 "\\)\\>\\)?[ \t]*\\(.*\\)")
4193 org-complex-heading-regexp
4194 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4195 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4196 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4197 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4198 org-nl-done-regexp
4199 (concat "\n\\*+[ \t]+"
4200 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4201 "\\)" "\\>")
4202 org-todo-line-tags-regexp
4203 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4204 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4205 (org-re
4206 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4207 org-looking-at-done-regexp
4208 (concat "^" "\\(?:"
4209 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4210 "\\>")
4211 org-deadline-regexp (concat "\\<" org-deadline-string)
4212 org-deadline-time-regexp
4213 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4214 org-deadline-line-regexp
4215 (concat "\\<\\(" org-deadline-string "\\).*")
4216 org-scheduled-regexp
4217 (concat "\\<" org-scheduled-string)
4218 org-scheduled-time-regexp
4219 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4220 org-closed-time-regexp
4221 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4222 org-keyword-time-regexp
4223 (concat "\\<\\(" org-scheduled-string
4224 "\\|" org-deadline-string
4225 "\\|" org-closed-string
4226 "\\|" org-clock-string "\\)"
4227 " *[[<]\\([^]>]+\\)[]>]")
4228 org-keyword-time-not-clock-regexp
4229 (concat "\\<\\(" org-scheduled-string
4230 "\\|" org-deadline-string
4231 "\\|" org-closed-string
4232 "\\)"
4233 " *[[<]\\([^]>]+\\)[]>]")
4234 org-maybe-keyword-time-regexp
4235 (concat "\\(\\<\\(" org-scheduled-string
4236 "\\|" org-deadline-string
4237 "\\|" org-closed-string
4238 "\\|" org-clock-string "\\)\\)?"
4239 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4240 org-planning-or-clock-line-re
4241 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4242 "\\|" org-deadline-string
4243 "\\|" org-closed-string "\\|" org-clock-string
4244 "\\)\\>\\)")
4247 (org-set-font-lock-defaults)))
4249 (defun org-remove-keyword-keys (list)
4250 (mapcar (lambda (x)
4251 (if (string-match "(..?)$" x)
4252 (substring x 0 (match-beginning 0))
4254 list))
4256 ;;; Some variables ujsed in various places
4258 (defvar org-window-configuration nil
4259 "Used in various places to store a window configuration.")
4260 (defvar org-finish-function nil
4261 "Function to be called when `C-c C-c' is used.
4262 This is for getting out of special buffers like remember.")
4264 ;;; Foreign variables, to inform the compiler
4266 ;; XEmacs only
4267 (defvar outline-mode-menu-heading)
4268 (defvar outline-mode-menu-show)
4269 (defvar outline-mode-menu-hide)
4270 (defvar zmacs-regions) ; XEmacs regions
4271 ;; Emacs only
4272 (defvar mark-active)
4274 ;; Packages that org-mode interacts with
4275 (defvar calc-embedded-close-formula)
4276 (defvar calc-embedded-open-formula)
4277 (defvar font-lock-unfontify-region-function)
4278 (defvar org-goto-start-pos)
4279 (defvar vm-message-pointer)
4280 (defvar vm-folder-directory)
4281 (defvar wl-summary-buffer-elmo-folder)
4282 (defvar wl-summary-buffer-folder-name)
4283 (defvar gnus-other-frame-object)
4284 (defvar gnus-group-name)
4285 (defvar gnus-article-current)
4286 (defvar w3m-current-url)
4287 (defvar w3m-current-title)
4288 (defvar mh-progs)
4289 (defvar mh-current-folder)
4290 (defvar mh-show-folder-buffer)
4291 (defvar mh-index-folder)
4292 (defvar mh-searcher)
4293 (defvar calendar-mode-map)
4294 (defvar Info-current-file)
4295 (defvar Info-current-node)
4296 (defvar texmathp-why)
4297 (defvar remember-save-after-remembering)
4298 (defvar remember-data-file)
4299 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4300 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4301 (defvar org-latex-regexps)
4302 (defvar constants-unit-system)
4304 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4306 ;; FIXME: Occasionally check by commenting these, to make sure
4307 ;; no other functions uses these, forgetting to let-bind them.
4308 (defvar entry)
4309 (defvar state)
4310 (defvar last-state)
4311 (defvar date)
4312 (defvar description)
4315 ;; Defined somewhere in this file, but used before definition.
4316 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4317 (defvar org-agenda-buffer-name)
4318 (defvar org-agenda-undo-list)
4319 (defvar org-agenda-pending-undo-list)
4320 (defvar org-agenda-overriding-header)
4321 (defvar orgtbl-mode)
4322 (defvar org-html-entities)
4323 (defvar org-struct-menu)
4324 (defvar org-org-menu)
4325 (defvar org-tbl-menu)
4326 (defvar org-agenda-keymap)
4328 ;;;; Emacs/XEmacs compatibility
4330 ;; Overlay compatibility functions
4331 (defun org-make-overlay (beg end &optional buffer)
4332 (if (featurep 'xemacs)
4333 (make-extent beg end buffer)
4334 (make-overlay beg end buffer)))
4335 (defun org-delete-overlay (ovl)
4336 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4337 (defun org-detach-overlay (ovl)
4338 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4339 (defun org-move-overlay (ovl beg end &optional buffer)
4340 (if (featurep 'xemacs)
4341 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4342 (move-overlay ovl beg end buffer)))
4343 (defun org-overlay-put (ovl prop value)
4344 (if (featurep 'xemacs)
4345 (set-extent-property ovl prop value)
4346 (overlay-put ovl prop value)))
4347 (defun org-overlay-display (ovl text &optional face evap)
4348 "Make overlay OVL display TEXT with face FACE."
4349 (if (featurep 'xemacs)
4350 (let ((gl (make-glyph text)))
4351 (and face (set-glyph-face gl face))
4352 (set-extent-property ovl 'invisible t)
4353 (set-extent-property ovl 'end-glyph gl))
4354 (overlay-put ovl 'display text)
4355 (if face (overlay-put ovl 'face face))
4356 (if evap (overlay-put ovl 'evaporate t))))
4357 (defun org-overlay-before-string (ovl text &optional face evap)
4358 "Make overlay OVL display TEXT with face FACE."
4359 (if (featurep 'xemacs)
4360 (let ((gl (make-glyph text)))
4361 (and face (set-glyph-face gl face))
4362 (set-extent-property ovl 'begin-glyph gl))
4363 (if face (org-add-props text nil 'face face))
4364 (overlay-put ovl 'before-string text)
4365 (if evap (overlay-put ovl 'evaporate t))))
4366 (defun org-overlay-get (ovl prop)
4367 (if (featurep 'xemacs)
4368 (extent-property ovl prop)
4369 (overlay-get ovl prop)))
4370 (defun org-overlays-at (pos)
4371 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4372 (defun org-overlays-in (&optional start end)
4373 (if (featurep 'xemacs)
4374 (extent-list nil start end)
4375 (overlays-in start end)))
4376 (defun org-overlay-start (o)
4377 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4378 (defun org-overlay-end (o)
4379 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4380 (defun org-find-overlays (prop &optional pos delete)
4381 "Find all overlays specifying PROP at POS or point.
4382 If DELETE is non-nil, delete all those overlays."
4383 (let ((overlays (org-overlays-at (or pos (point))))
4384 ov found)
4385 (while (setq ov (pop overlays))
4386 (if (org-overlay-get ov prop)
4387 (if delete (org-delete-overlay ov) (push ov found))))
4388 found))
4390 ;; Region compatibility
4392 (defun org-add-hook (hook function &optional append local)
4393 "Add-hook, compatible with both Emacsen."
4394 (if (and local (featurep 'xemacs))
4395 (add-local-hook hook function append)
4396 (add-hook hook function append local)))
4398 (defvar org-ignore-region nil
4399 "To temporarily disable the active region.")
4401 (defun org-region-active-p ()
4402 "Is `transient-mark-mode' on and the region active?
4403 Works on both Emacs and XEmacs."
4404 (if org-ignore-region
4406 (if (featurep 'xemacs)
4407 (and zmacs-regions (region-active-p))
4408 (and transient-mark-mode mark-active))))
4410 ;; Invisibility compatibility
4412 (defun org-add-to-invisibility-spec (arg)
4413 "Add elements to `buffer-invisibility-spec'.
4414 See documentation for `buffer-invisibility-spec' for the kind of elements
4415 that can be added."
4416 (cond
4417 ((fboundp 'add-to-invisibility-spec)
4418 (add-to-invisibility-spec arg))
4419 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4420 (setq buffer-invisibility-spec (list arg)))
4422 (setq buffer-invisibility-spec
4423 (cons arg buffer-invisibility-spec)))))
4425 (defun org-remove-from-invisibility-spec (arg)
4426 "Remove elements from `buffer-invisibility-spec'."
4427 (if (fboundp 'remove-from-invisibility-spec)
4428 (remove-from-invisibility-spec arg)
4429 (if (consp buffer-invisibility-spec)
4430 (setq buffer-invisibility-spec
4431 (delete arg buffer-invisibility-spec)))))
4433 (defun org-in-invisibility-spec-p (arg)
4434 "Is ARG a member of `buffer-invisibility-spec'?"
4435 (if (consp buffer-invisibility-spec)
4436 (member arg buffer-invisibility-spec)
4437 nil))
4439 ;;;; Define the Org-mode
4441 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4442 (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."))
4445 ;; We use a before-change function to check if a table might need
4446 ;; an update.
4447 (defvar org-table-may-need-update t
4448 "Indicates that a table might need an update.
4449 This variable is set by `org-before-change-function'.
4450 `org-table-align' sets it back to nil.")
4451 (defvar org-mode-map)
4452 (defvar org-mode-hook nil)
4453 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4454 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4455 (defvar org-table-buffer-is-an nil)
4456 (defconst org-outline-regexp "\\*+ ")
4458 ;;;###autoload
4459 (define-derived-mode org-mode outline-mode "Org"
4460 "Outline-based notes management and organizer, alias
4461 \"Carsten's outline-mode for keeping track of everything.\"
4463 Org-mode develops organizational tasks around a NOTES file which
4464 contains information about projects as plain text. Org-mode is
4465 implemented on top of outline-mode, which is ideal to keep the content
4466 of large files well structured. It supports ToDo items, deadlines and
4467 time stamps, which magically appear in the diary listing of the Emacs
4468 calendar. Tables are easily created with a built-in table editor.
4469 Plain text URL-like links connect to websites, emails (VM), Usenet
4470 messages (Gnus), BBDB entries, and any files related to the project.
4471 For printing and sharing of notes, an Org-mode file (or a part of it)
4472 can be exported as a structured ASCII or HTML file.
4474 The following commands are available:
4476 \\{org-mode-map}"
4478 ;; Get rid of Outline menus, they are not needed
4479 ;; Need to do this here because define-derived-mode sets up
4480 ;; the keymap so late. Still, it is a waste to call this each time
4481 ;; we switch another buffer into org-mode.
4482 (if (featurep 'xemacs)
4483 (when (boundp 'outline-mode-menu-heading)
4484 ;; Assume this is Greg's port, it used easymenu
4485 (easy-menu-remove outline-mode-menu-heading)
4486 (easy-menu-remove outline-mode-menu-show)
4487 (easy-menu-remove outline-mode-menu-hide))
4488 (define-key org-mode-map [menu-bar headings] 'undefined)
4489 (define-key org-mode-map [menu-bar hide] 'undefined)
4490 (define-key org-mode-map [menu-bar show] 'undefined))
4492 (easy-menu-add org-org-menu)
4493 (easy-menu-add org-tbl-menu)
4494 (org-install-agenda-files-menu)
4495 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4496 (org-add-to-invisibility-spec '(org-cwidth))
4497 (when (featurep 'xemacs)
4498 (org-set-local 'line-move-ignore-invisible t))
4499 (org-set-local 'outline-regexp org-outline-regexp)
4500 (org-set-local 'outline-level 'org-outline-level)
4501 (when (and org-ellipsis
4502 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4503 (fboundp 'make-glyph-code))
4504 (unless org-display-table
4505 (setq org-display-table (make-display-table)))
4506 (set-display-table-slot
4507 org-display-table 4
4508 (vconcat (mapcar
4509 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4510 org-ellipsis)))
4511 (if (stringp org-ellipsis) org-ellipsis "..."))))
4512 (setq buffer-display-table org-display-table))
4513 (org-set-regexps-and-options)
4514 ;; Calc embedded
4515 (org-set-local 'calc-embedded-open-mode "# ")
4516 (modify-syntax-entry ?# "<")
4517 (modify-syntax-entry ?@ "w")
4518 (if org-startup-truncated (setq truncate-lines t))
4519 (org-set-local 'font-lock-unfontify-region-function
4520 'org-unfontify-region)
4521 ;; Activate before-change-function
4522 (org-set-local 'org-table-may-need-update t)
4523 (org-add-hook 'before-change-functions 'org-before-change-function nil
4524 'local)
4525 ;; Check for running clock before killing a buffer
4526 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4527 ;; Paragraphs and auto-filling
4528 (org-set-autofill-regexps)
4529 (setq indent-line-function 'org-indent-line-function)
4530 (org-update-radio-target-regexp)
4532 ;; Comment characters
4533 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4534 (org-set-local 'comment-padding " ")
4536 ;; Make isearch reveal context
4537 (if (or (featurep 'xemacs)
4538 (not (boundp 'outline-isearch-open-invisible-function)))
4539 ;; Emacs 21 and XEmacs make use of the hook
4540 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4541 ;; Emacs 22 deals with this through a special variable
4542 (org-set-local 'outline-isearch-open-invisible-function
4543 (lambda (&rest ignore) (org-show-context 'isearch))))
4545 ;; If empty file that did not turn on org-mode automatically, make it to.
4546 (if (and org-insert-mode-line-in-empty-file
4547 (interactive-p)
4548 (= (point-min) (point-max)))
4549 (insert "# -*- mode: org -*-\n\n"))
4551 (unless org-inhibit-startup
4552 (when org-startup-align-all-tables
4553 (let ((bmp (buffer-modified-p)))
4554 (org-table-map-tables 'org-table-align)
4555 (set-buffer-modified-p bmp)))
4556 (org-cycle-hide-drawers 'all)
4557 (cond
4558 ((eq org-startup-folded t)
4559 (org-cycle '(4)))
4560 ((eq org-startup-folded 'content)
4561 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4562 (org-cycle '(4)) (org-cycle '(4)))))))
4564 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4566 (defsubst org-call-with-arg (command arg)
4567 "Call COMMAND interactively, but pretend prefix are was ARG."
4568 (let ((current-prefix-arg arg)) (call-interactively command)))
4570 (defsubst org-current-line (&optional pos)
4571 (save-excursion
4572 (and pos (goto-char pos))
4573 ;; works also in narrowed buffer, because we start at 1, not point-min
4574 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4576 (defun org-current-time ()
4577 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4578 (if (> org-time-stamp-rounding-minutes 0)
4579 (let ((r org-time-stamp-rounding-minutes)
4580 (time (decode-time)))
4581 (apply 'encode-time
4582 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4583 (nthcdr 2 time))))
4584 (current-time)))
4586 (defun org-add-props (string plist &rest props)
4587 "Add text properties to entire string, from beginning to end.
4588 PLIST may be a list of properties, PROPS are individual properties and values
4589 that will be added to PLIST. Returns the string that was modified."
4590 (add-text-properties
4591 0 (length string) (if props (append plist props) plist) string)
4592 string)
4593 (put 'org-add-props 'lisp-indent-function 2)
4596 ;;;; Font-Lock stuff, including the activators
4598 (defvar org-mouse-map (make-sparse-keymap))
4599 (org-defkey org-mouse-map
4600 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4601 (org-defkey org-mouse-map
4602 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4603 (when org-mouse-1-follows-link
4604 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4605 (when org-tab-follows-link
4606 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4607 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4608 (when org-return-follows-link
4609 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4610 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4612 (require 'font-lock)
4614 (defconst org-non-link-chars "]\t\n\r<>")
4615 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4616 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4617 (defvar org-link-re-with-space nil
4618 "Matches a link with spaces, optional angular brackets around it.")
4619 (defvar org-link-re-with-space2 nil
4620 "Matches a link with spaces, optional angular brackets around it.")
4621 (defvar org-angle-link-re nil
4622 "Matches link with angular brackets, spaces are allowed.")
4623 (defvar org-plain-link-re nil
4624 "Matches plain link, without spaces.")
4625 (defvar org-bracket-link-regexp nil
4626 "Matches a link in double brackets.")
4627 (defvar org-bracket-link-analytic-regexp nil
4628 "Regular expression used to analyze links.
4629 Here is what the match groups contain after a match:
4630 1: http:
4631 2: http
4632 3: path
4633 4: [desc]
4634 5: desc")
4635 (defvar org-any-link-re nil
4636 "Regular expression matching any link.")
4638 (defun org-make-link-regexps ()
4639 "Update the link regular expressions.
4640 This should be called after the variable `org-link-types' has changed."
4641 (setq org-link-re-with-space
4642 (concat
4643 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4644 "\\([^" org-non-link-chars " ]"
4645 "[^" org-non-link-chars "]*"
4646 "[^" org-non-link-chars " ]\\)>?")
4647 org-link-re-with-space2
4648 (concat
4649 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4650 "\\([^" org-non-link-chars " ]"
4651 "[^]\t\n\r]*"
4652 "[^" org-non-link-chars " ]\\)>?")
4653 org-angle-link-re
4654 (concat
4655 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4656 "\\([^" org-non-link-chars " ]"
4657 "[^" org-non-link-chars "]*"
4658 "\\)>")
4659 org-plain-link-re
4660 (concat
4661 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4662 "\\([^]\t\n\r<>,;() ]+\\)")
4663 org-bracket-link-regexp
4664 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4665 org-bracket-link-analytic-regexp
4666 (concat
4667 "\\[\\["
4668 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4669 "\\([^]]+\\)"
4670 "\\]"
4671 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4672 "\\]")
4673 org-any-link-re
4674 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4675 org-angle-link-re "\\)\\|\\("
4676 org-plain-link-re "\\)")))
4678 (org-make-link-regexps)
4680 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4681 "Regular expression for fast time stamp matching.")
4682 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4683 "Regular expression for fast time stamp matching.")
4684 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4685 "Regular expression matching time strings for analysis.
4686 This one does not require the space after the date.")
4687 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4688 "Regular expression matching time strings for analysis.")
4689 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4690 "Regular expression matching time stamps, with groups.")
4691 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4692 "Regular expression matching time stamps (also [..]), with groups.")
4693 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4694 "Regular expression matching a time stamp range.")
4695 (defconst org-tr-regexp-both
4696 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4697 "Regular expression matching a time stamp range.")
4698 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4699 org-ts-regexp "\\)?")
4700 "Regular expression matching a time stamp or time stamp range.")
4701 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4702 org-ts-regexp-both "\\)?")
4703 "Regular expression matching a time stamp or time stamp range.
4704 The time stamps may be either active or inactive.")
4706 (defvar org-emph-face nil)
4708 (defun org-do-emphasis-faces (limit)
4709 "Run through the buffer and add overlays to links."
4710 (let (rtn)
4711 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4712 (if (not (= (char-after (match-beginning 3))
4713 (char-after (match-beginning 4))))
4714 (progn
4715 (setq rtn t)
4716 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4717 'face
4718 (nth 1 (assoc (match-string 3)
4719 org-emphasis-alist)))
4720 (add-text-properties (match-beginning 2) (match-end 2)
4721 '(font-lock-multiline t))
4722 (backward-char 1))))
4723 rtn))
4725 (defun org-emphasize (&optional char)
4726 "Insert or change an emphasis, i.e. a font like bold or italic.
4727 If there is an active region, change that region to a new emphasis.
4728 If there is no region, just insert the marker characters and position
4729 the cursor between them.
4730 CHAR should be either the marker character, or the first character of the
4731 HTML tag associated with that emphasis. If CHAR is a space, the means
4732 to remove the emphasis of the selected region.
4733 If char is not given (for example in an interactive call) it
4734 will be prompted for."
4735 (interactive)
4736 (let ((eal org-emphasis-alist) e det
4737 (erc org-emphasis-regexp-components)
4738 (prompt "")
4739 (string "") beg end move tag c s)
4740 (if (org-region-active-p)
4741 (setq beg (region-beginning) end (region-end)
4742 string (buffer-substring beg end))
4743 (setq move t))
4745 (while (setq e (pop eal))
4746 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4747 c (aref tag 0))
4748 (push (cons c (string-to-char (car e))) det)
4749 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4750 (substring tag 1)))))
4751 (unless char
4752 (message "%s" (concat "Emphasis marker or tag:" prompt))
4753 (setq char (read-char-exclusive)))
4754 (setq char (or (cdr (assoc char det)) char))
4755 (if (equal char ?\ )
4756 (setq s "" move nil)
4757 (unless (assoc (char-to-string char) org-emphasis-alist)
4758 (error "No such emphasis marker: \"%c\"" char))
4759 (setq s (char-to-string char)))
4760 (while (and (> (length string) 1)
4761 (equal (substring string 0 1) (substring string -1))
4762 (assoc (substring string 0 1) org-emphasis-alist))
4763 (setq string (substring string 1 -1)))
4764 (setq string (concat s string s))
4765 (if beg (delete-region beg end))
4766 (unless (or (bolp)
4767 (string-match (concat "[" (nth 0 erc) "\n]")
4768 (char-to-string (char-before (point)))))
4769 (insert " "))
4770 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4771 (char-to-string (char-after (point))))
4772 (insert " ") (backward-char 1))
4773 (insert string)
4774 (and move (backward-char 1))))
4776 (defconst org-nonsticky-props
4777 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4780 (defun org-activate-plain-links (limit)
4781 "Run through the buffer and add overlays to links."
4782 (catch 'exit
4783 (let (f)
4784 (while (re-search-forward org-plain-link-re limit t)
4785 (setq f (get-text-property (match-beginning 0) 'face))
4786 (if (or (eq f 'org-tag)
4787 (and (listp f) (memq 'org-tag f)))
4789 (add-text-properties (match-beginning 0) (match-end 0)
4790 (list 'mouse-face 'highlight
4791 'rear-nonsticky org-nonsticky-props
4792 'keymap org-mouse-map
4794 (throw 'exit t))))))
4796 (defun org-activate-code (limit)
4797 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4798 (unless (get-text-property (match-beginning 1) 'face)
4799 (remove-text-properties (match-beginning 0) (match-end 0)
4800 '(display t invisible t intangible t))
4801 t)))
4803 (defun org-activate-angle-links (limit)
4804 "Run through the buffer and add overlays to links."
4805 (if (re-search-forward org-angle-link-re limit t)
4806 (progn
4807 (add-text-properties (match-beginning 0) (match-end 0)
4808 (list 'mouse-face 'highlight
4809 'rear-nonsticky org-nonsticky-props
4810 'keymap org-mouse-map
4812 t)))
4814 (defmacro org-maybe-intangible (props)
4815 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4816 In emacs 21, invisible text is not avoided by the command loop, so the
4817 intangible property is needed to make sure point skips this text.
4818 In Emacs 22, this is not necessary. The intangible text property has
4819 led to problems with flyspell. These problems are fixed in flyspell.el,
4820 but we still avoid setting the property in Emacs 22 and later.
4821 We use a macro so that the test can happen at compilation time."
4822 (if (< emacs-major-version 22)
4823 `(append '(intangible t) ,props)
4824 props))
4826 (defun org-activate-bracket-links (limit)
4827 "Run through the buffer and add overlays to bracketed links."
4828 (if (re-search-forward org-bracket-link-regexp limit t)
4829 (let* ((help (concat "LINK: "
4830 (org-match-string-no-properties 1)))
4831 ;; FIXME: above we should remove the escapes.
4832 ;; but that requires another match, protecting match data,
4833 ;; a lot of overhead for font-lock.
4834 (ip (org-maybe-intangible
4835 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4836 'keymap org-mouse-map 'mouse-face 'highlight
4837 'help-echo help)))
4838 (vp (list 'rear-nonsticky org-nonsticky-props
4839 'keymap org-mouse-map 'mouse-face 'highlight
4840 'help-echo help)))
4841 ;; We need to remove the invisible property here. Table narrowing
4842 ;; may have made some of this invisible.
4843 (remove-text-properties (match-beginning 0) (match-end 0)
4844 '(invisible nil))
4845 (if (match-end 3)
4846 (progn
4847 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4848 (add-text-properties (match-beginning 3) (match-end 3) vp)
4849 (add-text-properties (match-end 3) (match-end 0) ip))
4850 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4851 (add-text-properties (match-beginning 1) (match-end 1) vp)
4852 (add-text-properties (match-end 1) (match-end 0) ip))
4853 t)))
4855 (defun org-activate-dates (limit)
4856 "Run through the buffer and add overlays to dates."
4857 (if (re-search-forward org-tsr-regexp-both limit t)
4858 (progn
4859 (add-text-properties (match-beginning 0) (match-end 0)
4860 (list 'mouse-face 'highlight
4861 'rear-nonsticky org-nonsticky-props
4862 'keymap org-mouse-map))
4863 (when org-display-custom-times
4864 (if (match-end 3)
4865 (org-display-custom-time (match-beginning 3) (match-end 3)))
4866 (org-display-custom-time (match-beginning 1) (match-end 1)))
4867 t)))
4869 (defvar org-target-link-regexp nil
4870 "Regular expression matching radio targets in plain text.")
4871 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4872 "Regular expression matching a link target.")
4873 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4874 "Regular expression matching a radio target.")
4875 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4876 "Regular expression matching any target.")
4878 (defun org-activate-target-links (limit)
4879 "Run through the buffer and add overlays to target matches."
4880 (when org-target-link-regexp
4881 (let ((case-fold-search t))
4882 (if (re-search-forward org-target-link-regexp limit t)
4883 (progn
4884 (add-text-properties (match-beginning 0) (match-end 0)
4885 (list 'mouse-face 'highlight
4886 'rear-nonsticky org-nonsticky-props
4887 'keymap org-mouse-map
4888 'help-echo "Radio target link"
4889 'org-linked-text t))
4890 t)))))
4892 (defun org-update-radio-target-regexp ()
4893 "Find all radio targets in this file and update the regular expression."
4894 (interactive)
4895 (when (memq 'radio org-activate-links)
4896 (setq org-target-link-regexp
4897 (org-make-target-link-regexp (org-all-targets 'radio)))
4898 (org-restart-font-lock)))
4900 (defun org-hide-wide-columns (limit)
4901 (let (s e)
4902 (setq s (text-property-any (point) (or limit (point-max))
4903 'org-cwidth t))
4904 (when s
4905 (setq e (next-single-property-change s 'org-cwidth))
4906 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4907 (goto-char e)
4908 t)))
4910 (defun org-restart-font-lock ()
4911 "Restart font-lock-mode, to force refontification."
4912 (when (and (boundp 'font-lock-mode) font-lock-mode)
4913 (font-lock-mode -1)
4914 (font-lock-mode 1)))
4916 (defun org-all-targets (&optional radio)
4917 "Return a list of all targets in this file.
4918 With optional argument RADIO, only find radio targets."
4919 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4920 rtn)
4921 (save-excursion
4922 (goto-char (point-min))
4923 (while (re-search-forward re nil t)
4924 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4925 rtn)))
4927 (defun org-make-target-link-regexp (targets)
4928 "Make regular expression matching all strings in TARGETS.
4929 The regular expression finds the targets also if there is a line break
4930 between words."
4931 (and targets
4932 (concat
4933 "\\<\\("
4934 (mapconcat
4935 (lambda (x)
4936 (while (string-match " +" x)
4937 (setq x (replace-match "\\s-+" t t x)))
4939 targets
4940 "\\|")
4941 "\\)\\>")))
4943 (defun org-activate-tags (limit)
4944 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4945 (progn
4946 (add-text-properties (match-beginning 1) (match-end 1)
4947 (list 'mouse-face 'highlight
4948 'rear-nonsticky org-nonsticky-props
4949 'keymap org-mouse-map))
4950 t)))
4952 (defun org-outline-level ()
4953 (save-excursion
4954 (looking-at outline-regexp)
4955 (if (match-beginning 1)
4956 (+ (org-get-string-indentation (match-string 1)) 1000)
4957 (1- (- (match-end 0) (match-beginning 0))))))
4959 (defvar org-font-lock-keywords nil)
4961 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
4962 "Regular expression matching a property line.")
4964 (defun org-set-font-lock-defaults ()
4965 (let* ((em org-fontify-emphasized-text)
4966 (lk org-activate-links)
4967 (org-font-lock-extra-keywords
4968 (list
4969 ;; Headlines
4970 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4971 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4972 ;; Table lines
4973 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4974 (1 'org-table t))
4975 ;; Table internals
4976 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4977 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4978 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4979 ;; Drawers
4980 (list org-drawer-regexp '(0 'org-special-keyword t))
4981 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4982 ;; Properties
4983 (list org-property-re
4984 '(1 'org-special-keyword t)
4985 '(3 'org-property-value t))
4986 (if org-format-transports-properties-p
4987 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4988 ;; Links
4989 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4990 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4991 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4992 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4993 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4994 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4995 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4996 '(org-hide-wide-columns (0 nil append))
4997 ;; TODO lines
4998 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4999 '(1 (org-get-todo-face 1) t))
5000 ;; DONE
5001 (if org-fontify-done-headline
5002 (list (concat "^[*]+ +\\<\\("
5003 (mapconcat 'regexp-quote org-done-keywords "\\|")
5004 "\\)\\(.*\\)")
5005 '(2 'org-headline-done t))
5006 nil)
5007 ;; Priorities
5008 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5009 ;; Special keywords
5010 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5011 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5012 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5013 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5014 ;; Emphasis
5015 (if em
5016 (if (featurep 'xemacs)
5017 '(org-do-emphasis-faces (0 nil append))
5018 '(org-do-emphasis-faces)))
5019 ;; Checkboxes
5020 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5021 2 'bold prepend)
5022 (if org-provide-checkbox-statistics
5023 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5024 (0 (org-get-checkbox-statistics-face) t)))
5025 ;; COMMENT
5026 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5027 "\\|" org-quote-string "\\)\\>")
5028 '(1 'org-special-keyword t))
5029 '("^#.*" (0 'font-lock-comment-face t))
5030 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
5031 ;; Code
5032 '(org-activate-code (1 'org-code t))
5034 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5035 ;; Now set the full font-lock-keywords
5036 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5037 (org-set-local 'font-lock-defaults
5038 '(org-font-lock-keywords t nil nil backward-paragraph))
5039 (kill-local-variable 'font-lock-keywords) nil))
5041 (defvar org-m nil)
5042 (defvar org-l nil)
5043 (defvar org-f nil)
5044 (defun org-get-level-face (n)
5045 "Get the right face for match N in font-lock matching of healdines."
5046 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5047 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5048 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5049 (cond
5050 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5051 ((eq n 2) org-f)
5052 (t (if org-level-color-stars-only nil org-f))))
5054 (defun org-get-todo-face (kwd)
5055 "Get the right face for a TODO keyword KWD.
5056 If KWD is a number, get the corresponding match group."
5057 (if (numberp kwd) (setq kwd (match-string kwd)))
5058 (or (cdr (assoc kwd org-todo-keyword-faces))
5059 (and (member kwd org-done-keywords) 'org-done)
5060 'org-todo))
5062 (defun org-unfontify-region (beg end &optional maybe_loudly)
5063 "Remove fontification and activation overlays from links."
5064 (font-lock-default-unfontify-region beg end)
5065 (let* ((buffer-undo-list t)
5066 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5067 (inhibit-modification-hooks t)
5068 deactivate-mark buffer-file-name buffer-file-truename)
5069 (remove-text-properties beg end
5070 '(mouse-face t keymap t org-linked-text t
5071 invisible t intangible t))))
5073 ;;;; Visibility cycling, including org-goto and indirect buffer
5075 ;;; Cycling
5077 (defvar org-cycle-global-status nil)
5078 (make-variable-buffer-local 'org-cycle-global-status)
5079 (defvar org-cycle-subtree-status nil)
5080 (make-variable-buffer-local 'org-cycle-subtree-status)
5082 ;;;###autoload
5083 (defun org-cycle (&optional arg)
5084 "Visibility cycling for Org-mode.
5086 - When this function is called with a prefix argument, rotate the entire
5087 buffer through 3 states (global cycling)
5088 1. OVERVIEW: Show only top-level headlines.
5089 2. CONTENTS: Show all headlines of all levels, but no body text.
5090 3. SHOW ALL: Show everything.
5092 - When point is at the beginning of a headline, rotate the subtree started
5093 by this line through 3 different states (local cycling)
5094 1. FOLDED: Only the main headline is shown.
5095 2. CHILDREN: The main headline and the direct children are shown.
5096 From this state, you can move to one of the children
5097 and zoom in further.
5098 3. SUBTREE: Show the entire subtree, including body text.
5100 - When there is a numeric prefix, go up to a heading with level ARG, do
5101 a `show-subtree' and return to the previous cursor position. If ARG
5102 is negative, go up that many levels.
5104 - When point is not at the beginning of a headline, execute
5105 `indent-relative', like TAB normally does. See the option
5106 `org-cycle-emulate-tab' for details.
5108 - Special case: if point is at the beginning of the buffer and there is
5109 no headline in line 1, this function will act as if called with prefix arg.
5110 But only if also the variable `org-cycle-global-at-bob' is t."
5111 (interactive "P")
5112 (let* ((outline-regexp
5113 (if (and (org-mode-p) org-cycle-include-plain-lists)
5114 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5115 outline-regexp))
5116 (bob-special (and org-cycle-global-at-bob (bobp)
5117 (not (looking-at outline-regexp))))
5118 (org-cycle-hook
5119 (if bob-special
5120 (delq 'org-optimize-window-after-visibility-change
5121 (copy-sequence org-cycle-hook))
5122 org-cycle-hook))
5123 (pos (point)))
5125 (if (or bob-special (equal arg '(4)))
5126 ;; special case: use global cycling
5127 (setq arg t))
5129 (cond
5131 ((org-at-table-p 'any)
5132 ;; Enter the table or move to the next field in the table
5133 (or (org-table-recognize-table.el)
5134 (progn
5135 (if arg (org-table-edit-field t)
5136 (org-table-justify-field-maybe)
5137 (call-interactively 'org-table-next-field)))))
5139 ((eq arg t) ;; Global cycling
5141 (cond
5142 ((and (eq last-command this-command)
5143 (eq org-cycle-global-status 'overview))
5144 ;; We just created the overview - now do table of contents
5145 ;; This can be slow in very large buffers, so indicate action
5146 (message "CONTENTS...")
5147 (org-content)
5148 (message "CONTENTS...done")
5149 (setq org-cycle-global-status 'contents)
5150 (run-hook-with-args 'org-cycle-hook 'contents))
5152 ((and (eq last-command this-command)
5153 (eq org-cycle-global-status 'contents))
5154 ;; We just showed the table of contents - now show everything
5155 (show-all)
5156 (message "SHOW ALL")
5157 (setq org-cycle-global-status 'all)
5158 (run-hook-with-args 'org-cycle-hook 'all))
5161 ;; Default action: go to overview
5162 (org-overview)
5163 (message "OVERVIEW")
5164 (setq org-cycle-global-status 'overview)
5165 (run-hook-with-args 'org-cycle-hook 'overview))))
5167 ((and org-drawers org-drawer-regexp
5168 (save-excursion
5169 (beginning-of-line 1)
5170 (looking-at org-drawer-regexp)))
5171 ;; Toggle block visibility
5172 (org-flag-drawer
5173 (not (get-char-property (match-end 0) 'invisible))))
5175 ((integerp arg)
5176 ;; Show-subtree, ARG levels up from here.
5177 (save-excursion
5178 (org-back-to-heading)
5179 (outline-up-heading (if (< arg 0) (- arg)
5180 (- (funcall outline-level) arg)))
5181 (org-show-subtree)))
5183 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5184 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5185 ;; At a heading: rotate between three different views
5186 (org-back-to-heading)
5187 (let ((goal-column 0) eoh eol eos)
5188 ;; First, some boundaries
5189 (save-excursion
5190 (org-back-to-heading)
5191 (save-excursion
5192 (beginning-of-line 2)
5193 (while (and (not (eobp)) ;; this is like `next-line'
5194 (get-char-property (1- (point)) 'invisible))
5195 (beginning-of-line 2)) (setq eol (point)))
5196 (outline-end-of-heading) (setq eoh (point))
5197 (org-end-of-subtree t)
5198 (unless (eobp)
5199 (skip-chars-forward " \t\n")
5200 (beginning-of-line 1) ; in case this is an item
5202 (setq eos (1- (point))))
5203 ;; Find out what to do next and set `this-command'
5204 (cond
5205 ((= eos eoh)
5206 ;; Nothing is hidden behind this heading
5207 (message "EMPTY ENTRY")
5208 (setq org-cycle-subtree-status nil)
5209 (save-excursion
5210 (goto-char eos)
5211 (outline-next-heading)
5212 (if (org-invisible-p) (org-flag-heading nil))))
5213 ((or (>= eol eos)
5214 (not (string-match "\\S-" (buffer-substring eol eos))))
5215 ;; Entire subtree is hidden in one line: open it
5216 (org-show-entry)
5217 (show-children)
5218 (message "CHILDREN")
5219 (save-excursion
5220 (goto-char eos)
5221 (outline-next-heading)
5222 (if (org-invisible-p) (org-flag-heading nil)))
5223 (setq org-cycle-subtree-status 'children)
5224 (run-hook-with-args 'org-cycle-hook 'children))
5225 ((and (eq last-command this-command)
5226 (eq org-cycle-subtree-status 'children))
5227 ;; We just showed the children, now show everything.
5228 (org-show-subtree)
5229 (message "SUBTREE")
5230 (setq org-cycle-subtree-status 'subtree)
5231 (run-hook-with-args 'org-cycle-hook 'subtree))
5233 ;; Default action: hide the subtree.
5234 (hide-subtree)
5235 (message "FOLDED")
5236 (setq org-cycle-subtree-status 'folded)
5237 (run-hook-with-args 'org-cycle-hook 'folded)))))
5239 ;; TAB emulation
5240 (buffer-read-only (org-back-to-heading))
5242 ((org-try-cdlatex-tab))
5244 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5245 (or (not (bolp))
5246 (not (looking-at outline-regexp))))
5247 (call-interactively (global-key-binding "\t")))
5249 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5250 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5251 (or (and (eq org-cycle-emulate-tab 'white)
5252 (= (match-end 0) (point-at-eol)))
5253 (and (eq org-cycle-emulate-tab 'whitestart)
5254 (>= (match-end 0) pos))))
5256 (eq org-cycle-emulate-tab t))
5257 (if (and (looking-at "[ \n\r\t]")
5258 (string-match "^[ \t]*$" (buffer-substring
5259 (point-at-bol) (point))))
5260 (progn
5261 (beginning-of-line 1)
5262 (and (looking-at "[ \t]+") (replace-match ""))))
5263 (call-interactively (global-key-binding "\t")))
5265 (t (save-excursion
5266 (org-back-to-heading)
5267 (org-cycle))))))
5269 ;;;###autoload
5270 (defun org-global-cycle (&optional arg)
5271 "Cycle the global visibility. For details see `org-cycle'."
5272 (interactive "P")
5273 (let ((org-cycle-include-plain-lists
5274 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5275 (if (integerp arg)
5276 (progn
5277 (show-all)
5278 (hide-sublevels arg)
5279 (setq org-cycle-global-status 'contents))
5280 (org-cycle '(4)))))
5282 (defun org-overview ()
5283 "Switch to overview mode, shoing only top-level headlines.
5284 Really, this shows all headlines with level equal or greater than the level
5285 of the first headline in the buffer. This is important, because if the
5286 first headline is not level one, then (hide-sublevels 1) gives confusing
5287 results."
5288 (interactive)
5289 (let ((level (save-excursion
5290 (goto-char (point-min))
5291 (if (re-search-forward (concat "^" outline-regexp) nil t)
5292 (progn
5293 (goto-char (match-beginning 0))
5294 (funcall outline-level))))))
5295 (and level (hide-sublevels level))))
5297 (defun org-content (&optional arg)
5298 "Show all headlines in the buffer, like a table of contents.
5299 With numerical argument N, show content up to level N."
5300 (interactive "P")
5301 (save-excursion
5302 ;; Visit all headings and show their offspring
5303 (and (integerp arg) (org-overview))
5304 (goto-char (point-max))
5305 (catch 'exit
5306 (while (and (progn (condition-case nil
5307 (outline-previous-visible-heading 1)
5308 (error (goto-char (point-min))))
5310 (looking-at outline-regexp))
5311 (if (integerp arg)
5312 (show-children (1- arg))
5313 (show-branches))
5314 (if (bobp) (throw 'exit nil))))))
5317 (defun org-optimize-window-after-visibility-change (state)
5318 "Adjust the window after a change in outline visibility.
5319 This function is the default value of the hook `org-cycle-hook'."
5320 (when (get-buffer-window (current-buffer))
5321 (cond
5322 ; ((eq state 'overview) (org-first-headline-recenter 1))
5323 ; ((eq state 'overview) (org-beginning-of-line))
5324 ((eq state 'content) nil)
5325 ((eq state 'all) nil)
5326 ((eq state 'folded) nil)
5327 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5328 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5331 (defun org-cycle-show-empty-lines (state)
5332 "Show empty lines above all visible headlines.
5333 The region to be covered depends on STATE when called through
5334 `org-cycle-hook'. Lisp program can use t for STATE to get the
5335 entire buffer covered. Note that an empty line is only shown if there
5336 are at least `org-cycle-separator-lines' empty lines before the headeline."
5337 (when (> org-cycle-separator-lines 0)
5338 (save-excursion
5339 (let* ((n org-cycle-separator-lines)
5340 (re (cond
5341 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5342 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5343 (t (let ((ns (number-to-string (- n 2))))
5344 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5345 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5346 beg end)
5347 (cond
5348 ((memq state '(overview contents t))
5349 (setq beg (point-min) end (point-max)))
5350 ((memq state '(children folded))
5351 (setq beg (point) end (progn (org-end-of-subtree t t)
5352 (beginning-of-line 2)
5353 (point)))))
5354 (when beg
5355 (goto-char beg)
5356 (while (re-search-forward re end t)
5357 (if (not (get-char-property (match-end 1) 'invisible))
5358 (outline-flag-region
5359 (match-beginning 1) (match-end 1) nil)))))))
5360 ;; Never hide empty lines at the end of the file.
5361 (save-excursion
5362 (goto-char (point-max))
5363 (outline-previous-heading)
5364 (outline-end-of-heading)
5365 (if (and (looking-at "[ \t\n]+")
5366 (= (match-end 0) (point-max)))
5367 (outline-flag-region (point) (match-end 0) nil))))
5369 (defun org-subtree-end-visible-p ()
5370 "Is the end of the current subtree visible?"
5371 (pos-visible-in-window-p
5372 (save-excursion (org-end-of-subtree t) (point))))
5374 (defun org-first-headline-recenter (&optional N)
5375 "Move cursor to the first headline and recenter the headline.
5376 Optional argument N means, put the headline into the Nth line of the window."
5377 (goto-char (point-min))
5378 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5379 (beginning-of-line)
5380 (recenter (prefix-numeric-value N))))
5382 ;;; Org-goto
5384 (defvar org-goto-window-configuration nil)
5385 (defvar org-goto-marker nil)
5386 (defvar org-goto-map
5387 (let ((map (make-sparse-keymap)))
5388 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5389 (while (setq cmd (pop cmds))
5390 (substitute-key-definition cmd cmd map global-map)))
5391 (suppress-keymap map)
5392 (org-defkey map "\C-m" 'org-goto-ret)
5393 (org-defkey map [(left)] 'org-goto-left)
5394 (org-defkey map [(right)] 'org-goto-right)
5395 (org-defkey map [(?q)] 'org-goto-quit)
5396 (org-defkey map [(control ?g)] 'org-goto-quit)
5397 (org-defkey map "\C-i" 'org-cycle)
5398 (org-defkey map [(tab)] 'org-cycle)
5399 (org-defkey map [(down)] 'outline-next-visible-heading)
5400 (org-defkey map [(up)] 'outline-previous-visible-heading)
5401 (org-defkey map "n" 'outline-next-visible-heading)
5402 (org-defkey map "p" 'outline-previous-visible-heading)
5403 (org-defkey map "f" 'outline-forward-same-level)
5404 (org-defkey map "b" 'outline-backward-same-level)
5405 (org-defkey map "u" 'outline-up-heading)
5406 (org-defkey map "/" 'org-occur)
5407 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5408 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5409 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5410 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5411 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5412 map))
5414 (defconst org-goto-help
5415 "Browse copy of buffer to find location or copy text.
5416 RET=jump to location [Q]uit and return to previous location
5417 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5420 (defun org-goto ()
5421 "Look up a different location in the current file, keeping current visibility.
5423 When you want look-up or go to a different location in a document, the
5424 fastest way is often to fold the entire buffer and then dive into the tree.
5425 This method has the disadvantage, that the previous location will be folded,
5426 which may not be what you want.
5428 This command works around this by showing a copy of the current buffer
5429 in an indirect buffer, in overview mode. You can dive into the tree in
5430 that copy, use org-occur and incremental search to find a location.
5431 When pressing RET or `Q', the command returns to the original buffer in
5432 which the visibility is still unchanged. After RET is will also jump to
5433 the location selected in the indirect buffer and expose the
5434 the headline hierarchy above."
5435 (interactive)
5436 (let* ((org-goto-start-pos (point))
5437 (selected-point
5438 (car (org-get-location (current-buffer) org-goto-help))))
5439 (if selected-point
5440 (progn
5441 (org-mark-ring-push org-goto-start-pos)
5442 (goto-char selected-point)
5443 (if (or (org-invisible-p) (org-invisible-p2))
5444 (org-show-context 'org-goto)))
5445 (message "Quit"))))
5447 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5448 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5450 (defun org-get-location (buf help)
5451 "Let the user select a location in the Org-mode buffer BUF.
5452 This function uses a recursive edit. It returns the selected position
5453 or nil."
5454 (let (org-goto-selected-point org-goto-exit-command)
5455 (save-excursion
5456 (save-window-excursion
5457 (delete-other-windows)
5458 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5459 (switch-to-buffer
5460 (condition-case nil
5461 (make-indirect-buffer (current-buffer) "*org-goto*")
5462 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5463 (with-output-to-temp-buffer "*Help*"
5464 (princ help))
5465 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5466 (setq buffer-read-only nil)
5467 (let ((org-startup-truncated t)
5468 (org-startup-folded nil)
5469 (org-startup-align-all-tables nil))
5470 (org-mode)
5471 (org-overview))
5472 (setq buffer-read-only t)
5473 (if (and (boundp 'org-goto-start-pos)
5474 (integer-or-marker-p org-goto-start-pos))
5475 (let ((org-show-hierarchy-above t)
5476 (org-show-siblings t)
5477 (org-show-following-heading t))
5478 (goto-char org-goto-start-pos)
5479 (and (org-invisible-p) (org-show-context)))
5480 (goto-char (point-min)))
5481 (org-beginning-of-line)
5482 (message "Select location and press RET")
5483 ;; now we make sure that during selection, ony very few keys work
5484 ;; and that it is impossible to switch to another window.
5485 ; (let ((gm (current-global-map))
5486 ; (overriding-local-map org-goto-map))
5487 ; (unwind-protect
5488 ; (progn
5489 ; (use-global-map org-goto-map)
5490 ; (recursive-edit))
5491 ; (use-global-map gm)))
5492 (use-local-map org-goto-map)
5493 (recursive-edit)
5495 (kill-buffer "*org-goto*")
5496 (cons org-goto-selected-point org-goto-exit-command)))
5498 (defun org-goto-ret (&optional arg)
5499 "Finish `org-goto' by going to the new location."
5500 (interactive "P")
5501 (setq org-goto-selected-point (point)
5502 org-goto-exit-command 'return)
5503 (throw 'exit nil))
5505 (defun org-goto-left ()
5506 "Finish `org-goto' by going to the new location."
5507 (interactive)
5508 (if (org-on-heading-p)
5509 (progn
5510 (beginning-of-line 1)
5511 (setq org-goto-selected-point (point)
5512 org-goto-exit-command 'left)
5513 (throw 'exit nil))
5514 (error "Not on a heading")))
5516 (defun org-goto-right ()
5517 "Finish `org-goto' by going to the new location."
5518 (interactive)
5519 (if (org-on-heading-p)
5520 (progn
5521 (setq org-goto-selected-point (point)
5522 org-goto-exit-command 'right)
5523 (throw 'exit nil))
5524 (error "Not on a heading")))
5526 (defun org-goto-quit ()
5527 "Finish `org-goto' without cursor motion."
5528 (interactive)
5529 (setq org-goto-selected-point nil)
5530 (setq org-goto-exit-command 'quit)
5531 (throw 'exit nil))
5533 ;;; Indirect buffer display of subtrees
5535 (defvar org-indirect-dedicated-frame nil
5536 "This is the frame being used for indirect tree display.")
5537 (defvar org-last-indirect-buffer nil)
5539 (defun org-tree-to-indirect-buffer (&optional arg)
5540 "Create indirect buffer and narrow it to current subtree.
5541 With numerical prefix ARG, go up to this level and then take that tree.
5542 If ARG is negative, go up that many levels.
5543 Normally this command removes the indirect buffer previously made
5544 with this command. However, when called with a C-u prefix, the last buffer
5545 is kept so that you can work with several indirect buffers at the same time.
5546 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5547 requests that a new frame be made for the new buffer, so that the dedicated
5548 frame is not changed."
5549 (interactive "P")
5550 (let ((cbuf (current-buffer))
5551 (cwin (selected-window))
5552 (pos (point))
5553 beg end level heading ibuf)
5554 (save-excursion
5555 (org-back-to-heading t)
5556 (when (numberp arg)
5557 (setq level (org-outline-level))
5558 (if (< arg 0) (setq arg (+ level arg)))
5559 (while (> (setq level (org-outline-level)) arg)
5560 (outline-up-heading 1 t)))
5561 (setq beg (point)
5562 heading (org-get-heading))
5563 (org-end-of-subtree t) (setq end (point)))
5564 (if (and (not arg)
5565 (buffer-live-p org-last-indirect-buffer))
5566 (kill-buffer org-last-indirect-buffer))
5567 (setq ibuf (org-get-indirect-buffer cbuf)
5568 org-last-indirect-buffer ibuf)
5569 (cond
5570 ((or (eq org-indirect-buffer-display 'new-frame)
5571 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5572 (select-frame (make-frame))
5573 (delete-other-windows)
5574 (switch-to-buffer ibuf)
5575 (org-set-frame-title heading))
5576 ((eq org-indirect-buffer-display 'dedicated-frame)
5577 (raise-frame
5578 (select-frame (or (and org-indirect-dedicated-frame
5579 (frame-live-p org-indirect-dedicated-frame)
5580 org-indirect-dedicated-frame)
5581 (setq org-indirect-dedicated-frame (make-frame)))))
5582 (delete-other-windows)
5583 (switch-to-buffer ibuf)
5584 (org-set-frame-title (concat "Indirect: " heading)))
5585 ((eq org-indirect-buffer-display 'current-window)
5586 (switch-to-buffer ibuf))
5587 ((eq org-indirect-buffer-display 'other-window)
5588 (pop-to-buffer ibuf))
5589 (t (error "Invalid value.")))
5590 (if (featurep 'xemacs)
5591 (save-excursion (org-mode) (turn-on-font-lock)))
5592 (narrow-to-region beg end)
5593 (show-all)
5594 (goto-char pos)
5595 (and (window-live-p cwin) (select-window cwin))))
5597 (defun org-get-indirect-buffer (&optional buffer)
5598 (setq buffer (or buffer (current-buffer)))
5599 (let ((n 1) (base (buffer-name buffer)) bname)
5600 (while (buffer-live-p
5601 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5602 (setq n (1+ n)))
5603 (condition-case nil
5604 (make-indirect-buffer buffer bname 'clone)
5605 (error (make-indirect-buffer buffer bname)))))
5607 (defun org-set-frame-title (title)
5608 "Set the title of the current frame to the string TITLE."
5609 ;; FIXME: how to name a single frame in XEmacs???
5610 (unless (featurep 'xemacs)
5611 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5613 ;;;; Structure editing
5615 ;;; Inserting headlines
5617 (defun org-insert-heading (&optional force-heading)
5618 "Insert a new heading or item with same depth at point.
5619 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5620 If point is at the beginning of a headline, insert a sibling before the
5621 current headline. If point is in the middle of a headline, split the headline
5622 at that position and make the rest of the headline part of the sibling below
5623 the current headline."
5624 (interactive "P")
5625 (if (= (buffer-size) 0)
5626 (insert "\n* ")
5627 (when (or force-heading (not (org-insert-item)))
5628 (let* ((head (save-excursion
5629 (condition-case nil
5630 (progn
5631 (org-back-to-heading)
5632 (match-string 0))
5633 (error "*"))))
5634 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5635 pos)
5636 (cond
5637 ((and (org-on-heading-p) (bolp)
5638 (or (bobp)
5639 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5640 (open-line (if blank 2 1)))
5641 ((and (bolp)
5642 (or (bobp)
5643 (save-excursion
5644 (backward-char 1) (not (org-invisible-p)))))
5645 nil)
5646 (t (newline (if blank 2 1))))
5647 (insert head) (just-one-space)
5648 (setq pos (point))
5649 (end-of-line 1)
5650 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5651 (run-hooks 'org-insert-heading-hook)))))
5653 (defun org-insert-heading-after-current ()
5654 "Insert a new heading with same level as current, after current subtree."
5655 (interactive)
5656 (org-back-to-heading)
5657 (org-insert-heading)
5658 (org-move-subtree-down)
5659 (end-of-line 1))
5661 (defun org-insert-todo-heading (arg)
5662 "Insert a new heading with the same level and TODO state as current heading.
5663 If the heading has no TODO state, or if the state is DONE, use the first
5664 state (TODO by default). Also with prefix arg, force first state."
5665 (interactive "P")
5666 (when (not (org-insert-item 'checkbox))
5667 (org-insert-heading)
5668 (save-excursion
5669 (org-back-to-heading)
5670 (outline-previous-heading)
5671 (looking-at org-todo-line-regexp))
5672 (if (or arg
5673 (not (match-beginning 2))
5674 (member (match-string 2) org-done-keywords))
5675 (insert (car org-todo-keywords-1) " ")
5676 (insert (match-string 2) " "))))
5678 (defun org-insert-subheading (arg)
5679 "Insert a new subheading and demote it.
5680 Works for outline headings and for plain lists alike."
5681 (interactive "P")
5682 (org-insert-heading arg)
5683 (cond
5684 ((org-on-heading-p) (org-do-demote))
5685 ((org-at-item-p) (org-indent-item 1))))
5687 (defun org-insert-todo-subheading (arg)
5688 "Insert a new subheading with TODO keyword or checkbox and demote it.
5689 Works for outline headings and for plain lists alike."
5690 (interactive "P")
5691 (org-insert-todo-heading arg)
5692 (cond
5693 ((org-on-heading-p) (org-do-demote))
5694 ((org-at-item-p) (org-indent-item 1))))
5696 ;;; Promotion and Demotion
5698 (defun org-promote-subtree ()
5699 "Promote the entire subtree.
5700 See also `org-promote'."
5701 (interactive)
5702 (save-excursion
5703 (org-map-tree 'org-promote))
5704 (org-fix-position-after-promote))
5706 (defun org-demote-subtree ()
5707 "Demote the entire subtree. See `org-demote'.
5708 See also `org-promote'."
5709 (interactive)
5710 (save-excursion
5711 (org-map-tree 'org-demote))
5712 (org-fix-position-after-promote))
5715 (defun org-do-promote ()
5716 "Promote the current heading higher up the tree.
5717 If the region is active in `transient-mark-mode', promote all headings
5718 in the region."
5719 (interactive)
5720 (save-excursion
5721 (if (org-region-active-p)
5722 (org-map-region 'org-promote (region-beginning) (region-end))
5723 (org-promote)))
5724 (org-fix-position-after-promote))
5726 (defun org-do-demote ()
5727 "Demote the current heading lower down the tree.
5728 If the region is active in `transient-mark-mode', demote all headings
5729 in the region."
5730 (interactive)
5731 (save-excursion
5732 (if (org-region-active-p)
5733 (org-map-region 'org-demote (region-beginning) (region-end))
5734 (org-demote)))
5735 (org-fix-position-after-promote))
5737 (defun org-fix-position-after-promote ()
5738 "Make sure that after pro/demotion cursor position is right."
5739 (let ((pos (point)))
5740 (when (save-excursion
5741 (beginning-of-line 1)
5742 (looking-at org-todo-line-regexp)
5743 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5744 (cond ((eobp) (insert " "))
5745 ((eolp) (insert " "))
5746 ((equal (char-after) ?\ ) (forward-char 1))))))
5748 (defun org-reduced-level (l)
5749 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5751 (defun org-get-legal-level (level &optional change)
5752 "Rectify a level change under the influence of `org-odd-levels-only'
5753 LEVEL is a current level, CHANGE is by how much the level should be
5754 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5755 even level numbers will become the next higher odd number."
5756 (if org-odd-levels-only
5757 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5758 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5759 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5760 (max 1 (+ level change))))
5762 (defun org-promote ()
5763 "Promote the current heading higher up the tree.
5764 If the region is active in `transient-mark-mode', promote all headings
5765 in the region."
5766 (org-back-to-heading t)
5767 (let* ((level (save-match-data (funcall outline-level)))
5768 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5769 (diff (abs (- level (length up-head) -1))))
5770 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5771 (replace-match up-head nil t)
5772 ;; Fixup tag positioning
5773 (and org-auto-align-tags (org-set-tags nil t))
5774 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5776 (defun org-demote ()
5777 "Demote the current heading lower down the tree.
5778 If the region is active in `transient-mark-mode', demote all headings
5779 in the region."
5780 (org-back-to-heading t)
5781 (let* ((level (save-match-data (funcall outline-level)))
5782 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5783 (diff (abs (- level (length down-head) -1))))
5784 (replace-match down-head nil t)
5785 ;; Fixup tag positioning
5786 (and org-auto-align-tags (org-set-tags nil t))
5787 (if org-adapt-indentation (org-fixup-indentation diff))))
5789 (defun org-map-tree (fun)
5790 "Call FUN for every heading underneath the current one."
5791 (org-back-to-heading)
5792 (let ((level (funcall outline-level)))
5793 (save-excursion
5794 (funcall fun)
5795 (while (and (progn
5796 (outline-next-heading)
5797 (> (funcall outline-level) level))
5798 (not (eobp)))
5799 (funcall fun)))))
5801 (defun org-map-region (fun beg end)
5802 "Call FUN for every heading between BEG and END."
5803 (let ((org-ignore-region t))
5804 (save-excursion
5805 (setq end (copy-marker end))
5806 (goto-char beg)
5807 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5808 (< (point) end))
5809 (funcall fun))
5810 (while (and (progn
5811 (outline-next-heading)
5812 (< (point) end))
5813 (not (eobp)))
5814 (funcall fun)))))
5816 (defun org-fixup-indentation (diff)
5817 "Change the indentation in the current entry by DIFF
5818 However, if any line in the current entry has no indentation, or if it
5819 would end up with no indentation after the change, nothing at all is done."
5820 (save-excursion
5821 (let ((end (save-excursion (outline-next-heading)
5822 (point-marker)))
5823 (prohibit (if (> diff 0)
5824 "^\\S-"
5825 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5826 col)
5827 (unless (save-excursion (end-of-line 1)
5828 (re-search-forward prohibit end t))
5829 (while (re-search-forward "^[ \t]+" end t)
5830 (goto-char (match-end 0))
5831 (setq col (current-column))
5832 (if (< diff 0) (replace-match ""))
5833 (indent-to (+ diff col))))
5834 (move-marker end nil))))
5836 (defun org-convert-to-odd-levels ()
5837 "Convert an org-mode file with all levels allowed to one with odd levels.
5838 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5839 level 5 etc."
5840 (interactive)
5841 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5842 (let ((org-odd-levels-only nil) n)
5843 (save-excursion
5844 (goto-char (point-min))
5845 (while (re-search-forward "^\\*\\*+ " nil t)
5846 (setq n (- (length (match-string 0)) 2))
5847 (while (>= (setq n (1- n)) 0)
5848 (org-demote))
5849 (end-of-line 1))))))
5852 (defun org-convert-to-oddeven-levels ()
5853 "Convert an org-mode file with only odd levels to one with odd and even levels.
5854 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5855 section with an even level, conversion would destroy the structure of the file. An error
5856 is signaled in this case."
5857 (interactive)
5858 (goto-char (point-min))
5859 ;; First check if there are no even levels
5860 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5861 (org-show-context t)
5862 (error "Not all levels are odd in this file. Conversion not possible."))
5863 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5864 (let ((org-odd-levels-only nil) n)
5865 (save-excursion
5866 (goto-char (point-min))
5867 (while (re-search-forward "^\\*\\*+ " nil t)
5868 (setq n (/ (1- (length (match-string 0))) 2))
5869 (while (>= (setq n (1- n)) 0)
5870 (org-promote))
5871 (end-of-line 1))))))
5873 (defun org-tr-level (n)
5874 "Make N odd if required."
5875 (if org-odd-levels-only (1+ (/ n 2)) n))
5877 ;;; Vertical tree motion, cutting and pasting of subtrees
5879 (defun org-move-subtree-up (&optional arg)
5880 "Move the current subtree up past ARG headlines of the same level."
5881 (interactive "p")
5882 (org-move-subtree-down (- (prefix-numeric-value arg))))
5884 (defun org-move-subtree-down (&optional arg)
5885 "Move the current subtree down past ARG headlines of the same level."
5886 (interactive "p")
5887 (setq arg (prefix-numeric-value arg))
5888 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5889 'outline-get-last-sibling))
5890 (ins-point (make-marker))
5891 (cnt (abs arg))
5892 beg end txt folded)
5893 ;; Select the tree
5894 (org-back-to-heading)
5895 (setq beg (point))
5896 (save-match-data
5897 (save-excursion (outline-end-of-heading)
5898 (setq folded (org-invisible-p)))
5899 (outline-end-of-subtree))
5900 (outline-next-heading)
5901 (setq end (point))
5902 ;; Find insertion point, with error handling
5903 (goto-char beg)
5904 (while (> cnt 0)
5905 (or (and (funcall movfunc) (looking-at outline-regexp))
5906 (progn (goto-char beg)
5907 (error "Cannot move past superior level or buffer limit")))
5908 (setq cnt (1- cnt)))
5909 (if (> arg 0)
5910 ;; Moving forward - still need to move over subtree
5911 (progn (outline-end-of-subtree)
5912 (outline-next-heading)
5913 (if (not (or (looking-at (concat "^" outline-regexp))
5914 (bolp)))
5915 (newline))))
5916 (move-marker ins-point (point))
5917 (setq txt (buffer-substring beg end))
5918 (delete-region beg end)
5919 (insert txt)
5920 (or (bolp) (insert "\n"))
5921 (goto-char ins-point)
5922 (if folded (hide-subtree))
5923 (move-marker ins-point nil)))
5925 (defvar org-subtree-clip ""
5926 "Clipboard for cut and paste of subtrees.
5927 This is actually only a copy of the kill, because we use the normal kill
5928 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5930 (defvar org-subtree-clip-folded nil
5931 "Was the last copied subtree folded?
5932 This is used to fold the tree back after pasting.")
5934 (defun org-cut-subtree (&optional n)
5935 "Cut the current subtree into the clipboard.
5936 With prefix arg N, cut this many sequential subtrees.
5937 This is a short-hand for marking the subtree and then cutting it."
5938 (interactive "p")
5939 (org-copy-subtree n 'cut))
5941 (defun org-copy-subtree (&optional n cut)
5942 "Cut the current subtree into the clipboard.
5943 With prefix arg N, cut this many sequential subtrees.
5944 This is a short-hand for marking the subtree and then copying it.
5945 If CUT is non-nil, actually cut the subtree."
5946 (interactive "p")
5947 (let (beg end folded)
5948 (if (interactive-p)
5949 (org-back-to-heading nil) ; take what looks like a subtree
5950 (org-back-to-heading t)) ; take what is really there
5951 (setq beg (point))
5952 (save-match-data
5953 (save-excursion (outline-end-of-heading)
5954 (setq folded (org-invisible-p)))
5955 (condition-case nil
5956 (outline-forward-same-level (1- n))
5957 (error nil))
5958 (org-end-of-subtree t t))
5959 (setq end (point))
5960 (goto-char beg)
5961 (when (> end beg)
5962 (setq org-subtree-clip-folded folded)
5963 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5964 (setq org-subtree-clip (current-kill 0))
5965 (message "%s: Subtree(s) with %d characters"
5966 (if cut "Cut" "Copied")
5967 (length org-subtree-clip)))))
5969 (defun org-paste-subtree (&optional level tree)
5970 "Paste the clipboard as a subtree, with modification of headline level.
5971 The entire subtree is promoted or demoted in order to match a new headline
5972 level. By default, the new level is derived from the visible headings
5973 before and after the insertion point, and taken to be the inferior headline
5974 level of the two. So if the previous visible heading is level 3 and the
5975 next is level 4 (or vice versa), level 4 will be used for insertion.
5976 This makes sure that the subtree remains an independent subtree and does
5977 not swallow low level entries.
5979 You can also force a different level, either by using a numeric prefix
5980 argument, or by inserting the heading marker by hand. For example, if the
5981 cursor is after \"*****\", then the tree will be shifted to level 5.
5983 If you want to insert the tree as is, just use \\[yank].
5985 If optional TREE is given, use this text instead of the kill ring."
5986 (interactive "P")
5987 (unless (org-kill-is-subtree-p tree)
5988 (error
5989 (substitute-command-keys
5990 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5991 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5992 (^re (concat "^\\(" outline-regexp "\\)"))
5993 (re (concat "\\(" outline-regexp "\\)"))
5994 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5996 (old-level (if (string-match ^re txt)
5997 (- (match-end 0) (match-beginning 0) 1)
5998 -1))
5999 (force-level (cond (level (prefix-numeric-value level))
6000 ((string-match
6001 ^re_ (buffer-substring (point-at-bol) (point)))
6002 (- (match-end 1) (match-beginning 1)))
6003 (t nil)))
6004 (previous-level (save-excursion
6005 (condition-case nil
6006 (progn
6007 (outline-previous-visible-heading 1)
6008 (if (looking-at re)
6009 (- (match-end 0) (match-beginning 0) 1)
6011 (error 1))))
6012 (next-level (save-excursion
6013 (condition-case nil
6014 (progn
6015 (or (looking-at outline-regexp)
6016 (outline-next-visible-heading 1))
6017 (if (looking-at re)
6018 (- (match-end 0) (match-beginning 0) 1)
6020 (error 1))))
6021 (new-level (or force-level (max previous-level next-level)))
6022 (shift (if (or (= old-level -1)
6023 (= new-level -1)
6024 (= old-level new-level))
6026 (- new-level old-level)))
6027 (delta (if (> shift 0) -1 1))
6028 (func (if (> shift 0) 'org-demote 'org-promote))
6029 (org-odd-levels-only nil)
6030 beg end)
6031 ;; Remove the forced level indicator
6032 (if force-level
6033 (delete-region (point-at-bol) (point)))
6034 ;; Paste
6035 (beginning-of-line 1)
6036 (setq beg (point))
6037 (insert txt)
6038 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
6039 (setq end (point))
6040 (goto-char beg)
6041 ;; Shift if necessary
6042 (unless (= shift 0)
6043 (save-restriction
6044 (narrow-to-region beg end)
6045 (while (not (= shift 0))
6046 (org-map-region func (point-min) (point-max))
6047 (setq shift (+ delta shift)))
6048 (goto-char (point-min))))
6049 (when (interactive-p)
6050 (message "Clipboard pasted as level %d subtree" new-level))
6051 (if (and kill-ring
6052 (eq org-subtree-clip (current-kill 0))
6053 org-subtree-clip-folded)
6054 ;; The tree was folded before it was killed/copied
6055 (hide-subtree))))
6057 (defun org-kill-is-subtree-p (&optional txt)
6058 "Check if the current kill is an outline subtree, or a set of trees.
6059 Returns nil if kill does not start with a headline, or if the first
6060 headline level is not the largest headline level in the tree.
6061 So this will actually accept several entries of equal levels as well,
6062 which is OK for `org-paste-subtree'.
6063 If optional TXT is given, check this string instead of the current kill."
6064 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6065 (start-level (and kill
6066 (string-match (concat "\\`" org-outline-regexp) kill)
6067 (- (match-end 0) (match-beginning 0) 1)))
6068 (re (concat "^" org-outline-regexp))
6069 (start 1))
6070 (if (not start-level)
6071 (progn
6072 nil) ;; does not even start with a heading
6073 (catch 'exit
6074 (while (setq start (string-match re kill (1+ start)))
6075 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6076 (throw 'exit nil)))
6077 t))))
6079 (defun org-narrow-to-subtree ()
6080 "Narrow buffer to the current subtree."
6081 (interactive)
6082 (save-excursion
6083 (narrow-to-region
6084 (progn (org-back-to-heading) (point))
6085 (progn (org-end-of-subtree t t) (point)))))
6088 ;;; Outline Sorting
6090 (defun org-sort (with-case)
6091 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6092 Optional argument WITH-CASE means sort case-sensitively."
6093 (interactive "P")
6094 (if (org-at-table-p)
6095 (org-call-with-arg 'org-table-sort-lines with-case)
6096 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6098 (defvar org-priority-regexp) ; defined later in the file
6100 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6101 "Sort entries on a certain level of an outline tree.
6102 If there is an active region, the entries in the region are sorted.
6103 Else, if the cursor is before the first entry, sort the top-level items.
6104 Else, the children of the entry at point are sorted.
6106 Sorting can be alphabetically, numerically, and by date/time as given by
6107 the first time stamp in the entry. The command prompts for the sorting
6108 type unless it has been given to the function through the SORTING-TYPE
6109 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6110 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6111 called with point at the beginning of the record. It must return either
6112 a string or a number that should serve as the sorting key for that record.
6114 Comparing entries ignores case by default. However, with an optional argument
6115 WITH-CASE, the sorting considers case as well."
6116 (interactive "P")
6117 (let ((case-func (if with-case 'identity 'downcase))
6118 start beg end stars re re2
6119 txt what tmp plain-list-p)
6120 ;; Find beginning and end of region to sort
6121 (cond
6122 ((org-region-active-p)
6123 ;; we will sort the region
6124 (setq end (region-end)
6125 what "region")
6126 (goto-char (region-beginning))
6127 (if (not (org-on-heading-p)) (outline-next-heading))
6128 (setq start (point)))
6129 ((org-at-item-p)
6130 ;; we will sort this plain list
6131 (org-beginning-of-item-list) (setq start (point))
6132 (org-end-of-item-list) (setq end (point))
6133 (goto-char start)
6134 (setq plain-list-p t
6135 what "plain list"))
6136 ((or (org-on-heading-p)
6137 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6138 ;; we will sort the children of the current headline
6139 (org-back-to-heading)
6140 (setq start (point) end (org-end-of-subtree) what "children")
6141 (goto-char start)
6142 (show-subtree)
6143 (outline-next-heading))
6145 ;; we will sort the top-level entries in this file
6146 (goto-char (point-min))
6147 (or (org-on-heading-p) (outline-next-heading))
6148 (setq start (point) end (point-max) what "top-level")
6149 (goto-char start)
6150 (show-all)))
6152 (setq beg (point))
6153 (if (>= beg end) (error "Nothing to sort"))
6155 (unless plain-list-p
6156 (looking-at "\\(\\*+\\)")
6157 (setq stars (match-string 1)
6158 re (concat "^" (regexp-quote stars) " +")
6159 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6160 txt (buffer-substring beg end))
6161 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6162 (if (and (not (equal stars "*")) (string-match re2 txt))
6163 (error "Region to sort contains a level above the first entry")))
6165 (unless sorting-type
6166 (message
6167 (if plain-list-p
6168 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6169 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6170 what)
6171 (setq sorting-type (read-char-exclusive))
6173 (and (= (downcase sorting-type) ?f)
6174 (setq getkey-func
6175 (completing-read "Sort using function: "
6176 obarray 'fboundp t nil nil))
6177 (setq getkey-func (intern getkey-func)))
6179 (and (= (downcase sorting-type) ?r)
6180 (setq property
6181 (completing-read "Property: "
6182 (mapcar 'list (org-buffer-property-keys t))
6183 nil t))))
6185 (message "Sorting entries...")
6187 (save-restriction
6188 (narrow-to-region start end)
6190 (let ((dcst (downcase sorting-type))
6191 (now (current-time)))
6192 (sort-subr
6193 (/= dcst sorting-type)
6194 ;; This function moves to the beginning character of the "record" to
6195 ;; be sorted.
6196 (if plain-list-p
6197 (lambda nil
6198 (if (org-at-item-p) t (goto-char (point-max))))
6199 (lambda nil
6200 (if (re-search-forward re nil t)
6201 (goto-char (match-beginning 0))
6202 (goto-char (point-max)))))
6203 ;; This function moves to the last character of the "record" being
6204 ;; sorted.
6205 (if plain-list-p
6206 'org-end-of-item
6207 (lambda nil
6208 (save-match-data
6209 (condition-case nil
6210 (outline-forward-same-level 1)
6211 (error
6212 (goto-char (point-max)))))))
6214 ;; This function returns the value that gets sorted against.
6215 (if plain-list-p
6216 (lambda nil
6217 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6218 (cond
6219 ((= dcst ?n)
6220 (string-to-number (buffer-substring (match-end 0)
6221 (line-end-position))))
6222 ((= dcst ?a)
6223 (buffer-substring (match-end 0) (line-end-position)))
6224 ((= dcst ?t)
6225 (if (re-search-forward org-ts-regexp
6226 (line-end-position) t)
6227 (org-time-string-to-time (match-string 0))
6228 now))
6229 ((= dcst ?f)
6230 (if getkey-func
6231 (progn
6232 (setq tmp (funcall getkey-func))
6233 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6234 tmp)
6235 (error "Invalid key function `%s'" getkey-func)))
6236 (t (error "Invalid sorting type `%c'" sorting-type)))))
6237 (lambda nil
6238 (cond
6239 ((= dcst ?n)
6240 (if (looking-at outline-regexp)
6241 (string-to-number (buffer-substring (match-end 0)
6242 (line-end-position)))
6243 nil))
6244 ((= dcst ?a)
6245 (funcall case-func (buffer-substring (line-beginning-position)
6246 (line-end-position))))
6247 ((= dcst ?t)
6248 (if (re-search-forward org-ts-regexp
6249 (save-excursion
6250 (forward-line 2)
6251 (point)) t)
6252 (org-time-string-to-time (match-string 0))
6253 now))
6254 ((= dcst ?p)
6255 (if (re-search-forward org-priority-regexp (line-end-position) t)
6256 (string-to-char (match-string 2))
6257 org-default-priority))
6258 ((= dcst ?r)
6259 (or (org-entry-get nil property) ""))
6260 ((= dcst ?f)
6261 (if getkey-func
6262 (progn
6263 (setq tmp (funcall getkey-func))
6264 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6265 tmp)
6266 (error "Invalid key function `%s'" getkey-func)))
6267 (t (error "Invalid sorting type `%c'" sorting-type)))))
6269 (cond
6270 ((= dcst ?a) 'string<)
6271 ((= dcst ?t) 'time-less-p)
6272 (t nil)))))
6273 (message "Sorting entries...done")))
6275 (defun org-do-sort (table what &optional with-case sorting-type)
6276 "Sort TABLE of WHAT according to SORTING-TYPE.
6277 The user will be prompted for the SORTING-TYPE if the call to this
6278 function does not specify it. WHAT is only for the prompt, to indicate
6279 what is being sorted. The sorting key will be extracted from
6280 the car of the elements of the table.
6281 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6282 (unless sorting-type
6283 (message
6284 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6285 what)
6286 (setq sorting-type (read-char-exclusive)))
6287 (let ((dcst (downcase sorting-type))
6288 extractfun comparefun)
6289 ;; Define the appropriate functions
6290 (cond
6291 ((= dcst ?n)
6292 (setq extractfun 'string-to-number
6293 comparefun (if (= dcst sorting-type) '< '>)))
6294 ((= dcst ?a)
6295 (setq extractfun (if with-case 'identity 'downcase)
6296 comparefun (if (= dcst sorting-type)
6297 'string<
6298 (lambda (a b) (and (not (string< a b))
6299 (not (string= a b)))))))
6300 ((= dcst ?t)
6301 (setq extractfun
6302 (lambda (x)
6303 (if (string-match org-ts-regexp x)
6304 (time-to-seconds
6305 (org-time-string-to-time (match-string 0 x)))
6307 comparefun (if (= dcst sorting-type) '< '>)))
6308 (t (error "Invalid sorting type `%c'" sorting-type)))
6310 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6311 table)
6312 (lambda (a b) (funcall comparefun (car a) (car b))))))
6314 ;;;; Plain list items, including checkboxes
6316 ;;; Plain list items
6318 (defun org-at-item-p ()
6319 "Is point in a line starting a hand-formatted item?"
6320 (let ((llt org-plain-list-ordered-item-terminator))
6321 (save-excursion
6322 (goto-char (point-at-bol))
6323 (looking-at
6324 (cond
6325 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6326 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6327 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6328 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6330 (defun org-in-item-p ()
6331 "It the cursor inside a plain list item.
6332 Does not have to be the first line."
6333 (save-excursion
6334 (condition-case nil
6335 (progn
6336 (org-beginning-of-item)
6337 (org-at-item-p)
6339 (error nil))))
6341 (defun org-insert-item (&optional checkbox)
6342 "Insert a new item at the current level.
6343 Return t when things worked, nil when we are not in an item."
6344 (when (save-excursion
6345 (condition-case nil
6346 (progn
6347 (org-beginning-of-item)
6348 (org-at-item-p)
6349 (if (org-invisible-p) (error "Invisible item"))
6351 (error nil)))
6352 (let* ((bul (match-string 0))
6353 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6354 (match-end 0)))
6355 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6356 pos)
6357 (cond
6358 ((and (org-at-item-p) (<= (point) eow))
6359 ;; before the bullet
6360 (beginning-of-line 1)
6361 (open-line (if blank 2 1)))
6362 ((<= (point) eow)
6363 (beginning-of-line 1))
6364 (t (newline (if blank 2 1))))
6365 (insert bul (if checkbox "[ ]" ""))
6366 (just-one-space)
6367 (setq pos (point))
6368 (end-of-line 1)
6369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6370 (org-maybe-renumber-ordered-list)
6371 (and checkbox (org-update-checkbox-count-maybe))
6374 ;;; Checkboxes
6376 (defun org-at-item-checkbox-p ()
6377 "Is point at a line starting a plain-list item with a checklet?"
6378 (and (org-at-item-p)
6379 (save-excursion
6380 (goto-char (match-end 0))
6381 (skip-chars-forward " \t")
6382 (looking-at "\\[[- X]\\]"))))
6384 (defun org-toggle-checkbox (&optional arg)
6385 "Toggle the checkbox in the current line."
6386 (interactive "P")
6387 (catch 'exit
6388 (let (beg end status (firstnew 'unknown))
6389 (cond
6390 ((org-region-active-p)
6391 (setq beg (region-beginning) end (region-end)))
6392 ((org-on-heading-p)
6393 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6394 ((org-at-item-checkbox-p)
6395 (save-excursion
6396 (replace-match
6397 (cond (arg "[-]")
6398 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6399 (t "[ ]"))
6400 t t))
6401 (throw 'exit t))
6402 (t (error "Not at a checkbox or heading, and no active region")))
6403 (save-excursion
6404 (goto-char beg)
6405 (while (< (point) end)
6406 (when (org-at-item-checkbox-p)
6407 (setq status (equal (match-string 0) "[X]"))
6408 (when (eq firstnew 'unknown)
6409 (setq firstnew (not status)))
6410 (replace-match
6411 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6412 (beginning-of-line 2)))))
6413 (org-update-checkbox-count-maybe))
6415 (defun org-update-checkbox-count-maybe ()
6416 "Update checkbox statistics unless turned off by user."
6417 (when org-provide-checkbox-statistics
6418 (org-update-checkbox-count)))
6420 (defun org-update-checkbox-count (&optional all)
6421 "Update the checkbox statistics in the current section.
6422 This will find all statistic cookies like [57%] and [6/12] and update them
6423 with the current numbers. With optional prefix argument ALL, do this for
6424 the whole buffer."
6425 (interactive "P")
6426 (save-excursion
6427 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6428 (beg (condition-case nil
6429 (progn (outline-back-to-heading) (point))
6430 (error (point-min))))
6431 (end (move-marker (make-marker)
6432 (progn (outline-next-heading) (point))))
6433 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6434 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6435 b1 e1 f1 c-on c-off lim (cstat 0))
6436 (when all
6437 (goto-char (point-min))
6438 (outline-next-heading)
6439 (setq beg (point) end (point-max)))
6440 (goto-char beg)
6441 (while (re-search-forward re end t)
6442 (setq cstat (1+ cstat)
6443 b1 (match-beginning 0)
6444 e1 (match-end 0)
6445 f1 (match-beginning 1)
6446 lim (cond
6447 ((org-on-heading-p) (outline-next-heading) (point))
6448 ((org-at-item-p) (org-end-of-item) (point))
6449 (t nil))
6450 c-on 0 c-off 0)
6451 (goto-char e1)
6452 (when lim
6453 (while (re-search-forward re-box lim t)
6454 (if (member (match-string 2) '("[ ]" "[-]"))
6455 (setq c-off (1+ c-off))
6456 (setq c-on (1+ c-on))))
6457 ; (delete-region b1 e1)
6458 (goto-char b1)
6459 (insert (if f1
6460 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6461 (format "[%d/%d]" c-on (+ c-on c-off))))
6462 (and (looking-at "\\[.*?\\]")
6463 (replace-match ""))))
6464 (when (interactive-p)
6465 (message "Checkbox satistics updated %s (%d places)"
6466 (if all "in entire file" "in current outline entry") cstat)))))
6468 (defun org-get-checkbox-statistics-face ()
6469 "Select the face for checkbox statistics.
6470 The face will be `org-done' when all relevant boxes are checked. Otherwise
6471 it will be `org-todo'."
6472 (if (match-end 1)
6473 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6474 (if (and (> (match-end 2) (match-beginning 2))
6475 (equal (match-string 2) (match-string 3)))
6476 'org-done
6477 'org-todo)))
6479 (defun org-get-indentation (&optional line)
6480 "Get the indentation of the current line, interpreting tabs.
6481 When LINE is given, assume it represents a line and compute its indentation."
6482 (if line
6483 (if (string-match "^ *" (org-remove-tabs line))
6484 (match-end 0))
6485 (save-excursion
6486 (beginning-of-line 1)
6487 (skip-chars-forward " \t")
6488 (current-column))))
6490 (defun org-remove-tabs (s &optional width)
6491 "Replace tabulators in S with spaces.
6492 Assumes that s is a single line, starting in column 0."
6493 (setq width (or width tab-width))
6494 (while (string-match "\t" s)
6495 (setq s (replace-match
6496 (make-string
6497 (- (* width (/ (+ (match-beginning 0) width) width))
6498 (match-beginning 0)) ?\ )
6499 t t s)))
6502 (defun org-fix-indentation (line ind)
6503 "Fix indentation in LINE.
6504 IND is a cons cell with target and minimum indentation.
6505 If the current indenation in LINE is smaller than the minimum,
6506 leave it alone. If it is larger than ind, set it to the target."
6507 (let* ((l (org-remove-tabs line))
6508 (i (org-get-indentation l))
6509 (i1 (car ind)) (i2 (cdr ind)))
6510 (if (>= i i2) (setq l (substring line i2)))
6511 (if (> i1 0)
6512 (concat (make-string i1 ?\ ) l)
6513 l)))
6515 (defcustom org-empty-line-terminates-plain-lists nil
6516 "Non-nil means, an empty line ends all plain list levels.
6517 When nil, empty lines are part of the preceeding item."
6518 :group 'org-plain-lists
6519 :type 'boolean)
6521 (defun org-beginning-of-item ()
6522 "Go to the beginning of the current hand-formatted item.
6523 If the cursor is not in an item, throw an error."
6524 (interactive)
6525 (let ((pos (point))
6526 (limit (save-excursion
6527 (condition-case nil
6528 (progn
6529 (org-back-to-heading)
6530 (beginning-of-line 2) (point))
6531 (error (point-min)))))
6532 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6533 ind ind1)
6534 (if (org-at-item-p)
6535 (beginning-of-line 1)
6536 (beginning-of-line 1)
6537 (skip-chars-forward " \t")
6538 (setq ind (current-column))
6539 (if (catch 'exit
6540 (while t
6541 (beginning-of-line 0)
6542 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6544 (if (looking-at "[ \t]*$")
6545 (setq ind1 ind-empty)
6546 (skip-chars-forward " \t")
6547 (setq ind1 (current-column)))
6548 (if (< ind1 ind)
6549 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6551 (goto-char pos)
6552 (error "Not in an item")))))
6554 (defun org-end-of-item ()
6555 "Go to the end of the current hand-formatted item.
6556 If the cursor is not in an item, throw an error."
6557 (interactive)
6558 (let* ((pos (point))
6559 ind1
6560 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6561 (limit (save-excursion (outline-next-heading) (point)))
6562 (ind (save-excursion
6563 (org-beginning-of-item)
6564 (skip-chars-forward " \t")
6565 (current-column)))
6566 (end (catch 'exit
6567 (while t
6568 (beginning-of-line 2)
6569 (if (eobp) (throw 'exit (point)))
6570 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6571 (if (looking-at "[ \t]*$")
6572 (setq ind1 ind-empty)
6573 (skip-chars-forward " \t")
6574 (setq ind1 (current-column)))
6575 (if (<= ind1 ind)
6576 (throw 'exit (point-at-bol)))))))
6577 (if end
6578 (goto-char end)
6579 (goto-char pos)
6580 (error "Not in an item"))))
6582 (defun org-next-item ()
6583 "Move to the beginning of the next item in the current plain list.
6584 Error if not at a plain list, or if this is the last item in the list."
6585 (interactive)
6586 (let (ind ind1 (pos (point)))
6587 (org-beginning-of-item)
6588 (setq ind (org-get-indentation))
6589 (org-end-of-item)
6590 (setq ind1 (org-get-indentation))
6591 (unless (and (org-at-item-p) (= ind ind1))
6592 (goto-char pos)
6593 (error "On last item"))))
6595 (defun org-previous-item ()
6596 "Move to the beginning of the previous item in the current plain list.
6597 Error if not at a plain list, or if this is the first item in the list."
6598 (interactive)
6599 (let (beg ind ind1 (pos (point)))
6600 (org-beginning-of-item)
6601 (setq beg (point))
6602 (setq ind (org-get-indentation))
6603 (goto-char beg)
6604 (catch 'exit
6605 (while t
6606 (beginning-of-line 0)
6607 (if (looking-at "[ \t]*$")
6609 (if (<= (setq ind1 (org-get-indentation)) ind)
6610 (throw 'exit t)))))
6611 (condition-case nil
6612 (if (or (not (org-at-item-p))
6613 (< ind1 (1- ind)))
6614 (error "")
6615 (org-beginning-of-item))
6616 (error (goto-char pos)
6617 (error "On first item")))))
6619 (defun org-move-item-down ()
6620 "Move the plain list item at point down, i.e. swap with following item.
6621 Subitems (items with larger indentation) are considered part of the item,
6622 so this really moves item trees."
6623 (interactive)
6624 (let (beg end ind ind1 (pos (point)) txt)
6625 (org-beginning-of-item)
6626 (setq beg (point))
6627 (setq ind (org-get-indentation))
6628 (org-end-of-item)
6629 (setq end (point))
6630 (setq ind1 (org-get-indentation))
6631 (if (and (org-at-item-p) (= ind ind1))
6632 (progn
6633 (org-end-of-item)
6634 (setq txt (buffer-substring beg end))
6635 (save-excursion
6636 (delete-region beg end))
6637 (setq pos (point))
6638 (insert txt)
6639 (goto-char pos)
6640 (org-maybe-renumber-ordered-list))
6641 (goto-char pos)
6642 (error "Cannot move this item further down"))))
6644 (defun org-move-item-up (arg)
6645 "Move the plain list item at point up, i.e. swap with previous item.
6646 Subitems (items with larger indentation) are considered part of the item,
6647 so this really moves item trees."
6648 (interactive "p")
6649 (let (beg end ind ind1 (pos (point)) txt)
6650 (org-beginning-of-item)
6651 (setq beg (point))
6652 (setq ind (org-get-indentation))
6653 (org-end-of-item)
6654 (setq end (point))
6655 (goto-char beg)
6656 (catch 'exit
6657 (while t
6658 (beginning-of-line 0)
6659 (if (looking-at "[ \t]*$")
6660 (if org-empty-line-terminates-plain-lists
6661 (progn
6662 (goto-char pos)
6663 (error "Cannot move this item further up"))
6664 nil)
6665 (if (<= (setq ind1 (org-get-indentation)) ind)
6666 (throw 'exit t)))))
6667 (condition-case nil
6668 (org-beginning-of-item)
6669 (error (goto-char beg)
6670 (error "Cannot move this item further up")))
6671 (setq ind1 (org-get-indentation))
6672 (if (and (org-at-item-p) (= ind ind1))
6673 (progn
6674 (setq txt (buffer-substring beg end))
6675 (save-excursion
6676 (delete-region beg end))
6677 (setq pos (point))
6678 (insert txt)
6679 (goto-char pos)
6680 (org-maybe-renumber-ordered-list))
6681 (goto-char pos)
6682 (error "Cannot move this item further up"))))
6684 (defun org-maybe-renumber-ordered-list ()
6685 "Renumber the ordered list at point if setup allows it.
6686 This tests the user option `org-auto-renumber-ordered-lists' before
6687 doing the renumbering."
6688 (interactive)
6689 (when (and org-auto-renumber-ordered-lists
6690 (org-at-item-p))
6691 (if (match-beginning 3)
6692 (org-renumber-ordered-list 1)
6693 (org-fix-bullet-type))))
6695 (defun org-maybe-renumber-ordered-list-safe ()
6696 (condition-case nil
6697 (save-excursion
6698 (org-maybe-renumber-ordered-list))
6699 (error nil)))
6701 (defun org-cycle-list-bullet (&optional which)
6702 "Cycle through the different itemize/enumerate bullets.
6703 This cycle the entire list level through the sequence:
6705 `-' -> `+' -> `*' -> `1.' -> `1)'
6707 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6708 0 meand `-', 1 means `+' etc."
6709 (interactive "P")
6710 (org-preserve-lc
6711 (org-beginning-of-item-list)
6712 (org-at-item-p)
6713 (beginning-of-line 1)
6714 (let ((current (match-string 0))
6715 (prevp (eq which 'previous))
6716 new)
6717 (setq new (cond
6718 ((and (numberp which)
6719 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6720 ((string-match "-" current) (if prevp "1)" "+"))
6721 ((string-match "\\+" current)
6722 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6723 ((string-match "\\*" current) (if prevp "+" "1."))
6724 ((string-match "\\." current) (if prevp "*" "1)"))
6725 ((string-match ")" current) (if prevp "1." "-"))
6726 (t (error "This should not happen"))))
6727 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6728 (org-fix-bullet-type)
6729 (org-maybe-renumber-ordered-list))))
6731 (defun org-get-string-indentation (s)
6732 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6733 (let ((n -1) (i 0) (w tab-width) c)
6734 (catch 'exit
6735 (while (< (setq n (1+ n)) (length s))
6736 (setq c (aref s n))
6737 (cond ((= c ?\ ) (setq i (1+ i)))
6738 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6739 (t (throw 'exit t)))))
6742 (defun org-renumber-ordered-list (arg)
6743 "Renumber an ordered plain list.
6744 Cursor needs to be in the first line of an item, the line that starts
6745 with something like \"1.\" or \"2)\"."
6746 (interactive "p")
6747 (unless (and (org-at-item-p)
6748 (match-beginning 3))
6749 (error "This is not an ordered list"))
6750 (let ((line (org-current-line))
6751 (col (current-column))
6752 (ind (org-get-string-indentation
6753 (buffer-substring (point-at-bol) (match-beginning 3))))
6754 ;; (term (substring (match-string 3) -1))
6755 ind1 (n (1- arg))
6756 fmt)
6757 ;; find where this list begins
6758 (org-beginning-of-item-list)
6759 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6760 (setq fmt (concat "%d" (match-string 1)))
6761 (beginning-of-line 0)
6762 ;; walk forward and replace these numbers
6763 (catch 'exit
6764 (while t
6765 (catch 'next
6766 (beginning-of-line 2)
6767 (if (eobp) (throw 'exit nil))
6768 (if (looking-at "[ \t]*$") (throw 'next nil))
6769 (skip-chars-forward " \t") (setq ind1 (current-column))
6770 (if (> ind1 ind) (throw 'next t))
6771 (if (< ind1 ind) (throw 'exit t))
6772 (if (not (org-at-item-p)) (throw 'exit nil))
6773 (delete-region (match-beginning 2) (match-end 2))
6774 (goto-char (match-beginning 2))
6775 (insert (format fmt (setq n (1+ n)))))))
6776 (goto-line line)
6777 (move-to-column col)))
6779 (defun org-fix-bullet-type ()
6780 "Make sure all items in this list have the same bullet as the firsst item."
6781 (interactive)
6782 (unless (org-at-item-p) (error "This is not a list"))
6783 (let ((line (org-current-line))
6784 (col (current-column))
6785 (ind (current-indentation))
6786 ind1 bullet)
6787 ;; find where this list begins
6788 (org-beginning-of-item-list)
6789 (beginning-of-line 1)
6790 ;; find out what the bullet type is
6791 (looking-at "[ \t]*\\(\\S-+\\)")
6792 (setq bullet (match-string 1))
6793 ;; walk forward and replace these numbers
6794 (beginning-of-line 0)
6795 (catch 'exit
6796 (while t
6797 (catch 'next
6798 (beginning-of-line 2)
6799 (if (eobp) (throw 'exit nil))
6800 (if (looking-at "[ \t]*$") (throw 'next nil))
6801 (skip-chars-forward " \t") (setq ind1 (current-column))
6802 (if (> ind1 ind) (throw 'next t))
6803 (if (< ind1 ind) (throw 'exit t))
6804 (if (not (org-at-item-p)) (throw 'exit nil))
6805 (skip-chars-forward " \t")
6806 (looking-at "\\S-+")
6807 (replace-match bullet))))
6808 (goto-line line)
6809 (move-to-column col)
6810 (if (string-match "[0-9]" bullet)
6811 (org-renumber-ordered-list 1))))
6813 (defun org-beginning-of-item-list ()
6814 "Go to the beginning of the current item list.
6815 I.e. to the first item in this list."
6816 (interactive)
6817 (org-beginning-of-item)
6818 (let ((pos (point-at-bol))
6819 (ind (org-get-indentation))
6820 ind1)
6821 ;; find where this list begins
6822 (catch 'exit
6823 (while t
6824 (catch 'next
6825 (beginning-of-line 0)
6826 (if (looking-at "[ \t]*$")
6827 (throw (if (bobp) 'exit 'next) t))
6828 (skip-chars-forward " \t") (setq ind1 (current-column))
6829 (if (or (< ind1 ind)
6830 (and (= ind1 ind)
6831 (not (org-at-item-p)))
6832 (bobp))
6833 (throw 'exit t)
6834 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6835 (goto-char pos)))
6838 (defun org-end-of-item-list ()
6839 "Go to the end of the current item list.
6840 I.e. to the text after the last item."
6841 (interactive)
6842 (org-beginning-of-item)
6843 (let ((pos (point-at-bol))
6844 (ind (org-get-indentation))
6845 ind1)
6846 ;; find where this list begins
6847 (catch 'exit
6848 (while t
6849 (catch 'next
6850 (beginning-of-line 2)
6851 (if (looking-at "[ \t]*$")
6852 (throw (if (eobp) 'exit 'next) t))
6853 (skip-chars-forward " \t") (setq ind1 (current-column))
6854 (if (or (< ind1 ind)
6855 (and (= ind1 ind)
6856 (not (org-at-item-p)))
6857 (eobp))
6858 (progn
6859 (setq pos (point-at-bol))
6860 (throw 'exit t))))))
6861 (goto-char pos)))
6864 (defvar org-last-indent-begin-marker (make-marker))
6865 (defvar org-last-indent-end-marker (make-marker))
6867 (defun org-outdent-item (arg)
6868 "Outdent a local list item."
6869 (interactive "p")
6870 (org-indent-item (- arg)))
6872 (defun org-indent-item (arg)
6873 "Indent a local list item."
6874 (interactive "p")
6875 (unless (org-at-item-p)
6876 (error "Not on an item"))
6877 (save-excursion
6878 (let (beg end ind ind1 tmp delta ind-down ind-up)
6879 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6880 (setq beg org-last-indent-begin-marker
6881 end org-last-indent-end-marker)
6882 (org-beginning-of-item)
6883 (setq beg (move-marker org-last-indent-begin-marker (point)))
6884 (org-end-of-item)
6885 (setq end (move-marker org-last-indent-end-marker (point))))
6886 (goto-char beg)
6887 (setq tmp (org-item-indent-positions)
6888 ind (car tmp)
6889 ind-down (nth 2 tmp)
6890 ind-up (nth 1 tmp)
6891 delta (if (> arg 0)
6892 (if ind-down (- ind-down ind) 2)
6893 (if ind-up (- ind-up ind) -2)))
6894 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6895 (while (< (point) end)
6896 (beginning-of-line 1)
6897 (skip-chars-forward " \t") (setq ind1 (current-column))
6898 (delete-region (point-at-bol) (point))
6899 (or (eolp) (indent-to-column (+ ind1 delta)))
6900 (beginning-of-line 2))))
6901 (org-fix-bullet-type)
6902 (org-maybe-renumber-ordered-list-safe)
6903 (save-excursion
6904 (beginning-of-line 0)
6905 (condition-case nil (org-beginning-of-item) (error nil))
6906 (org-maybe-renumber-ordered-list-safe)))
6908 (defun org-item-indent-positions ()
6909 "Return indentation for plain list items.
6910 This returns a list with three values: The current indentation, the
6911 parent indentation and the indentation a child should habe.
6912 Assumes cursor in item line."
6913 (let* ((bolpos (point-at-bol))
6914 (ind (org-get-indentation))
6915 ind-down ind-up pos)
6916 (save-excursion
6917 (org-beginning-of-item-list)
6918 (skip-chars-backward "\n\r \t")
6919 (when (org-in-item-p)
6920 (org-beginning-of-item)
6921 (setq ind-up (org-get-indentation))))
6922 (setq pos (point))
6923 (save-excursion
6924 (cond
6925 ((and (condition-case nil (progn (org-previous-item) t)
6926 (error nil))
6927 (or (forward-char 1) t)
6928 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6929 (setq ind-down (org-get-indentation)))
6930 ((and (goto-char pos)
6931 (org-at-item-p))
6932 (goto-char (match-end 0))
6933 (skip-chars-forward " \t")
6934 (setq ind-down (current-column)))))
6935 (list ind ind-up ind-down)))
6937 ;;; The orgstruct minor mode
6939 ;; Define a minor mode which can be used in other modes in order to
6940 ;; integrate the org-mode structure editing commands.
6942 ;; This is really a hack, because the org-mode structure commands use
6943 ;; keys which normally belong to the major mode. Here is how it
6944 ;; works: The minor mode defines all the keys necessary to operate the
6945 ;; structure commands, but wraps the commands into a function which
6946 ;; tests if the cursor is currently at a headline or a plain list
6947 ;; item. If that is the case, the structure command is used,
6948 ;; temporarily setting many Org-mode variables like regular
6949 ;; expressions for filling etc. However, when any of those keys is
6950 ;; used at a different location, function uses `key-binding' to look
6951 ;; up if the key has an associated command in another currently active
6952 ;; keymap (minor modes, major mode, global), and executes that
6953 ;; command. There might be problems if any of the keys is otherwise
6954 ;; used as a prefix key.
6956 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6957 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6958 ;; addresses this by checking explicitly for both bindings.
6960 (defvar orgstruct-mode-map (make-sparse-keymap)
6961 "Keymap for the minor `orgstruct-mode'.")
6963 (defvar org-local-vars nil
6964 "List of local variables, for use by `orgstruct-mode'")
6966 ;;;###autoload
6967 (define-minor-mode orgstruct-mode
6968 "Toggle the minor more `orgstruct-mode'.
6969 This mode is for using Org-mode structure commands in other modes.
6970 The following key behave as if Org-mode was active, if the cursor
6971 is on a headline, or on a plain list item (both in the definition
6972 of Org-mode).
6974 M-up Move entry/item up
6975 M-down Move entry/item down
6976 M-left Promote
6977 M-right Demote
6978 M-S-up Move entry/item up
6979 M-S-down Move entry/item down
6980 M-S-left Promote subtree
6981 M-S-right Demote subtree
6982 M-q Fill paragraph and items like in Org-mode
6983 C-c ^ Sort entries
6984 C-c - Cycle list bullet
6985 TAB Cycle item visibility
6986 M-RET Insert new heading/item
6987 S-M-RET Insert new TODO heading / Chekbox item
6988 C-c C-c Set tags / toggle checkbox"
6989 nil " OrgStruct" nil
6990 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6992 ;;;###autoload
6993 (defun turn-on-orgstruct ()
6994 "Unconditionally turn on `orgstruct-mode'."
6995 (orgstruct-mode 1))
6997 ;;;###autoload
6998 (defun turn-on-orgstruct++ ()
6999 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7000 In addition to setting orgstruct-mode, this also exports all indentation and
7001 autofilling variables from org-mode into the buffer. Note that turning
7002 off orgstruct-mode will *not* remove these additonal settings."
7003 (orgstruct-mode 1)
7004 (let (var val)
7005 (mapc
7006 (lambda (x)
7007 (when (string-match
7008 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7009 (symbol-name (car x)))
7010 (setq var (car x) val (nth 1 x))
7011 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7012 org-local-vars)))
7014 (defun orgstruct-error ()
7015 "Error when there is no default binding for a structure key."
7016 (interactive)
7017 (error "This key is has no function outside structure elements"))
7019 (defun orgstruct-setup ()
7020 "Setup orgstruct keymaps."
7021 (let ((nfunc 0)
7022 (bindings
7023 (list
7024 '([(meta up)] org-metaup)
7025 '([(meta down)] org-metadown)
7026 '([(meta left)] org-metaleft)
7027 '([(meta right)] org-metaright)
7028 '([(meta shift up)] org-shiftmetaup)
7029 '([(meta shift down)] org-shiftmetadown)
7030 '([(meta shift left)] org-shiftmetaleft)
7031 '([(meta shift right)] org-shiftmetaright)
7032 '([(shift up)] org-shiftup)
7033 '([(shift down)] org-shiftdown)
7034 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7035 '("\M-q" fill-paragraph)
7036 '("\C-c^" org-sort)
7037 '("\C-c-" org-cycle-list-bullet)))
7038 elt key fun cmd)
7039 (while (setq elt (pop bindings))
7040 (setq nfunc (1+ nfunc))
7041 (setq key (org-key (car elt))
7042 fun (nth 1 elt)
7043 cmd (orgstruct-make-binding fun nfunc key))
7044 (org-defkey orgstruct-mode-map key cmd))
7046 ;; Special treatment needed for TAB and RET
7047 (org-defkey orgstruct-mode-map [(tab)]
7048 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7049 (org-defkey orgstruct-mode-map "\C-i"
7050 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7052 (org-defkey orgstruct-mode-map "\M-\C-m"
7053 (orgstruct-make-binding 'org-insert-heading 105
7054 "\M-\C-m" [(meta return)]))
7055 (org-defkey orgstruct-mode-map [(meta return)]
7056 (orgstruct-make-binding 'org-insert-heading 106
7057 [(meta return)] "\M-\C-m"))
7059 (org-defkey orgstruct-mode-map [(shift meta return)]
7060 (orgstruct-make-binding 'org-insert-todo-heading 107
7061 [(meta return)] "\M-\C-m"))
7063 (unless org-local-vars
7064 (setq org-local-vars (org-get-local-variables)))
7068 (defun orgstruct-make-binding (fun n &rest keys)
7069 "Create a function for binding in the structure minor mode.
7070 FUN is the command to call inside a table. N is used to create a unique
7071 command name. KEYS are keys that should be checked in for a command
7072 to execute outside of tables."
7073 (eval
7074 (list 'defun
7075 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7076 '(arg)
7077 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7078 "Outside of structure, run the binding of `"
7079 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7080 "'.")
7081 '(interactive "p")
7082 (list 'if
7083 '(org-context-p 'headline 'item)
7084 (list 'org-run-like-in-org-mode (list 'quote fun))
7085 (list 'let '(orgstruct-mode)
7086 (list 'call-interactively
7087 (append '(or)
7088 (mapcar (lambda (k)
7089 (list 'key-binding k))
7090 keys)
7091 '('orgstruct-error))))))))
7093 (defun org-context-p (&rest contexts)
7094 "Check if local context is and of CONTEXTS.
7095 Possible values in the list of contexts are `table', `headline', and `item'."
7096 (let ((pos (point)))
7097 (goto-char (point-at-bol))
7098 (prog1 (or (and (memq 'table contexts)
7099 (looking-at "[ \t]*|"))
7100 (and (memq 'headline contexts)
7101 (looking-at "\\*+"))
7102 (and (memq 'item contexts)
7103 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7104 (goto-char pos))))
7106 (defun org-get-local-variables ()
7107 "Return a list of all local variables in an org-mode buffer."
7108 (let (varlist)
7109 (with-current-buffer (get-buffer-create "*Org tmp*")
7110 (erase-buffer)
7111 (org-mode)
7112 (setq varlist (buffer-local-variables)))
7113 (kill-buffer "*Org tmp*")
7114 (delq nil
7115 (mapcar
7116 (lambda (x)
7117 (setq x
7118 (if (symbolp x)
7119 (list x)
7120 (list (car x) (list 'quote (cdr x)))))
7121 (if (string-match
7122 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7123 (symbol-name (car x)))
7124 x nil))
7125 varlist))))
7127 ;;;###autoload
7128 (defun org-run-like-in-org-mode (cmd)
7129 (unless org-local-vars
7130 (setq org-local-vars (org-get-local-variables)))
7131 (eval (list 'let org-local-vars
7132 (list 'call-interactively (list 'quote cmd)))))
7134 ;;;; Archiving
7136 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7138 (defun org-archive-subtree (&optional find-done)
7139 "Move the current subtree to the archive.
7140 The archive can be a certain top-level heading in the current file, or in
7141 a different file. The tree will be moved to that location, the subtree
7142 heading be marked DONE, and the current time will be added.
7144 When called with prefix argument FIND-DONE, find whole trees without any
7145 open TODO items and archive them (after getting confirmation from the user).
7146 If the cursor is not at a headline when this comand is called, try all level
7147 1 trees. If the cursor is on a headline, only try the direct children of
7148 this heading."
7149 (interactive "P")
7150 (if find-done
7151 (org-archive-all-done)
7152 ;; Save all relevant TODO keyword-relatex variables
7154 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7155 (tr-org-todo-keywords-1 org-todo-keywords-1)
7156 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7157 (tr-org-done-keywords org-done-keywords)
7158 (tr-org-todo-regexp org-todo-regexp)
7159 (tr-org-todo-line-regexp org-todo-line-regexp)
7160 (tr-org-odd-levels-only org-odd-levels-only)
7161 (this-buffer (current-buffer))
7162 (org-archive-location org-archive-location)
7163 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7164 ;; start of variables that will be used for savind context
7165 (file (abbreviate-file-name (buffer-file-name)))
7166 (time (format-time-string
7167 (substring (cdr org-time-stamp-formats) 1 -1)
7168 (current-time)))
7169 afile heading buffer level newfile-p
7170 category todo priority
7171 ;; start of variables that will be used for savind context
7172 ltags itags prop)
7174 ;; Try to find a local archive location
7175 (save-excursion
7176 (save-restriction
7177 (widen)
7178 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7179 (if (and prop (string-match "\\S-" prop))
7180 (setq org-archive-location prop)
7181 (if (or (re-search-backward re nil t)
7182 (re-search-forward re nil t))
7183 (setq org-archive-location (match-string 1))))))
7185 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7186 (progn
7187 (setq afile (format (match-string 1 org-archive-location)
7188 (file-name-nondirectory buffer-file-name))
7189 heading (match-string 2 org-archive-location)))
7190 (error "Invalid `org-archive-location'"))
7191 (if (> (length afile) 0)
7192 (setq newfile-p (not (file-exists-p afile))
7193 buffer (find-file-noselect afile))
7194 (setq buffer (current-buffer)))
7195 (unless buffer
7196 (error "Cannot access file \"%s\"" afile))
7197 (if (and (> (length heading) 0)
7198 (string-match "^\\*+" heading))
7199 (setq level (match-end 0))
7200 (setq heading nil level 0))
7201 (save-excursion
7202 (org-back-to-heading t)
7203 ;; Get context information that will be lost by moving the tree
7204 (org-refresh-category-properties)
7205 (setq category (org-get-category)
7206 todo (and (looking-at org-todo-line-regexp)
7207 (match-string 2))
7208 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7209 ltags (org-get-tags)
7210 itags (org-delete-all ltags (org-get-tags-at)))
7211 (setq ltags (mapconcat 'identity ltags " ")
7212 itags (mapconcat 'identity itags " "))
7213 ;; We first only copy, in case something goes wrong
7214 ;; we need to protect this-command, to avoid kill-region sets it,
7215 ;; which would lead to duplication of subtrees
7216 (let (this-command) (org-copy-subtree))
7217 (set-buffer buffer)
7218 ;; Enforce org-mode for the archive buffer
7219 (if (not (org-mode-p))
7220 ;; Force the mode for future visits.
7221 (let ((org-insert-mode-line-in-empty-file t)
7222 (org-inhibit-startup t))
7223 (call-interactively 'org-mode)))
7224 (when newfile-p
7225 (goto-char (point-max))
7226 (insert (format "\nArchived entries from file %s\n\n"
7227 (buffer-file-name this-buffer))))
7228 ;; Force the TODO keywords of the original buffer
7229 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7230 (org-todo-keywords-1 tr-org-todo-keywords-1)
7231 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7232 (org-done-keywords tr-org-done-keywords)
7233 (org-todo-regexp tr-org-todo-regexp)
7234 (org-todo-line-regexp tr-org-todo-line-regexp)
7235 (org-odd-levels-only
7236 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7237 org-odd-levels-only
7238 tr-org-odd-levels-only)))
7239 (goto-char (point-min))
7240 (if heading
7241 (progn
7242 (if (re-search-forward
7243 (concat "^" (regexp-quote heading)
7244 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7245 nil t)
7246 (goto-char (match-end 0))
7247 ;; Heading not found, just insert it at the end
7248 (goto-char (point-max))
7249 (or (bolp) (insert "\n"))
7250 (insert "\n" heading "\n")
7251 (end-of-line 0))
7252 ;; Make the subtree visible
7253 (show-subtree)
7254 (org-end-of-subtree t)
7255 (skip-chars-backward " \t\r\n")
7256 (and (looking-at "[ \t\r\n]*")
7257 (replace-match "\n\n")))
7258 ;; No specific heading, just go to end of file.
7259 (goto-char (point-max)) (insert "\n"))
7260 ;; Paste
7261 (org-paste-subtree (org-get-legal-level level 1))
7263 ;; Mark the entry as done
7264 (when (and org-archive-mark-done
7265 (looking-at org-todo-line-regexp)
7266 (or (not (match-end 2))
7267 (not (member (match-string 2) org-done-keywords))))
7268 (let (org-log-done)
7269 (org-todo
7270 (car (or (member org-archive-mark-done org-done-keywords)
7271 org-done-keywords)))))
7273 ;; Add the context info
7274 (when org-archive-save-context-info
7275 (let ((l org-archive-save-context-info) e n v)
7276 (while (setq e (pop l))
7277 (when (and (setq v (symbol-value e))
7278 (stringp v) (string-match "\\S-" v))
7279 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7280 (org-entry-put (point) n v)))))
7282 ;; Save the buffer, if it is not the same buffer.
7283 (if (not (eq this-buffer buffer)) (save-buffer))))
7284 ;; Here we are back in the original buffer. Everything seems to have
7285 ;; worked. So now cut the tree and finish up.
7286 (let (this-command) (org-cut-subtree))
7287 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7288 (message "Subtree archived %s"
7289 (if (eq this-buffer buffer)
7290 (concat "under heading: " heading)
7291 (concat "in file: " (abbreviate-file-name afile)))))))
7293 (defun org-refresh-category-properties ()
7294 "Refresh category text properties in teh buffer."
7295 (let ((def-cat (cond
7296 ((null org-category)
7297 (if buffer-file-name
7298 (file-name-sans-extension
7299 (file-name-nondirectory buffer-file-name))
7300 "???"))
7301 ((symbolp org-category) (symbol-name org-category))
7302 (t org-category)))
7303 beg end cat pos optionp)
7304 (org-unmodified
7305 (save-excursion
7306 (save-restriction
7307 (widen)
7308 (goto-char (point-min))
7309 (put-text-property (point) (point-max) 'org-category def-cat)
7310 (while (re-search-forward
7311 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7312 (setq pos (match-end 0)
7313 optionp (equal (char-after (match-beginning 0)) ?#)
7314 cat (org-trim (match-string 2)))
7315 (if optionp
7316 (setq beg (point-at-bol) end (point-max))
7317 (org-back-to-heading t)
7318 (setq beg (point) end (org-end-of-subtree t t)))
7319 (put-text-property beg end 'org-category cat)
7320 (goto-char pos)))))))
7322 (defun org-archive-all-done (&optional tag)
7323 "Archive sublevels of the current tree without open TODO items.
7324 If the cursor is not on a headline, try all level 1 trees. If
7325 it is on a headline, try all direct children.
7326 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7327 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7328 (rea (concat ".*:" org-archive-tag ":"))
7329 (begm (make-marker))
7330 (endm (make-marker))
7331 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7332 "Move subtree to archive (no open TODO items)? "))
7333 beg end (cntarch 0))
7334 (if (org-on-heading-p)
7335 (progn
7336 (setq re1 (concat "^" (regexp-quote
7337 (make-string
7338 (1+ (- (match-end 0) (match-beginning 0)))
7339 ?*))
7340 " "))
7341 (move-marker begm (point))
7342 (move-marker endm (org-end-of-subtree t)))
7343 (setq re1 "^* ")
7344 (move-marker begm (point-min))
7345 (move-marker endm (point-max)))
7346 (save-excursion
7347 (goto-char begm)
7348 (while (re-search-forward re1 endm t)
7349 (setq beg (match-beginning 0)
7350 end (save-excursion (org-end-of-subtree t) (point)))
7351 (goto-char beg)
7352 (if (re-search-forward re end t)
7353 (goto-char end)
7354 (goto-char beg)
7355 (if (and (or (not tag) (not (looking-at rea)))
7356 (y-or-n-p question))
7357 (progn
7358 (if tag
7359 (org-toggle-tag org-archive-tag 'on)
7360 (org-archive-subtree))
7361 (setq cntarch (1+ cntarch)))
7362 (goto-char end)))))
7363 (message "%d trees archived" cntarch)))
7365 (defun org-cycle-hide-drawers (state)
7366 "Re-hide all drawers after a visibility state change."
7367 (when (and (org-mode-p)
7368 (not (memq state '(overview folded))))
7369 (save-excursion
7370 (let* ((globalp (memq state '(contents all)))
7371 (beg (if globalp (point-min) (point)))
7372 (end (if globalp (point-max) (org-end-of-subtree t))))
7373 (goto-char beg)
7374 (while (re-search-forward org-drawer-regexp end t)
7375 (org-flag-drawer t))))))
7377 (defun org-flag-drawer (flag)
7378 (save-excursion
7379 (beginning-of-line 1)
7380 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7381 (let ((b (match-end 0)))
7382 (if (re-search-forward
7383 "^[ \t]*:END:"
7384 (save-excursion (outline-next-heading) (point)) t)
7385 (outline-flag-region b (point-at-eol) flag)
7386 (error ":END: line missing"))))))
7388 (defun org-cycle-hide-archived-subtrees (state)
7389 "Re-hide all archived subtrees after a visibility state change."
7390 (when (and (not org-cycle-open-archived-trees)
7391 (not (memq state '(overview folded))))
7392 (save-excursion
7393 (let* ((globalp (memq state '(contents all)))
7394 (beg (if globalp (point-min) (point)))
7395 (end (if globalp (point-max) (org-end-of-subtree t))))
7396 (org-hide-archived-subtrees beg end)
7397 (goto-char beg)
7398 (if (looking-at (concat ".*:" org-archive-tag ":"))
7399 (message (substitute-command-keys
7400 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7402 (defun org-force-cycle-archived ()
7403 "Cycle subtree even if it is archived."
7404 (interactive)
7405 (setq this-command 'org-cycle)
7406 (let ((org-cycle-open-archived-trees t))
7407 (call-interactively 'org-cycle)))
7409 (defun org-hide-archived-subtrees (beg end)
7410 "Re-hide all archived subtrees after a visibility state change."
7411 (save-excursion
7412 (let* ((re (concat ":" org-archive-tag ":")))
7413 (goto-char beg)
7414 (while (re-search-forward re end t)
7415 (and (org-on-heading-p) (hide-subtree))
7416 (org-end-of-subtree t)))))
7418 (defun org-toggle-tag (tag &optional onoff)
7419 "Toggle the tag TAG for the current line.
7420 If ONOFF is `on' or `off', don't toggle but set to this state."
7421 (unless (org-on-heading-p t) (error "Not on headling"))
7422 (let (res current)
7423 (save-excursion
7424 (beginning-of-line)
7425 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7426 (point-at-eol) t)
7427 (progn
7428 (setq current (match-string 1))
7429 (replace-match ""))
7430 (setq current ""))
7431 (setq current (nreverse (org-split-string current ":")))
7432 (cond
7433 ((eq onoff 'on)
7434 (setq res t)
7435 (or (member tag current) (push tag current)))
7436 ((eq onoff 'off)
7437 (or (not (member tag current)) (setq current (delete tag current))))
7438 (t (if (member tag current)
7439 (setq current (delete tag current))
7440 (setq res t)
7441 (push tag current))))
7442 (end-of-line 1)
7443 (if current
7444 (progn
7445 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7446 (org-set-tags nil t))
7447 (delete-horizontal-space))
7448 (run-hooks 'org-after-tags-change-hook))
7449 res))
7451 (defun org-toggle-archive-tag (&optional arg)
7452 "Toggle the archive tag for the current headline.
7453 With prefix ARG, check all children of current headline and offer tagging
7454 the children that do not contain any open TODO items."
7455 (interactive "P")
7456 (if arg
7457 (org-archive-all-done 'tag)
7458 (let (set)
7459 (save-excursion
7460 (org-back-to-heading t)
7461 (setq set (org-toggle-tag org-archive-tag))
7462 (when set (hide-subtree)))
7463 (and set (beginning-of-line 1))
7464 (message "Subtree %s" (if set "archived" "unarchived")))))
7467 ;;;; Tables
7469 ;;; The table editor
7471 ;; Watch out: Here we are talking about two different kind of tables.
7472 ;; Most of the code is for the tables created with the Org-mode table editor.
7473 ;; Sometimes, we talk about tables created and edited with the table.el
7474 ;; Emacs package. We call the former org-type tables, and the latter
7475 ;; table.el-type tables.
7477 (defun org-before-change-function (beg end)
7478 "Every change indicates that a table might need an update."
7479 (setq org-table-may-need-update t))
7481 (defconst org-table-line-regexp "^[ \t]*|"
7482 "Detects an org-type table line.")
7483 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7484 "Detects an org-type table line.")
7485 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7486 "Detects a table line marked for automatic recalculation.")
7487 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7488 "Detects a table line marked for automatic recalculation.")
7489 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7490 "Detects a table line marked for automatic recalculation.")
7491 (defconst org-table-hline-regexp "^[ \t]*|-"
7492 "Detects an org-type table hline.")
7493 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7494 "Detects a table-type table hline.")
7495 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7496 "Detects an org-type or table-type table.")
7497 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7498 "Searching from within a table (any type) this finds the first line
7499 outside the table.")
7500 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7501 "Searching from within a table (any type) this finds the first line
7502 outside the table.")
7504 (defvar org-table-last-highlighted-reference nil)
7505 (defvar org-table-formula-history nil)
7507 (defvar org-table-column-names nil
7508 "Alist with column names, derived from the `!' line.")
7509 (defvar org-table-column-name-regexp nil
7510 "Regular expression matching the current column names.")
7511 (defvar org-table-local-parameters nil
7512 "Alist with parameter names, derived from the `$' line.")
7513 (defvar org-table-named-field-locations nil
7514 "Alist with locations of named fields.")
7516 (defvar org-table-current-line-types nil
7517 "Table row types, non-nil only for the duration of a comand.")
7518 (defvar org-table-current-begin-line nil
7519 "Table begin line, non-nil only for the duration of a comand.")
7520 (defvar org-table-current-begin-pos nil
7521 "Table begin position, non-nil only for the duration of a comand.")
7522 (defvar org-table-dlines nil
7523 "Vector of data line line numbers in the current table.")
7524 (defvar org-table-hlines nil
7525 "Vector of hline line numbers in the current table.")
7527 (defconst org-table-range-regexp
7528 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7529 ;; 1 2 3 4 5
7530 "Regular expression for matching ranges in formulas.")
7532 (defconst org-table-range-regexp2
7533 (concat
7534 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7535 "\\.\\."
7536 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7537 "Match a range for reference display.")
7539 (defconst org-table-translate-regexp
7540 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7541 "Match a reference that needs translation, for reference display.")
7543 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7545 (defun org-table-create-with-table.el ()
7546 "Use the table.el package to insert a new table.
7547 If there is already a table at point, convert between Org-mode tables
7548 and table.el tables."
7549 (interactive)
7550 (require 'table)
7551 (cond
7552 ((org-at-table.el-p)
7553 (if (y-or-n-p "Convert table to Org-mode table? ")
7554 (org-table-convert)))
7555 ((org-at-table-p)
7556 (if (y-or-n-p "Convert table to table.el table? ")
7557 (org-table-convert)))
7558 (t (call-interactively 'table-insert))))
7560 (defun org-table-create-or-convert-from-region (arg)
7561 "Convert region to table, or create an empty table.
7562 If there is an active region, convert it to a table, using the function
7563 `org-table-convert-region'. See the documentation of that function
7564 to learn how the prefix argument is interpreted to determine the field
7565 separator.
7566 If there is no such region, create an empty table with `org-table-create'."
7567 (interactive "P")
7568 (if (org-region-active-p)
7569 (org-table-convert-region (region-beginning) (region-end) arg)
7570 (org-table-create arg)))
7572 (defun org-table-create (&optional size)
7573 "Query for a size and insert a table skeleton.
7574 SIZE is a string Columns x Rows like for example \"3x2\"."
7575 (interactive "P")
7576 (unless size
7577 (setq size (read-string
7578 (concat "Table size Columns x Rows [e.g. "
7579 org-table-default-size "]: ")
7580 "" nil org-table-default-size)))
7582 (let* ((pos (point))
7583 (indent (make-string (current-column) ?\ ))
7584 (split (org-split-string size " *x *"))
7585 (rows (string-to-number (nth 1 split)))
7586 (columns (string-to-number (car split)))
7587 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7588 "\n")))
7589 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7590 (point-at-bol) (point)))
7591 (beginning-of-line 1)
7592 (newline))
7593 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7594 (dotimes (i rows) (insert line))
7595 (goto-char pos)
7596 (if (> rows 1)
7597 ;; Insert a hline after the first row.
7598 (progn
7599 (end-of-line 1)
7600 (insert "\n|-")
7601 (goto-char pos)))
7602 (org-table-align)))
7604 (defun org-table-convert-region (beg0 end0 &optional separator)
7605 "Convert region to a table.
7606 The region goes from BEG0 to END0, but these borders will be moved
7607 slightly, to make sure a beginning of line in the first line is included.
7609 SEPARATOR specifies the field separator in the lines. It can have the
7610 following values:
7612 '(4) Use the comma as a field separator
7613 '(16) Use a TAB as field separator
7614 integer When a number, use that many spaces as field separator
7615 nil When nil, the command tries to be smart and figure out the
7616 separator in the following way:
7617 - when each line contains a TAB, assume TAB-separated material
7618 - when each line contains a comme, assume CSV material
7619 - else, assume one or more SPACE charcters as separator."
7620 (interactive "rP")
7621 (let* ((beg (min beg0 end0))
7622 (end (max beg0 end0))
7624 (goto-char beg)
7625 (beginning-of-line 1)
7626 (setq beg (move-marker (make-marker) (point)))
7627 (goto-char end)
7628 (if (bolp) (backward-char 1) (end-of-line 1))
7629 (setq end (move-marker (make-marker) (point)))
7630 ;; Get the right field separator
7631 (unless separator
7632 (goto-char beg)
7633 (setq separator
7634 (cond
7635 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7636 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7637 (t 1))))
7638 (setq re (cond
7639 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7640 ((equal separator '(16)) "^\\|\t")
7641 ((integerp separator)
7642 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7643 (t (error "This should not happen"))))
7644 (goto-char beg)
7645 (while (re-search-forward re end t)
7646 (replace-match "| " t t))
7647 (goto-char beg)
7648 (insert " ")
7649 (org-table-align)))
7651 (defun org-table-import (file arg)
7652 "Import FILE as a table.
7653 The file is assumed to be tab-separated. Such files can be produced by most
7654 spreadsheet and database applications. If no tabs (at least one per line)
7655 are found, lines will be split on whitespace into fields."
7656 (interactive "f\nP")
7657 (or (bolp) (newline))
7658 (let ((beg (point))
7659 (pm (point-max)))
7660 (insert-file-contents file)
7661 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7663 (defun org-table-export ()
7664 "Export table as a tab-separated file.
7665 Such a file can be imported into a spreadsheet program like Excel."
7666 (interactive)
7667 (let* ((beg (org-table-begin))
7668 (end (org-table-end))
7669 (table (buffer-substring beg end))
7670 (file (read-file-name "Export table to: "))
7671 buf)
7672 (unless (or (not (file-exists-p file))
7673 (y-or-n-p (format "Overwrite file %s? " file)))
7674 (error "Abort"))
7675 (with-current-buffer (find-file-noselect file)
7676 (setq buf (current-buffer))
7677 (erase-buffer)
7678 (fundamental-mode)
7679 (insert table)
7680 (goto-char (point-min))
7681 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7682 (replace-match "" t t)
7683 (end-of-line 1))
7684 (goto-char (point-min))
7685 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7686 (replace-match "" t t)
7687 (goto-char (min (1+ (point)) (point-max))))
7688 (goto-char (point-min))
7689 (while (re-search-forward "^-[-+]*$" nil t)
7690 (replace-match "")
7691 (if (looking-at "\n")
7692 (delete-char 1)))
7693 (goto-char (point-min))
7694 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7695 (replace-match "\t" t t))
7696 (save-buffer))
7697 (kill-buffer buf)))
7699 (defvar org-table-aligned-begin-marker (make-marker)
7700 "Marker at the beginning of the table last aligned.
7701 Used to check if cursor still is in that table, to minimize realignment.")
7702 (defvar org-table-aligned-end-marker (make-marker)
7703 "Marker at the end of the table last aligned.
7704 Used to check if cursor still is in that table, to minimize realignment.")
7705 (defvar org-table-last-alignment nil
7706 "List of flags for flushright alignment, from the last re-alignment.
7707 This is being used to correctly align a single field after TAB or RET.")
7708 (defvar org-table-last-column-widths nil
7709 "List of max width of fields in each column.
7710 This is being used to correctly align a single field after TAB or RET.")
7711 (defvar org-table-overlay-coordinates nil
7712 "Overlay coordinates after each align of a table.")
7713 (make-variable-buffer-local 'org-table-overlay-coordinates)
7715 (defvar org-last-recalc-line nil)
7716 (defconst org-narrow-column-arrow "=>"
7717 "Used as display property in narrowed table columns.")
7719 (defun org-table-align ()
7720 "Align the table at point by aligning all vertical bars."
7721 (interactive)
7722 (let* (
7723 ;; Limits of table
7724 (beg (org-table-begin))
7725 (end (org-table-end))
7726 ;; Current cursor position
7727 (linepos (org-current-line))
7728 (colpos (org-table-current-column))
7729 (winstart (window-start))
7730 (winstartline (org-current-line (min winstart (1- (point-max)))))
7731 lines (new "") lengths l typenums ty fields maxfields i
7732 column
7733 (indent "") cnt frac
7734 rfmt hfmt
7735 (spaces '(1 . 1))
7736 (sp1 (car spaces))
7737 (sp2 (cdr spaces))
7738 (rfmt1 (concat
7739 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7740 (hfmt1 (concat
7741 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7742 emptystrings links dates narrow fmax f1 len c e)
7743 (untabify beg end)
7744 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7745 ;; Check if we have links or dates
7746 (goto-char beg)
7747 (setq links (re-search-forward org-bracket-link-regexp end t))
7748 (goto-char beg)
7749 (setq dates (and org-display-custom-times
7750 (re-search-forward org-ts-regexp-both end t)))
7751 ;; Make sure the link properties are right
7752 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7753 ;; Make sure the date properties are right
7754 (when dates (goto-char beg) (while (org-activate-dates end)))
7756 ;; Check if we are narrowing any columns
7757 (goto-char beg)
7758 (setq narrow (and org-format-transports-properties-p
7759 (re-search-forward "<[0-9]+>" end t)))
7760 ;; Get the rows
7761 (setq lines (org-split-string
7762 (buffer-substring beg end) "\n"))
7763 ;; Store the indentation of the first line
7764 (if (string-match "^ *" (car lines))
7765 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7766 ;; Mark the hlines by setting the corresponding element to nil
7767 ;; At the same time, we remove trailing space.
7768 (setq lines (mapcar (lambda (l)
7769 (if (string-match "^ *|-" l)
7771 (if (string-match "[ \t]+$" l)
7772 (substring l 0 (match-beginning 0))
7773 l)))
7774 lines))
7775 ;; Get the data fields by splitting the lines.
7776 (setq fields (mapcar
7777 (lambda (l)
7778 (org-split-string l " *| *"))
7779 (delq nil (copy-sequence lines))))
7780 ;; How many fields in the longest line?
7781 (condition-case nil
7782 (setq maxfields (apply 'max (mapcar 'length fields)))
7783 (error
7784 (kill-region beg end)
7785 (org-table-create org-table-default-size)
7786 (error "Empty table - created default table")))
7787 ;; A list of empty strings to fill any short rows on output
7788 (setq emptystrings (make-list maxfields ""))
7789 ;; Check for special formatting.
7790 (setq i -1)
7791 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7792 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7793 ;; Check if there is an explicit width specified
7794 (when narrow
7795 (setq c column fmax nil)
7796 (while c
7797 (setq e (pop c))
7798 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7799 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7800 ;; Find fields that are wider than fmax, and shorten them
7801 (when fmax
7802 (loop for xx in column do
7803 (when (and (stringp xx)
7804 (> (org-string-width xx) fmax))
7805 (org-add-props xx nil
7806 'help-echo
7807 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7808 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7809 (unless (> f1 1)
7810 (error "Cannot narrow field starting with wide link \"%s\""
7811 (match-string 0 xx)))
7812 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7813 (add-text-properties (- f1 2) f1
7814 (list 'display org-narrow-column-arrow)
7815 xx)))))
7816 ;; Get the maximum width for each column
7817 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7818 ;; Get the fraction of numbers, to decide about alignment of the column
7819 (setq cnt 0 frac 0.0)
7820 (loop for x in column do
7821 (if (equal x "")
7823 (setq frac ( / (+ (* frac cnt)
7824 (if (string-match org-table-number-regexp x) 1 0))
7825 (setq cnt (1+ cnt))))))
7826 (push (>= frac org-table-number-fraction) typenums))
7827 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7829 ;; Store the alignment of this table, for later editing of single fields
7830 (setq org-table-last-alignment typenums
7831 org-table-last-column-widths lengths)
7833 ;; With invisible characters, `format' does not get the field width right
7834 ;; So we need to make these fields wide by hand.
7835 (when links
7836 (loop for i from 0 upto (1- maxfields) do
7837 (setq len (nth i lengths))
7838 (loop for j from 0 upto (1- (length fields)) do
7839 (setq c (nthcdr i (car (nthcdr j fields))))
7840 (if (and (stringp (car c))
7841 (string-match org-bracket-link-regexp (car c))
7842 (< (org-string-width (car c)) len))
7843 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7845 ;; Compute the formats needed for output of the table
7846 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7847 (while (setq l (pop lengths))
7848 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7849 (setq rfmt (concat rfmt (format rfmt1 ty l))
7850 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7851 (setq rfmt (concat rfmt "\n")
7852 hfmt (concat (substring hfmt 0 -1) "|\n"))
7854 (setq new (mapconcat
7855 (lambda (l)
7856 (if l (apply 'format rfmt
7857 (append (pop fields) emptystrings))
7858 hfmt))
7859 lines ""))
7860 ;; Replace the old one
7861 (delete-region beg end)
7862 (move-marker end nil)
7863 (move-marker org-table-aligned-begin-marker (point))
7864 (insert new)
7865 (move-marker org-table-aligned-end-marker (point))
7866 (when (and orgtbl-mode (not (org-mode-p)))
7867 (goto-char org-table-aligned-begin-marker)
7868 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7869 ;; Try to move to the old location
7870 (goto-line winstartline)
7871 (setq winstart (point-at-bol))
7872 (goto-line linepos)
7873 (set-window-start (selected-window) winstart 'noforce)
7874 (org-table-goto-column colpos)
7875 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7876 (setq org-table-may-need-update nil)
7879 (defun org-string-width (s)
7880 "Compute width of string, ignoring invisible characters.
7881 This ignores character with invisibility property `org-link', and also
7882 characters with property `org-cwidth', because these will become invisible
7883 upon the next fontification round."
7884 (let (b l)
7885 (when (or (eq t buffer-invisibility-spec)
7886 (assq 'org-link buffer-invisibility-spec))
7887 (while (setq b (text-property-any 0 (length s)
7888 'invisible 'org-link s))
7889 (setq s (concat (substring s 0 b)
7890 (substring s (or (next-single-property-change
7891 b 'invisible s) (length s)))))))
7892 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7893 (setq s (concat (substring s 0 b)
7894 (substring s (or (next-single-property-change
7895 b 'org-cwidth s) (length s))))))
7896 (setq l (string-width s) b -1)
7897 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7898 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7901 (defun org-table-begin (&optional table-type)
7902 "Find the beginning of the table and return its position.
7903 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7904 (save-excursion
7905 (if (not (re-search-backward
7906 (if table-type org-table-any-border-regexp
7907 org-table-border-regexp)
7908 nil t))
7909 (progn (goto-char (point-min)) (point))
7910 (goto-char (match-beginning 0))
7911 (beginning-of-line 2)
7912 (point))))
7914 (defun org-table-end (&optional table-type)
7915 "Find the end of the table and return its position.
7916 With argument TABLE-TYPE, go to the end of a table.el-type table."
7917 (save-excursion
7918 (if (not (re-search-forward
7919 (if table-type org-table-any-border-regexp
7920 org-table-border-regexp)
7921 nil t))
7922 (goto-char (point-max))
7923 (goto-char (match-beginning 0)))
7924 (point-marker)))
7926 (defun org-table-justify-field-maybe (&optional new)
7927 "Justify the current field, text to left, number to right.
7928 Optional argument NEW may specify text to replace the current field content."
7929 (cond
7930 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7931 ((org-at-table-hline-p))
7932 ((and (not new)
7933 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7934 (current-buffer)))
7935 (< (point) org-table-aligned-begin-marker)
7936 (>= (point) org-table-aligned-end-marker)))
7937 ;; This is not the same table, force a full re-align
7938 (setq org-table-may-need-update t))
7939 (t ;; realign the current field, based on previous full realign
7940 (let* ((pos (point)) s
7941 (col (org-table-current-column))
7942 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7943 l f n o e)
7944 (when (> col 0)
7945 (skip-chars-backward "^|\n")
7946 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7947 (progn
7948 (setq s (match-string 1)
7949 o (match-string 0)
7950 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7951 e (not (= (match-beginning 2) (match-end 2))))
7952 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7953 l (if e "|" (setq org-table-may-need-update t) ""))
7954 n (format f s))
7955 (if new
7956 (if (<= (length new) l) ;; FIXME: length -> str-width?
7957 (setq n (format f new))
7958 (setq n (concat new "|") org-table-may-need-update t)))
7959 (or (equal n o)
7960 (let (org-table-may-need-update)
7961 (replace-match n t t))))
7962 (setq org-table-may-need-update t))
7963 (goto-char pos))))))
7965 (defun org-table-next-field ()
7966 "Go to the next field in the current table, creating new lines as needed.
7967 Before doing so, re-align the table if necessary."
7968 (interactive)
7969 (org-table-maybe-eval-formula)
7970 (org-table-maybe-recalculate-line)
7971 (if (and org-table-automatic-realign
7972 org-table-may-need-update)
7973 (org-table-align))
7974 (let ((end (org-table-end)))
7975 (if (org-at-table-hline-p)
7976 (end-of-line 1))
7977 (condition-case nil
7978 (progn
7979 (re-search-forward "|" end)
7980 (if (looking-at "[ \t]*$")
7981 (re-search-forward "|" end))
7982 (if (and (looking-at "-")
7983 org-table-tab-jumps-over-hlines
7984 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7985 (goto-char (match-beginning 1)))
7986 (if (looking-at "-")
7987 (progn
7988 (beginning-of-line 0)
7989 (org-table-insert-row 'below))
7990 (if (looking-at " ") (forward-char 1))))
7991 (error
7992 (org-table-insert-row 'below)))))
7994 (defun org-table-previous-field ()
7995 "Go to the previous field in the table.
7996 Before doing so, re-align the table if necessary."
7997 (interactive)
7998 (org-table-justify-field-maybe)
7999 (org-table-maybe-recalculate-line)
8000 (if (and org-table-automatic-realign
8001 org-table-may-need-update)
8002 (org-table-align))
8003 (if (org-at-table-hline-p)
8004 (end-of-line 1))
8005 (re-search-backward "|" (org-table-begin))
8006 (re-search-backward "|" (org-table-begin))
8007 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8008 (re-search-backward "|" (org-table-begin)))
8009 (if (looking-at "| ?")
8010 (goto-char (match-end 0))))
8012 (defun org-table-next-row ()
8013 "Go to the next row (same column) in the current table.
8014 Before doing so, re-align the table if necessary."
8015 (interactive)
8016 (org-table-maybe-eval-formula)
8017 (org-table-maybe-recalculate-line)
8018 (if (or (looking-at "[ \t]*$")
8019 (save-excursion (skip-chars-backward " \t") (bolp)))
8020 (newline)
8021 (if (and org-table-automatic-realign
8022 org-table-may-need-update)
8023 (org-table-align))
8024 (let ((col (org-table-current-column)))
8025 (beginning-of-line 2)
8026 (if (or (not (org-at-table-p))
8027 (org-at-table-hline-p))
8028 (progn
8029 (beginning-of-line 0)
8030 (org-table-insert-row 'below)))
8031 (org-table-goto-column col)
8032 (skip-chars-backward "^|\n\r")
8033 (if (looking-at " ") (forward-char 1)))))
8035 (defun org-table-copy-down (n)
8036 "Copy a field down in the current column.
8037 If the field at the cursor is empty, copy into it the content of the nearest
8038 non-empty field above. With argument N, use the Nth non-empty field.
8039 If the current field is not empty, it is copied down to the next row, and
8040 the cursor is moved with it. Therefore, repeating this command causes the
8041 column to be filled row-by-row.
8042 If the variable `org-table-copy-increment' is non-nil and the field is an
8043 integer or a timestamp, it will be incremented while copying. In the case of
8044 a timestamp, if the cursor is on the year, change the year. If it is on the
8045 month or the day, change that. Point will stay on the current date field
8046 in order to easily repeat the interval."
8047 (interactive "p")
8048 (let* ((colpos (org-table-current-column))
8049 (col (current-column))
8050 (field (org-table-get-field))
8051 (non-empty (string-match "[^ \t]" field))
8052 (beg (org-table-begin))
8053 txt)
8054 (org-table-check-inside-data-field)
8055 (if non-empty
8056 (progn
8057 (setq txt (org-trim field))
8058 (org-table-next-row)
8059 (org-table-blank-field))
8060 (save-excursion
8061 (setq txt
8062 (catch 'exit
8063 (while (progn (beginning-of-line 1)
8064 (re-search-backward org-table-dataline-regexp
8065 beg t))
8066 (org-table-goto-column colpos t)
8067 (if (and (looking-at
8068 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8069 (= (setq n (1- n)) 0))
8070 (throw 'exit (match-string 1))))))))
8071 (if txt
8072 (progn
8073 (if (and org-table-copy-increment
8074 (string-match "^[0-9]+$" txt))
8075 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8076 (insert txt)
8077 (move-to-column col)
8078 (if (and org-table-copy-increment (org-at-timestamp-p t))
8079 (org-timestamp-up 1)
8080 (org-table-maybe-recalculate-line))
8081 (org-table-align)
8082 (move-to-column col))
8083 (error "No non-empty field found"))))
8085 (defun org-table-check-inside-data-field ()
8086 "Is point inside a table data field?
8087 I.e. not on a hline or before the first or after the last column?
8088 This actually throws an error, so it aborts the current command."
8089 (if (or (not (org-at-table-p))
8090 (= (org-table-current-column) 0)
8091 (org-at-table-hline-p)
8092 (looking-at "[ \t]*$"))
8093 (error "Not in table data field")))
8095 (defvar org-table-clip nil
8096 "Clipboard for table regions.")
8098 (defun org-table-blank-field ()
8099 "Blank the current table field or active region."
8100 (interactive)
8101 (org-table-check-inside-data-field)
8102 (if (and (interactive-p) (org-region-active-p))
8103 (let (org-table-clip)
8104 (org-table-cut-region (region-beginning) (region-end)))
8105 (skip-chars-backward "^|")
8106 (backward-char 1)
8107 (if (looking-at "|[^|\n]+")
8108 (let* ((pos (match-beginning 0))
8109 (match (match-string 0))
8110 (len (org-string-width match)))
8111 (replace-match (concat "|" (make-string (1- len) ?\ )))
8112 (goto-char (+ 2 pos))
8113 (substring match 1)))))
8115 (defun org-table-get-field (&optional n replace)
8116 "Return the value of the field in column N of current row.
8117 N defaults to current field.
8118 If REPLACE is a string, replace field with this value. The return value
8119 is always the old value."
8120 (and n (org-table-goto-column n))
8121 (skip-chars-backward "^|\n")
8122 (backward-char 1)
8123 (if (looking-at "|[^|\r\n]*")
8124 (let* ((pos (match-beginning 0))
8125 (val (buffer-substring (1+ pos) (match-end 0))))
8126 (if replace
8127 (replace-match (concat "|" replace) t t))
8128 (goto-char (min (point-at-eol) (+ 2 pos)))
8129 val)
8130 (forward-char 1) ""))
8132 (defun org-table-field-info (arg)
8133 "Show info about the current field, and highlight any reference at point."
8134 (interactive "P")
8135 (org-table-get-specials)
8136 (save-excursion
8137 (let* ((pos (point))
8138 (col (org-table-current-column))
8139 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8140 (name (car (rassoc (list (org-current-line) col)
8141 org-table-named-field-locations)))
8142 (eql (org-table-get-stored-formulas))
8143 (dline (org-table-current-dline))
8144 (ref (format "@%d$%d" dline col))
8145 (ref1 (org-table-convert-refs-to-an ref))
8146 (fequation (or (assoc name eql) (assoc ref eql)))
8147 (cequation (assoc (int-to-string col) eql))
8148 (eqn (or fequation cequation)))
8149 (goto-char pos)
8150 (condition-case nil
8151 (org-table-show-reference 'local)
8152 (error nil))
8153 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8154 dline col
8155 (if cname (concat " or $" cname) "")
8156 dline col ref1
8157 (if name (concat " or $" name) "")
8158 ;; FIXME: formula info not correct if special table line
8159 (if eqn
8160 (concat ", formula: "
8161 (org-table-formula-to-user
8162 (concat
8163 (if (string-match "^[$@]"(car eqn)) "" "$")
8164 (car eqn) "=" (cdr eqn))))
8165 "")))))
8167 (defun org-table-current-column ()
8168 "Find out which column we are in.
8169 When called interactively, column is also displayed in echo area."
8170 (interactive)
8171 (if (interactive-p) (org-table-check-inside-data-field))
8172 (save-excursion
8173 (let ((cnt 0) (pos (point)))
8174 (beginning-of-line 1)
8175 (while (search-forward "|" pos t)
8176 (setq cnt (1+ cnt)))
8177 (if (interactive-p) (message "This is table column %d" cnt))
8178 cnt)))
8180 (defun org-table-current-dline ()
8181 "Find out what table data line we are in.
8182 Only datalins count for this."
8183 (interactive)
8184 (if (interactive-p) (org-table-check-inside-data-field))
8185 (save-excursion
8186 (let ((cnt 0) (pos (point)))
8187 (goto-char (org-table-begin))
8188 (while (<= (point) pos)
8189 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8190 (beginning-of-line 2))
8191 (if (interactive-p) (message "This is table line %d" cnt))
8192 cnt)))
8194 (defun org-table-goto-column (n &optional on-delim force)
8195 "Move the cursor to the Nth column in the current table line.
8196 With optional argument ON-DELIM, stop with point before the left delimiter
8197 of the field.
8198 If there are less than N fields, just go to after the last delimiter.
8199 However, when FORCE is non-nil, create new columns if necessary."
8200 (interactive "p")
8201 (let ((pos (point-at-eol)))
8202 (beginning-of-line 1)
8203 (when (> n 0)
8204 (while (and (> (setq n (1- n)) -1)
8205 (or (search-forward "|" pos t)
8206 (and force
8207 (progn (end-of-line 1)
8208 (skip-chars-backward "^|")
8209 (insert " | "))))))
8210 ; (backward-char 2) t)))))
8211 (when (and force (not (looking-at ".*|")))
8212 (save-excursion (end-of-line 1) (insert " | ")))
8213 (if on-delim
8214 (backward-char 1)
8215 (if (looking-at " ") (forward-char 1))))))
8217 (defun org-at-table-p (&optional table-type)
8218 "Return t if the cursor is inside an org-type table.
8219 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8220 (if org-enable-table-editor
8221 (save-excursion
8222 (beginning-of-line 1)
8223 (looking-at (if table-type org-table-any-line-regexp
8224 org-table-line-regexp)))
8225 nil))
8227 (defun org-at-table.el-p ()
8228 "Return t if and only if we are at a table.el table."
8229 (and (org-at-table-p 'any)
8230 (save-excursion
8231 (goto-char (org-table-begin 'any))
8232 (looking-at org-table1-hline-regexp))))
8234 (defun org-table-recognize-table.el ()
8235 "If there is a table.el table nearby, recognize it and move into it."
8236 (if org-table-tab-recognizes-table.el
8237 (if (org-at-table.el-p)
8238 (progn
8239 (beginning-of-line 1)
8240 (if (looking-at org-table-dataline-regexp)
8242 (if (looking-at org-table1-hline-regexp)
8243 (progn
8244 (beginning-of-line 2)
8245 (if (looking-at org-table-any-border-regexp)
8246 (beginning-of-line -1)))))
8247 (if (re-search-forward "|" (org-table-end t) t)
8248 (progn
8249 (require 'table)
8250 (if (table--at-cell-p (point))
8252 (message "recognizing table.el table...")
8253 (table-recognize-table)
8254 (message "recognizing table.el table...done")))
8255 (error "This should not happen..."))
8257 nil)
8258 nil))
8260 (defun org-at-table-hline-p ()
8261 "Return t if the cursor is inside a hline in a table."
8262 (if org-enable-table-editor
8263 (save-excursion
8264 (beginning-of-line 1)
8265 (looking-at org-table-hline-regexp))
8266 nil))
8268 (defun org-table-insert-column ()
8269 "Insert a new column into the table."
8270 (interactive)
8271 (if (not (org-at-table-p))
8272 (error "Not at a table"))
8273 (org-table-find-dataline)
8274 (let* ((col (max 1 (org-table-current-column)))
8275 (beg (org-table-begin))
8276 (end (org-table-end))
8277 ;; Current cursor position
8278 (linepos (org-current-line))
8279 (colpos col))
8280 (goto-char beg)
8281 (while (< (point) end)
8282 (if (org-at-table-hline-p)
8284 (org-table-goto-column col t)
8285 (insert "| "))
8286 (beginning-of-line 2))
8287 (move-marker end nil)
8288 (goto-line linepos)
8289 (org-table-goto-column colpos)
8290 (org-table-align)
8291 (org-table-fix-formulas "$" nil (1- col) 1)))
8293 (defun org-table-find-dataline ()
8294 "Find a dataline in the current table, which is needed for column commands."
8295 (if (and (org-at-table-p)
8296 (not (org-at-table-hline-p)))
8298 (let ((col (current-column))
8299 (end (org-table-end)))
8300 (move-to-column col)
8301 (while (and (< (point) end)
8302 (or (not (= (current-column) col))
8303 (org-at-table-hline-p)))
8304 (beginning-of-line 2)
8305 (move-to-column col))
8306 (if (and (org-at-table-p)
8307 (not (org-at-table-hline-p)))
8309 (error
8310 "Please position cursor in a data line for column operations")))))
8312 (defun org-table-delete-column ()
8313 "Delete a column from the table."
8314 (interactive)
8315 (if (not (org-at-table-p))
8316 (error "Not at a table"))
8317 (org-table-find-dataline)
8318 (org-table-check-inside-data-field)
8319 (let* ((col (org-table-current-column))
8320 (beg (org-table-begin))
8321 (end (org-table-end))
8322 ;; Current cursor position
8323 (linepos (org-current-line))
8324 (colpos col))
8325 (goto-char beg)
8326 (while (< (point) end)
8327 (if (org-at-table-hline-p)
8329 (org-table-goto-column col t)
8330 (and (looking-at "|[^|\n]+|")
8331 (replace-match "|")))
8332 (beginning-of-line 2))
8333 (move-marker end nil)
8334 (goto-line linepos)
8335 (org-table-goto-column colpos)
8336 (org-table-align)
8337 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8338 col -1 col)))
8340 (defun org-table-move-column-right ()
8341 "Move column to the right."
8342 (interactive)
8343 (org-table-move-column nil))
8344 (defun org-table-move-column-left ()
8345 "Move column to the left."
8346 (interactive)
8347 (org-table-move-column 'left))
8349 (defun org-table-move-column (&optional left)
8350 "Move the current column to the right. With arg LEFT, move to the left."
8351 (interactive "P")
8352 (if (not (org-at-table-p))
8353 (error "Not at a table"))
8354 (org-table-find-dataline)
8355 (org-table-check-inside-data-field)
8356 (let* ((col (org-table-current-column))
8357 (col1 (if left (1- col) col))
8358 (beg (org-table-begin))
8359 (end (org-table-end))
8360 ;; Current cursor position
8361 (linepos (org-current-line))
8362 (colpos (if left (1- col) (1+ col))))
8363 (if (and left (= col 1))
8364 (error "Cannot move column further left"))
8365 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8366 (error "Cannot move column further right"))
8367 (goto-char beg)
8368 (while (< (point) end)
8369 (if (org-at-table-hline-p)
8371 (org-table-goto-column col1 t)
8372 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8373 (replace-match "|\\2|\\1|")))
8374 (beginning-of-line 2))
8375 (move-marker end nil)
8376 (goto-line linepos)
8377 (org-table-goto-column colpos)
8378 (org-table-align)
8379 (org-table-fix-formulas
8380 "$" (list (cons (number-to-string col) (number-to-string colpos))
8381 (cons (number-to-string colpos) (number-to-string col))))))
8383 (defun org-table-move-row-down ()
8384 "Move table row down."
8385 (interactive)
8386 (org-table-move-row nil))
8387 (defun org-table-move-row-up ()
8388 "Move table row up."
8389 (interactive)
8390 (org-table-move-row 'up))
8392 (defun org-table-move-row (&optional up)
8393 "Move the current table line down. With arg UP, move it up."
8394 (interactive "P")
8395 (let* ((col (current-column))
8396 (pos (point))
8397 (hline1p (save-excursion (beginning-of-line 1)
8398 (looking-at org-table-hline-regexp)))
8399 (dline1 (org-table-current-dline))
8400 (dline2 (+ dline1 (if up -1 1)))
8401 (tonew (if up 0 2))
8402 txt hline2p)
8403 (beginning-of-line tonew)
8404 (unless (org-at-table-p)
8405 (goto-char pos)
8406 (error "Cannot move row further"))
8407 (setq hline2p (looking-at org-table-hline-regexp))
8408 (goto-char pos)
8409 (beginning-of-line 1)
8410 (setq pos (point))
8411 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8412 (delete-region (point) (1+ (point-at-eol)))
8413 (beginning-of-line tonew)
8414 (insert txt)
8415 (beginning-of-line 0)
8416 (move-to-column col)
8417 (unless (or hline1p hline2p)
8418 (org-table-fix-formulas
8419 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8420 (cons (number-to-string dline2) (number-to-string dline1)))))))
8422 (defun org-table-insert-row (&optional arg)
8423 "Insert a new row above the current line into the table.
8424 With prefix ARG, insert below the current line."
8425 (interactive "P")
8426 (if (not (org-at-table-p))
8427 (error "Not at a table"))
8428 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8429 (new (org-table-clean-line line)))
8430 ;; Fix the first field if necessary
8431 (if (string-match "^[ \t]*| *[#$] *|" line)
8432 (setq new (replace-match (match-string 0 line) t t new)))
8433 (beginning-of-line (if arg 2 1))
8434 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8435 (beginning-of-line 0)
8436 (re-search-forward "| ?" (point-at-eol) t)
8437 (and (or org-table-may-need-update org-table-overlay-coordinates)
8438 (org-table-align))
8439 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8441 (defun org-table-insert-hline (&optional above)
8442 "Insert a horizontal-line below the current line into the table.
8443 With prefix ABOVE, insert above the current line."
8444 (interactive "P")
8445 (if (not (org-at-table-p))
8446 (error "Not at a table"))
8447 (let ((line (org-table-clean-line
8448 (buffer-substring (point-at-bol) (point-at-eol))))
8449 (col (current-column)))
8450 (while (string-match "|\\( +\\)|" line)
8451 (setq line (replace-match
8452 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8453 ?-) "|") t t line)))
8454 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8455 (beginning-of-line (if above 1 2))
8456 (insert line "\n")
8457 (beginning-of-line (if above 1 -1))
8458 (move-to-column col)
8459 (and org-table-overlay-coordinates (org-table-align))))
8461 (defun org-table-hline-and-move (&optional same-column)
8462 "Insert a hline and move to the row below that line."
8463 (interactive "P")
8464 (let ((col (org-table-current-column)))
8465 (org-table-maybe-eval-formula)
8466 (org-table-maybe-recalculate-line)
8467 (org-table-insert-hline)
8468 (end-of-line 2)
8469 (if (looking-at "\n[ \t]*|-")
8470 (progn (insert "\n|") (org-table-align))
8471 (org-table-next-field))
8472 (if same-column (org-table-goto-column col))))
8474 (defun org-table-clean-line (s)
8475 "Convert a table line S into a string with only \"|\" and space.
8476 In particular, this does handle wide and invisible characters."
8477 (if (string-match "^[ \t]*|-" s)
8478 ;; It's a hline, just map the characters
8479 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8480 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8481 (setq s (replace-match
8482 (concat "|" (make-string (org-string-width (match-string 1 s))
8483 ?\ ) "|")
8484 t t s)))
8487 (defun org-table-kill-row ()
8488 "Delete the current row or horizontal line from the table."
8489 (interactive)
8490 (if (not (org-at-table-p))
8491 (error "Not at a table"))
8492 (let ((col (current-column))
8493 (dline (org-table-current-dline)))
8494 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8495 (if (not (org-at-table-p)) (beginning-of-line 0))
8496 (move-to-column col)
8497 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8498 dline -1 dline)))
8500 (defun org-table-sort-lines (with-case &optional sorting-type)
8501 "Sort table lines according to the column at point.
8503 The position of point indicates the column to be used for
8504 sorting, and the range of lines is the range between the nearest
8505 horizontal separator lines, or the entire table of no such lines
8506 exist. If point is before the first column, you will be prompted
8507 for the sorting column. If there is an active region, the mark
8508 specifies the first line and the sorting column, while point
8509 should be in the last line to be included into the sorting.
8511 The command then prompts for the sorting type which can be
8512 alphabetically, numerically, or by time (as given in a time stamp
8513 in the field). Sorting in reverse order is also possible.
8515 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8517 If SORTING-TYPE is specified when this function is called from a Lisp
8518 program, no prompting will take place. SORTING-TYPE must be a character,
8519 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8520 should be done in reverse order."
8521 (interactive "P")
8522 (let* ((thisline (org-current-line))
8523 (thiscol (org-table-current-column))
8524 beg end bcol ecol tend tbeg column lns pos)
8525 (when (equal thiscol 0)
8526 (if (interactive-p)
8527 (setq thiscol
8528 (string-to-number
8529 (read-string "Use column N for sorting: ")))
8530 (setq thiscol 1))
8531 (org-table-goto-column thiscol))
8532 (org-table-check-inside-data-field)
8533 (if (org-region-active-p)
8534 (progn
8535 (setq beg (region-beginning) end (region-end))
8536 (goto-char beg)
8537 (setq column (org-table-current-column)
8538 beg (point-at-bol))
8539 (goto-char end)
8540 (setq end (point-at-bol 2)))
8541 (setq column (org-table-current-column)
8542 pos (point)
8543 tbeg (org-table-begin)
8544 tend (org-table-end))
8545 (if (re-search-backward org-table-hline-regexp tbeg t)
8546 (setq beg (point-at-bol 2))
8547 (goto-char tbeg)
8548 (setq beg (point-at-bol 1)))
8549 (goto-char pos)
8550 (if (re-search-forward org-table-hline-regexp tend t)
8551 (setq end (point-at-bol 1))
8552 (goto-char tend)
8553 (setq end (point-at-bol))))
8554 (setq beg (move-marker (make-marker) beg)
8555 end (move-marker (make-marker) end))
8556 (untabify beg end)
8557 (goto-char beg)
8558 (org-table-goto-column column)
8559 (skip-chars-backward "^|")
8560 (setq bcol (current-column))
8561 (org-table-goto-column (1+ column))
8562 (skip-chars-backward "^|")
8563 (setq ecol (1- (current-column)))
8564 (org-table-goto-column column)
8565 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8566 (org-split-string (buffer-substring beg end) "\n")))
8567 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8568 (delete-region beg end)
8569 (move-marker beg nil)
8570 (move-marker end nil)
8571 (insert (mapconcat 'cdr lns "\n") "\n")
8572 (goto-line thisline)
8573 (org-table-goto-column thiscol)
8574 (message "%d lines sorted, based on column %d" (length lns) column)))
8576 (defun org-table-cut-region (beg end)
8577 "Copy region in table to the clipboard and blank all relevant fields."
8578 (interactive "r")
8579 (org-table-copy-region beg end 'cut))
8581 (defun org-table-copy-region (beg end &optional cut)
8582 "Copy rectangular region in table to clipboard.
8583 A special clipboard is used which can only be accessed
8584 with `org-table-paste-rectangle'."
8585 (interactive "rP")
8586 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8587 region cols
8588 (rpl (if cut " " nil)))
8589 (goto-char beg)
8590 (org-table-check-inside-data-field)
8591 (setq l01 (org-current-line)
8592 c01 (org-table-current-column))
8593 (goto-char end)
8594 (org-table-check-inside-data-field)
8595 (setq l02 (org-current-line)
8596 c02 (org-table-current-column))
8597 (setq l1 (min l01 l02) l2 (max l01 l02)
8598 c1 (min c01 c02) c2 (max c01 c02))
8599 (catch 'exit
8600 (while t
8601 (catch 'nextline
8602 (if (> l1 l2) (throw 'exit t))
8603 (goto-line l1)
8604 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8605 (setq cols nil ic1 c1 ic2 c2)
8606 (while (< ic1 (1+ ic2))
8607 (push (org-table-get-field ic1 rpl) cols)
8608 (setq ic1 (1+ ic1)))
8609 (push (nreverse cols) region)
8610 (setq l1 (1+ l1)))))
8611 (setq org-table-clip (nreverse region))
8612 (if cut (org-table-align))
8613 org-table-clip))
8615 (defun org-table-paste-rectangle ()
8616 "Paste a rectangular region into a table.
8617 The upper right corner ends up in the current field. All involved fields
8618 will be overwritten. If the rectangle does not fit into the present table,
8619 the table is enlarged as needed. The process ignores horizontal separator
8620 lines."
8621 (interactive)
8622 (unless (and org-table-clip (listp org-table-clip))
8623 (error "First cut/copy a region to paste!"))
8624 (org-table-check-inside-data-field)
8625 (let* ((clip org-table-clip)
8626 (line (org-current-line))
8627 (col (org-table-current-column))
8628 (org-enable-table-editor t)
8629 (org-table-automatic-realign nil)
8630 c cols field)
8631 (while (setq cols (pop clip))
8632 (while (org-at-table-hline-p) (beginning-of-line 2))
8633 (if (not (org-at-table-p))
8634 (progn (end-of-line 0) (org-table-next-field)))
8635 (setq c col)
8636 (while (setq field (pop cols))
8637 (org-table-goto-column c nil 'force)
8638 (org-table-get-field nil field)
8639 (setq c (1+ c)))
8640 (beginning-of-line 2))
8641 (goto-line line)
8642 (org-table-goto-column col)
8643 (org-table-align)))
8645 (defun org-table-convert ()
8646 "Convert from `org-mode' table to table.el and back.
8647 Obviously, this only works within limits. When an Org-mode table is
8648 converted to table.el, all horizontal separator lines get lost, because
8649 table.el uses these as cell boundaries and has no notion of horizontal lines.
8650 A table.el table can be converted to an Org-mode table only if it does not
8651 do row or column spanning. Multiline cells will become multiple cells.
8652 Beware, Org-mode does not test if the table can be successfully converted - it
8653 blindly applies a recipe that works for simple tables."
8654 (interactive)
8655 (require 'table)
8656 (if (org-at-table.el-p)
8657 ;; convert to Org-mode table
8658 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8659 (end (move-marker (make-marker) (org-table-end t))))
8660 (table-unrecognize-region beg end)
8661 (goto-char beg)
8662 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8663 (replace-match ""))
8664 (goto-char beg))
8665 (if (org-at-table-p)
8666 ;; convert to table.el table
8667 (let ((beg (move-marker (make-marker) (org-table-begin)))
8668 (end (move-marker (make-marker) (org-table-end))))
8669 ;; first, get rid of all horizontal lines
8670 (goto-char beg)
8671 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8672 (replace-match ""))
8673 ;; insert a hline before first
8674 (goto-char beg)
8675 (org-table-insert-hline 'above)
8676 (beginning-of-line -1)
8677 ;; insert a hline after each line
8678 (while (progn (beginning-of-line 3) (< (point) end))
8679 (org-table-insert-hline))
8680 (goto-char beg)
8681 (setq end (move-marker end (org-table-end)))
8682 ;; replace "+" at beginning and ending of hlines
8683 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8684 (replace-match "\\1+-"))
8685 (goto-char beg)
8686 (while (re-search-forward "-|[ \t]*$" end t)
8687 (replace-match "-+"))
8688 (goto-char beg)))))
8690 (defun org-table-wrap-region (arg)
8691 "Wrap several fields in a column like a paragraph.
8692 This is useful if you'd like to spread the contents of a field over several
8693 lines, in order to keep the table compact.
8695 If there is an active region, and both point and mark are in the same column,
8696 the text in the column is wrapped to minimum width for the given number of
8697 lines. Generally, this makes the table more compact. A prefix ARG may be
8698 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8699 formats the selected text to two lines. If the region was longer than two
8700 lines, the remaining lines remain empty. A negative prefix argument reduces
8701 the current number of lines by that amount. The wrapped text is pasted back
8702 into the table. If you formatted it to more lines than it was before, fields
8703 further down in the table get overwritten - so you might need to make space in
8704 the table first.
8706 If there is no region, the current field is split at the cursor position and
8707 the text fragment to the right of the cursor is prepended to the field one
8708 line down.
8710 If there is no region, but you specify a prefix ARG, the current field gets
8711 blank, and the content is appended to the field above."
8712 (interactive "P")
8713 (org-table-check-inside-data-field)
8714 (if (org-region-active-p)
8715 ;; There is a region: fill as a paragraph
8716 (let* ((beg (region-beginning))
8717 (cline (save-excursion (goto-char beg) (org-current-line)))
8718 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8719 nlines)
8720 (org-table-cut-region (region-beginning) (region-end))
8721 (if (> (length (car org-table-clip)) 1)
8722 (error "Region must be limited to single column"))
8723 (setq nlines (if arg
8724 (if (< arg 1)
8725 (+ (length org-table-clip) arg)
8726 arg)
8727 (length org-table-clip)))
8728 (setq org-table-clip
8729 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8730 nil nlines)))
8731 (goto-line cline)
8732 (org-table-goto-column ccol)
8733 (org-table-paste-rectangle))
8734 ;; No region, split the current field at point
8735 (if arg
8736 ;; combine with field above
8737 (let ((s (org-table-blank-field))
8738 (col (org-table-current-column)))
8739 (beginning-of-line 0)
8740 (while (org-at-table-hline-p) (beginning-of-line 0))
8741 (org-table-goto-column col)
8742 (skip-chars-forward "^|")
8743 (skip-chars-backward " ")
8744 (insert " " (org-trim s))
8745 (org-table-align))
8746 ;; split field
8747 (when (looking-at "\\([^|]+\\)+|")
8748 (let ((s (match-string 1)))
8749 (replace-match " |")
8750 (goto-char (match-beginning 0))
8751 (org-table-next-row)
8752 (insert (org-trim s) " ")
8753 (org-table-align))))))
8755 (defvar org-field-marker nil)
8757 (defun org-table-edit-field (arg)
8758 "Edit table field in a different window.
8759 This is mainly useful for fields that contain hidden parts.
8760 When called with a \\[universal-argument] prefix, just make the full field visible so that
8761 it can be edited in place."
8762 (interactive "P")
8763 (if arg
8764 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8765 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8766 (remove-text-properties b e '(org-cwidth t invisible t
8767 display t intangible t))
8768 (if (and (boundp 'font-lock-mode) font-lock-mode)
8769 (font-lock-fontify-block)))
8770 (let ((pos (move-marker (make-marker) (point)))
8771 (field (org-table-get-field))
8772 (cw (current-window-configuration))
8774 (org-switch-to-buffer-other-window "*Org tmp*")
8775 (erase-buffer)
8776 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8777 (let ((org-inhibit-startup t)) (org-mode))
8778 (goto-char (setq p (point-max)))
8779 (insert (org-trim field))
8780 (remove-text-properties p (point-max)
8781 '(invisible t org-cwidth t display t
8782 intangible t))
8783 (goto-char p)
8784 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8785 (org-set-local 'org-window-configuration cw)
8786 (org-set-local 'org-field-marker pos)
8787 (message "Edit and finish with C-c C-c"))))
8789 (defun org-table-finish-edit-field ()
8790 "Finish editing a table data field.
8791 Remove all newline characters, insert the result into the table, realign
8792 the table and kill the editing buffer."
8793 (let ((pos org-field-marker)
8794 (cw org-window-configuration)
8795 (cb (current-buffer))
8796 text)
8797 (goto-char (point-min))
8798 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8799 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8800 (replace-match " "))
8801 (setq text (org-trim (buffer-string)))
8802 (set-window-configuration cw)
8803 (kill-buffer cb)
8804 (select-window (get-buffer-window (marker-buffer pos)))
8805 (goto-char pos)
8806 (move-marker pos nil)
8807 (org-table-check-inside-data-field)
8808 (org-table-get-field nil text)
8809 (org-table-align)
8810 (message "New field value inserted")))
8812 (defun org-trim (s)
8813 "Remove whitespace at beginning and end of string."
8814 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8815 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8818 (defun org-wrap (string &optional width lines)
8819 "Wrap string to either a number of lines, or a width in characters.
8820 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8821 that costs. If there is a word longer than WIDTH, the text is actually
8822 wrapped to the length of that word.
8823 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8824 many lines, whatever width that takes.
8825 The return value is a list of lines, without newlines at the end."
8826 (let* ((words (org-split-string string "[ \t\n]+"))
8827 (maxword (apply 'max (mapcar 'org-string-width words)))
8828 w ll)
8829 (cond (width
8830 (org-do-wrap words (max maxword width)))
8831 (lines
8832 (setq w maxword)
8833 (setq ll (org-do-wrap words maxword))
8834 (if (<= (length ll) lines)
8836 (setq ll words)
8837 (while (> (length ll) lines)
8838 (setq w (1+ w))
8839 (setq ll (org-do-wrap words w)))
8840 ll))
8841 (t (error "Cannot wrap this")))))
8844 (defun org-do-wrap (words width)
8845 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8846 (let (lines line)
8847 (while words
8848 (setq line (pop words))
8849 (while (and words (< (+ (length line) (length (car words))) width))
8850 (setq line (concat line " " (pop words))))
8851 (setq lines (push line lines)))
8852 (nreverse lines)))
8854 (defun org-split-string (string &optional separators)
8855 "Splits STRING into substrings at SEPARATORS.
8856 No empty strings are returned if there are matches at the beginning
8857 and end of string."
8858 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8859 (start 0)
8860 notfirst
8861 (list nil))
8862 (while (and (string-match rexp string
8863 (if (and notfirst
8864 (= start (match-beginning 0))
8865 (< start (length string)))
8866 (1+ start) start))
8867 (< (match-beginning 0) (length string)))
8868 (setq notfirst t)
8869 (or (eq (match-beginning 0) 0)
8870 (and (eq (match-beginning 0) (match-end 0))
8871 (eq (match-beginning 0) start))
8872 (setq list
8873 (cons (substring string start (match-beginning 0))
8874 list)))
8875 (setq start (match-end 0)))
8876 (or (eq start (length string))
8877 (setq list
8878 (cons (substring string start)
8879 list)))
8880 (nreverse list)))
8882 (defun org-table-map-tables (function)
8883 "Apply FUNCTION to the start of all tables in the buffer."
8884 (save-excursion
8885 (save-restriction
8886 (widen)
8887 (goto-char (point-min))
8888 (while (re-search-forward org-table-any-line-regexp nil t)
8889 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8890 (beginning-of-line 1)
8891 (if (looking-at org-table-line-regexp)
8892 (save-excursion (funcall function)))
8893 (re-search-forward org-table-any-border-regexp nil 1))))
8894 (message "Mapping tables: done"))
8896 (defvar org-timecnt) ; dynamically scoped parameter
8898 (defun org-table-sum (&optional beg end nlast)
8899 "Sum numbers in region of current table column.
8900 The result will be displayed in the echo area, and will be available
8901 as kill to be inserted with \\[yank].
8903 If there is an active region, it is interpreted as a rectangle and all
8904 numbers in that rectangle will be summed. If there is no active
8905 region and point is located in a table column, sum all numbers in that
8906 column.
8908 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8909 numbers are assumed to be times as well (in decimal hours) and the
8910 numbers are added as such.
8912 If NLAST is a number, only the NLAST fields will actually be summed."
8913 (interactive)
8914 (save-excursion
8915 (let (col (org-timecnt 0) diff h m s org-table-clip)
8916 (cond
8917 ((and beg end)) ; beg and end given explicitly
8918 ((org-region-active-p)
8919 (setq beg (region-beginning) end (region-end)))
8921 (setq col (org-table-current-column))
8922 (goto-char (org-table-begin))
8923 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8924 (error "No table data"))
8925 (org-table-goto-column col)
8926 (setq beg (point))
8927 (goto-char (org-table-end))
8928 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8929 (error "No table data"))
8930 (org-table-goto-column col)
8931 (setq end (point))))
8932 (let* ((items (apply 'append (org-table-copy-region beg end)))
8933 (items1 (cond ((not nlast) items)
8934 ((>= nlast (length items)) items)
8935 (t (setq items (reverse items))
8936 (setcdr (nthcdr (1- nlast) items) nil)
8937 (nreverse items))))
8938 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8939 items1)))
8940 (res (apply '+ numbers))
8941 (sres (if (= org-timecnt 0)
8942 (format "%g" res)
8943 (setq diff (* 3600 res)
8944 h (floor (/ diff 3600)) diff (mod diff 3600)
8945 m (floor (/ diff 60)) diff (mod diff 60)
8946 s diff)
8947 (format "%d:%02d:%02d" h m s))))
8948 (kill-new sres)
8949 (if (interactive-p)
8950 (message "%s"
8951 (substitute-command-keys
8952 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8953 (length numbers) sres))))
8954 sres))))
8956 (defun org-table-get-number-for-summing (s)
8957 (let (n)
8958 (if (string-match "^ *|? *" s)
8959 (setq s (replace-match "" nil nil s)))
8960 (if (string-match " *|? *$" s)
8961 (setq s (replace-match "" nil nil s)))
8962 (setq n (string-to-number s))
8963 (cond
8964 ((and (string-match "0" s)
8965 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8966 ((string-match "\\`[ \t]+\\'" s) nil)
8967 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8968 (let ((h (string-to-number (or (match-string 1 s) "0")))
8969 (m (string-to-number (or (match-string 2 s) "0")))
8970 (s (string-to-number (or (match-string 4 s) "0"))))
8971 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8972 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8973 ((equal n 0) nil)
8974 (t n))))
8976 (defun org-table-current-field-formula (&optional key noerror)
8977 "Return the formula active for the current field.
8978 Assumes that specials are in place.
8979 If KEY is given, return the key to this formula.
8980 Otherwise return the formula preceeded with \"=\" or \":=\"."
8981 (let* ((name (car (rassoc (list (org-current-line)
8982 (org-table-current-column))
8983 org-table-named-field-locations)))
8984 (col (org-table-current-column))
8985 (scol (int-to-string col))
8986 (ref (format "@%d$%d" (org-table-current-dline) col))
8987 (stored-list (org-table-get-stored-formulas noerror))
8988 (ass (or (assoc name stored-list)
8989 (assoc ref stored-list)
8990 (assoc scol stored-list))))
8991 (if key
8992 (car ass)
8993 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
8994 (cdr ass))))))
8996 (defun org-table-get-formula (&optional equation named)
8997 "Read a formula from the minibuffer, offer stored formula as default.
8998 When NAMED is non-nil, look for a named equation."
8999 (let* ((stored-list (org-table-get-stored-formulas))
9000 (name (car (rassoc (list (org-current-line)
9001 (org-table-current-column))
9002 org-table-named-field-locations)))
9003 (ref (format "@%d$%d" (org-table-current-dline)
9004 (org-table-current-column)))
9005 (refass (assoc ref stored-list))
9006 (scol (if named
9007 (if name name ref)
9008 (int-to-string (org-table-current-column))))
9009 (dummy (and (or name refass) (not named)
9010 (not (y-or-n-p "Replace field formula with column formula? " ))
9011 (error "Abort")))
9012 (name (or name ref))
9013 (org-table-may-need-update nil)
9014 (stored (cdr (assoc scol stored-list)))
9015 (eq (cond
9016 ((and stored equation (string-match "^ *=? *$" equation))
9017 stored)
9018 ((stringp equation)
9019 equation)
9020 (t (org-table-formula-from-user
9021 (read-string
9022 (org-table-formula-to-user
9023 (format "%s formula %s%s="
9024 (if named "Field" "Column")
9025 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9026 scol))
9027 (if stored (org-table-formula-to-user stored) "")
9028 'org-table-formula-history
9029 )))))
9030 mustsave)
9031 (when (not (string-match "\\S-" eq))
9032 ;; remove formula
9033 (setq stored-list (delq (assoc scol stored-list) stored-list))
9034 (org-table-store-formulas stored-list)
9035 (error "Formula removed"))
9036 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9037 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9038 (if (and name (not named))
9039 ;; We set the column equation, delete the named one.
9040 (setq stored-list (delq (assoc name stored-list) stored-list)
9041 mustsave t))
9042 (if stored
9043 (setcdr (assoc scol stored-list) eq)
9044 (setq stored-list (cons (cons scol eq) stored-list)))
9045 (if (or mustsave (not (equal stored eq)))
9046 (org-table-store-formulas stored-list))
9047 eq))
9049 (defun org-table-store-formulas (alist)
9050 "Store the list of formulas below the current table."
9051 (setq alist (sort alist 'org-table-formula-less-p))
9052 (save-excursion
9053 (goto-char (org-table-end))
9054 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9055 (progn
9056 ;; don't overwrite TBLFM, we might use text properties to store stuff
9057 (goto-char (match-beginning 2))
9058 (delete-region (match-beginning 2) (match-end 0)))
9059 (insert "#+TBLFM:"))
9060 (insert " "
9061 (mapconcat (lambda (x)
9062 (concat
9063 (if (equal (string-to-char (car x)) ?@) "" "$")
9064 (car x) "=" (cdr x)))
9065 alist "::")
9066 "\n")))
9068 (defsubst org-table-formula-make-cmp-string (a)
9069 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9070 (concat
9071 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9072 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9073 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9075 (defun org-table-formula-less-p (a b)
9076 "Compare two formulas for sorting."
9077 (let ((as (org-table-formula-make-cmp-string (car a)))
9078 (bs (org-table-formula-make-cmp-string (car b))))
9079 (and as bs (string< as bs))))
9081 (defun org-table-get-stored-formulas (&optional noerror)
9082 "Return an alist with the stored formulas directly after current table."
9083 (interactive)
9084 (let (scol eq eq-alist strings string seen)
9085 (save-excursion
9086 (goto-char (org-table-end))
9087 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9088 (setq strings (org-split-string (match-string 2) " *:: *"))
9089 (while (setq string (pop strings))
9090 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9091 (setq scol (if (match-end 2)
9092 (match-string 2 string)
9093 (match-string 1 string))
9094 eq (match-string 3 string)
9095 eq-alist (cons (cons scol eq) eq-alist))
9096 (if (member scol seen)
9097 (if noerror
9098 (progn
9099 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9100 (ding)
9101 (sit-for 2))
9102 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9103 (push scol seen))))))
9104 (nreverse eq-alist)))
9106 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9107 "Modify the equations after the table structure has been edited.
9108 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9109 For all numbers larger than LIMIT, shift them by DELTA."
9110 (save-excursion
9111 (goto-char (org-table-end))
9112 (when (looking-at "#\\+TBLFM:")
9113 (let ((re (concat key "\\([0-9]+\\)"))
9114 (re2
9115 (when remove
9116 (if (equal key "$")
9117 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9118 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9119 s n a)
9120 (when remove
9121 (while (re-search-forward re2 (point-at-eol) t)
9122 (replace-match "")))
9123 (while (re-search-forward re (point-at-eol) t)
9124 (setq s (match-string 1) n (string-to-number s))
9125 (cond
9126 ((setq a (assoc s replace))
9127 (replace-match (concat key (cdr a)) t t))
9128 ((and limit (> n limit))
9129 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9131 (defun org-table-get-specials ()
9132 "Get the column names and local parameters for this table."
9133 (save-excursion
9134 (let ((beg (org-table-begin)) (end (org-table-end))
9135 names name fields fields1 field cnt
9136 c v l line col types dlines hlines)
9137 (setq org-table-column-names nil
9138 org-table-local-parameters nil
9139 org-table-named-field-locations nil
9140 org-table-current-begin-line nil
9141 org-table-current-begin-pos nil
9142 org-table-current-line-types nil)
9143 (goto-char beg)
9144 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9145 (setq names (org-split-string (match-string 1) " *| *")
9146 cnt 1)
9147 (while (setq name (pop names))
9148 (setq cnt (1+ cnt))
9149 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9150 (push (cons name (int-to-string cnt)) org-table-column-names))))
9151 (setq org-table-column-names (nreverse org-table-column-names))
9152 (setq org-table-column-name-regexp
9153 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9154 (goto-char beg)
9155 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9156 (setq fields (org-split-string (match-string 1) " *| *"))
9157 (while (setq field (pop fields))
9158 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9159 (push (cons (match-string 1 field) (match-string 2 field))
9160 org-table-local-parameters))))
9161 (goto-char beg)
9162 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9163 (setq c (match-string 1)
9164 fields (org-split-string (match-string 2) " *| *"))
9165 (save-excursion
9166 (beginning-of-line (if (equal c "_") 2 0))
9167 (setq line (org-current-line) col 1)
9168 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9169 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9170 (while (and fields1 (setq field (pop fields)))
9171 (setq v (pop fields1) col (1+ col))
9172 (when (and (stringp field) (stringp v)
9173 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9174 (push (cons field v) org-table-local-parameters)
9175 (push (list field line col) org-table-named-field-locations))))
9176 ;; Analyse the line types
9177 (goto-char beg)
9178 (setq org-table-current-begin-line (org-current-line)
9179 org-table-current-begin-pos (point)
9180 l org-table-current-begin-line)
9181 (while (looking-at "[ \t]*|\\(-\\)?")
9182 (push (if (match-end 1) 'hline 'dline) types)
9183 (if (match-end 1) (push l hlines) (push l dlines))
9184 (beginning-of-line 2)
9185 (setq l (1+ l)))
9186 (setq org-table-current-line-types (apply 'vector (nreverse types))
9187 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9188 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9190 (defun org-table-maybe-eval-formula ()
9191 "Check if the current field starts with \"=\" or \":=\".
9192 If yes, store the formula and apply it."
9193 ;; We already know we are in a table. Get field will only return a formula
9194 ;; when appropriate. It might return a separator line, but no problem.
9195 (when org-table-formula-evaluate-inline
9196 (let* ((field (org-trim (or (org-table-get-field) "")))
9197 named eq)
9198 (when (string-match "^:?=\\(.*\\)" field)
9199 (setq named (equal (string-to-char field) ?:)
9200 eq (match-string 1 field))
9201 (if (or (fboundp 'calc-eval)
9202 (equal (substring eq 0 (min 2 (length eq))) "'("))
9203 (org-table-eval-formula (if named '(4) nil)
9204 (org-table-formula-from-user eq))
9205 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9207 (defvar org-recalc-commands nil
9208 "List of commands triggering the recalculation of a line.
9209 Will be filled automatically during use.")
9211 (defvar org-recalc-marks
9212 '((" " . "Unmarked: no special line, no automatic recalculation")
9213 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9214 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9215 ("!" . "Column name definition line. Reference in formula as $name.")
9216 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9217 ("_" . "Names for values in row below this one.")
9218 ("^" . "Names for values in row above this one.")))
9220 (defun org-table-rotate-recalc-marks (&optional newchar)
9221 "Rotate the recalculation mark in the first column.
9222 If in any row, the first field is not consistent with a mark,
9223 insert a new column for the markers.
9224 When there is an active region, change all the lines in the region,
9225 after prompting for the marking character.
9226 After each change, a message will be displayed indicating the meaning
9227 of the new mark."
9228 (interactive)
9229 (unless (org-at-table-p) (error "Not at a table"))
9230 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9231 (beg (org-table-begin))
9232 (end (org-table-end))
9233 (l (org-current-line))
9234 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9235 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9236 (have-col
9237 (save-excursion
9238 (goto-char beg)
9239 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9240 (col (org-table-current-column))
9241 (forcenew (car (assoc newchar org-recalc-marks)))
9242 epos new)
9243 (when l1
9244 (message "Change region to what mark? Type # * ! $ or SPC: ")
9245 (setq newchar (char-to-string (read-char-exclusive))
9246 forcenew (car (assoc newchar org-recalc-marks))))
9247 (if (and newchar (not forcenew))
9248 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9249 newchar))
9250 (if l1 (goto-line l1))
9251 (save-excursion
9252 (beginning-of-line 1)
9253 (unless (looking-at org-table-dataline-regexp)
9254 (error "Not at a table data line")))
9255 (unless have-col
9256 (org-table-goto-column 1)
9257 (org-table-insert-column)
9258 (org-table-goto-column (1+ col)))
9259 (setq epos (point-at-eol))
9260 (save-excursion
9261 (beginning-of-line 1)
9262 (org-table-get-field
9263 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9264 (concat " "
9265 (setq new (or forcenew
9266 (cadr (member (match-string 1) marks))))
9267 " ")
9268 " # ")))
9269 (if (and l1 l2)
9270 (progn
9271 (goto-line l1)
9272 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9273 (and (looking-at org-table-dataline-regexp)
9274 (org-table-get-field 1 (concat " " new " "))))
9275 (goto-line l1)))
9276 (if (not (= epos (point-at-eol))) (org-table-align))
9277 (goto-line l)
9278 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9280 (defun org-table-maybe-recalculate-line ()
9281 "Recompute the current line if marked for it, and if we haven't just done it."
9282 (interactive)
9283 (and org-table-allow-automatic-line-recalculation
9284 (not (and (memq last-command org-recalc-commands)
9285 (equal org-last-recalc-line (org-current-line))))
9286 (save-excursion (beginning-of-line 1)
9287 (looking-at org-table-auto-recalculate-regexp))
9288 (org-table-recalculate) t))
9290 (defvar org-table-formula-debug nil
9291 "Non-nil means, debug table formulas.
9292 When nil, simply write \"#ERROR\" in corrupted fields.")
9293 (make-variable-buffer-local 'org-table-formula-debug)
9295 (defvar modes)
9296 (defsubst org-set-calc-mode (var &optional value)
9297 (if (stringp var)
9298 (setq var (assoc var '(("D" calc-angle-mode deg)
9299 ("R" calc-angle-mode rad)
9300 ("F" calc-prefer-frac t)
9301 ("S" calc-symbolic-mode t)))
9302 value (nth 2 var) var (nth 1 var)))
9303 (if (memq var modes)
9304 (setcar (cdr (memq var modes)) value)
9305 (cons var (cons value modes)))
9306 modes)
9308 (defun org-table-eval-formula (&optional arg equation
9309 suppress-align suppress-const
9310 suppress-store suppress-analysis)
9311 "Replace the table field value at the cursor by the result of a calculation.
9313 This function makes use of Dave Gillespie's Calc package, in my view the
9314 most exciting program ever written for GNU Emacs. So you need to have Calc
9315 installed in order to use this function.
9317 In a table, this command replaces the value in the current field with the
9318 result of a formula. It also installs the formula as the \"current\" column
9319 formula, by storing it in a special line below the table. When called
9320 with a `C-u' prefix, the current field must ba a named field, and the
9321 formula is installed as valid in only this specific field.
9323 When called with two `C-u' prefixes, insert the active equation
9324 for the field back into the current field, so that it can be
9325 edited there. This is useful in order to use \\[org-table-show-reference]
9326 to check the referenced fields.
9328 When called, the command first prompts for a formula, which is read in
9329 the minibuffer. Previously entered formulas are available through the
9330 history list, and the last used formula is offered as a default.
9331 These stored formulas are adapted correctly when moving, inserting, or
9332 deleting columns with the corresponding commands.
9334 The formula can be any algebraic expression understood by the Calc package.
9335 For details, see the Org-mode manual.
9337 This function can also be called from Lisp programs and offers
9338 additional arguments: EQUATION can be the formula to apply. If this
9339 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9340 used to speed-up recursive calls by by-passing unnecessary aligns.
9341 SUPPRESS-CONST suppresses the interpretation of constants in the
9342 formula, assuming that this has been done already outside the function.
9343 SUPPRESS-STORE means the formula should not be stored, either because
9344 it is already stored, or because it is a modified equation that should
9345 not overwrite the stored one."
9346 (interactive "P")
9347 (org-table-check-inside-data-field)
9348 (or suppress-analysis (org-table-get-specials))
9349 (if (equal arg '(16))
9350 (let ((eq (org-table-current-field-formula)))
9351 (or eq (error "No equation active for current field"))
9352 (org-table-get-field nil eq)
9353 (org-table-align)
9354 (setq org-table-may-need-update t))
9355 (let* (fields
9356 (ndown (if (integerp arg) arg 1))
9357 (org-table-automatic-realign nil)
9358 (case-fold-search nil)
9359 (down (> ndown 1))
9360 (formula (if (and equation suppress-store)
9361 equation
9362 (org-table-get-formula equation (equal arg '(4)))))
9363 (n0 (org-table-current-column))
9364 (modes (copy-sequence org-calc-default-modes))
9365 (numbers nil) ; was a variable, now fixed default
9366 (keep-empty nil)
9367 n form form0 bw fmt x ev orig c lispp literal)
9368 ;; Parse the format string. Since we have a lot of modes, this is
9369 ;; a lot of work. However, I think calc still uses most of the time.
9370 (if (string-match ";" formula)
9371 (let ((tmp (org-split-string formula ";")))
9372 (setq formula (car tmp)
9373 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9374 (nth 1 tmp)))
9375 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9376 (setq c (string-to-char (match-string 1 fmt))
9377 n (string-to-number (match-string 2 fmt)))
9378 (if (= c ?p)
9379 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9380 (setq modes (org-set-calc-mode
9381 'calc-float-format
9382 (list (cdr (assoc c '((?n . float) (?f . fix)
9383 (?s . sci) (?e . eng))))
9384 n))))
9385 (setq fmt (replace-match "" t t fmt)))
9386 (if (string-match "[NT]" fmt)
9387 (setq numbers (equal (match-string 0 fmt) "N")
9388 fmt (replace-match "" t t fmt)))
9389 (if (string-match "L" fmt)
9390 (setq literal t
9391 fmt (replace-match "" t t fmt)))
9392 (if (string-match "E" fmt)
9393 (setq keep-empty t
9394 fmt (replace-match "" t t fmt)))
9395 (while (string-match "[DRFS]" fmt)
9396 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9397 (setq fmt (replace-match "" t t fmt)))
9398 (unless (string-match "\\S-" fmt)
9399 (setq fmt nil))))
9400 (if (and (not suppress-const) org-table-formula-use-constants)
9401 (setq formula (org-table-formula-substitute-names formula)))
9402 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9403 (while (> ndown 0)
9404 (setq fields (org-split-string
9405 (org-no-properties
9406 (buffer-substring (point-at-bol) (point-at-eol)))
9407 " *| *"))
9408 (if (eq numbers t)
9409 (setq fields (mapcar
9410 (lambda (x) (number-to-string (string-to-number x)))
9411 fields)))
9412 (setq ndown (1- ndown))
9413 (setq form (copy-sequence formula)
9414 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9415 (if (and lispp literal) (setq lispp 'literal))
9416 ;; Check for old vertical references
9417 (setq form (org-rewrite-old-row-references form))
9418 ;; Insert complex ranges
9419 (while (string-match org-table-range-regexp form)
9420 (setq form
9421 (replace-match
9422 (save-match-data
9423 (org-table-make-reference
9424 (org-table-get-range (match-string 0 form) nil n0)
9425 keep-empty numbers lispp))
9426 t t form)))
9427 ;; Insert simple ranges
9428 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9429 (setq form
9430 (replace-match
9431 (save-match-data
9432 (org-table-make-reference
9433 (org-sublist
9434 fields (string-to-number (match-string 1 form))
9435 (string-to-number (match-string 2 form)))
9436 keep-empty numbers lispp))
9437 t t form)))
9438 (setq form0 form)
9439 ;; Insert the references to fields in same row
9440 (while (string-match "\\$\\([0-9]+\\)" form)
9441 (setq n (string-to-number (match-string 1 form))
9442 x (nth (1- (if (= n 0) n0 n)) fields))
9443 (unless x (error "Invalid field specifier \"%s\""
9444 (match-string 0 form)))
9445 (setq form (replace-match
9446 (save-match-data
9447 (org-table-make-reference x nil numbers lispp))
9448 t t form)))
9450 (if lispp
9451 (setq ev (condition-case nil
9452 (eval (eval (read form)))
9453 (error "#ERROR"))
9454 ev (if (numberp ev) (number-to-string ev) ev))
9455 (or (fboundp 'calc-eval)
9456 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9457 (setq ev (calc-eval (cons form modes)
9458 (if numbers 'num))))
9460 (when org-table-formula-debug
9461 (with-output-to-temp-buffer "*Substitution History*"
9462 (princ (format "Substitution history of formula
9463 Orig: %s
9464 $xyz-> %s
9465 @r$c-> %s
9466 $1-> %s\n" orig formula form0 form))
9467 (if (listp ev)
9468 (princ (format " %s^\nError: %s"
9469 (make-string (car ev) ?\-) (nth 1 ev)))
9470 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9471 ev (or fmt "NONE")
9472 (if fmt (format fmt (string-to-number ev)) ev)))))
9473 (setq bw (get-buffer-window "*Substitution History*"))
9474 (shrink-window-if-larger-than-buffer bw)
9475 (unless (and (interactive-p) (not ndown))
9476 (unless (let (inhibit-redisplay)
9477 (y-or-n-p "Debugging Formula. Continue to next? "))
9478 (org-table-align)
9479 (error "Abort"))
9480 (delete-window bw)
9481 (message "")))
9482 (if (listp ev) (setq fmt nil ev "#ERROR"))
9483 (org-table-justify-field-maybe
9484 (if fmt (format fmt (string-to-number ev)) ev))
9485 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9486 (call-interactively 'org-return)
9487 (setq ndown 0)))
9488 (and down (org-table-maybe-recalculate-line))
9489 (or suppress-align (and org-table-may-need-update
9490 (org-table-align))))))
9492 (defun org-table-put-field-property (prop value)
9493 (save-excursion
9494 (put-text-property (progn (skip-chars-backward "^|") (point))
9495 (progn (skip-chars-forward "^|") (point))
9496 prop value)))
9498 (defun org-table-get-range (desc &optional tbeg col highlight)
9499 "Get a calc vector from a column, accorting to descriptor DESC.
9500 Optional arguments TBEG and COL can give the beginning of the table and
9501 the current column, to avoid unnecessary parsing.
9502 HIGHLIGHT means, just highlight the range."
9503 (if (not (equal (string-to-char desc) ?@))
9504 (setq desc (concat "@" desc)))
9505 (save-excursion
9506 (or tbeg (setq tbeg (org-table-begin)))
9507 (or col (setq col (org-table-current-column)))
9508 (let ((thisline (org-current-line))
9509 beg end c1 c2 r1 r2 rangep tmp)
9510 (unless (string-match org-table-range-regexp desc)
9511 (error "Invalid table range specifier `%s'" desc))
9512 (setq rangep (match-end 3)
9513 r1 (and (match-end 1) (match-string 1 desc))
9514 r2 (and (match-end 4) (match-string 4 desc))
9515 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9516 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9518 (and c1 (setq c1 (+ (string-to-number c1)
9519 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9520 (and c2 (setq c2 (+ (string-to-number c2)
9521 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9522 (if (equal r1 "") (setq r1 nil))
9523 (if (equal r2 "") (setq r2 nil))
9524 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9525 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9526 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9527 (if (not r1) (setq r1 thisline))
9528 (if (not r2) (setq r2 thisline))
9529 (if (not c1) (setq c1 col))
9530 (if (not c2) (setq c2 col))
9531 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9532 ;; just one field
9533 (progn
9534 (goto-line r1)
9535 (while (not (looking-at org-table-dataline-regexp))
9536 (beginning-of-line 2))
9537 (prog1 (org-trim (org-table-get-field c1))
9538 (if highlight (org-table-highlight-rectangle (point) (point)))))
9539 ;; A range, return a vector
9540 ;; First sort the numbers to get a regular ractangle
9541 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9542 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9543 (goto-line r1)
9544 (while (not (looking-at org-table-dataline-regexp))
9545 (beginning-of-line 2))
9546 (org-table-goto-column c1)
9547 (setq beg (point))
9548 (goto-line r2)
9549 (while (not (looking-at org-table-dataline-regexp))
9550 (beginning-of-line 0))
9551 (org-table-goto-column c2)
9552 (setq end (point))
9553 (if highlight
9554 (org-table-highlight-rectangle
9555 beg (progn (skip-chars-forward "^|\n") (point))))
9556 ;; return string representation of calc vector
9557 (mapcar 'org-trim
9558 (apply 'append (org-table-copy-region beg end)))))))
9560 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9561 "Analyze descriptor DESC and retrieve the corresponding line number.
9562 The cursor is currently in line CLINE, the table begins in line BLINE,
9563 and TABLE is a vector with line types."
9564 (if (string-match "^[0-9]+$" desc)
9565 (aref org-table-dlines (string-to-number desc))
9566 (setq cline (or cline (org-current-line))
9567 bline (or bline org-table-current-begin-line)
9568 table (or table org-table-current-line-types))
9569 (if (or
9570 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9571 ;; 1 2 3 4 5 6
9572 (and (not (match-end 3)) (not (match-end 6)))
9573 (and (match-end 3) (match-end 6) (not (match-end 5))))
9574 (error "invalid row descriptor `%s'" desc))
9575 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9576 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9577 (odir (and (match-end 5) (match-string 5 desc)))
9578 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9579 (i (- cline bline))
9580 (rel (and (match-end 6)
9581 (or (and (match-end 1) (not (match-end 3)))
9582 (match-end 5)))))
9583 (if (and hn (not hdir))
9584 (progn
9585 (setq i 0 hdir "+")
9586 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9587 (if (and (not hn) on (not odir))
9588 (error "should never happen");;(aref org-table-dlines on)
9589 (if (and hn (> hn 0))
9590 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9591 (if on
9592 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9593 (+ bline i)))))
9595 (defun org-find-row-type (table i type backwards relative n)
9596 (let ((l (length table)))
9597 (while (> n 0)
9598 (while (and (setq i (+ i (if backwards -1 1)))
9599 (>= i 0) (< i l)
9600 (not (eq (aref table i) type))
9601 (if (and relative (eq (aref table i) 'hline))
9602 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9603 t)))
9604 (setq n (1- n)))
9605 (if (or (< i 0) (>= i l))
9606 (error "Row descriptior leads outside table")
9607 i)))
9609 (defun org-rewrite-old-row-references (s)
9610 (if (string-match "&[-+0-9I]" s)
9611 (error "Formula contains old &row reference, please rewrite using @-syntax")
9614 (defun org-table-make-reference (elements keep-empty numbers lispp)
9615 "Convert list ELEMENTS to something appropriate to insert into formula.
9616 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9617 NUMBERS indicates that everything should be converted to numbers.
9618 LISPP means to return something appropriate for a Lisp list."
9619 (if (stringp elements) ; just a single val
9620 (if lispp
9621 (if (eq lispp 'literal)
9622 elements
9623 (prin1-to-string (if numbers (string-to-number elements) elements)))
9624 (if (equal elements "") (setq elements "0"))
9625 (if numbers (number-to-string (string-to-number elements)) elements))
9626 (unless keep-empty
9627 (setq elements
9628 (delq nil
9629 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9630 elements))))
9631 (setq elements (or elements '("0")))
9632 (if lispp
9633 (mapconcat
9634 (lambda (x)
9635 (if (eq lispp 'literal)
9637 (prin1-to-string (if numbers (string-to-number x) x))))
9638 elements " ")
9639 (concat "[" (mapconcat
9640 (lambda (x)
9641 (if numbers (number-to-string (string-to-number x)) x))
9642 elements
9643 ",") "]"))))
9645 (defun org-table-recalculate (&optional all noalign)
9646 "Recalculate the current table line by applying all stored formulas.
9647 With prefix arg ALL, do this for all lines in the table."
9648 (interactive "P")
9649 (or (memq this-command org-recalc-commands)
9650 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9651 (unless (org-at-table-p) (error "Not at a table"))
9652 (if (equal all '(16))
9653 (org-table-iterate)
9654 (org-table-get-specials)
9655 (let* ((eqlist (sort (org-table-get-stored-formulas)
9656 (lambda (a b) (string< (car a) (car b)))))
9657 (inhibit-redisplay (not debug-on-error))
9658 (line-re org-table-dataline-regexp)
9659 (thisline (org-current-line))
9660 (thiscol (org-table-current-column))
9661 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9662 ;; Insert constants in all formulas
9663 (setq eqlist
9664 (mapcar (lambda (x)
9665 (setcdr x (org-table-formula-substitute-names (cdr x)))
9667 eqlist))
9668 ;; Split the equation list
9669 (while (setq eq (pop eqlist))
9670 (if (<= (string-to-char (car eq)) ?9)
9671 (push eq eqlnum)
9672 (push eq eqlname)))
9673 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9674 (if all
9675 (progn
9676 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9677 (goto-char (setq beg (org-table-begin)))
9678 (if (re-search-forward org-table-calculate-mark-regexp end t)
9679 ;; This is a table with marked lines, compute selected lines
9680 (setq line-re org-table-recalculate-regexp)
9681 ;; Move forward to the first non-header line
9682 (if (and (re-search-forward org-table-dataline-regexp end t)
9683 (re-search-forward org-table-hline-regexp end t)
9684 (re-search-forward org-table-dataline-regexp end t))
9685 (setq beg (match-beginning 0))
9686 nil))) ;; just leave beg where it is
9687 (setq beg (point-at-bol)
9688 end (move-marker (make-marker) (1+ (point-at-eol)))))
9689 (goto-char beg)
9690 (and all (message "Re-applying formulas to full table..."))
9692 ;; First find the named fields, and mark them untouchanble
9693 (remove-text-properties beg end '(org-untouchable t))
9694 (while (setq eq (pop eqlname))
9695 (setq name (car eq)
9696 a (assoc name org-table-named-field-locations))
9697 (and (not a)
9698 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9699 (setq a (list name
9700 (aref org-table-dlines
9701 (string-to-number (match-string 1 name)))
9702 (string-to-number (match-string 2 name)))))
9703 (when (and a (or all (equal (nth 1 a) thisline)))
9704 (message "Re-applying formula to field: %s" name)
9705 (goto-line (nth 1 a))
9706 (org-table-goto-column (nth 2 a))
9707 (push (append a (list (cdr eq))) eqlname1)
9708 (org-table-put-field-property :org-untouchable t)))
9710 ;; Now evauluate the column formulas, but skip fields covered by
9711 ;; field formulas
9712 (goto-char beg)
9713 (while (re-search-forward line-re end t)
9714 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9715 ;; Unprotected line, recalculate
9716 (and all (message "Re-applying formulas to full table...(line %d)"
9717 (setq cnt (1+ cnt))))
9718 (setq org-last-recalc-line (org-current-line))
9719 (setq eql eqlnum)
9720 (while (setq entry (pop eql))
9721 (goto-line org-last-recalc-line)
9722 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9723 (unless (get-text-property (point) :org-untouchable)
9724 (org-table-eval-formula nil (cdr entry)
9725 'noalign 'nocst 'nostore 'noanalysis)))))
9727 ;; Now evaluate the field formulas
9728 (while (setq eq (pop eqlname1))
9729 (message "Re-applying formula to field: %s" (car eq))
9730 (goto-line (nth 1 eq))
9731 (org-table-goto-column (nth 2 eq))
9732 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9733 'nostore 'noanalysis))
9735 (goto-line thisline)
9736 (org-table-goto-column thiscol)
9737 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9738 (or noalign (and org-table-may-need-update (org-table-align))
9739 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9741 ;; back to initial position
9742 (message "Re-applying formulas...done")
9743 (goto-line thisline)
9744 (org-table-goto-column thiscol)
9745 (or noalign (and org-table-may-need-update (org-table-align))
9746 (and all (message "Re-applying formulas...done"))))))
9748 (defun org-table-iterate (&optional arg)
9749 "Recalculate the table until it does not change anymore."
9750 (interactive "P")
9751 (let ((imax (if arg (prefix-numeric-value arg) 10))
9752 (i 0)
9753 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9754 thistbl)
9755 (catch 'exit
9756 (while (< i imax)
9757 (setq i (1+ i))
9758 (org-table-recalculate 'all)
9759 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9760 (if (not (string= lasttbl thistbl))
9761 (setq lasttbl thistbl)
9762 (if (> i 1)
9763 (message "Convergence after %d iterations" i)
9764 (message "Table was already stable"))
9765 (throw 'exit t)))
9766 (error "No convergence after %d iterations" i))))
9768 (defun org-table-formula-substitute-names (f)
9769 "Replace $const with values in string F."
9770 (let ((start 0) a (f1 f))
9771 ;; First, check for column names
9772 (while (setq start (string-match org-table-column-name-regexp f start))
9773 (setq start (1+ start))
9774 (setq a (assoc (match-string 1 f) org-table-column-names))
9775 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9776 ;; Parameters and constants
9777 (setq start 0)
9778 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9779 (setq start (1+ start))
9780 (if (setq a (save-match-data
9781 (org-table-get-constant (match-string 1 f))))
9782 (setq f (replace-match (concat "(" a ")") t t f))))
9783 (if org-table-formula-debug
9784 (put-text-property 0 (length f) :orig-formula f1 f))
9787 (defun org-table-get-constant (const)
9788 "Find the value for a parameter or constant in a formula.
9789 Parameters get priority."
9790 (or (cdr (assoc const org-table-local-parameters))
9791 (cdr (assoc const org-table-formula-constants-local))
9792 (cdr (assoc const org-table-formula-constants))
9793 (and (fboundp 'constants-get) (constants-get const))
9794 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9795 (org-entry-get nil (substring const 5) 'inherit))
9796 "#UNDEFINED_NAME"))
9798 (defvar org-table-fedit-map
9799 (let ((map (make-sparse-keymap)))
9800 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9801 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9802 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9803 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9804 (org-defkey map "\C-c?" 'org-table-show-reference)
9805 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9806 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9807 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9808 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9809 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9810 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9811 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9812 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9813 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9814 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9815 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9816 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9817 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9818 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9819 map))
9821 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9822 '("Edit-Formulas"
9823 ["Finish and Install" org-table-fedit-finish t]
9824 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9825 ["Abort" org-table-fedit-abort t]
9826 "--"
9827 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9828 ["Complete Lisp Symbol" lisp-complete-symbol t]
9829 "--"
9830 "Shift Reference at Point"
9831 ["Up" org-table-fedit-ref-up t]
9832 ["Down" org-table-fedit-ref-down t]
9833 ["Left" org-table-fedit-ref-left t]
9834 ["Right" org-table-fedit-ref-right t]
9836 "Change Test Row for Column Formulas"
9837 ["Up" org-table-fedit-line-up t]
9838 ["Down" org-table-fedit-line-down t]
9839 "--"
9840 ["Scroll Table Window" org-table-fedit-scroll t]
9841 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9842 ["Show Table Grid" org-table-fedit-toggle-coordinates
9843 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9844 org-table-overlay-coordinates)]
9845 "--"
9846 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9847 :style toggle :selected org-table-buffer-is-an]))
9849 (defvar org-pos)
9851 (defun org-table-edit-formulas ()
9852 "Edit the formulas of the current table in a separate buffer."
9853 (interactive)
9854 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9855 (beginning-of-line 0))
9856 (unless (org-at-table-p) (error "Not at a table"))
9857 (org-table-get-specials)
9858 (let ((key (org-table-current-field-formula 'key 'noerror))
9859 (eql (sort (org-table-get-stored-formulas 'noerror)
9860 'org-table-formula-less-p))
9861 (pos (move-marker (make-marker) (point)))
9862 (startline 1)
9863 (wc (current-window-configuration))
9864 (titles '((column . "# Column Formulas\n")
9865 (field . "# Field Formulas\n")
9866 (named . "# Named Field Formulas\n")))
9867 entry s type title)
9868 (org-switch-to-buffer-other-window "*Edit Formulas*")
9869 (erase-buffer)
9870 ;; Keep global-font-lock-mode from turning on font-lock-mode
9871 (let ((font-lock-global-modes '(not fundamental-mode)))
9872 (fundamental-mode))
9873 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9874 (org-set-local 'org-pos pos)
9875 (org-set-local 'org-window-configuration wc)
9876 (use-local-map org-table-fedit-map)
9877 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9878 (easy-menu-add org-table-fedit-menu)
9879 (setq startline (org-current-line))
9880 (while (setq entry (pop eql))
9881 (setq type (cond
9882 ((equal (string-to-char (car entry)) ?@) 'field)
9883 ((string-match "^[0-9]" (car entry)) 'column)
9884 (t 'named)))
9885 (when (setq title (assq type titles))
9886 (or (bobp) (insert "\n"))
9887 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9888 (setq titles (delq title titles)))
9889 (if (equal key (car entry)) (setq startline (org-current-line)))
9890 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9891 (car entry) " = " (cdr entry) "\n"))
9892 (remove-text-properties 0 (length s) '(face nil) s)
9893 (insert s))
9894 (if (eq org-table-use-standard-references t)
9895 (org-table-fedit-toggle-ref-type))
9896 (goto-line startline)
9897 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9899 (defun org-table-fedit-post-command ()
9900 (when (not (memq this-command '(lisp-complete-symbol)))
9901 (let ((win (selected-window)))
9902 (save-excursion
9903 (condition-case nil
9904 (org-table-show-reference)
9905 (error nil))
9906 (select-window win)))))
9908 (defun org-table-formula-to-user (s)
9909 "Convert a formula from internal to user representation."
9910 (if (eq org-table-use-standard-references t)
9911 (org-table-convert-refs-to-an s)
9914 (defun org-table-formula-from-user (s)
9915 "Convert a formula from user to internal representation."
9916 (if org-table-use-standard-references
9917 (org-table-convert-refs-to-rc s)
9920 (defun org-table-convert-refs-to-rc (s)
9921 "Convert spreadsheet references from AB7 to @7$28.
9922 Works for single references, but also for entire formulas and even the
9923 full TBLFM line."
9924 (let ((start 0))
9925 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9926 (cond
9927 ((match-end 3)
9928 ;; format match, just advance
9929 (setq start (match-end 0)))
9930 ((and (> (match-beginning 0) 0)
9931 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9932 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9933 ;; 3.e5 or something like this.
9934 (setq start (match-end 0)))
9936 (setq start (match-beginning 0)
9937 s (replace-match
9938 (if (equal (match-string 2 s) "&")
9939 (format "$%d" (org-letters-to-number (match-string 1 s)))
9940 (format "@%d$%d"
9941 (string-to-number (match-string 2 s))
9942 (org-letters-to-number (match-string 1 s))))
9943 t t s)))))
9946 (defun org-table-convert-refs-to-an (s)
9947 "Convert spreadsheet references from to @7$28 to AB7.
9948 Works for single references, but also for entire formulas and even the
9949 full TBLFM line."
9950 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9951 (setq s (replace-match
9952 (format "%s%d"
9953 (org-number-to-letters
9954 (string-to-number (match-string 2 s)))
9955 (string-to-number (match-string 1 s)))
9956 t t s)))
9957 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9958 (setq s (replace-match (concat "\\1"
9959 (org-number-to-letters
9960 (string-to-number (match-string 2 s))) "&")
9961 t nil s)))
9964 (defun org-letters-to-number (s)
9965 "Convert a base 26 number represented by letters into an integer.
9966 For example: AB -> 28."
9967 (let ((n 0))
9968 (setq s (upcase s))
9969 (while (> (length s) 0)
9970 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9971 s (substring s 1)))
9974 (defun org-number-to-letters (n)
9975 "Convert an integer into a base 26 number represented by letters.
9976 For example: 28 -> AB."
9977 (let ((s ""))
9978 (while (> n 0)
9979 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9980 n (/ (1- n) 26)))
9983 (defun org-table-fedit-convert-buffer (function)
9984 "Convert all references in this buffer, using FUNTION."
9985 (let ((line (org-current-line)))
9986 (goto-char (point-min))
9987 (while (not (eobp))
9988 (insert (funcall function (buffer-substring (point) (point-at-eol))))
9989 (delete-region (point) (point-at-eol))
9990 (or (eobp) (forward-char 1)))
9991 (goto-line line)))
9993 (defun org-table-fedit-toggle-ref-type ()
9994 "Convert all references in the buffer from B3 to @3$2 and back."
9995 (interactive)
9996 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
9997 (org-table-fedit-convert-buffer
9998 (if org-table-buffer-is-an
9999 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10000 (message "Reference type switched to %s"
10001 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10003 (defun org-table-fedit-ref-up ()
10004 "Shift the reference at point one row/hline up."
10005 (interactive)
10006 (org-table-fedit-shift-reference 'up))
10007 (defun org-table-fedit-ref-down ()
10008 "Shift the reference at point one row/hline down."
10009 (interactive)
10010 (org-table-fedit-shift-reference 'down))
10011 (defun org-table-fedit-ref-left ()
10012 "Shift the reference at point one field to the left."
10013 (interactive)
10014 (org-table-fedit-shift-reference 'left))
10015 (defun org-table-fedit-ref-right ()
10016 "Shift the reference at point one field to the right."
10017 (interactive)
10018 (org-table-fedit-shift-reference 'right))
10020 (defun org-table-fedit-shift-reference (dir)
10021 (cond
10022 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10023 (if (memq dir '(left right))
10024 (org-rematch-and-replace 1 (eq dir 'left))
10025 (error "Cannot shift reference in this direction")))
10026 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10027 ;; A B3-like reference
10028 (if (memq dir '(up down))
10029 (org-rematch-and-replace 2 (eq dir 'up))
10030 (org-rematch-and-replace 1 (eq dir 'left))))
10031 ((org-at-regexp-p
10032 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10033 ;; An internal reference
10034 (if (memq dir '(up down))
10035 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10036 (org-rematch-and-replace 5 (eq dir 'left))))))
10038 (defun org-rematch-and-replace (n &optional decr hline)
10039 "Re-match the group N, and replace it with the shifted refrence."
10040 (or (match-end n) (error "Cannot shift reference in this direction"))
10041 (goto-char (match-beginning n))
10042 (and (looking-at (regexp-quote (match-string n)))
10043 (replace-match (org-shift-refpart (match-string 0) decr hline)
10044 t t)))
10046 (defun org-shift-refpart (ref &optional decr hline)
10047 "Shift a refrence part REF.
10048 If DECR is set, decrease the references row/column, else increase.
10049 If HLINE is set, this may be a hline reference, it certainly is not
10050 a translation reference."
10051 (save-match-data
10052 (let* ((sign (string-match "^[-+]" ref)) n)
10054 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10055 (cond
10056 ((and hline (string-match "^I+" ref))
10057 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10058 (setq n (+ n (if decr -1 1)))
10059 (if (= n 0) (setq n (+ n (if decr -1 1))))
10060 (if sign
10061 (setq sign (if (< n 0) "-" "+") n (abs n))
10062 (setq n (max 1 n)))
10063 (concat sign (make-string n ?I)))
10065 ((string-match "^[0-9]+" ref)
10066 (setq n (string-to-number (concat sign ref)))
10067 (setq n (+ n (if decr -1 1)))
10068 (if sign
10069 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10070 (number-to-string (max 1 n))))
10072 ((string-match "^[a-zA-Z]+" ref)
10073 (org-number-to-letters
10074 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10076 (t (error "Cannot shift reference"))))))
10078 (defun org-table-fedit-toggle-coordinates ()
10079 "Toggle the display of coordinates in the refrenced table."
10080 (interactive)
10081 (let ((pos (marker-position org-pos)))
10082 (with-current-buffer (marker-buffer org-pos)
10083 (save-excursion
10084 (goto-char pos)
10085 (org-table-toggle-coordinate-overlays)))))
10087 (defun org-table-fedit-finish (&optional arg)
10088 "Parse the buffer for formula definitions and install them.
10089 With prefix ARG, apply the new formulas to the table."
10090 (interactive "P")
10091 (org-table-remove-rectangle-highlight)
10092 (if org-table-use-standard-references
10093 (progn
10094 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10095 (setq org-table-buffer-is-an nil)))
10096 (let ((pos org-pos) eql var form)
10097 (goto-char (point-min))
10098 (while (re-search-forward
10099 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10100 nil t)
10101 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10102 form (match-string 3))
10103 (setq form (org-trim form))
10104 (when (not (equal form ""))
10105 (while (string-match "[ \t]*\n[ \t]*" form)
10106 (setq form (replace-match " " t t form)))
10107 (when (assoc var eql)
10108 (error "Double formulas for %s" var))
10109 (push (cons var form) eql)))
10110 (setq org-pos nil)
10111 (set-window-configuration org-window-configuration)
10112 (select-window (get-buffer-window (marker-buffer pos)))
10113 (goto-char pos)
10114 (unless (org-at-table-p)
10115 (error "Lost table position - cannot install formulae"))
10116 (org-table-store-formulas eql)
10117 (move-marker pos nil)
10118 (kill-buffer "*Edit Formulas*")
10119 (if arg
10120 (org-table-recalculate 'all)
10121 (message "New formulas installed - press C-u C-c C-c to apply."))))
10123 (defun org-table-fedit-abort ()
10124 "Abort editing formulas, without installing the changes."
10125 (interactive)
10126 (org-table-remove-rectangle-highlight)
10127 (let ((pos org-pos))
10128 (set-window-configuration org-window-configuration)
10129 (select-window (get-buffer-window (marker-buffer pos)))
10130 (goto-char pos)
10131 (move-marker pos nil)
10132 (message "Formula editing aborted without installing changes")))
10134 (defun org-table-fedit-lisp-indent ()
10135 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10136 (interactive)
10137 (let ((pos (point)) beg end ind)
10138 (beginning-of-line 1)
10139 (cond
10140 ((looking-at "[ \t]")
10141 (goto-char pos)
10142 (call-interactively 'lisp-indent-line))
10143 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10144 ((not (fboundp 'pp-buffer))
10145 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10146 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10147 (goto-char (- (match-end 0) 2))
10148 (setq beg (point))
10149 (setq ind (make-string (current-column) ?\ ))
10150 (condition-case nil (forward-sexp 1)
10151 (error
10152 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10153 (setq end (point))
10154 (save-restriction
10155 (narrow-to-region beg end)
10156 (if (eq last-command this-command)
10157 (progn
10158 (goto-char (point-min))
10159 (setq this-command nil)
10160 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10161 (replace-match " ")))
10162 (pp-buffer)
10163 (untabify (point-min) (point-max))
10164 (goto-char (1+ (point-min)))
10165 (while (re-search-forward "^." nil t)
10166 (beginning-of-line 1)
10167 (insert ind))
10168 (goto-char (point-max))
10169 (backward-delete-char 1)))
10170 (goto-char beg))
10171 (t nil))))
10173 (defvar org-show-positions nil)
10175 (defun org-table-show-reference (&optional local)
10176 "Show the location/value of the $ expression at point."
10177 (interactive)
10178 (org-table-remove-rectangle-highlight)
10179 (catch 'exit
10180 (let ((pos (if local (point) org-pos))
10181 (face2 'highlight)
10182 (org-inhibit-highlight-removal t)
10183 (win (selected-window))
10184 (org-show-positions nil)
10185 var name e what match dest)
10186 (if local (org-table-get-specials))
10187 (setq what (cond
10188 ((or (org-at-regexp-p org-table-range-regexp2)
10189 (org-at-regexp-p org-table-translate-regexp)
10190 (org-at-regexp-p org-table-range-regexp))
10191 (setq match
10192 (save-match-data
10193 (org-table-convert-refs-to-rc (match-string 0))))
10194 'range)
10195 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10196 ((org-at-regexp-p "\\$[0-9]+") 'column)
10197 ((not local) nil)
10198 (t (error "No reference at point")))
10199 match (and what (or match (match-string 0))))
10200 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10201 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10202 'secondary-selection))
10203 (org-add-hook 'before-change-functions
10204 'org-table-remove-rectangle-highlight)
10205 (if (eq what 'name) (setq var (substring match 1)))
10206 (when (eq what 'range)
10207 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10208 (setq match (org-table-formula-substitute-names match)))
10209 (unless local
10210 (save-excursion
10211 (end-of-line 1)
10212 (re-search-backward "^\\S-" nil t)
10213 (beginning-of-line 1)
10214 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10215 (setq dest
10216 (save-match-data
10217 (org-table-convert-refs-to-rc (match-string 1))))
10218 (org-table-add-rectangle-overlay
10219 (match-beginning 1) (match-end 1) face2))))
10220 (if (and (markerp pos) (marker-buffer pos))
10221 (if (get-buffer-window (marker-buffer pos))
10222 (select-window (get-buffer-window (marker-buffer pos)))
10223 (org-switch-to-buffer-other-window (get-buffer-window
10224 (marker-buffer pos)))))
10225 (goto-char pos)
10226 (org-table-force-dataline)
10227 (when dest
10228 (setq name (substring dest 1))
10229 (cond
10230 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10231 (setq e (assoc name org-table-named-field-locations))
10232 (goto-line (nth 1 e))
10233 (org-table-goto-column (nth 2 e)))
10234 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10235 (let ((l (string-to-number (match-string 1 dest)))
10236 (c (string-to-number (match-string 2 dest))))
10237 (goto-line (aref org-table-dlines l))
10238 (org-table-goto-column c)))
10239 (t (org-table-goto-column (string-to-number name))))
10240 (move-marker pos (point))
10241 (org-table-highlight-rectangle nil nil face2))
10242 (cond
10243 ((equal dest match))
10244 ((not match))
10245 ((eq what 'range)
10246 (condition-case nil
10247 (save-excursion
10248 (org-table-get-range match nil nil 'highlight))
10249 (error nil)))
10250 ((setq e (assoc var org-table-named-field-locations))
10251 (goto-line (nth 1 e))
10252 (org-table-goto-column (nth 2 e))
10253 (org-table-highlight-rectangle (point) (point))
10254 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10255 ((setq e (assoc var org-table-column-names))
10256 (org-table-goto-column (string-to-number (cdr e)))
10257 (org-table-highlight-rectangle (point) (point))
10258 (goto-char (org-table-begin))
10259 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10260 (org-table-end) t)
10261 (progn
10262 (goto-char (match-beginning 1))
10263 (org-table-highlight-rectangle)
10264 (message "Named column (column %s)" (cdr e)))
10265 (error "Column name not found")))
10266 ((eq what 'column)
10267 ;; column number
10268 (org-table-goto-column (string-to-number (substring match 1)))
10269 (org-table-highlight-rectangle (point) (point))
10270 (message "Column %s" (substring match 1)))
10271 ((setq e (assoc var org-table-local-parameters))
10272 (goto-char (org-table-begin))
10273 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10274 (progn
10275 (goto-char (match-beginning 1))
10276 (org-table-highlight-rectangle)
10277 (message "Local parameter."))
10278 (error "Parameter not found")))
10280 (cond
10281 ((not var) (error "No reference at point"))
10282 ((setq e (assoc var org-table-formula-constants-local))
10283 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10284 var (cdr e)))
10285 ((setq e (assoc var org-table-formula-constants))
10286 (message "Constant: $%s=%s in `org-table-formula-constants'."
10287 var (cdr e)))
10288 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10289 (message "Constant: $%s=%s, from `constants.el'%s."
10290 var e (format " (%s units)" constants-unit-system)))
10291 (t (error "Undefined name $%s" var)))))
10292 (goto-char pos)
10293 (when (and org-show-positions
10294 (not (memq this-command '(org-table-fedit-scroll
10295 org-table-fedit-scroll-down))))
10296 (push pos org-show-positions)
10297 (push org-table-current-begin-pos org-show-positions)
10298 (let ((min (apply 'min org-show-positions))
10299 (max (apply 'max org-show-positions)))
10300 (goto-char min) (recenter 0)
10301 (goto-char max)
10302 (or (pos-visible-in-window-p max) (recenter -1))))
10303 (select-window win))))
10305 (defun org-table-force-dataline ()
10306 "Make sure the cursor is in a dataline in a table."
10307 (unless (save-excursion
10308 (beginning-of-line 1)
10309 (looking-at org-table-dataline-regexp))
10310 (let* ((re org-table-dataline-regexp)
10311 (p1 (save-excursion (re-search-forward re nil 'move)))
10312 (p2 (save-excursion (re-search-backward re nil 'move))))
10313 (cond ((and p1 p2)
10314 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10315 p1 p2)))
10316 ((or p1 p2) (goto-char (or p1 p2)))
10317 (t (error "No table dataline around here"))))))
10319 (defun org-table-fedit-line-up ()
10320 "Move cursor one line up in the window showing the table."
10321 (interactive)
10322 (org-table-fedit-move 'previous-line))
10324 (defun org-table-fedit-line-down ()
10325 "Move cursor one line down in the window showing the table."
10326 (interactive)
10327 (org-table-fedit-move 'next-line))
10329 (defun org-table-fedit-move (command)
10330 "Move the cursor in the window shoinw the table.
10331 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10332 (let ((org-table-allow-automatic-line-recalculation nil)
10333 (pos org-pos) (win (selected-window)) p)
10334 (select-window (get-buffer-window (marker-buffer org-pos)))
10335 (setq p (point))
10336 (call-interactively command)
10337 (while (and (org-at-table-p)
10338 (org-at-table-hline-p))
10339 (call-interactively command))
10340 (or (org-at-table-p) (goto-char p))
10341 (move-marker pos (point))
10342 (select-window win)))
10344 (defun org-table-fedit-scroll (N)
10345 (interactive "p")
10346 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10347 (scroll-other-window N)))
10349 (defun org-table-fedit-scroll-down (N)
10350 (interactive "p")
10351 (org-table-fedit-scroll (- N)))
10353 (defvar org-table-rectangle-overlays nil)
10355 (defun org-table-add-rectangle-overlay (beg end &optional face)
10356 "Add a new overlay."
10357 (let ((ov (org-make-overlay beg end)))
10358 (org-overlay-put ov 'face (or face 'secondary-selection))
10359 (push ov org-table-rectangle-overlays)))
10361 (defun org-table-highlight-rectangle (&optional beg end face)
10362 "Highlight rectangular region in a table."
10363 (setq beg (or beg (point)) end (or end (point)))
10364 (let ((b (min beg end))
10365 (e (max beg end))
10366 l1 c1 l2 c2 tmp)
10367 (and (boundp 'org-show-positions)
10368 (setq org-show-positions (cons b (cons e org-show-positions))))
10369 (goto-char (min beg end))
10370 (setq l1 (org-current-line)
10371 c1 (org-table-current-column))
10372 (goto-char (max beg end))
10373 (setq l2 (org-current-line)
10374 c2 (org-table-current-column))
10375 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10376 (goto-line l1)
10377 (beginning-of-line 1)
10378 (loop for line from l1 to l2 do
10379 (when (looking-at org-table-dataline-regexp)
10380 (org-table-goto-column c1)
10381 (skip-chars-backward "^|\n") (setq beg (point))
10382 (org-table-goto-column c2)
10383 (skip-chars-forward "^|\n") (setq end (point))
10384 (org-table-add-rectangle-overlay beg end face))
10385 (beginning-of-line 2))
10386 (goto-char b))
10387 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10389 (defun org-table-remove-rectangle-highlight (&rest ignore)
10390 "Remove the rectangle overlays."
10391 (unless org-inhibit-highlight-removal
10392 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10393 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10394 (setq org-table-rectangle-overlays nil)))
10396 (defvar org-table-coordinate-overlays nil
10397 "Collects the cooordinate grid overlays, so that they can be removed.")
10398 (make-variable-buffer-local 'org-table-coordinate-overlays)
10400 (defun org-table-overlay-coordinates ()
10401 "Add overlays to the table at point, to show row/column coordinates."
10402 (interactive)
10403 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10404 (setq org-table-coordinate-overlays nil)
10405 (save-excursion
10406 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10407 (goto-char (org-table-begin))
10408 (while (org-at-table-p)
10409 (setq eol (point-at-eol))
10410 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10411 (push ov org-table-coordinate-overlays)
10412 (setq hline (looking-at org-table-hline-regexp))
10413 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10414 (format "%4d" (setq id (1+ id)))))
10415 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10416 (when hline
10417 (setq ic 0)
10418 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10419 (setq beg (1+ (match-beginning 0))
10420 ic (1+ ic)
10421 s1 (concat "$" (int-to-string ic))
10422 s2 (org-number-to-letters ic)
10423 str (if (eq org-table-use-standard-references t) s2 s1))
10424 (setq ov (org-make-overlay beg (+ beg (length str))))
10425 (push ov org-table-coordinate-overlays)
10426 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10427 (beginning-of-line 2)))))
10429 (defun org-table-toggle-coordinate-overlays ()
10430 "Toggle the display of Row/Column numbers in tables."
10431 (interactive)
10432 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10433 (message "Row/Column number display turned %s"
10434 (if org-table-overlay-coordinates "on" "off"))
10435 (if (and (org-at-table-p) org-table-overlay-coordinates)
10436 (org-table-align))
10437 (unless org-table-overlay-coordinates
10438 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10439 (setq org-table-coordinate-overlays nil)))
10441 (defun org-table-toggle-formula-debugger ()
10442 "Toggle the formula debugger in tables."
10443 (interactive)
10444 (setq org-table-formula-debug (not org-table-formula-debug))
10445 (message "Formula debugging has been turned %s"
10446 (if org-table-formula-debug "on" "off")))
10448 ;;; The orgtbl minor mode
10450 ;; Define a minor mode which can be used in other modes in order to
10451 ;; integrate the org-mode table editor.
10453 ;; This is really a hack, because the org-mode table editor uses several
10454 ;; keys which normally belong to the major mode, for example the TAB and
10455 ;; RET keys. Here is how it works: The minor mode defines all the keys
10456 ;; necessary to operate the table editor, but wraps the commands into a
10457 ;; function which tests if the cursor is currently inside a table. If that
10458 ;; is the case, the table editor command is executed. However, when any of
10459 ;; those keys is used outside a table, the function uses `key-binding' to
10460 ;; look up if the key has an associated command in another currently active
10461 ;; keymap (minor modes, major mode, global), and executes that command.
10462 ;; There might be problems if any of the keys used by the table editor is
10463 ;; otherwise used as a prefix key.
10465 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10466 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10467 ;; addresses this by checking explicitly for both bindings.
10469 ;; The optimized version (see variable `orgtbl-optimized') takes over
10470 ;; all keys which are bound to `self-insert-command' in the *global map*.
10471 ;; Some modes bind other commands to simple characters, for example
10472 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10473 ;; active, this binding is ignored inside tables and replaced with a
10474 ;; modified self-insert.
10476 (defvar orgtbl-mode nil
10477 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10478 table editor in arbitrary modes.")
10479 (make-variable-buffer-local 'orgtbl-mode)
10481 (defvar orgtbl-mode-map (make-keymap)
10482 "Keymap for `orgtbl-mode'.")
10484 ;;;###autoload
10485 (defun turn-on-orgtbl ()
10486 "Unconditionally turn on `orgtbl-mode'."
10487 (orgtbl-mode 1))
10489 (defvar org-old-auto-fill-inhibit-regexp nil
10490 "Local variable used by `orgtbl-mode'")
10492 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10493 "Matches a line belonging to an orgtbl.")
10495 (defconst orgtbl-extra-font-lock-keywords
10496 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10497 0 (quote 'org-table) 'prepend))
10498 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10500 ;;;###autoload
10501 (defun orgtbl-mode (&optional arg)
10502 "The `org-mode' table editor as a minor mode for use in other modes."
10503 (interactive)
10504 (if (org-mode-p)
10505 ;; Exit without error, in case some hook functions calls this
10506 ;; by accident in org-mode.
10507 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10508 (setq orgtbl-mode
10509 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10510 (if orgtbl-mode
10511 (progn
10512 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10513 ;; Make sure we are first in minor-mode-map-alist
10514 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10515 (and c (setq minor-mode-map-alist
10516 (cons c (delq c minor-mode-map-alist)))))
10517 (org-set-local (quote org-table-may-need-update) t)
10518 (org-add-hook 'before-change-functions 'org-before-change-function
10519 nil 'local)
10520 (org-set-local 'org-old-auto-fill-inhibit-regexp
10521 auto-fill-inhibit-regexp)
10522 (org-set-local 'auto-fill-inhibit-regexp
10523 (if auto-fill-inhibit-regexp
10524 (concat orgtbl-line-start-regexp "\\|"
10525 auto-fill-inhibit-regexp)
10526 orgtbl-line-start-regexp))
10527 (org-add-to-invisibility-spec '(org-cwidth))
10528 (when (fboundp 'font-lock-add-keywords)
10529 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10530 (org-restart-font-lock))
10531 (easy-menu-add orgtbl-mode-menu)
10532 (run-hooks 'orgtbl-mode-hook))
10533 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10534 (org-cleanup-narrow-column-properties)
10535 (org-remove-from-invisibility-spec '(org-cwidth))
10536 (remove-hook 'before-change-functions 'org-before-change-function t)
10537 (when (fboundp 'font-lock-remove-keywords)
10538 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10539 (org-restart-font-lock))
10540 (easy-menu-remove orgtbl-mode-menu)
10541 (force-mode-line-update 'all))))
10543 (defun org-cleanup-narrow-column-properties ()
10544 "Remove all properties related to narrow-column invisibility."
10545 (let ((s 1))
10546 (while (setq s (text-property-any s (point-max)
10547 'display org-narrow-column-arrow))
10548 (remove-text-properties s (1+ s) '(display t)))
10549 (setq s 1)
10550 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10551 (remove-text-properties s (1+ s) '(org-cwidth t)))
10552 (setq s 1)
10553 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10554 (remove-text-properties s (1+ s) '(invisible t)))))
10556 ;; Install it as a minor mode.
10557 (put 'orgtbl-mode :included t)
10558 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10559 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10561 (defun orgtbl-make-binding (fun n &rest keys)
10562 "Create a function for binding in the table minor mode.
10563 FUN is the command to call inside a table. N is used to create a unique
10564 command name. KEYS are keys that should be checked in for a command
10565 to execute outside of tables."
10566 (eval
10567 (list 'defun
10568 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10569 '(arg)
10570 (concat "In tables, run `" (symbol-name fun) "'.\n"
10571 "Outside of tables, run the binding of `"
10572 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10573 "'.")
10574 '(interactive "p")
10575 (list 'if
10576 '(org-at-table-p)
10577 (list 'call-interactively (list 'quote fun))
10578 (list 'let '(orgtbl-mode)
10579 (list 'call-interactively
10580 (append '(or)
10581 (mapcar (lambda (k)
10582 (list 'key-binding k))
10583 keys)
10584 '('orgtbl-error))))))))
10586 (defun orgtbl-error ()
10587 "Error when there is no default binding for a table key."
10588 (interactive)
10589 (error "This key is has no function outside tables"))
10591 (defun orgtbl-setup ()
10592 "Setup orgtbl keymaps."
10593 (let ((nfunc 0)
10594 (bindings
10595 (list
10596 '([(meta shift left)] org-table-delete-column)
10597 '([(meta left)] org-table-move-column-left)
10598 '([(meta right)] org-table-move-column-right)
10599 '([(meta shift right)] org-table-insert-column)
10600 '([(meta shift up)] org-table-kill-row)
10601 '([(meta shift down)] org-table-insert-row)
10602 '([(meta up)] org-table-move-row-up)
10603 '([(meta down)] org-table-move-row-down)
10604 '("\C-c\C-w" org-table-cut-region)
10605 '("\C-c\M-w" org-table-copy-region)
10606 '("\C-c\C-y" org-table-paste-rectangle)
10607 '("\C-c-" org-table-insert-hline)
10608 '("\C-c}" org-table-toggle-coordinate-overlays)
10609 '("\C-c{" org-table-toggle-formula-debugger)
10610 '("\C-m" org-table-next-row)
10611 '([(shift return)] org-table-copy-down)
10612 '("\C-c\C-q" org-table-wrap-region)
10613 '("\C-c?" org-table-field-info)
10614 '("\C-c " org-table-blank-field)
10615 '("\C-c+" org-table-sum)
10616 '("\C-c=" org-table-eval-formula)
10617 '("\C-c'" org-table-edit-formulas)
10618 '("\C-c`" org-table-edit-field)
10619 '("\C-c*" org-table-recalculate)
10620 '("\C-c|" org-table-create-or-convert-from-region)
10621 '("\C-c^" org-table-sort-lines)
10622 '([(control ?#)] org-table-rotate-recalc-marks)))
10623 elt key fun cmd)
10624 (while (setq elt (pop bindings))
10625 (setq nfunc (1+ nfunc))
10626 (setq key (org-key (car elt))
10627 fun (nth 1 elt)
10628 cmd (orgtbl-make-binding fun nfunc key))
10629 (org-defkey orgtbl-mode-map key cmd))
10631 ;; Special treatment needed for TAB and RET
10632 (org-defkey orgtbl-mode-map [(return)]
10633 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10634 (org-defkey orgtbl-mode-map "\C-m"
10635 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10637 (org-defkey orgtbl-mode-map [(tab)]
10638 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10639 (org-defkey orgtbl-mode-map "\C-i"
10640 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10642 (org-defkey orgtbl-mode-map [(shift tab)]
10643 (orgtbl-make-binding 'org-table-previous-field 104
10644 [(shift tab)] [(tab)] "\C-i"))
10646 (org-defkey orgtbl-mode-map "\M-\C-m"
10647 (orgtbl-make-binding 'org-table-wrap-region 105
10648 "\M-\C-m" [(meta return)]))
10649 (org-defkey orgtbl-mode-map [(meta return)]
10650 (orgtbl-make-binding 'org-table-wrap-region 106
10651 [(meta return)] "\M-\C-m"))
10653 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10654 (when orgtbl-optimized
10655 ;; If the user wants maximum table support, we need to hijack
10656 ;; some standard editing functions
10657 (org-remap orgtbl-mode-map
10658 'self-insert-command 'orgtbl-self-insert-command
10659 'delete-char 'org-delete-char
10660 'delete-backward-char 'org-delete-backward-char)
10661 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10662 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10663 '("OrgTbl"
10664 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10665 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10666 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10667 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10668 "--"
10669 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10670 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10671 ["Copy Field from Above"
10672 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10673 "--"
10674 ("Column"
10675 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10676 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10677 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10678 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10679 ("Row"
10680 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10681 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10682 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10683 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10684 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10685 "--"
10686 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10687 ("Rectangle"
10688 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10689 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10690 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10691 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10692 "--"
10693 ("Radio tables"
10694 ["Insert table template" orgtbl-insert-radio-table
10695 (assq major-mode orgtbl-radio-table-templates)]
10696 ["Comment/uncomment table" orgtbl-toggle-comment t])
10697 "--"
10698 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10699 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10700 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10701 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10702 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10703 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10704 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10705 ["Sum Column/Rectangle" org-table-sum
10706 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10707 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10708 ["Debug Formulas"
10709 org-table-toggle-formula-debugger :active (org-at-table-p)
10710 :keys "C-c {"
10711 :style toggle :selected org-table-formula-debug]
10712 ["Show Col/Row Numbers"
10713 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10714 :keys "C-c }"
10715 :style toggle :selected org-table-overlay-coordinates]
10719 (defun orgtbl-ctrl-c-ctrl-c (arg)
10720 "If the cursor is inside a table, realign the table.
10721 It it is a table to be sent away to a receiver, do it.
10722 With prefix arg, also recompute table."
10723 (interactive "P")
10724 (let ((pos (point)) action)
10725 (save-excursion
10726 (beginning-of-line 1)
10727 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10728 ((looking-at "[ \t]*|") pos)
10729 ((looking-at "#\\+TBLFM:") 'recalc))))
10730 (cond
10731 ((integerp action)
10732 (goto-char action)
10733 (org-table-maybe-eval-formula)
10734 (if arg
10735 (call-interactively 'org-table-recalculate)
10736 (org-table-maybe-recalculate-line))
10737 (call-interactively 'org-table-align)
10738 (orgtbl-send-table 'maybe))
10739 ((eq action 'recalc)
10740 (save-excursion
10741 (beginning-of-line 1)
10742 (skip-chars-backward " \r\n\t")
10743 (if (org-at-table-p)
10744 (org-call-with-arg 'org-table-recalculate t))))
10745 (t (let (orgtbl-mode)
10746 (call-interactively (key-binding "\C-c\C-c")))))))
10748 (defun orgtbl-tab (arg)
10749 "Justification and field motion for `orgtbl-mode'."
10750 (interactive "P")
10751 (if arg (org-table-edit-field t)
10752 (org-table-justify-field-maybe)
10753 (org-table-next-field)))
10755 (defun orgtbl-ret ()
10756 "Justification and field motion for `orgtbl-mode'."
10757 (interactive)
10758 (org-table-justify-field-maybe)
10759 (org-table-next-row))
10761 (defun orgtbl-self-insert-command (N)
10762 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10763 If the cursor is in a table looking at whitespace, the whitespace is
10764 overwritten, and the table is not marked as requiring realignment."
10765 (interactive "p")
10766 (if (and (org-at-table-p)
10768 (and org-table-auto-blank-field
10769 (member last-command
10770 '(orgtbl-hijacker-command-100
10771 orgtbl-hijacker-command-101
10772 orgtbl-hijacker-command-102
10773 orgtbl-hijacker-command-103
10774 orgtbl-hijacker-command-104
10775 orgtbl-hijacker-command-105))
10776 (org-table-blank-field))
10778 (eq N 1)
10779 (looking-at "[^|\n]* +|"))
10780 (let (org-table-may-need-update)
10781 (goto-char (1- (match-end 0)))
10782 (delete-backward-char 1)
10783 (goto-char (match-beginning 0))
10784 (self-insert-command N))
10785 (setq org-table-may-need-update t)
10786 (let (orgtbl-mode)
10787 (call-interactively (key-binding (vector last-input-event))))))
10789 (defun org-force-self-insert (N)
10790 "Needed to enforce self-insert under remapping."
10791 (interactive "p")
10792 (self-insert-command N))
10794 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10795 "Regula expression matching exponentials as produced by calc.")
10797 (defvar org-table-clean-did-remove-column nil)
10799 (defun orgtbl-export (table target)
10800 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10801 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10802 org-table-last-alignment org-table-last-column-widths
10803 maxcol column)
10804 (if (not (fboundp func))
10805 (error "Cannot export orgtbl table to %s" target))
10806 (setq lines (org-table-clean-before-export lines))
10807 (setq table
10808 (mapcar
10809 (lambda (x)
10810 (if (string-match org-table-hline-regexp x)
10811 'hline
10812 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10813 lines))
10814 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10815 table)))
10816 (loop for i from (1- maxcol) downto 0 do
10817 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10818 (setq column (delq nil column))
10819 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10820 (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))
10821 (funcall func table nil)))
10823 (defun orgtbl-send-table (&optional maybe)
10824 "Send a tranformed version of this table to the receiver position.
10825 With argument MAYBE, fail quietly if no transformation is defined for
10826 this table."
10827 (interactive)
10828 (catch 'exit
10829 (unless (org-at-table-p) (error "Not at a table"))
10830 ;; when non-interactive, we assume align has just happened.
10831 (when (interactive-p) (org-table-align))
10832 (save-excursion
10833 (goto-char (org-table-begin))
10834 (beginning-of-line 0)
10835 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10836 (if maybe
10837 (throw 'exit nil)
10838 (error "Don't know how to transform this table."))))
10839 (let* ((name (match-string 1))
10841 (transform (intern (match-string 2)))
10842 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10843 (skip (plist-get params :skip))
10844 (skipcols (plist-get params :skipcols))
10845 (txt (buffer-substring-no-properties
10846 (org-table-begin) (org-table-end)))
10847 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10848 (lines (org-table-clean-before-export lines))
10849 (i0 (if org-table-clean-did-remove-column 2 1))
10850 (table (mapcar
10851 (lambda (x)
10852 (if (string-match org-table-hline-regexp x)
10853 'hline
10854 (org-remove-by-index
10855 (org-split-string (org-trim x) "\\s-*|\\s-*")
10856 skipcols i0)))
10857 lines))
10858 (fun (if (= i0 2) 'cdr 'identity))
10859 (org-table-last-alignment
10860 (org-remove-by-index (funcall fun org-table-last-alignment)
10861 skipcols i0))
10862 (org-table-last-column-widths
10863 (org-remove-by-index (funcall fun org-table-last-column-widths)
10864 skipcols i0)))
10866 (unless (fboundp transform)
10867 (error "No such transformation function %s" transform))
10868 (setq txt (funcall transform table params))
10869 ;; Find the insertion place
10870 (save-excursion
10871 (goto-char (point-min))
10872 (unless (re-search-forward
10873 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10874 (error "Don't know where to insert translated table"))
10875 (goto-char (match-beginning 0))
10876 (beginning-of-line 2)
10877 (setq beg (point))
10878 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10879 (error "Cannot find end of insertion region"))
10880 (beginning-of-line 1)
10881 (delete-region beg (point))
10882 (goto-char beg)
10883 (insert txt "\n"))
10884 (message "Table converted and installed at receiver location"))))
10886 (defun org-remove-by-index (list indices &optional i0)
10887 "Remove the elements in LIST with indices in INDICES.
10888 First element has index 0, or I0 if given."
10889 (if (not indices)
10890 list
10891 (if (integerp indices) (setq indices (list indices)))
10892 (setq i0 (1- (or i0 0)))
10893 (delq :rm (mapcar (lambda (x)
10894 (setq i0 (1+ i0))
10895 (if (memq i0 indices) :rm x))
10896 list))))
10898 (defun orgtbl-toggle-comment ()
10899 "Comment or uncomment the orgtbl at point."
10900 (interactive)
10901 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10902 (re2 (concat "^" orgtbl-line-start-regexp))
10903 (commented (save-excursion (beginning-of-line 1)
10904 (cond ((looking-at re1) t)
10905 ((looking-at re2) nil)
10906 (t (error "Not at an org table")))))
10907 (re (if commented re1 re2))
10908 beg end)
10909 (save-excursion
10910 (beginning-of-line 1)
10911 (while (looking-at re) (beginning-of-line 0))
10912 (beginning-of-line 2)
10913 (setq beg (point))
10914 (while (looking-at re) (beginning-of-line 2))
10915 (setq end (point)))
10916 (comment-region beg end (if commented '(4) nil))))
10918 (defun orgtbl-insert-radio-table ()
10919 "Insert a radio table template appropriate for this major mode."
10920 (interactive)
10921 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10922 (txt (nth 1 e))
10923 name pos)
10924 (unless e (error "No radio table setup defined for %s" major-mode))
10925 (setq name (read-string "Table name: "))
10926 (while (string-match "%n" txt)
10927 (setq txt (replace-match name t t txt)))
10928 (or (bolp) (insert "\n"))
10929 (setq pos (point))
10930 (insert txt)
10931 (goto-char pos)))
10933 (defun org-get-param (params header i sym &optional hsym)
10934 "Get parameter value for symbol SYM.
10935 If this is a header line, actually get the value for the symbol with an
10936 additional \"h\" inserted after the colon.
10937 If the value is a protperty list, get the element for the current column.
10938 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10939 (let ((val (plist-get params sym)))
10940 (and hsym header (setq val (or (plist-get params hsym) val)))
10941 (if (consp val) (plist-get val i) val)))
10943 (defun orgtbl-to-generic (table params)
10944 "Convert the orgtbl-mode TABLE to some other format.
10945 This generic routine can be used for many standard cases.
10946 TABLE is a list, each entry either the symbol `hline' for a horizontal
10947 separator line, or a list of fields for that line.
10948 PARAMS is a property list of parameters that can influence the conversion.
10949 For the generic converter, some parameters are obligatory: You need to
10950 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10951 :splice, you must have :tstart and :tend.
10953 Valid parameters are
10955 :tstart String to start the table. Ignored when :splice is t.
10956 :tend String to end the table. Ignored when :splice is t.
10958 :splice When set to t, return only table body lines, don't wrap
10959 them into :tstart and :tend. Default is nil.
10961 :hline String to be inserted on horizontal separation lines.
10962 May be nil to ignore hlines.
10964 :lstart String to start a new table line.
10965 :lend String to end a table line
10966 :sep Separator between two fields
10967 :lfmt Format for entire line, with enough %s to capture all fields.
10968 If this is present, :lstart, :lend, and :sep are ignored.
10969 :fmt A format to be used to wrap the field, should contain
10970 %s for the original field value. For example, to wrap
10971 everything in dollars, you could use :fmt \"$%s$\".
10972 This may also be a property list with column numbers and
10973 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10975 :hlstart :hlend :hlsep :hlfmt :hfmt
10976 Same as above, specific for the header lines in the table.
10977 All lines before the first hline are treated as header.
10978 If any of these is not present, the data line value is used.
10980 :efmt Use this format to print numbers with exponentials.
10981 The format should have %s twice for inserting mantissa
10982 and exponent, for example \"%s\\\\times10^{%s}\". This
10983 may also be a property list with column numbers and
10984 formats. :fmt will still be applied after :efmt.
10986 In addition to this, the parameters :skip and :skipcols are always handled
10987 directly by `orgtbl-send-table'. See manual."
10988 (interactive)
10989 (let* ((p params)
10990 (splicep (plist-get p :splice))
10991 (hline (plist-get p :hline))
10992 rtn line i fm efm lfmt h)
10994 ;; Do we have a header?
10995 (if (and (not splicep) (listp (car table)) (memq 'hline table))
10996 (setq h t))
10998 ;; Put header
10999 (unless splicep
11000 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11002 ;; Now loop over all lines
11003 (while (setq line (pop table))
11004 (if (eq line 'hline)
11005 ;; A horizontal separator line
11006 (progn (if hline (push hline rtn))
11007 (setq h nil)) ; no longer in header
11008 ;; A normal line. Convert the fields, push line onto the result list
11009 (setq i 0)
11010 (setq line
11011 (mapcar
11012 (lambda (f)
11013 (setq i (1+ i)
11014 fm (org-get-param p h i :fmt :hfmt)
11015 efm (org-get-param p h i :efmt))
11016 (if (and efm (string-match orgtbl-exp-regexp f))
11017 (setq f (format
11018 efm (match-string 1 f) (match-string 2 f))))
11019 (if fm (setq f (format fm f)))
11021 line))
11022 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11023 (push (apply 'format lfmt line) rtn)
11024 (push (concat
11025 (org-get-param p h i :lstart :hlstart)
11026 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11027 (org-get-param p h i :lend :hlend))
11028 rtn))))
11030 (unless splicep
11031 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11033 (mapconcat 'identity (nreverse rtn) "\n")))
11035 (defun orgtbl-to-latex (table params)
11036 "Convert the orgtbl-mode TABLE to LaTeX.
11037 TABLE is a list, each entry either the symbol `hline' for a horizontal
11038 separator line, or a list of fields for that line.
11039 PARAMS is a property list of parameters that can influence the conversion.
11040 Supports all parameters from `orgtbl-to-generic'. Most important for
11041 LaTeX are:
11043 :splice When set to t, return only table body lines, don't wrap
11044 them into a tabular environment. Default is nil.
11046 :fmt A format to be used to wrap the field, should contain %s for the
11047 original field value. For example, to wrap everything in dollars,
11048 use :fmt \"$%s$\". This may also be a property list with column
11049 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11051 :efmt Format for transforming numbers with exponentials. The format
11052 should have %s twice for inserting mantissa and exponent, for
11053 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11054 This may also be a property list with column numbers and formats.
11056 The general parameters :skip and :skipcols have already been applied when
11057 this function is called."
11058 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11059 org-table-last-alignment ""))
11060 (params2
11061 (list
11062 :tstart (concat "\\begin{tabular}{" alignment "}")
11063 :tend "\\end{tabular}"
11064 :lstart "" :lend " \\\\" :sep " & "
11065 :efmt "%s\\,(%s)" :hline "\\hline")))
11066 (orgtbl-to-generic table (org-combine-plists params2 params))))
11068 (defun orgtbl-to-html (table params)
11069 "Convert the orgtbl-mode TABLE to LaTeX.
11070 TABLE is a list, each entry either the symbol `hline' for a horizontal
11071 separator line, or a list of fields for that line.
11072 PARAMS is a property list of parameters that can influence the conversion.
11073 Currently this function recognizes the following parameters:
11075 :splice When set to t, return only table body lines, don't wrap
11076 them into a <table> environment. Default is nil.
11078 The general parameters :skip and :skipcols have already been applied when
11079 this function is called. The function does *not* use `orgtbl-to-generic',
11080 so you cannot specify parameters for it."
11081 (let* ((splicep (plist-get params :splice))
11082 html)
11083 ;; Just call the formatter we already have
11084 ;; We need to make text lines for it, so put the fields back together.
11085 (setq html (org-format-org-table-html
11086 (mapcar
11087 (lambda (x)
11088 (if (eq x 'hline)
11089 "|----+----|"
11090 (concat "| " (mapconcat 'identity x " | ") " |")))
11091 table)
11092 splicep))
11093 (if (string-match "\n+\\'" html)
11094 (setq html (replace-match "" t t html)))
11095 html))
11097 (defun orgtbl-to-texinfo (table params)
11098 "Convert the orgtbl-mode TABLE to TeXInfo.
11099 TABLE is a list, each entry either the symbol `hline' for a horizontal
11100 separator line, or a list of fields for that line.
11101 PARAMS is a property list of parameters that can influence the conversion.
11102 Supports all parameters from `orgtbl-to-generic'. Most important for
11103 TeXInfo are:
11105 :splice nil/t When set to t, return only table body lines, don't wrap
11106 them into a multitable environment. Default is nil.
11108 :fmt fmt A format to be used to wrap the field, should contain
11109 %s for the original field value. For example, to wrap
11110 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11111 This may also be a property list with column numbers and
11112 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11114 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11115 are computed automatically from the width of the columns
11116 under org-mode.
11118 The general parameters :skip and :skipcols have already been applied when
11119 this function is called."
11120 (let* ((total (float (apply '+ org-table-last-column-widths)))
11121 (colfrac (or (plist-get params :cf)
11122 (mapconcat
11123 (lambda (x) (format "%.3f" (/ (float x) total)))
11124 org-table-last-column-widths " ")))
11125 (params2
11126 (list
11127 :tstart (concat "@multitable @columnfractions " colfrac)
11128 :tend "@end multitable"
11129 :lstart "@item " :lend "" :sep " @tab "
11130 :hlstart "@headitem ")))
11131 (orgtbl-to-generic table (org-combine-plists params2 params))))
11133 ;;;; Link Stuff
11135 ;;; Link abbreviations
11137 (defun org-link-expand-abbrev (link)
11138 "Apply replacements as defined in `org-link-abbrev-alist."
11139 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11140 (let* ((key (match-string 1 link))
11141 (as (or (assoc key org-link-abbrev-alist-local)
11142 (assoc key org-link-abbrev-alist)))
11143 (tag (and (match-end 2) (match-string 3 link)))
11144 rpl)
11145 (if (not as)
11146 link
11147 (setq rpl (cdr as))
11148 (cond
11149 ((symbolp rpl) (funcall rpl tag))
11150 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11151 (t (concat rpl tag)))))
11152 link))
11154 ;;; Storing and inserting links
11156 (defvar org-insert-link-history nil
11157 "Minibuffer history for links inserted with `org-insert-link'.")
11159 (defvar org-stored-links nil
11160 "Contains the links stored with `org-store-link'.")
11162 (defvar org-store-link-plist nil
11163 "Plist with info about the most recently link created with `org-store-link'.")
11165 (defvar org-link-protocols nil
11166 "Link protocols added to Org-mode using `org-add-link-type'.")
11168 (defvar org-store-link-functions nil
11169 "List of functions that are called to create and store a link.
11170 Each function will be called in turn until one returns a non-nil
11171 value. Each function should check if it is responsible for creating
11172 this link (for example by looking at the major mode).
11173 If not, it must exit and return nil.
11174 If yes, it should return a non-nil value after a calling
11175 `org-store-link-properties' with a list of properties and values.
11176 Special properties are:
11178 :type The link prefix. like \"http\". This must be given.
11179 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11180 This is obligatory as well.
11181 :description Optional default description for the second pair
11182 of brackets in an Org-mode link. The user can still change
11183 this when inserting this link into an Org-mode buffer.
11185 In addition to these, any additional properties can be specified
11186 and then used in remember templates.")
11188 (defun org-add-link-type (type &optional follow publish)
11189 "Add TYPE to the list of `org-link-types'.
11190 Re-compute all regular expressions depending on `org-link-types'
11191 FOLLOW and PUBLISH are two functions. Both take the link path as
11192 an argument.
11193 FOLLOW should do whatever is necessary to follow the link, for example
11194 to find a file or display a mail message.
11195 PUBLISH takes the path and retuns the string that should be used when
11196 this document is published."
11197 (add-to-list 'org-link-types type t)
11198 (org-make-link-regexps)
11199 (add-to-list 'org-link-protocols
11200 (list type follow publish)))
11202 (defun org-add-agenda-custom-command (entry)
11203 "Replace or add a command in `org-agenda-custom-commands'.
11204 This is mostly for hacking and trying a new command - once the command
11205 works you probably want to add it to `org-agenda-custom-commands' for good."
11206 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11207 (if ass
11208 (setcdr ass (cdr entry))
11209 (push entry org-agenda-custom-commands))))
11211 ;;;###autoload
11212 (defun org-store-link (arg)
11213 "\\<org-mode-map>Store an org-link to the current location.
11214 This link can later be inserted into an org-buffer with
11215 \\[org-insert-link].
11216 For some link types, a prefix arg is interpreted:
11217 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11218 For file links, arg negates `org-context-in-file-links'."
11219 (interactive "P")
11220 (setq org-store-link-plist nil) ; reset
11221 (let (link cpltxt desc description search txt)
11222 (cond
11224 ((run-hook-with-args-until-success 'org-store-link-functions)
11225 (setq link (plist-get org-store-link-plist :link)
11226 desc (or (plist-get org-store-link-plist :description) link)))
11228 ((eq major-mode 'bbdb-mode)
11229 (let ((name (bbdb-record-name (bbdb-current-record)))
11230 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11231 (setq cpltxt (concat "bbdb:" (or name company))
11232 link (org-make-link cpltxt))
11233 (org-store-link-props :type "bbdb" :name name :company company)))
11235 ((eq major-mode 'Info-mode)
11236 (setq link (org-make-link "info:"
11237 (file-name-nondirectory Info-current-file)
11238 ":" Info-current-node))
11239 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11240 ":" Info-current-node))
11241 (org-store-link-props :type "info" :file Info-current-file
11242 :node Info-current-node))
11244 ((eq major-mode 'calendar-mode)
11245 (let ((cd (calendar-cursor-to-date)))
11246 (setq link
11247 (format-time-string
11248 (car org-time-stamp-formats)
11249 (apply 'encode-time
11250 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11251 nil nil nil))))
11252 (org-store-link-props :type "calendar" :date cd)))
11254 ((or (eq major-mode 'vm-summary-mode)
11255 (eq major-mode 'vm-presentation-mode))
11256 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11257 (vm-follow-summary-cursor)
11258 (save-excursion
11259 (vm-select-folder-buffer)
11260 (let* ((message (car vm-message-pointer))
11261 (folder buffer-file-name)
11262 (subject (vm-su-subject message))
11263 (to (vm-get-header-contents message "To"))
11264 (from (vm-get-header-contents message "From"))
11265 (message-id (vm-su-message-id message)))
11266 (org-store-link-props :type "vm" :from from :to to :subject subject
11267 :message-id message-id)
11268 (setq message-id (org-remove-angle-brackets message-id))
11269 (setq folder (abbreviate-file-name folder))
11270 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11271 folder)
11272 (setq folder (replace-match "" t t folder)))
11273 (setq cpltxt (org-email-link-description))
11274 (setq link (org-make-link "vm:" folder "#" message-id)))))
11276 ((eq major-mode 'wl-summary-mode)
11277 (let* ((msgnum (wl-summary-message-number))
11278 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11279 msgnum 'message-id))
11280 (wl-message-entity
11281 (if (fboundp 'elmo-message-entity)
11282 (elmo-message-entity
11283 wl-summary-buffer-elmo-folder msgnum)
11284 (elmo-msgdb-overview-get-entity
11285 msgnum (wl-summary-buffer-msgdb))))
11286 (from (wl-summary-line-from))
11287 (to (elmo-message-entity-field wl-message-entity 'to))
11288 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11289 (wl-summary-line-subject))))
11290 (org-store-link-props :type "wl" :from from :to to
11291 :subject subject :message-id message-id)
11292 (setq message-id (org-remove-angle-brackets message-id))
11293 (setq cpltxt (org-email-link-description))
11294 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11295 "#" message-id))))
11297 ((or (equal major-mode 'mh-folder-mode)
11298 (equal major-mode 'mh-show-mode))
11299 (let ((from (org-mhe-get-header "From:"))
11300 (to (org-mhe-get-header "To:"))
11301 (message-id (org-mhe-get-header "Message-Id:"))
11302 (subject (org-mhe-get-header "Subject:")))
11303 (org-store-link-props :type "mh" :from from :to to
11304 :subject subject :message-id message-id)
11305 (setq cpltxt (org-email-link-description))
11306 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11307 (org-remove-angle-brackets message-id)))))
11309 ((eq major-mode 'rmail-mode)
11310 (save-excursion
11311 (save-restriction
11312 (rmail-narrow-to-non-pruned-header)
11313 (let ((folder buffer-file-name)
11314 (message-id (mail-fetch-field "message-id"))
11315 (from (mail-fetch-field "from"))
11316 (to (mail-fetch-field "to"))
11317 (subject (mail-fetch-field "subject")))
11318 (org-store-link-props
11319 :type "rmail" :from from :to to
11320 :subject subject :message-id message-id)
11321 (setq message-id (org-remove-angle-brackets message-id))
11322 (setq cpltxt (org-email-link-description))
11323 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11325 ((eq major-mode 'gnus-group-mode)
11326 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11327 (gnus-group-group-name)) ; version
11328 ((fboundp 'gnus-group-name)
11329 (gnus-group-name))
11330 (t "???"))))
11331 (unless group (error "Not on a group"))
11332 (org-store-link-props :type "gnus" :group group)
11333 (setq cpltxt (concat
11334 (if (org-xor arg org-usenet-links-prefer-google)
11335 "http://groups.google.com/groups?group="
11336 "gnus:")
11337 group)
11338 link (org-make-link cpltxt))))
11340 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11341 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11342 (let* ((group gnus-newsgroup-name)
11343 (article (gnus-summary-article-number))
11344 (header (gnus-summary-article-header article))
11345 (from (mail-header-from header))
11346 (message-id (mail-header-id header))
11347 (date (mail-header-date header))
11348 (subject (gnus-summary-subject-string)))
11349 (org-store-link-props :type "gnus" :from from :subject subject
11350 :message-id message-id :group group)
11351 (setq cpltxt (org-email-link-description))
11352 (if (org-xor arg org-usenet-links-prefer-google)
11353 (setq link
11354 (concat
11355 cpltxt "\n "
11356 (format "http://groups.google.com/groups?as_umsgid=%s"
11357 (org-fixup-message-id-for-http message-id))))
11358 (setq link (org-make-link "gnus:" group
11359 "#" (number-to-string article))))))
11361 ((eq major-mode 'w3-mode)
11362 (setq cpltxt (url-view-url t)
11363 link (org-make-link cpltxt))
11364 (org-store-link-props :type "w3" :url (url-view-url t)))
11366 ((eq major-mode 'w3m-mode)
11367 (setq cpltxt (or w3m-current-title w3m-current-url)
11368 link (org-make-link w3m-current-url))
11369 (org-store-link-props :type "w3m" :url (url-view-url t)))
11371 ((setq search (run-hook-with-args-until-success
11372 'org-create-file-search-functions))
11373 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11374 "::" search))
11375 (setq cpltxt (or description link)))
11377 ((eq major-mode 'image-mode)
11378 (setq cpltxt (concat "file:"
11379 (abbreviate-file-name buffer-file-name))
11380 link (org-make-link cpltxt))
11381 (org-store-link-props :type "image" :file buffer-file-name))
11383 ((eq major-mode 'dired-mode)
11384 ;; link to the file in the current line
11385 (setq cpltxt (concat "file:"
11386 (abbreviate-file-name
11387 (expand-file-name
11388 (dired-get-filename nil t))))
11389 link (org-make-link cpltxt)))
11391 ((and buffer-file-name (org-mode-p))
11392 ;; Just link to current headline
11393 (setq cpltxt (concat "file:"
11394 (abbreviate-file-name buffer-file-name)))
11395 ;; Add a context search string
11396 (when (org-xor org-context-in-file-links arg)
11397 ;; Check if we are on a target
11398 (if (org-in-regexp "<<\\(.*?\\)>>")
11399 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11400 (setq txt (cond
11401 ((org-on-heading-p) nil)
11402 ((org-region-active-p)
11403 (buffer-substring (region-beginning) (region-end)))
11404 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11405 (when (or (null txt) (string-match "\\S-" txt))
11406 (setq cpltxt
11407 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11408 desc "NONE"))))
11409 (if (string-match "::\\'" cpltxt)
11410 (setq cpltxt (substring cpltxt 0 -2)))
11411 (setq link (org-make-link cpltxt)))
11413 ((buffer-file-name (buffer-base-buffer))
11414 ;; Just link to this file here.
11415 (setq cpltxt (concat "file:"
11416 (abbreviate-file-name
11417 (buffer-file-name (buffer-base-buffer)))))
11418 ;; Add a context string
11419 (when (org-xor org-context-in-file-links arg)
11420 (setq txt (if (org-region-active-p)
11421 (buffer-substring (region-beginning) (region-end))
11422 (buffer-substring (point-at-bol) (point-at-eol))))
11423 ;; Only use search option if there is some text.
11424 (when (string-match "\\S-" txt)
11425 (setq cpltxt
11426 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11427 desc "NONE")))
11428 (setq link (org-make-link cpltxt)))
11430 ((interactive-p)
11431 (error "Cannot link to a buffer which is not visiting a file"))
11433 (t (setq link nil)))
11435 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11436 (setq link (or link cpltxt)
11437 desc (or desc cpltxt))
11438 (if (equal desc "NONE") (setq desc nil))
11440 (if (and (interactive-p) link)
11441 (progn
11442 (setq org-stored-links
11443 (cons (list link desc) org-stored-links))
11444 (message "Stored: %s" (or desc link)))
11445 (and link (org-make-link-string link desc)))))
11447 (defun org-store-link-props (&rest plist)
11448 "Store link properties, extract names and addresses."
11449 (let (x adr)
11450 (when (setq x (plist-get plist :from))
11451 (setq adr (mail-extract-address-components x))
11452 (plist-put plist :fromname (car adr))
11453 (plist-put plist :fromaddress (nth 1 adr)))
11454 (when (setq x (plist-get plist :to))
11455 (setq adr (mail-extract-address-components x))
11456 (plist-put plist :toname (car adr))
11457 (plist-put plist :toaddress (nth 1 adr))))
11458 (let ((from (plist-get plist :from))
11459 (to (plist-get plist :to)))
11460 (when (and from to org-from-is-user-regexp)
11461 (plist-put plist :fromto
11462 (if (string-match org-from-is-user-regexp from)
11463 (concat "to %t")
11464 (concat "from %f")))))
11465 (setq org-store-link-plist plist))
11467 (defun org-email-link-description (&optional fmt)
11468 "Return the description part of an email link.
11469 This takes information from `org-store-link-plist' and formats it
11470 according to FMT (default from `org-email-link-description-format')."
11471 (setq fmt (or fmt org-email-link-description-format))
11472 (let* ((p org-store-link-plist)
11473 (to (plist-get p :toaddress))
11474 (from (plist-get p :fromaddress))
11475 (table
11476 (list
11477 (cons "%c" (plist-get p :fromto))
11478 (cons "%F" (plist-get p :from))
11479 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11480 (cons "%T" (plist-get p :to))
11481 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11482 (cons "%s" (plist-get p :subject))
11483 (cons "%m" (plist-get p :message-id)))))
11484 (when (string-match "%c" fmt)
11485 ;; Check if the user wrote this message
11486 (if (and org-from-is-user-regexp from to
11487 (save-match-data (string-match org-from-is-user-regexp from)))
11488 (setq fmt (replace-match "to %t" t t fmt))
11489 (setq fmt (replace-match "from %f" t t fmt))))
11490 (org-replace-escapes fmt table)))
11492 (defun org-make-org-heading-search-string (&optional string heading)
11493 "Make search string for STRING or current headline."
11494 (interactive)
11495 (let ((s (or string (org-get-heading))))
11496 (unless (and string (not heading))
11497 ;; We are using a headline, clean up garbage in there.
11498 (if (string-match org-todo-regexp s)
11499 (setq s (replace-match "" t t s)))
11500 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11501 (setq s (replace-match "" t t s)))
11502 (setq s (org-trim s))
11503 (if (string-match (concat "^\\(" org-quote-string "\\|"
11504 org-comment-string "\\)") s)
11505 (setq s (replace-match "" t t s)))
11506 (while (string-match org-ts-regexp s)
11507 (setq s (replace-match "" t t s))))
11508 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11509 (setq s (replace-match " " t t s)))
11510 (or string (setq s (concat "*" s))) ; Add * for headlines
11511 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11513 (defun org-make-link (&rest strings)
11514 "Concatenate STRINGS."
11515 (apply 'concat strings))
11517 (defun org-make-link-string (link &optional description)
11518 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11519 (unless (string-match "\\S-" link)
11520 (error "Empty link"))
11521 (when (stringp description)
11522 ;; Remove brackets from the description, they are fatal.
11523 (while (string-match "\\[\\|\\]" description)
11524 (setq description (replace-match "" t t description))))
11525 (when (equal (org-link-escape link) description)
11526 ;; No description needed, it is identical
11527 (setq description nil))
11528 (when (and (not description)
11529 (not (equal link (org-link-escape link))))
11530 (setq description link))
11531 (concat "[[" (org-link-escape link) "]"
11532 (if description (concat "[" description "]") "")
11533 "]"))
11535 (defconst org-link-escape-chars
11536 '((" " . "%20")
11537 ("[" . "%5B")
11538 ("]" . "%5d")
11539 ("\340" . "%E0") ; `a
11540 ("\342" . "%E2") ; ^a
11541 ("\347" . "%E7") ; ,c
11542 ("\350" . "%E8") ; `e
11543 ("\351" . "%E9") ; 'e
11544 ("\352" . "%EA") ; ^e
11545 ("\356" . "%EE") ; ^i
11546 ("\364" . "%F4") ; ^o
11547 ("\371" . "%F9") ; `u
11548 ("\373" . "%FB") ; ^u
11549 (";" . "%3B")
11550 ("?" . "%3F")
11551 ("=" . "%3D")
11552 ("+" . "%2B")
11554 "Association list of escapes for some characters problematic in links.
11555 This is the list that is used for internal purposes.")
11557 (defconst org-link-escape-chars-browser
11558 '((" " . "%20"))
11559 "Association list of escapes for some characters problematic in links.
11560 This is the list that is used before handing over to the browser.")
11562 (defun org-link-escape (text &optional table)
11563 "Escape charaters in TEXT that are problematic for links."
11564 (setq table (or table org-link-escape-chars))
11565 (when text
11566 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11567 table "\\|")))
11568 (while (string-match re text)
11569 (setq text
11570 (replace-match
11571 (cdr (assoc (match-string 0 text) table))
11572 t t text)))
11573 text)))
11575 (defun org-link-unescape (text &optional table)
11576 "Reverse the action of `org-link-escape'."
11577 (setq table (or table org-link-escape-chars))
11578 (when text
11579 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11580 table "\\|")))
11581 (while (string-match re text)
11582 (setq text
11583 (replace-match
11584 (car (rassoc (match-string 0 text) table))
11585 t t text)))
11586 text)))
11588 (defun org-xor (a b)
11589 "Exclusive or."
11590 (if a (not b) b))
11592 (defun org-get-header (header)
11593 "Find a header field in the current buffer."
11594 (save-excursion
11595 (goto-char (point-min))
11596 (let ((case-fold-search t) s)
11597 (cond
11598 ((eq header 'from)
11599 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11600 (setq s (match-string 1)))
11601 (while (string-match "\"" s)
11602 (setq s (replace-match "" t t s)))
11603 (if (string-match "[<(].*" s)
11604 (setq s (replace-match "" t t s))))
11605 ((eq header 'message-id)
11606 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11607 (setq s (match-string 1))))
11608 ((eq header 'subject)
11609 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11610 (setq s (match-string 1)))))
11611 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11612 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11613 s)))
11616 (defun org-fixup-message-id-for-http (s)
11617 "Replace special characters in a message id, so it can be used in an http query."
11618 (while (string-match "<" s)
11619 (setq s (replace-match "%3C" t t s)))
11620 (while (string-match ">" s)
11621 (setq s (replace-match "%3E" t t s)))
11622 (while (string-match "@" s)
11623 (setq s (replace-match "%40" t t s)))
11626 ;;;###autoload
11627 (defun org-insert-link-global ()
11628 "Insert a link like Org-mode does.
11629 This command can be called in any mode to insert a link in Org-mode syntax."
11630 (interactive)
11631 (org-run-like-in-org-mode 'org-insert-link))
11633 (defun org-insert-link (&optional complete-file)
11634 "Insert a link. At the prompt, enter the link.
11636 Completion can be used to select a link previously stored with
11637 `org-store-link'. When the empty string is entered (i.e. if you just
11638 press RET at the prompt), the link defaults to the most recently
11639 stored link. As SPC triggers completion in the minibuffer, you need to
11640 use M-SPC or C-q SPC to force the insertion of a space character.
11642 You will also be prompted for a description, and if one is given, it will
11643 be displayed in the buffer instead of the link.
11645 If there is already a link at point, this command will allow you to edit link
11646 and description parts.
11648 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11649 selected using completion. The path to the file will be relative to
11650 the current directory if the file is in the current directory or a
11651 subdirectory. Otherwise, the link will be the absolute path as
11652 completed in the minibuffer (i.e. normally ~/path/to/file).
11654 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11655 is in the current directory or below.
11656 With three \\[universal-argument] prefixes, negate the meaning of
11657 `org-keep-stored-link-after-insertion'."
11658 (interactive "P")
11659 (let* ((wcf (current-window-configuration))
11660 (region (if (org-region-active-p)
11661 (buffer-substring (region-beginning) (region-end))))
11662 (remove (and region (list (region-beginning) (region-end))))
11663 (desc region)
11664 tmphist ; byte-compile incorrectly complains about this
11665 link entry file)
11666 (cond
11667 ((org-in-regexp org-bracket-link-regexp 1)
11668 ;; We do have a link at point, and we are going to edit it.
11669 (setq remove (list (match-beginning 0) (match-end 0)))
11670 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11671 (setq link (read-string "Link: "
11672 (org-link-unescape
11673 (org-match-string-no-properties 1)))))
11674 ((or (org-in-regexp org-angle-link-re)
11675 (org-in-regexp org-plain-link-re))
11676 ;; Convert to bracket link
11677 (setq remove (list (match-beginning 0) (match-end 0))
11678 link (read-string "Link: "
11679 (org-remove-angle-brackets (match-string 0)))))
11680 ((equal complete-file '(4))
11681 ;; Completing read for file names.
11682 (setq file (read-file-name "File: "))
11683 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11684 (pwd1 (file-name-as-directory (abbreviate-file-name
11685 (expand-file-name ".")))))
11686 (cond
11687 ((equal complete-file '(16))
11688 (setq link (org-make-link
11689 "file:"
11690 (abbreviate-file-name (expand-file-name file)))))
11691 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11692 (setq link (org-make-link "file:" (match-string 1 file))))
11693 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11694 (expand-file-name file))
11695 (setq link (org-make-link
11696 "file:" (match-string 1 (expand-file-name file)))))
11697 (t (setq link (org-make-link "file:" file))))))
11699 ;; Read link, with completion for stored links.
11700 (with-output-to-temp-buffer "*Org Links*"
11701 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11702 (when org-stored-links
11703 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11704 (princ (mapconcat
11705 (lambda (x)
11706 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11707 (reverse org-stored-links) "\n"))))
11708 (let ((cw (selected-window)))
11709 (select-window (get-buffer-window "*Org Links*"))
11710 (shrink-window-if-larger-than-buffer)
11711 (setq truncate-lines t)
11712 (select-window cw))
11713 ;; Fake a link history, containing the stored links.
11714 (setq tmphist (append (mapcar 'car org-stored-links)
11715 org-insert-link-history))
11716 (unwind-protect
11717 (setq link (org-completing-read
11718 "Link: "
11719 (append
11720 (mapcar (lambda (x) (list (concat (car x) ":")))
11721 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11722 (mapcar (lambda (x) (list (concat x ":")))
11723 org-link-types))
11724 nil nil nil
11725 'tmphist
11726 (or (car (car org-stored-links)))))
11727 (set-window-configuration wcf)
11728 (kill-buffer "*Org Links*"))
11729 (setq entry (assoc link org-stored-links))
11730 (or entry (push link org-insert-link-history))
11731 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11732 (not org-keep-stored-link-after-insertion))
11733 (setq org-stored-links (delq (assoc link org-stored-links)
11734 org-stored-links)))
11735 (setq desc (or desc (nth 1 entry)))))
11737 (if (string-match org-plain-link-re link)
11738 ;; URL-like link, normalize the use of angular brackets.
11739 (setq link (org-make-link (org-remove-angle-brackets link))))
11741 ;; Check if we are linking to the current file with a search option
11742 ;; If yes, simplify the link by using only the search option.
11743 (when (and buffer-file-name
11744 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11745 (let* ((path (match-string 1 link))
11746 (case-fold-search nil)
11747 (search (match-string 2 link)))
11748 (save-match-data
11749 (if (equal (file-truename buffer-file-name) (file-truename path))
11750 ;; We are linking to this same file, with a search option
11751 (setq link search)))))
11753 ;; Check if we can/should use a relative path. If yes, simplify the link
11754 (when (string-match "\\<file:\\(.*\\)" link)
11755 (let* ((path (match-string 1 link))
11756 (origpath path)
11757 (desc-is-link (equal link desc))
11758 (case-fold-search nil))
11759 (cond
11760 ((eq org-link-file-path-type 'absolute)
11761 (setq path (abbreviate-file-name (expand-file-name path))))
11762 ((eq org-link-file-path-type 'noabbrev)
11763 (setq path (expand-file-name path)))
11764 ((eq org-link-file-path-type 'relative)
11765 (setq path (file-relative-name path)))
11767 (save-match-data
11768 (if (string-match (concat "^" (regexp-quote
11769 (file-name-as-directory
11770 (expand-file-name "."))))
11771 (expand-file-name path))
11772 ;; We are linking a file with relative path name.
11773 (setq path (substring (expand-file-name path)
11774 (match-end 0)))))))
11775 (setq link (concat "file:" path))
11776 (if (equal desc origpath)
11777 (setq desc path))))
11779 (setq desc (read-string "Description: " desc))
11780 (unless (string-match "\\S-" desc) (setq desc nil))
11781 (if remove (apply 'delete-region remove))
11782 (insert (org-make-link-string link desc))))
11784 (defun org-completing-read (&rest args)
11785 (let ((minibuffer-local-completion-map
11786 (copy-keymap minibuffer-local-completion-map)))
11787 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11788 (apply 'completing-read args)))
11790 ;;; Opening/following a link
11791 (defvar org-link-search-failed nil)
11793 (defun org-next-link ()
11794 "Move forward to the next link.
11795 If the link is in hidden text, expose it."
11796 (interactive)
11797 (when (and org-link-search-failed (eq this-command last-command))
11798 (goto-char (point-min))
11799 (message "Link search wrapped back to beginning of buffer"))
11800 (setq org-link-search-failed nil)
11801 (let* ((pos (point))
11802 (ct (org-context))
11803 (a (assoc :link ct)))
11804 (if a (goto-char (nth 2 a)))
11805 (if (re-search-forward org-any-link-re nil t)
11806 (progn
11807 (goto-char (match-beginning 0))
11808 (if (org-invisible-p) (org-show-context)))
11809 (goto-char pos)
11810 (setq org-link-search-failed t)
11811 (error "No further link found"))))
11813 (defun org-previous-link ()
11814 "Move backward to the previous link.
11815 If the link is in hidden text, expose it."
11816 (interactive)
11817 (when (and org-link-search-failed (eq this-command last-command))
11818 (goto-char (point-max))
11819 (message "Link search wrapped back to end of buffer"))
11820 (setq org-link-search-failed nil)
11821 (let* ((pos (point))
11822 (ct (org-context))
11823 (a (assoc :link ct)))
11824 (if a (goto-char (nth 1 a)))
11825 (if (re-search-backward org-any-link-re nil t)
11826 (progn
11827 (goto-char (match-beginning 0))
11828 (if (org-invisible-p) (org-show-context)))
11829 (goto-char pos)
11830 (setq org-link-search-failed t)
11831 (error "No further link found"))))
11833 (defun org-find-file-at-mouse (ev)
11834 "Open file link or URL at mouse."
11835 (interactive "e")
11836 (mouse-set-point ev)
11837 (org-open-at-point 'in-emacs))
11839 (defun org-open-at-mouse (ev)
11840 "Open file link or URL at mouse."
11841 (interactive "e")
11842 (mouse-set-point ev)
11843 (org-open-at-point))
11845 (defvar org-window-config-before-follow-link nil
11846 "The window configuration before following a link.
11847 This is saved in case the need arises to restore it.")
11849 (defvar org-open-link-marker (make-marker)
11850 "Marker pointing to the location where `org-open-at-point; was called.")
11852 ;;;###autoload
11853 (defun org-open-at-point-global ()
11854 "Follow a link like Org-mode does.
11855 This command can be called in any mode to follow a link that has
11856 Org-mode syntax."
11857 (interactive)
11858 (org-run-like-in-org-mode 'org-open-at-point))
11860 (defun org-open-at-point (&optional in-emacs)
11861 "Open link at or after point.
11862 If there is no link at point, this function will search forward up to
11863 the end of the current subtree.
11864 Normally, files will be opened by an appropriate application. If the
11865 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11866 (interactive "P")
11867 (move-marker org-open-link-marker (point))
11868 (setq org-window-config-before-follow-link (current-window-configuration))
11869 (org-remove-occur-highlights nil nil t)
11870 (if (org-at-timestamp-p t)
11871 (org-follow-timestamp-link)
11872 (let (type path link line search (pos (point)))
11873 (catch 'match
11874 (save-excursion
11875 (skip-chars-forward "^]\n\r")
11876 (when (org-in-regexp org-bracket-link-regexp)
11877 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11878 (while (string-match " *\n *" link)
11879 (setq link (replace-match " " t t link)))
11880 (setq link (org-link-expand-abbrev link))
11881 (if (string-match org-link-re-with-space2 link)
11882 (setq type (match-string 1 link) path (match-string 2 link))
11883 (setq type "thisfile" path link))
11884 (throw 'match t)))
11886 (when (get-text-property (point) 'org-linked-text)
11887 (setq type "thisfile"
11888 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11889 (1+ (point)) (point))
11890 path (buffer-substring
11891 (previous-single-property-change pos 'org-linked-text)
11892 (next-single-property-change pos 'org-linked-text)))
11893 (throw 'match t))
11895 (save-excursion
11896 (when (or (org-in-regexp org-angle-link-re)
11897 (org-in-regexp org-plain-link-re))
11898 (setq type (match-string 1) path (match-string 2))
11899 (throw 'match t)))
11900 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11901 (setq type "tree-match"
11902 path (match-string 1))
11903 (throw 'match t))
11904 (save-excursion
11905 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11906 (setq type "tags"
11907 path (match-string 1))
11908 (while (string-match ":" path)
11909 (setq path (replace-match "+" t t path)))
11910 (throw 'match t))))
11911 (unless path
11912 (error "No link found"))
11913 ;; Remove any trailing spaces in path
11914 (if (string-match " +\\'" path)
11915 (setq path (replace-match "" t t path)))
11917 (cond
11919 ((assoc type org-link-protocols)
11920 (funcall (nth 1 (assoc type org-link-protocols)) path))
11922 ((equal type "mailto")
11923 (let ((cmd (car org-link-mailto-program))
11924 (args (cdr org-link-mailto-program)) args1
11925 (address path) (subject "") a)
11926 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11927 (setq address (match-string 1 path)
11928 subject (org-link-escape (match-string 2 path))))
11929 (while args
11930 (cond
11931 ((not (stringp (car args))) (push (pop args) args1))
11932 (t (setq a (pop args))
11933 (if (string-match "%a" a)
11934 (setq a (replace-match address t t a)))
11935 (if (string-match "%s" a)
11936 (setq a (replace-match subject t t a)))
11937 (push a args1))))
11938 (apply cmd (nreverse args1))))
11940 ((member type '("http" "https" "ftp" "news"))
11941 (browse-url (concat type ":" (org-link-escape
11942 path org-link-escape-chars-browser))))
11944 ((string= type "tags")
11945 (org-tags-view in-emacs path))
11946 ((string= type "thisfile")
11947 (if in-emacs
11948 (switch-to-buffer-other-window
11949 (org-get-buffer-for-internal-link (current-buffer)))
11950 (org-mark-ring-push))
11951 (let ((cmd `(org-link-search
11952 ,path
11953 ,(cond ((equal in-emacs '(4)) 'occur)
11954 ((equal in-emacs '(16)) 'org-occur)
11955 (t nil))
11956 ,pos)))
11957 (condition-case nil (eval cmd)
11958 (error (progn (widen) (eval cmd))))))
11960 ((string= type "tree-match")
11961 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11963 ((string= type "file")
11964 (if (string-match "::\\([0-9]+\\)\\'" path)
11965 (setq line (string-to-number (match-string 1 path))
11966 path (substring path 0 (match-beginning 0)))
11967 (if (string-match "::\\(.+\\)\\'" path)
11968 (setq search (match-string 1 path)
11969 path (substring path 0 (match-beginning 0)))))
11970 (org-open-file path in-emacs line search))
11972 ((string= type "news")
11973 (org-follow-gnus-link path))
11975 ((string= type "bbdb")
11976 (org-follow-bbdb-link path))
11978 ((string= type "info")
11979 (org-follow-info-link path))
11981 ((string= type "gnus")
11982 (let (group article)
11983 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11984 (error "Error in Gnus link"))
11985 (setq group (match-string 1 path)
11986 article (match-string 3 path))
11987 (org-follow-gnus-link group article)))
11989 ((string= type "vm")
11990 (let (folder article)
11991 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11992 (error "Error in VM link"))
11993 (setq folder (match-string 1 path)
11994 article (match-string 3 path))
11995 ;; in-emacs is the prefix arg, will be interpreted as read-only
11996 (org-follow-vm-link folder article in-emacs)))
11998 ((string= type "wl")
11999 (let (folder article)
12000 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12001 (error "Error in Wanderlust link"))
12002 (setq folder (match-string 1 path)
12003 article (match-string 3 path))
12004 (org-follow-wl-link folder article)))
12006 ((string= type "mhe")
12007 (let (folder article)
12008 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12009 (error "Error in MHE link"))
12010 (setq folder (match-string 1 path)
12011 article (match-string 3 path))
12012 (org-follow-mhe-link folder article)))
12014 ((string= type "rmail")
12015 (let (folder article)
12016 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12017 (error "Error in RMAIL link"))
12018 (setq folder (match-string 1 path)
12019 article (match-string 3 path))
12020 (org-follow-rmail-link folder article)))
12022 ((string= type "shell")
12023 (let ((cmd path))
12024 ;; The following is only for backward compatibility
12025 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12026 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12027 (if (or (not org-confirm-shell-link-function)
12028 (funcall org-confirm-shell-link-function
12029 (format "Execute \"%s\" in shell? "
12030 (org-add-props cmd nil
12031 'face 'org-warning))))
12032 (progn
12033 (message "Executing %s" cmd)
12034 (shell-command cmd))
12035 (error "Abort"))))
12037 ((string= type "elisp")
12038 (let ((cmd path))
12039 (if (or (not org-confirm-elisp-link-function)
12040 (funcall org-confirm-elisp-link-function
12041 (format "Execute \"%s\" as elisp? "
12042 (org-add-props cmd nil
12043 'face 'org-warning))))
12044 (message "%s => %s" cmd (eval (read cmd)))
12045 (error "Abort"))))
12048 (browse-url-at-point)))))
12049 (move-marker org-open-link-marker nil))
12051 ;;; File search
12053 (defvar org-create-file-search-functions nil
12054 "List of functions to construct the right search string for a file link.
12055 These functions are called in turn with point at the location to
12056 which the link should point.
12058 A function in the hook should first test if it would like to
12059 handle this file type, for example by checking the major-mode or
12060 the file extension. If it decides not to handle this file, it
12061 should just return nil to give other functions a chance. If it
12062 does handle the file, it must return the search string to be used
12063 when following the link. The search string will be part of the
12064 file link, given after a double colon, and `org-open-at-point'
12065 will automatically search for it. If special measures must be
12066 taken to make the search successful, another function should be
12067 added to the companion hook `org-execute-file-search-functions',
12068 which see.
12070 A function in this hook may also use `setq' to set the variable
12071 `description' to provide a suggestion for the descriptive text to
12072 be used for this link when it gets inserted into an Org-mode
12073 buffer with \\[org-insert-link].")
12075 (defvar org-execute-file-search-functions nil
12076 "List of functions to execute a file search triggered by a link.
12078 Functions added to this hook must accept a single argument, the
12079 search string that was part of the file link, the part after the
12080 double colon. The function must first check if it would like to
12081 handle this search, for example by checking the major-mode or the
12082 file extension. If it decides not to handle this search, it
12083 should just return nil to give other functions a chance. If it
12084 does handle the search, it must return a non-nil value to keep
12085 other functions from trying.
12087 Each function can access the current prefix argument through the
12088 variable `current-prefix-argument'. Note that a single prefix is
12089 used to force opening a link in Emacs, so it may be good to only
12090 use a numeric or double prefix to guide the search function.
12092 In case this is needed, a function in this hook can also restore
12093 the window configuration before `org-open-at-point' was called using:
12095 (set-window-configuration org-window-config-before-follow-link)")
12097 (defun org-link-search (s &optional type avoid-pos)
12098 "Search for a link search option.
12099 If S is surrounded by forward slashes, it is interpreted as a
12100 regular expression. In org-mode files, this will create an `org-occur'
12101 sparse tree. In ordinary files, `occur' will be used to list matches.
12102 If the current buffer is in `dired-mode', grep will be used to search
12103 in all files. If AVOID-POS is given, ignore matches near that position."
12104 (let ((case-fold-search t)
12105 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12106 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12107 (append '(("") (" ") ("\t") ("\n"))
12108 org-emphasis-alist)
12109 "\\|") "\\)"))
12110 (pos (point))
12111 (pre "") (post "")
12112 words re0 re1 re2 re3 re4 re5 re2a reall)
12113 (cond
12114 ;; First check if there are any special
12115 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12116 ;; Now try the builtin stuff
12117 ((save-excursion
12118 (goto-char (point-min))
12119 (and
12120 (re-search-forward
12121 (concat "<<" (regexp-quote s0) ">>") nil t)
12122 (setq pos (match-beginning 0))))
12123 ;; There is an exact target for this
12124 (goto-char pos))
12125 ((string-match "^/\\(.*\\)/$" s)
12126 ;; A regular expression
12127 (cond
12128 ((org-mode-p)
12129 (org-occur (match-string 1 s)))
12130 ;;((eq major-mode 'dired-mode)
12131 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12132 (t (org-do-occur (match-string 1 s)))))
12134 ;; A normal search strings
12135 (when (equal (string-to-char s) ?*)
12136 ;; Anchor on headlines, post may include tags.
12137 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12138 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12139 s (substring s 1)))
12140 (remove-text-properties
12141 0 (length s)
12142 '(face nil mouse-face nil keymap nil fontified nil) s)
12143 ;; Make a series of regular expressions to find a match
12144 (setq words (org-split-string s "[ \n\r\t]+")
12145 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12146 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12147 "\\)" markers)
12148 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12149 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12150 re1 (concat pre re2 post)
12151 re3 (concat pre re4 post)
12152 re5 (concat pre ".*" re4)
12153 re2 (concat pre re2)
12154 re2a (concat pre re2a)
12155 re4 (concat pre re4)
12156 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12157 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12158 re5 "\\)"
12160 (cond
12161 ((eq type 'org-occur) (org-occur reall))
12162 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12163 (t (goto-char (point-min))
12164 (if (or (org-search-not-self 1 re0 nil t)
12165 (org-search-not-self 1 re1 nil t)
12166 (org-search-not-self 1 re2 nil t)
12167 (org-search-not-self 1 re2a nil t)
12168 (org-search-not-self 1 re3 nil t)
12169 (org-search-not-self 1 re4 nil t)
12170 (org-search-not-self 1 re5 nil t)
12172 (goto-char (match-beginning 1))
12173 (goto-char pos)
12174 (error "No match")))))
12176 ;; Normal string-search
12177 (goto-char (point-min))
12178 (if (search-forward s nil t)
12179 (goto-char (match-beginning 0))
12180 (error "No match"))))
12181 (and (org-mode-p) (org-show-context 'link-search))))
12183 (defun org-search-not-self (group &rest args)
12184 "Execute `re-search-forward', but only accept matches that do not
12185 enclose the position of `org-open-link-marker'."
12186 (let ((m org-open-link-marker))
12187 (catch 'exit
12188 (while (apply 're-search-forward args)
12189 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12190 (goto-char (match-end group))
12191 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12192 (> (match-beginning 0) (marker-position m))
12193 (< (match-end 0) (marker-position m)))
12194 (save-match-data
12195 (or (not (org-in-regexp
12196 org-bracket-link-analytic-regexp 1))
12197 (not (match-end 4)) ; no description
12198 (and (<= (match-beginning 4) (point))
12199 (>= (match-end 4) (point))))))
12200 (throw 'exit (point))))))))
12202 (defun org-get-buffer-for-internal-link (buffer)
12203 "Return a buffer to be used for displaying the link target of internal links."
12204 (cond
12205 ((not org-display-internal-link-with-indirect-buffer)
12206 buffer)
12207 ((string-match "(Clone)$" (buffer-name buffer))
12208 (message "Buffer is already a clone, not making another one")
12209 ;; we also do not modify visibility in this case
12210 buffer)
12211 (t ; make a new indirect buffer for displaying the link
12212 (let* ((bn (buffer-name buffer))
12213 (ibn (concat bn "(Clone)"))
12214 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12215 (with-current-buffer ib (org-overview))
12216 ib))))
12218 (defun org-do-occur (regexp &optional cleanup)
12219 "Call the Emacs command `occur'.
12220 If CLEANUP is non-nil, remove the printout of the regular expression
12221 in the *Occur* buffer. This is useful if the regex is long and not useful
12222 to read."
12223 (occur regexp)
12224 (when cleanup
12225 (let ((cwin (selected-window)) win beg end)
12226 (when (setq win (get-buffer-window "*Occur*"))
12227 (select-window win))
12228 (goto-char (point-min))
12229 (when (re-search-forward "match[a-z]+" nil t)
12230 (setq beg (match-end 0))
12231 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12232 (setq end (1- (match-beginning 0)))))
12233 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12234 (goto-char (point-min))
12235 (select-window cwin))))
12237 ;;; The mark ring for links jumps
12239 (defvar org-mark-ring nil
12240 "Mark ring for positions before jumps in Org-mode.")
12241 (defvar org-mark-ring-last-goto nil
12242 "Last position in the mark ring used to go back.")
12243 ;; Fill and close the ring
12244 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12245 (loop for i from 1 to org-mark-ring-length do
12246 (push (make-marker) org-mark-ring))
12247 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12248 org-mark-ring)
12250 (defun org-mark-ring-push (&optional pos buffer)
12251 "Put the current position or POS into the mark ring and rotate it."
12252 (interactive)
12253 (setq pos (or pos (point)))
12254 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12255 (move-marker (car org-mark-ring)
12256 (or pos (point))
12257 (or buffer (current-buffer)))
12258 (message
12259 (substitute-command-keys
12260 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12262 (defun org-mark-ring-goto (&optional n)
12263 "Jump to the previous position in the mark ring.
12264 With prefix arg N, jump back that many stored positions. When
12265 called several times in succession, walk through the entire ring.
12266 Org-mode commands jumping to a different position in the current file,
12267 or to another Org-mode file, automatically push the old position
12268 onto the ring."
12269 (interactive "p")
12270 (let (p m)
12271 (if (eq last-command this-command)
12272 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12273 (setq p org-mark-ring))
12274 (setq org-mark-ring-last-goto p)
12275 (setq m (car p))
12276 (switch-to-buffer (marker-buffer m))
12277 (goto-char m)
12278 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12280 (defun org-remove-angle-brackets (s)
12281 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12282 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12284 (defun org-add-angle-brackets (s)
12285 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12286 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12289 ;;; Following specific links
12291 (defun org-follow-timestamp-link ()
12292 (cond
12293 ((org-at-date-range-p t)
12294 (let ((org-agenda-start-on-weekday)
12295 (t1 (match-string 1))
12296 (t2 (match-string 2)))
12297 (setq t1 (time-to-days (org-time-string-to-time t1))
12298 t2 (time-to-days (org-time-string-to-time t2)))
12299 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12300 ((org-at-timestamp-p t)
12301 (org-agenda-list nil (time-to-days (org-time-string-to-time
12302 (substring (match-string 1) 0 10)))
12304 (t (error "This should not happen"))))
12307 (defun org-follow-bbdb-link (name)
12308 "Follow a BBDB link to NAME."
12309 (require 'bbdb)
12310 (let ((inhibit-redisplay (not debug-on-error))
12311 (bbdb-electric-p nil))
12312 (catch 'exit
12313 ;; Exact match on name
12314 (bbdb-name (concat "\\`" name "\\'") nil)
12315 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12316 ;; Exact match on name
12317 (bbdb-company (concat "\\`" name "\\'") nil)
12318 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12319 ;; Partial match on name
12320 (bbdb-name name nil)
12321 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12322 ;; Partial match on company
12323 (bbdb-company name nil)
12324 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12325 ;; General match including network address and notes
12326 (bbdb name nil)
12327 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12328 (delete-window (get-buffer-window "*BBDB*"))
12329 (error "No matching BBDB record")))))
12331 (defun org-follow-info-link (name)
12332 "Follow an info file & node link to NAME."
12333 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12334 (string-match "\\(.*\\)" name))
12335 (progn
12336 (require 'info)
12337 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12338 (Info-find-node (match-string 1 name) (match-string 2 name))
12339 (Info-find-node (match-string 1 name) "Top")))
12340 (message (concat "Could not open: " name))))
12342 (defun org-follow-gnus-link (&optional group article)
12343 "Follow a Gnus link to GROUP and ARTICLE."
12344 (require 'gnus)
12345 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12346 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12347 (cond ((and group article)
12348 (gnus-group-read-group 1 nil group)
12349 (gnus-summary-goto-article (string-to-number article) nil t))
12350 (group (gnus-group-jump-to-group group))))
12352 (defun org-follow-vm-link (&optional folder article readonly)
12353 "Follow a VM link to FOLDER and ARTICLE."
12354 (require 'vm)
12355 (setq article (org-add-angle-brackets article))
12356 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12357 ;; ange-ftp or efs or tramp access
12358 (let ((user (or (match-string 1 folder) (user-login-name)))
12359 (host (match-string 2 folder))
12360 (file (match-string 3 folder)))
12361 (cond
12362 ((featurep 'tramp)
12363 ;; use tramp to access the file
12364 (if (featurep 'xemacs)
12365 (setq folder (format "[%s@%s]%s" user host file))
12366 (setq folder (format "/%s@%s:%s" user host file))))
12368 ;; use ange-ftp or efs
12369 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12370 (setq folder (format "/%s@%s:%s" user host file))))))
12371 (when folder
12372 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12373 (sit-for 0.1)
12374 (when article
12375 (vm-select-folder-buffer)
12376 (widen)
12377 (let ((case-fold-search t))
12378 (goto-char (point-min))
12379 (if (not (re-search-forward
12380 (concat "^" "message-id: *" (regexp-quote article))))
12381 (error "Could not find the specified message in this folder"))
12382 (vm-isearch-update)
12383 (vm-isearch-narrow)
12384 (vm-beginning-of-message)
12385 (vm-summarize)))))
12387 (defun org-follow-wl-link (folder article)
12388 "Follow a Wanderlust link to FOLDER and ARTICLE."
12389 (if (and (string= folder "%")
12390 article
12391 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12392 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12393 ;; Thus, we recompose folder and article ids.
12394 (setq folder (format "%s#%s" folder (match-string 1 article))
12395 article (match-string 3 article)))
12396 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12397 (error "No such folder: %s" folder))
12398 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12399 (and article
12400 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12401 (wl-summary-redisplay)))
12403 (defun org-follow-rmail-link (folder article)
12404 "Follow an RMAIL link to FOLDER and ARTICLE."
12405 (setq article (org-add-angle-brackets article))
12406 (let (message-number)
12407 (save-excursion
12408 (save-window-excursion
12409 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12410 (setq message-number
12411 (save-restriction
12412 (widen)
12413 (goto-char (point-max))
12414 (if (re-search-backward
12415 (concat "^Message-ID:\\s-+" (regexp-quote
12416 (or article "")))
12417 nil t)
12418 (rmail-what-message))))))
12419 (if message-number
12420 (progn
12421 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12422 (rmail-show-message message-number)
12423 message-number)
12424 (error "Message not found"))))
12426 ;;; mh-e integration based on planner-mode
12427 (defun org-mhe-get-message-real-folder ()
12428 "Return the name of the current message real folder, so if you use
12429 sequences, it will now work."
12430 (save-excursion
12431 (let* ((folder
12432 (if (equal major-mode 'mh-folder-mode)
12433 mh-current-folder
12434 ;; Refer to the show buffer
12435 mh-show-folder-buffer))
12436 (end-index
12437 (if (boundp 'mh-index-folder)
12438 (min (length mh-index-folder) (length folder))))
12440 ;; a simple test on mh-index-data does not work, because
12441 ;; mh-index-data is always nil in a show buffer.
12442 (if (and (boundp 'mh-index-folder)
12443 (string= mh-index-folder (substring folder 0 end-index)))
12444 (if (equal major-mode 'mh-show-mode)
12445 (save-window-excursion
12446 (let (pop-up-frames)
12447 (when (buffer-live-p (get-buffer folder))
12448 (progn
12449 (pop-to-buffer folder)
12450 (org-mhe-get-message-folder-from-index)
12453 (org-mhe-get-message-folder-from-index)
12455 folder
12459 (defun org-mhe-get-message-folder-from-index ()
12460 "Returns the name of the message folder in a index folder buffer."
12461 (save-excursion
12462 (mh-index-previous-folder)
12463 (re-search-forward "^\\(+.*\\)$" nil t)
12464 (message (match-string 1))))
12466 (defun org-mhe-get-message-folder ()
12467 "Return the name of the current message folder. Be careful if you
12468 use sequences."
12469 (save-excursion
12470 (if (equal major-mode 'mh-folder-mode)
12471 mh-current-folder
12472 ;; Refer to the show buffer
12473 mh-show-folder-buffer)))
12475 (defun org-mhe-get-message-num ()
12476 "Return the number of the current message. Be careful if you
12477 use sequences."
12478 (save-excursion
12479 (if (equal major-mode 'mh-folder-mode)
12480 (mh-get-msg-num nil)
12481 ;; Refer to the show buffer
12482 (mh-show-buffer-message-number))))
12484 (defun org-mhe-get-header (header)
12485 "Return a header of the message in folder mode. This will create a
12486 show buffer for the corresponding message. If you have a more clever
12487 idea..."
12488 (let* ((folder (org-mhe-get-message-folder))
12489 (num (org-mhe-get-message-num))
12490 (buffer (get-buffer-create (concat "show-" folder)))
12491 (header-field))
12492 (with-current-buffer buffer
12493 (mh-display-msg num folder)
12494 (if (equal major-mode 'mh-folder-mode)
12495 (mh-header-display)
12496 (mh-show-header-display))
12497 (set-buffer buffer)
12498 (setq header-field (mh-get-header-field header))
12499 (if (equal major-mode 'mh-folder-mode)
12500 (mh-show)
12501 (mh-show-show))
12502 header-field)))
12504 (defun org-follow-mhe-link (folder article)
12505 "Follow an MHE link to FOLDER and ARTICLE.
12506 If ARTICLE is nil FOLDER is shown. If the configuration variable
12507 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12508 ARTICLE is searched in all folders. Indexed searches (swish++,
12509 namazu, and others supported by MH-E) will always search in all
12510 folders."
12511 (require 'mh-e)
12512 (require 'mh-search)
12513 (require 'mh-utils)
12514 (mh-find-path)
12515 (if (not article)
12516 (mh-visit-folder (mh-normalize-folder-name folder))
12517 (setq article (org-add-angle-brackets article))
12518 (mh-search-choose)
12519 (if (equal mh-searcher 'pick)
12520 (progn
12521 (mh-search folder (list "--message-id" article))
12522 (when (and org-mhe-search-all-folders
12523 (not (org-mhe-get-message-real-folder)))
12524 (kill-this-buffer)
12525 (mh-search "+" (list "--message-id" article))))
12526 (mh-search "+" article))
12527 (if (org-mhe-get-message-real-folder)
12528 (mh-show-msg 1)
12529 (kill-this-buffer)
12530 (error "Message not found"))))
12532 ;;; BibTeX links
12534 ;; Use the custom search meachnism to construct and use search strings for
12535 ;; file links to BibTeX database entries.
12537 (defun org-create-file-search-in-bibtex ()
12538 "Create the search string and description for a BibTeX database entry."
12539 (when (eq major-mode 'bibtex-mode)
12540 ;; yes, we want to construct this search string.
12541 ;; Make a good description for this entry, using names, year and the title
12542 ;; Put it into the `description' variable which is dynamically scoped.
12543 (let ((bibtex-autokey-names 1)
12544 (bibtex-autokey-names-stretch 1)
12545 (bibtex-autokey-name-case-convert-function 'identity)
12546 (bibtex-autokey-name-separator " & ")
12547 (bibtex-autokey-additional-names " et al.")
12548 (bibtex-autokey-year-length 4)
12549 (bibtex-autokey-name-year-separator " ")
12550 (bibtex-autokey-titlewords 3)
12551 (bibtex-autokey-titleword-separator " ")
12552 (bibtex-autokey-titleword-case-convert-function 'identity)
12553 (bibtex-autokey-titleword-length 'infty)
12554 (bibtex-autokey-year-title-separator ": "))
12555 (setq description (bibtex-generate-autokey)))
12556 ;; Now parse the entry, get the key and return it.
12557 (save-excursion
12558 (bibtex-beginning-of-entry)
12559 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12561 (defun org-execute-file-search-in-bibtex (s)
12562 "Find the link search string S as a key for a database entry."
12563 (when (eq major-mode 'bibtex-mode)
12564 ;; Yes, we want to do the search in this file.
12565 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12566 (goto-char (point-min))
12567 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12568 (regexp-quote s) "[ \t\n]*,") nil t)
12569 (goto-char (match-beginning 0)))
12570 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12571 ;; Use double prefix to indicate that any web link should be browsed
12572 (let ((b (current-buffer)) (p (point)))
12573 ;; Restore the window configuration because we just use the web link
12574 (set-window-configuration org-window-config-before-follow-link)
12575 (save-excursion (set-buffer b) (goto-char p)
12576 (bibtex-url)))
12577 (recenter 0)) ; Move entry start to beginning of window
12578 ;; return t to indicate that the search is done.
12581 ;; Finally add the functions to the right hooks.
12582 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12583 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12585 ;; end of Bibtex link setup
12587 ;;; Following file links
12589 (defun org-open-file (path &optional in-emacs line search)
12590 "Open the file at PATH.
12591 First, this expands any special file name abbreviations. Then the
12592 configuration variable `org-file-apps' is checked if it contains an
12593 entry for this file type, and if yes, the corresponding command is launched.
12594 If no application is found, Emacs simply visits the file.
12595 With optional argument IN-EMACS, Emacs will visit the file.
12596 Optional LINE specifies a line to go to, optional SEARCH a string to
12597 search for. If LINE or SEARCH is given, the file will always be
12598 opened in Emacs.
12599 If the file does not exist, an error is thrown."
12600 (setq in-emacs (or in-emacs line search))
12601 (let* ((file (if (equal path "")
12602 buffer-file-name
12603 (substitute-in-file-name (expand-file-name path))))
12604 (apps (append org-file-apps (org-default-apps)))
12605 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12606 (dirp (if remp nil (file-directory-p file)))
12607 (dfile (downcase file))
12608 (old-buffer (current-buffer))
12609 (old-pos (point))
12610 (old-mode major-mode)
12611 ext cmd)
12612 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12613 (setq ext (match-string 1 dfile))
12614 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12615 (setq ext (match-string 1 dfile))))
12616 (if in-emacs
12617 (setq cmd 'emacs)
12618 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12619 (and dirp (cdr (assoc 'directory apps)))
12620 (cdr (assoc ext apps))
12621 (cdr (assoc t apps)))))
12622 (when (eq cmd 'mailcap)
12623 (require 'mailcap)
12624 (mailcap-parse-mailcaps)
12625 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12626 (command (mailcap-mime-info mime-type)))
12627 (if (stringp command)
12628 (setq cmd command)
12629 (setq cmd 'emacs))))
12630 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12631 (not (file-exists-p file))
12632 (not org-open-non-existing-files))
12633 (error "No such file: %s" file))
12634 (cond
12635 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12636 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12637 (if (string-match "['\"]%s['\"]" cmd)
12638 (setq cmd (replace-match "%s" t t cmd)))
12639 (setq cmd (format cmd (shell-quote-argument file)))
12640 (save-window-excursion
12641 (start-process-shell-command cmd nil cmd)))
12642 ((or (stringp cmd)
12643 (eq cmd 'emacs))
12644 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12645 (widen)
12646 (if line (goto-line line)
12647 (if search (org-link-search search))))
12648 ((consp cmd)
12649 (eval cmd))
12650 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12651 (and (org-mode-p) (eq old-mode 'org-mode)
12652 (or (not (equal old-buffer (current-buffer)))
12653 (not (equal old-pos (point))))
12654 (org-mark-ring-push old-pos old-buffer))))
12656 (defun org-default-apps ()
12657 "Return the default applications for this operating system."
12658 (cond
12659 ((eq system-type 'darwin)
12660 org-file-apps-defaults-macosx)
12661 ((eq system-type 'windows-nt)
12662 org-file-apps-defaults-windowsnt)
12663 (t org-file-apps-defaults-gnu)))
12665 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12666 (defun org-file-remote-p (file)
12667 "Test whether FILE specifies a location on a remote system.
12668 Return non-nil if the location is indeed remote.
12670 For example, the filename \"/user@host:/foo\" specifies a location
12671 on the system \"/user@host:\"."
12672 (cond ((fboundp 'file-remote-p)
12673 (file-remote-p file))
12674 ((fboundp 'tramp-handle-file-remote-p)
12675 (tramp-handle-file-remote-p file))
12676 ((and (boundp 'ange-ftp-name-format)
12677 (string-match (car ange-ftp-name-format) file))
12679 (t nil)))
12682 ;;;; Hooks for remember.el
12684 ;;;###autoload
12685 (defun org-remember-annotation ()
12686 "Return a link to the current location as an annotation for remember.el.
12687 If you are using Org-mode files as target for data storage with
12688 remember.el, then the annotations should include a link compatible with the
12689 conventions in Org-mode. This function returns such a link."
12690 (org-store-link nil))
12692 (defconst org-remember-help
12693 "Select a destination location for the note.
12694 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12695 RET on headline -> Store as sublevel entry to current headline
12696 RET at beg-of-buf -> Append to file as level 2 headline
12697 <left>/<right> -> before/after current headline, same headings level")
12699 (defvar org-remember-previous-location nil)
12700 (defvar org-force-remember-template-char) ;; dynamically scoped
12702 ;;;###autoload
12703 (defun org-remember-apply-template (&optional use-char skip-interactive)
12704 "Initialize *remember* buffer with template, invoke `org-mode'.
12705 This function should be placed into `remember-mode-hook' and in fact requires
12706 to be run from that hook to fucntion properly."
12707 (if org-remember-templates
12708 (let* ((templates (mapcar (lambda (x)
12709 (if (stringp (car x))
12710 (append (list (nth 1 x) (car x)) (cddr x))
12711 (append (list (car x) "") (cdr x))))
12712 org-remember-templates))
12713 (char (or use-char
12714 (cond
12715 ((= (length templates) 1)
12716 (caar templates))
12717 ((and (boundp 'org-force-remember-template-char)
12718 org-force-remember-template-char)
12719 (if (stringp org-force-remember-template-char)
12720 (string-to-char org-force-remember-template-char)
12721 org-force-remember-template-char))
12723 (message "Select template: %s"
12724 (mapconcat
12725 (lambda (x)
12726 (cond
12727 ((not (string-match "\\S-" (nth 1 x)))
12728 (format "[%c]" (car x)))
12729 ((equal (downcase (car x))
12730 (downcase (aref (nth 1 x) 0)))
12731 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12732 (t (format "[%c]%s" (car x) (nth 1 x)))))
12733 templates " "))
12734 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12735 (when (equal char0 ?\C-g)
12736 (jump-to-register remember-register)
12737 (kill-buffer remember-buffer))
12738 char0)))))
12739 (entry (cddr (assoc char templates)))
12740 (tpl (car entry))
12741 (plist-p (if org-store-link-plist t nil))
12742 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12743 (string-match "\\S-" (nth 1 entry)))
12744 (nth 1 entry)
12745 org-default-notes-file))
12746 (headline (nth 2 entry))
12747 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12748 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12749 (v-u (concat "[" (substring v-t 1 -1) "]"))
12750 (v-U (concat "[" (substring v-T 1 -1) "]"))
12751 ;; `initial' and `annotation' are bound in `remember'
12752 (v-i (if (boundp 'initial) initial))
12753 (v-a (if (and (boundp 'annotation) annotation)
12754 (if (equal annotation "[[]]") "" annotation)
12755 ""))
12756 (v-A (if (and v-a
12757 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12758 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12759 v-a))
12760 (v-n user-full-name)
12761 (org-startup-folded nil)
12762 org-time-was-given org-end-time-was-given x prompt char time)
12763 (setq org-store-link-plist
12764 (append (list :annotation v-a :initial v-i)
12765 org-store-link-plist))
12766 (unless tpl (setq tpl "") (message "No template") (ding))
12767 (erase-buffer)
12768 (insert (substitute-command-keys
12769 (format
12770 "## Filing location: Select interactively, default, or last used:
12771 ## %s to select file and header location interactively.
12772 ## %s \"%s\" -> \"* %s\"
12773 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12774 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12775 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12776 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12777 (abbreviate-file-name (or file org-default-notes-file))
12778 (or headline "")
12779 (or (car org-remember-previous-location) "???")
12780 (or (cdr org-remember-previous-location) "???"))))
12781 (insert tpl) (goto-char (point-min))
12782 ;; Simple %-escapes
12783 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12784 (when (and initial (equal (match-string 0) "%i"))
12785 (save-match-data
12786 (let* ((lead (buffer-substring
12787 (point-at-bol) (match-beginning 0))))
12788 (setq v-i (mapconcat 'identity
12789 (org-split-string initial "\n")
12790 (concat "\n" lead))))))
12791 (replace-match
12792 (or (eval (intern (concat "v-" (match-string 1)))) "")
12793 t t))
12794 ;; From the property list
12795 (when plist-p
12796 (goto-char (point-min))
12797 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12798 (and (setq x (plist-get org-store-link-plist
12799 (intern (match-string 1))))
12800 (replace-match x t t))))
12801 ;; Turn on org-mode in the remember buffer, set local variables
12802 (org-mode)
12803 (org-set-local 'org-finish-function 'remember-buffer)
12804 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12805 (org-set-local 'org-default-notes-file file))
12806 (if (and headline (stringp headline) (string-match "\\S-" headline))
12807 (org-set-local 'org-remember-default-headline headline))
12808 ;; Interactive template entries
12809 (goto-char (point-min))
12810 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12811 (setq char (if (match-end 3) (match-string 3))
12812 prompt (if (match-end 2) (match-string 2)))
12813 (goto-char (match-beginning 0))
12814 (replace-match "")
12815 (cond
12816 ((member char '("G" "g"))
12817 (let* ((org-last-tags-completion-table
12818 (org-global-tags-completion-table
12819 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12820 (org-add-colon-after-tag-completion t)
12821 (ins (completing-read
12822 (if prompt (concat prompt ": ") "Tags: ")
12823 'org-tags-completion-function nil nil nil
12824 'org-tags-history)))
12825 (setq ins (mapconcat 'identity
12826 (org-split-string ins (org-re "[^[:alnum:]]+"))
12827 ":"))
12828 (when (string-match "\\S-" ins)
12829 (or (equal (char-before) ?:) (insert ":"))
12830 (insert ins)
12831 (or (equal (char-after) ?:) (insert ":")))))
12832 (char
12833 (setq org-time-was-given (equal (upcase char) char))
12834 (setq time (org-read-date (equal (upcase char) "U") t nil
12835 prompt))
12836 (org-insert-time-stamp time org-time-was-given
12837 (member char '("u" "U"))
12838 nil nil (list org-end-time-was-given)))
12840 (insert (read-string
12841 (if prompt (concat prompt ": ") "Enter string"))))))
12842 (goto-char (point-min))
12843 (if (re-search-forward "%\\?" nil t)
12844 (replace-match "")
12845 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12846 (org-mode)
12847 (org-set-local 'org-finish-function 'remember-buffer)))
12849 ;;;###autoload
12850 (defun org-remember (&optional org-force-remember-template-char)
12851 "Call `remember'. If this is already a remember buffer, re-apply template.
12852 If there is an active region, make sure remember uses it as initial content
12853 of the remember buffer."
12854 (interactive)
12855 (if (eq org-finish-function 'remember-buffer)
12856 (progn
12857 (when (< (length org-remember-templates) 2)
12858 (error "No other template available"))
12859 (erase-buffer)
12860 (let ((annotation (plist-get org-store-link-plist :annotation))
12861 (initial (plist-get org-store-link-plist :initial)))
12862 (org-remember-apply-template))
12863 (message "Press C-c C-c to remember data"))
12864 (if (org-region-active-p)
12865 (remember (buffer-substring (point) (mark)))
12866 (call-interactively 'remember))))
12868 (defvar org-note-abort nil) ; dynamically scoped
12870 ;;;###autoload
12871 (defun org-remember-handler ()
12872 "Store stuff from remember.el into an org file.
12873 First prompts for an org file. If the user just presses return, the value
12874 of `org-default-notes-file' is used.
12875 Then the command offers the headings tree of the selected file in order to
12876 file the text at a specific location.
12877 You can either immediately press RET to get the note appended to the
12878 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12879 find a better place. Then press RET or <left> or <right> in insert the note.
12881 Key Cursor position Note gets inserted
12882 -----------------------------------------------------------------------------
12883 RET buffer-start as level 1 heading at end of file
12884 RET on headline as sublevel of the heading at cursor
12885 RET no heading at cursor position, level taken from context.
12886 Or use prefix arg to specify level manually.
12887 <left> on headline as same level, before current heading
12888 <right> on headline as same level, after current heading
12890 So the fastest way to store the note is to press RET RET to append it to
12891 the default file. This way your current train of thought is not
12892 interrupted, in accordance with the principles of remember.el.
12893 You can also get the fast execution without prompting by using
12894 C-u C-c C-c to exit the remember buffer. See also the variable
12895 `org-remember-store-without-prompt'.
12897 Before being stored away, the function ensures that the text has a
12898 headline, i.e. a first line that starts with a \"*\". If not, a headline
12899 is constructed from the current date and some additional data.
12901 If the variable `org-adapt-indentation' is non-nil, the entire text is
12902 also indented so that it starts in the same column as the headline
12903 \(i.e. after the stars).
12905 See also the variable `org-reverse-note-order'."
12906 (goto-char (point-min))
12907 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12908 (replace-match ""))
12909 (goto-char (point-max))
12910 (unless (equal (char-before) ?\n) (insert "\n"))
12911 (catch 'quit
12912 (if org-note-abort (throw 'quit nil))
12913 (let* ((txt (buffer-substring (point-min) (point-max)))
12914 (fastp (org-xor (equal current-prefix-arg '(4))
12915 org-remember-store-without-prompt))
12916 (file (if fastp org-default-notes-file (org-get-org-file)))
12917 (heading org-remember-default-headline)
12918 (visiting (org-find-base-buffer-visiting file))
12919 (org-startup-folded nil)
12920 (org-startup-align-all-tables nil)
12921 (org-goto-start-pos 1)
12922 spos exitcmd level indent reversed)
12923 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12924 (setq file (car org-remember-previous-location)
12925 heading (cdr org-remember-previous-location)))
12926 (setq current-prefix-arg nil)
12927 ;; Modify text so that it becomes a nice subtree which can be inserted
12928 ;; into an org tree.
12929 (let* ((lines (split-string txt "\n"))
12930 first)
12931 (setq first (car lines) lines (cdr lines))
12932 (if (string-match "^\\*+ " first)
12933 ;; Is already a headline
12934 (setq indent nil)
12935 ;; We need to add a headline: Use time and first buffer line
12936 (setq lines (cons first lines)
12937 first (concat "* " (current-time-string)
12938 " (" (remember-buffer-desc) ")")
12939 indent " "))
12940 (if (and org-adapt-indentation indent)
12941 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12942 (setq txt (concat first "\n"
12943 (mapconcat 'identity lines "\n"))))
12944 ;; Find the file
12945 (if (not visiting) (find-file-noselect file))
12946 (with-current-buffer (or visiting (get-file-buffer file))
12947 (unless (org-mode-p)
12948 (error "Target files for remember notes must be in Org-mode"))
12949 (save-excursion
12950 (save-restriction
12951 (widen)
12952 (and (goto-char (point-min))
12953 (not (re-search-forward "^\\* " nil t))
12954 (insert "\n* " (or heading "Notes") "\n"))
12955 (setq reversed (org-notes-order-reversed-p))
12957 ;; Find the default location
12958 (when (and heading (stringp heading) (string-match "\\S-" heading))
12959 (goto-char (point-min))
12960 (if (re-search-forward
12961 (concat "^\\*+[ \t]+" (regexp-quote heading)
12962 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12963 nil t)
12964 (setq org-goto-start-pos (match-beginning 0))
12965 (when fastp
12966 (goto-char (point-max))
12967 (unless (bolp) (newline))
12968 (insert "* " heading "\n")
12969 (setq org-goto-start-pos (point-at-bol 0)))))
12971 ;; Ask the User for a location
12972 (if fastp
12973 (setq spos org-goto-start-pos
12974 exitcmd 'return)
12975 (setq spos (org-get-location (current-buffer) org-remember-help)
12976 exitcmd (cdr spos)
12977 spos (car spos)))
12978 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12979 ; not handle this note
12980 (goto-char spos)
12981 (cond ((org-on-heading-p t)
12982 (org-back-to-heading t)
12983 (setq level (funcall outline-level))
12984 (cond
12985 ((eq exitcmd 'return)
12986 ;; sublevel of current
12987 (setq org-remember-previous-location
12988 (cons (abbreviate-file-name file)
12989 (org-get-heading 'notags)))
12990 (if reversed
12991 (outline-next-heading)
12992 (org-end-of-subtree)
12993 (if (not (bolp))
12994 (if (looking-at "[ \t]*\n")
12995 (beginning-of-line 2)
12996 (end-of-line 1)
12997 (insert "\n"))))
12998 (org-paste-subtree (org-get-legal-level level 1) txt))
12999 ((eq exitcmd 'left)
13000 ;; before current
13001 (org-paste-subtree level txt))
13002 ((eq exitcmd 'right)
13003 ;; after current
13004 (org-end-of-subtree t)
13005 (org-paste-subtree level txt))
13006 (t (error "This should not happen"))))
13008 ((and (bobp) (not reversed))
13009 ;; Put it at the end, one level below level 1
13010 (save-restriction
13011 (widen)
13012 (goto-char (point-max))
13013 (if (not (bolp)) (newline))
13014 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13016 ((and (bobp) reversed)
13017 ;; Put it at the start, as level 1
13018 (save-restriction
13019 (widen)
13020 (goto-char (point-min))
13021 (re-search-forward "^\\*+ " nil t)
13022 (beginning-of-line 1)
13023 (org-paste-subtree 1 txt)))
13025 ;; Put it right there, with automatic level determined by
13026 ;; org-paste-subtree or from prefix arg
13027 (org-paste-subtree
13028 (if (numberp current-prefix-arg) current-prefix-arg)
13029 txt)))
13030 (when remember-save-after-remembering
13031 (save-buffer)
13032 (if (not visiting) (kill-buffer (current-buffer)))))))))
13033 t) ;; return t to indicate that we took care of this note.
13035 (defun org-get-org-file ()
13036 "Read a filename, with default directory `org-directory'."
13037 (let ((default (or org-default-notes-file remember-data-file)))
13038 (read-file-name (format "File name [%s]: " default)
13039 (file-name-as-directory org-directory)
13040 default)))
13042 (defun org-notes-order-reversed-p ()
13043 "Check if the current file should receive notes in reversed order."
13044 (cond
13045 ((not org-reverse-note-order) nil)
13046 ((eq t org-reverse-note-order) t)
13047 ((not (listp org-reverse-note-order)) nil)
13048 (t (catch 'exit
13049 (let ((all org-reverse-note-order)
13050 entry)
13051 (while (setq entry (pop all))
13052 (if (string-match (car entry) buffer-file-name)
13053 (throw 'exit (cdr entry))))
13054 nil)))))
13056 ;;;; Dynamic blocks
13058 (defun org-find-dblock (name)
13059 "Find the first dynamic block with name NAME in the buffer.
13060 If not found, stay at current position and return nil."
13061 (let (pos)
13062 (save-excursion
13063 (goto-char (point-min))
13064 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13065 nil t)
13066 (match-beginning 0))))
13067 (if pos (goto-char pos))
13068 pos))
13070 (defconst org-dblock-start-re
13071 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13072 "Matches the startline of a dynamic block, with parameters.")
13074 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13075 "Matches the end of a dyhamic block.")
13077 (defun org-create-dblock (plist)
13078 "Create a dynamic block section, with parameters taken from PLIST.
13079 PLIST must containe a :name entry which is used as name of the block."
13080 (unless (bolp) (newline))
13081 (let ((name (plist-get plist :name)))
13082 (insert "#+BEGIN: " name)
13083 (while plist
13084 (if (eq (car plist) :name)
13085 (setq plist (cddr plist))
13086 (insert " " (prin1-to-string (pop plist)))))
13087 (insert "\n\n#+END:\n")
13088 (beginning-of-line -2)))
13090 (defun org-prepare-dblock ()
13091 "Prepare dynamic block for refresh.
13092 This empties the block, puts the cursor at the insert position and returns
13093 the property list including an extra property :name with the block name."
13094 (unless (looking-at org-dblock-start-re)
13095 (error "Not at a dynamic block"))
13096 (let* ((begdel (1+ (match-end 0)))
13097 (name (org-no-properties (match-string 1)))
13098 (params (append (list :name name)
13099 (read (concat "(" (match-string 3) ")")))))
13100 (unless (re-search-forward org-dblock-end-re nil t)
13101 (error "Dynamic block not terminated"))
13102 (delete-region begdel (match-beginning 0))
13103 (goto-char begdel)
13104 (open-line 1)
13105 params))
13107 (defun org-map-dblocks (&optional command)
13108 "Apply COMMAND to all dynamic blocks in the current buffer.
13109 If COMMAND is not given, use `org-update-dblock'."
13110 (let ((cmd (or command 'org-update-dblock))
13111 pos)
13112 (save-excursion
13113 (goto-char (point-min))
13114 (while (re-search-forward org-dblock-start-re nil t)
13115 (goto-char (setq pos (match-beginning 0)))
13116 (condition-case nil
13117 (funcall cmd)
13118 (error (message "Error during update of dynamic block")))
13119 (goto-char pos)
13120 (unless (re-search-forward org-dblock-end-re nil t)
13121 (error "Dynamic block not terminated"))))))
13123 (defun org-dblock-update (&optional arg)
13124 "User command for updating dynamic blocks.
13125 Update the dynamic block at point. With prefix ARG, update all dynamic
13126 blocks in the buffer."
13127 (interactive "P")
13128 (if arg
13129 (org-update-all-dblocks)
13130 (or (looking-at org-dblock-start-re)
13131 (org-beginning-of-dblock))
13132 (org-update-dblock)))
13134 (defun org-update-dblock ()
13135 "Update the dynamic block at point
13136 This means to empty the block, parse for parameters and then call
13137 the correct writing function."
13138 (save-window-excursion
13139 (let* ((pos (point))
13140 (line (org-current-line))
13141 (params (org-prepare-dblock))
13142 (name (plist-get params :name))
13143 (cmd (intern (concat "org-dblock-write:" name))))
13144 (message "Updating dynamic block `%s' at line %d..." name line)
13145 (funcall cmd params)
13146 (message "Updating dynamic block `%s' at line %d...done" name line)
13147 (goto-char pos))))
13149 (defun org-beginning-of-dblock ()
13150 "Find the beginning of the dynamic block at point.
13151 Error if there is no scuh block at point."
13152 (let ((pos (point))
13153 beg)
13154 (end-of-line 1)
13155 (if (and (re-search-backward org-dblock-start-re nil t)
13156 (setq beg (match-beginning 0))
13157 (re-search-forward org-dblock-end-re nil t)
13158 (> (match-end 0) pos))
13159 (goto-char beg)
13160 (goto-char pos)
13161 (error "Not in a dynamic block"))))
13163 (defun org-update-all-dblocks ()
13164 "Update all dynamic blocks in the buffer.
13165 This function can be used in a hook."
13166 (when (org-mode-p)
13167 (org-map-dblocks 'org-update-dblock)))
13170 ;;;; Completion
13172 (defconst org-additional-option-like-keywords
13173 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13174 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:"))
13176 (defun org-complete (&optional arg)
13177 "Perform completion on word at point.
13178 At the beginning of a headline, this completes TODO keywords as given in
13179 `org-todo-keywords'.
13180 If the current word is preceded by a backslash, completes the TeX symbols
13181 that are supported for HTML support.
13182 If the current word is preceded by \"#+\", completes special words for
13183 setting file options.
13184 In the line after \"#+STARTUP:, complete valid keywords.\"
13185 At all other locations, this simply calls the value of
13186 `org-completion-fallback-command'."
13187 (interactive "P")
13188 (org-without-partial-completion
13189 (catch 'exit
13190 (let* ((end (point))
13191 (beg1 (save-excursion
13192 (skip-chars-backward (org-re "[:alnum:]_@"))
13193 (point)))
13194 (beg (save-excursion
13195 (skip-chars-backward "a-zA-Z0-9_:$")
13196 (point)))
13197 (confirm (lambda (x) (stringp (car x))))
13198 (searchhead (equal (char-before beg) ?*))
13199 (tag (and (equal (char-before beg1) ?:)
13200 (equal (char-after (point-at-bol)) ?*)))
13201 (prop (and (equal (char-before beg1) ?:)
13202 (not (equal (char-after (point-at-bol)) ?*))))
13203 (texp (equal (char-before beg) ?\\))
13204 (link (equal (char-before beg) ?\[))
13205 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13206 beg)
13207 "#+"))
13208 (startup (string-match "^#\\+STARTUP:.*"
13209 (buffer-substring (point-at-bol) (point))))
13210 (completion-ignore-case opt)
13211 (type nil)
13212 (tbl nil)
13213 (table (cond
13214 (opt
13215 (setq type :opt)
13216 (append
13217 (mapcar
13218 (lambda (x)
13219 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13220 (cons (match-string 2 x) (match-string 1 x)))
13221 (org-split-string (org-get-current-options) "\n"))
13222 (mapcar 'list org-additional-option-like-keywords)))
13223 (startup
13224 (setq type :startup)
13225 org-startup-options)
13226 (link (append org-link-abbrev-alist-local
13227 org-link-abbrev-alist))
13228 (texp
13229 (setq type :tex)
13230 org-html-entities)
13231 ((string-match "\\`\\*+[ \t]+\\'"
13232 (buffer-substring (point-at-bol) beg))
13233 (setq type :todo)
13234 (mapcar 'list org-todo-keywords-1))
13235 (searchhead
13236 (setq type :searchhead)
13237 (save-excursion
13238 (goto-char (point-min))
13239 (while (re-search-forward org-todo-line-regexp nil t)
13240 (push (list
13241 (org-make-org-heading-search-string
13242 (match-string 3) t))
13243 tbl)))
13244 tbl)
13245 (tag (setq type :tag beg beg1)
13246 (or org-tag-alist (org-get-buffer-tags)))
13247 (prop (setq type :prop beg beg1)
13248 (mapcar 'list (org-buffer-property-keys)))
13249 (t (progn
13250 (call-interactively org-completion-fallback-command)
13251 (throw 'exit nil)))))
13252 (pattern (buffer-substring-no-properties beg end))
13253 (completion (try-completion pattern table confirm)))
13254 (cond ((eq completion t)
13255 (if (not (assoc (upcase pattern) table))
13256 (message "Already complete")
13257 (if (equal type :opt)
13258 (insert (substring (cdr (assoc (upcase pattern) table))
13259 (length pattern)))
13260 (if (memq type '(:tag :prop)) (insert ":")))))
13261 ((null completion)
13262 (message "Can't find completion for \"%s\"" pattern)
13263 (ding))
13264 ((not (string= pattern completion))
13265 (delete-region beg end)
13266 (if (string-match " +$" completion)
13267 (setq completion (replace-match "" t t completion)))
13268 (insert completion)
13269 (if (get-buffer-window "*Completions*")
13270 (delete-window (get-buffer-window "*Completions*")))
13271 (if (assoc completion table)
13272 (if (eq type :todo) (insert " ")
13273 (if (memq type '(:tag :prop)) (insert ":"))))
13274 (if (and (equal type :opt) (assoc completion table))
13275 (message "%s" (substitute-command-keys
13276 "Press \\[org-complete] again to insert example settings"))))
13278 (message "Making completion list...")
13279 (let ((list (sort (all-completions pattern table confirm)
13280 'string<)))
13281 (with-output-to-temp-buffer "*Completions*"
13282 (condition-case nil
13283 ;; Protection needed for XEmacs and emacs 21
13284 (display-completion-list list pattern)
13285 (error (display-completion-list list)))))
13286 (message "Making completion list...%s" "done")))))))
13288 ;;;; TODO, DEADLINE, Comments
13290 (defun org-toggle-comment ()
13291 "Change the COMMENT state of an entry."
13292 (interactive)
13293 (save-excursion
13294 (org-back-to-heading)
13295 (if (looking-at (concat outline-regexp
13296 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13297 (replace-match "" t t nil 1)
13298 (if (looking-at outline-regexp)
13299 (progn
13300 (goto-char (match-end 0))
13301 (insert org-comment-string " "))))))
13303 (defvar org-last-todo-state-is-todo nil
13304 "This is non-nil when the last TODO state change led to a TODO state.
13305 If the last change removed the TODO tag or switched to DONE, then
13306 this is nil.")
13308 (defvar org-setting-tags nil) ; dynamically skiped
13310 ;; FIXME: better place
13311 (defun org-property-or-variable-value (var &optional inherit)
13312 "Check if there is a property fixing the value of VAR.
13313 If yes, return this value. If not, return the current value of the variable."
13314 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13315 (if (and prop (stringp prop) (string-match "\\S-" prop))
13316 (read prop)
13317 (symbol-value var))))
13319 (defun org-parse-local-options (string var)
13320 "Parse STRING for startup setting relevant for variable VAR."
13321 (let ((rtn (symbol-value var))
13322 e opts)
13323 (save-match-data
13324 (if (or (not string) (not (string-match "\\S-" string)))
13326 (setq opts (delq nil (mapcar (lambda (x)
13327 (setq e (assoc x org-startup-options))
13328 (if (eq (nth 1 e) var) e nil))
13329 (org-split-string string "[ \t]+"))))
13330 (if (not opts)
13332 (setq rtn nil)
13333 (while (setq e (pop opts))
13334 (if (not (nth 3 e))
13335 (setq rtn (nth 2 e))
13336 (if (not (listp rtn)) (setq rtn nil))
13337 (push (nth 2 e) rtn)))
13338 rtn)))))
13340 (defvar org-blocker-hook nil
13341 "Hook for functions that are allowed to block a state change.
13343 Each function gets as its single argument a property list, see
13344 `org-trigger-hook' for more information about this list.
13346 If any of the functions in this hook returns nil, the state change
13347 is blocked.")
13349 (defvar org-trigger-hook nil
13350 "Hook for functions that are triggered by a state change.
13352 Each function gets as its single argument a property list with at least
13353 the following elements:
13355 (:type type-of-change :position pos-at-entry-start
13356 :from old-state :to new-state)
13358 Depending on the type, more properties may be present.
13360 This mechanism is currently implemented for:
13362 TODO state changes
13363 ------------------
13364 :type todo-state-change
13365 :from previous state (keyword as a string), or nil
13366 :to new state (keyword as a string), or nil")
13369 (defun org-todo (&optional arg)
13370 "Change the TODO state of an item.
13371 The state of an item is given by a keyword at the start of the heading,
13372 like
13373 *** TODO Write paper
13374 *** DONE Call mom
13376 The different keywords are specified in the variable `org-todo-keywords'.
13377 By default the available states are \"TODO\" and \"DONE\".
13378 So for this example: when the item starts with TODO, it is changed to DONE.
13379 When it starts with DONE, the DONE is removed. And when neither TODO nor
13380 DONE are present, add TODO at the beginning of the heading.
13382 With C-u prefix arg, use completion to determine the new state.
13383 With numeric prefix arg, switch to that state.
13385 For calling through lisp, arg is also interpreted in the following way:
13386 'none -> empty state
13387 \"\"(empty string) -> switch to empty state
13388 'done -> switch to DONE
13389 'nextset -> switch to the next set of keywords
13390 'previousset -> switch to the previous set of keywords
13391 \"WAITING\" -> switch to the specified keyword, but only if it
13392 really is a member of `org-todo-keywords'."
13393 (interactive "P")
13394 (save-excursion
13395 (catch 'exit
13396 (org-back-to-heading)
13397 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13398 (or (looking-at (concat " +" org-todo-regexp " *"))
13399 (looking-at " *"))
13400 (let* ((startpos (line-beginning-position))
13401 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13402 (org-log-done (org-parse-local-options logging 'org-log-done))
13403 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13404 (this (match-string 1))
13405 (hl-pos (match-beginning 0))
13406 (head (org-get-todo-sequence-head this))
13407 (ass (assoc head org-todo-kwd-alist))
13408 (interpret (nth 1 ass))
13409 (done-word (nth 3 ass))
13410 (final-done-word (nth 4 ass))
13411 (last-state (or this ""))
13412 (completion-ignore-case t)
13413 (member (member this org-todo-keywords-1))
13414 (tail (cdr member))
13415 (state (cond
13416 ((and org-todo-key-trigger
13417 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13418 (and (not arg) org-use-fast-todo-selection
13419 (not (eq org-use-fast-todo-selection 'prefix)))))
13420 ;; Use fast selection
13421 (org-fast-todo-selection))
13422 ((and (equal arg '(4))
13423 (or (not org-use-fast-todo-selection)
13424 (not org-todo-key-trigger)))
13425 ;; Read a state with completion
13426 (completing-read "State: " (mapcar (lambda(x) (list x))
13427 org-todo-keywords-1)
13428 nil t))
13429 ((eq arg 'right)
13430 (if this
13431 (if tail (car tail) nil)
13432 (car org-todo-keywords-1)))
13433 ((eq arg 'left)
13434 (if (equal member org-todo-keywords-1)
13436 (if this
13437 (nth (- (length org-todo-keywords-1) (length tail) 2)
13438 org-todo-keywords-1)
13439 (org-last org-todo-keywords-1))))
13440 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13441 (setq arg nil))) ; hack to fall back to cycling
13442 (arg
13443 ;; user or caller requests a specific state
13444 (cond
13445 ((equal arg "") nil)
13446 ((eq arg 'none) nil)
13447 ((eq arg 'done) (or done-word (car org-done-keywords)))
13448 ((eq arg 'nextset)
13449 (or (car (cdr (member head org-todo-heads)))
13450 (car org-todo-heads)))
13451 ((eq arg 'previousset)
13452 (let ((org-todo-heads (reverse org-todo-heads)))
13453 (or (car (cdr (member head org-todo-heads)))
13454 (car org-todo-heads))))
13455 ((car (member arg org-todo-keywords-1)))
13456 ((nth (1- (prefix-numeric-value arg))
13457 org-todo-keywords-1))))
13458 ((null member) (or head (car org-todo-keywords-1)))
13459 ((equal this final-done-word) nil) ;; -> make empty
13460 ((null tail) nil) ;; -> first entry
13461 ((eq interpret 'sequence)
13462 (car tail))
13463 ((memq interpret '(type priority))
13464 (if (eq this-command last-command)
13465 (car tail)
13466 (if (> (length tail) 0)
13467 (or done-word (car org-done-keywords))
13468 nil)))
13469 (t nil)))
13470 (next (if state (concat " " state " ") " "))
13471 (change-plist (list :type 'todo-state-change :from this :to state
13472 :position startpos))
13473 dostates)
13474 (when org-blocker-hook
13475 (unless (save-excursion
13476 (save-match-data
13477 (run-hook-with-args-until-failure
13478 'org-blocker-hook change-plist)))
13479 (if (interactive-p)
13480 (error "TODO state change from %s to %s blocked" this state)
13481 ;; fail silently
13482 (message "TODO state change from %s to %s blocked" this state)
13483 (throw 'exit nil))))
13484 (replace-match next t t)
13485 (unless (pos-visible-in-window-p hl-pos)
13486 (message "TODO state changed to %s" (org-trim next)))
13487 (unless head
13488 (setq head (org-get-todo-sequence-head state)
13489 ass (assoc head org-todo-kwd-alist)
13490 interpret (nth 1 ass)
13491 done-word (nth 3 ass)
13492 final-done-word (nth 4 ass)))
13493 (when (memq arg '(nextset previousset))
13494 (message "Keyword-Set %d/%d: %s"
13495 (- (length org-todo-sets) -1
13496 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13497 (length org-todo-sets)
13498 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13499 (setq org-last-todo-state-is-todo
13500 (not (member state org-done-keywords)))
13501 (when (and org-log-done (not (memq arg '(nextset previousset))))
13502 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13503 (or (not org-todo-log-states)
13504 (member state org-todo-log-states))))
13506 (cond
13507 ((and state (member state org-not-done-keywords)
13508 (not (member this org-not-done-keywords)))
13509 ;; This is now a todo state and was not one before
13510 ;; Remove any CLOSED timestamp, and possibly log the state change
13511 (org-add-planning-info nil nil 'closed)
13512 (and dostates (org-add-log-maybe 'state state 'findpos)))
13513 ((and state dostates)
13514 ;; This is a non-nil state, and we need to log it
13515 (org-add-log-maybe 'state state 'findpos))
13516 ((and (member state org-done-keywords)
13517 (not (member this org-done-keywords)))
13518 ;; It is now done, and it was not done before
13519 (org-add-planning-info 'closed (org-current-time))
13520 (org-add-log-maybe 'done state 'findpos))))
13521 ;; Fixup tag positioning
13522 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13523 (run-hooks 'org-after-todo-state-change-hook)
13524 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13525 (if (and arg (not (member state org-done-keywords)))
13526 (setq head (org-get-todo-sequence-head state)))
13527 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13528 ;; Fixup cursor location if close to the keyword
13529 (if (and (outline-on-heading-p)
13530 (not (bolp))
13531 (save-excursion (beginning-of-line 1)
13532 (looking-at org-todo-line-regexp))
13533 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13534 (progn
13535 (goto-char (or (match-end 2) (match-end 1)))
13536 (just-one-space)))
13537 (when org-trigger-hook
13538 (save-excursion
13539 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13541 (defun org-get-todo-sequence-head (kwd)
13542 "Return the head of the TODO sequence to which KWD belongs.
13543 If KWD is not set, check if there is a text property remembering the
13544 right sequence."
13545 (let (p)
13546 (cond
13547 ((not kwd)
13548 (or (get-text-property (point-at-bol) 'org-todo-head)
13549 (progn
13550 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13551 nil (point-at-eol)))
13552 (get-text-property p 'org-todo-head))))
13553 ((not (member kwd org-todo-keywords-1))
13554 (car org-todo-keywords-1))
13555 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13557 (defun org-fast-todo-selection ()
13558 "Fast TODO keyword selection with single keys.
13559 Returns the new TODO keyword, or nil if no state change should occur."
13560 (let* ((fulltable org-todo-key-alist)
13561 (done-keywords org-done-keywords) ;; needed for the faces.
13562 (maxlen (apply 'max (mapcar
13563 (lambda (x)
13564 (if (stringp (car x)) (string-width (car x)) 0))
13565 fulltable)))
13566 (expert nil)
13567 (fwidth (+ maxlen 3 1 3))
13568 (ncol (/ (- (window-width) 4) fwidth))
13569 tg cnt e c tbl
13570 groups ingroup)
13571 (save-window-excursion
13572 (if expert
13573 (set-buffer (get-buffer-create " *Org todo*"))
13574 ; (delete-other-windows)
13575 ; (split-window-vertically)
13576 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
13577 (erase-buffer)
13578 (org-set-local 'org-done-keywords done-keywords)
13579 (setq tbl fulltable cnt 0)
13580 (while (setq e (pop tbl))
13581 (cond
13582 ((equal e '(:startgroup))
13583 (push '() groups) (setq ingroup t)
13584 (when (not (= cnt 0))
13585 (setq cnt 0)
13586 (insert "\n"))
13587 (insert "{ "))
13588 ((equal e '(:endgroup))
13589 (setq ingroup nil cnt 0)
13590 (insert "}\n"))
13592 (setq tg (car e) c (cdr e))
13593 (if ingroup (push tg (car groups)))
13594 (setq tg (org-add-props tg nil 'face
13595 (org-get-todo-face tg)))
13596 (if (and (= cnt 0) (not ingroup)) (insert " "))
13597 (insert "[" c "] " tg (make-string
13598 (- fwidth 4 (length tg)) ?\ ))
13599 (when (= (setq cnt (1+ cnt)) ncol)
13600 (insert "\n")
13601 (if ingroup (insert " "))
13602 (setq cnt 0)))))
13603 (insert "\n")
13604 (goto-char (point-min))
13605 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13606 (fit-window-to-buffer))
13607 (message "[a-z..]:Set [SPC]:clear")
13608 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13609 (cond
13610 ((or (= c ?\C-g)
13611 (and (= c ?q) (not (rassoc c fulltable))))
13612 (setq quit-flag t))
13613 ((= c ?\ ) nil)
13614 ((setq e (rassoc c fulltable) tg (car e))
13616 (t (setq quit-flag t))))))
13618 (defun org-get-repeat ()
13619 "Check if tere is a deadline/schedule with repeater in this entry."
13620 (save-match-data
13621 (save-excursion
13622 (org-back-to-heading t)
13623 (if (re-search-forward
13624 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13625 (match-string 1)))))
13627 (defvar org-last-changed-timestamp)
13628 (defvar org-log-post-message)
13629 (defun org-auto-repeat-maybe ()
13630 "Check if the current headline contains a repeated deadline/schedule.
13631 If yes, set TODO state back to what it was and change the base date
13632 of repeating deadline/scheduled time stamps to new date.
13633 This function should be run in the `org-after-todo-state-change-hook'."
13634 ;; last-state is dynamically scoped into this function
13635 (let* ((repeat (org-get-repeat))
13636 (aa (assoc last-state org-todo-kwd-alist))
13637 (interpret (nth 1 aa))
13638 (head (nth 2 aa))
13639 (done-word (nth 3 aa))
13640 (whata '(("d" . day) ("m" . month) ("y" . year)))
13641 (msg "Entry repeats: ")
13642 (org-log-done)
13643 re type n what ts)
13644 (when repeat
13645 (org-todo (if (eq interpret 'type) last-state head))
13646 (when (and org-log-repeat
13647 (not (memq 'org-add-log-note
13648 (default-value 'post-command-hook))))
13649 ;; Make sure a note is taken
13650 (let ((org-log-done '(done)))
13651 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13652 'findpos)))
13653 (org-back-to-heading t)
13654 (org-add-planning-info nil nil 'closed)
13655 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13656 org-deadline-time-regexp "\\)"))
13657 (while (re-search-forward
13658 re (save-excursion (outline-next-heading) (point)) t)
13659 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13660 ts (match-string (if (match-end 2) 2 4)))
13661 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13662 (setq n (string-to-number (match-string 1 ts))
13663 what (match-string 2 ts))
13664 (if (equal what "w") (setq n (* n 7) what "d"))
13665 (org-timestamp-change n (cdr (assoc what whata))))
13666 (setq msg (concat msg type org-last-changed-timestamp " ")))
13667 (setq org-log-post-message msg)
13668 (message msg))))
13670 (defun org-show-todo-tree (arg)
13671 "Make a compact tree which shows all headlines marked with TODO.
13672 The tree will show the lines where the regexp matches, and all higher
13673 headlines above the match.
13674 With \\[universal-argument] prefix, also show the DONE entries.
13675 With a numeric prefix N, construct a sparse tree for the Nth element
13676 of `org-todo-keywords-1'."
13677 (interactive "P")
13678 (let ((case-fold-search nil)
13679 (kwd-re
13680 (cond ((null arg) org-not-done-regexp)
13681 ((equal arg '(4))
13682 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13683 (mapcar 'list org-todo-keywords-1))))
13684 (concat "\\("
13685 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13686 "\\)\\>")))
13687 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13688 (regexp-quote (nth (1- (prefix-numeric-value arg))
13689 org-todo-keywords-1)))
13690 (t (error "Invalid prefix argument: %s" arg)))))
13691 (message "%d TODO entries found"
13692 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13694 (defun org-deadline (&optional remove)
13695 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13696 With argument REMOVE, remove any deadline from the item."
13697 (interactive "P")
13698 (if remove
13699 (progn
13700 (org-add-planning-info nil nil 'deadline)
13701 (message "Item no longer has a deadline."))
13702 (org-add-planning-info 'deadline nil 'closed)))
13704 (defun org-schedule (&optional remove)
13705 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13706 With argument REMOVE, remove any scheduling date from the item."
13707 (interactive "P")
13708 (if remove
13709 (progn
13710 (org-add-planning-info nil nil 'scheduled)
13711 (message "Item is no longer scheduled."))
13712 (org-add-planning-info 'scheduled nil 'closed)))
13714 (defun org-add-planning-info (what &optional time &rest remove)
13715 "Insert new timestamp with keyword in the line directly after the headline.
13716 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13717 If non is given, the user is prompted for a date.
13718 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13719 be removed."
13720 (interactive)
13721 (let (org-time-was-given org-end-time-was-given)
13722 (when what (setq time (or time (org-read-date nil 'to-time))))
13723 (when (and org-insert-labeled-timestamps-at-point
13724 (member what '(scheduled deadline)))
13725 (insert
13726 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13727 (org-insert-time-stamp time org-time-was-given
13728 nil nil nil (list org-end-time-was-given))
13729 (setq what nil))
13730 (save-excursion
13731 (save-restriction
13732 (let (col list elt ts buffer-invisibility-spec)
13733 (org-back-to-heading t)
13734 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13735 (goto-char (match-end 1))
13736 (setq col (current-column))
13737 (goto-char (match-end 0))
13738 (if (eobp) (insert "\n"))
13739 (forward-char 1)
13740 (if (and (not (looking-at outline-regexp))
13741 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13742 "[^\r\n]*"))
13743 (not (equal (match-string 1) org-clock-string)))
13744 (narrow-to-region (match-beginning 0) (match-end 0))
13745 (insert-before-markers "\n")
13746 (backward-char 1)
13747 (narrow-to-region (point) (point))
13748 (indent-to-column col))
13749 ;; Check if we have to remove something.
13750 (setq list (cons what remove))
13751 (while list
13752 (setq elt (pop list))
13753 (goto-char (point-min))
13754 (when (or (and (eq elt 'scheduled)
13755 (re-search-forward org-scheduled-time-regexp nil t))
13756 (and (eq elt 'deadline)
13757 (re-search-forward org-deadline-time-regexp nil t))
13758 (and (eq elt 'closed)
13759 (re-search-forward org-closed-time-regexp nil t)))
13760 (replace-match "")
13761 (if (looking-at "--+<[^>]+>") (replace-match ""))
13762 (if (looking-at " +") (replace-match ""))))
13763 (goto-char (point-max))
13764 (when what
13765 (insert
13766 (if (not (equal (char-before) ?\ )) " " "")
13767 (cond ((eq what 'scheduled) org-scheduled-string)
13768 ((eq what 'deadline) org-deadline-string)
13769 ((eq what 'closed) org-closed-string))
13770 " ")
13771 (setq ts (org-insert-time-stamp
13772 time
13773 (or org-time-was-given
13774 (and (eq what 'closed) org-log-done-with-time))
13775 (eq what 'closed)
13776 nil nil (list org-end-time-was-given)))
13777 (end-of-line 1))
13778 (goto-char (point-min))
13779 (widen)
13780 (if (looking-at "[ \t]+\r?\n")
13781 (replace-match ""))
13782 ts)))))
13784 (defvar org-log-note-marker (make-marker))
13785 (defvar org-log-note-purpose nil)
13786 (defvar org-log-note-state nil)
13787 (defvar org-log-note-window-configuration nil)
13788 (defvar org-log-note-return-to (make-marker))
13789 (defvar org-log-post-message nil
13790 "Message to be displayed after a log note has been stored.
13791 The auto-repeater uses this.")
13793 (defun org-add-log-maybe (&optional purpose state findpos)
13794 "Set up the post command hook to take a note."
13795 (save-excursion
13796 (when (and (listp org-log-done)
13797 (memq purpose org-log-done))
13798 (when findpos
13799 (org-back-to-heading t)
13800 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13801 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13802 "[^\r\n]*\\)?"))
13803 (goto-char (match-end 0))
13804 (unless org-log-states-order-reversed
13805 (and (= (char-after) ?\n) (forward-char 1))
13806 (org-skip-over-state-notes)
13807 (skip-chars-backward " \t\n\r")))
13808 (move-marker org-log-note-marker (point))
13809 (setq org-log-note-purpose purpose)
13810 (setq org-log-note-state state)
13811 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13813 (defun org-skip-over-state-notes ()
13814 "Skip past the list of State notes in an entry."
13815 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13816 (while (looking-at "[ \t]*- State")
13817 (condition-case nil
13818 (org-next-item)
13819 (error (org-end-of-item)))))
13821 (defun org-add-log-note (&optional purpose)
13822 "Pop up a window for taking a note, and add this note later at point."
13823 (remove-hook 'post-command-hook 'org-add-log-note)
13824 (setq org-log-note-window-configuration (current-window-configuration))
13825 (delete-other-windows)
13826 (move-marker org-log-note-return-to (point))
13827 (switch-to-buffer (marker-buffer org-log-note-marker))
13828 (goto-char org-log-note-marker)
13829 (org-switch-to-buffer-other-window "*Org Note*")
13830 (erase-buffer)
13831 (let ((org-inhibit-startup t)) (org-mode))
13832 (insert (format "# Insert note for %s.
13833 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13834 (cond
13835 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13836 ((eq org-log-note-purpose 'done) "closed todo item")
13837 ((eq org-log-note-purpose 'state)
13838 (format "state change to \"%s\"" org-log-note-state))
13839 (t (error "This should not happen")))))
13840 (org-set-local 'org-finish-function 'org-store-log-note))
13842 (defun org-store-log-note ()
13843 "Finish taking a log note, and insert it to where it belongs."
13844 (let ((txt (buffer-string))
13845 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13846 lines ind)
13847 (kill-buffer (current-buffer))
13848 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13849 (setq txt (replace-match "" t t txt)))
13850 (if (string-match "\\s-+\\'" txt)
13851 (setq txt (replace-match "" t t txt)))
13852 (setq lines (org-split-string txt "\n"))
13853 (when (and note (string-match "\\S-" note))
13854 (setq note
13855 (org-replace-escapes
13856 note
13857 (list (cons "%u" (user-login-name))
13858 (cons "%U" user-full-name)
13859 (cons "%t" (format-time-string
13860 (org-time-stamp-format 'long 'inactive)
13861 (current-time)))
13862 (cons "%s" (if org-log-note-state
13863 (concat "\"" org-log-note-state "\"")
13864 "")))))
13865 (if lines (setq note (concat note " \\\\")))
13866 (push note lines))
13867 (when (or current-prefix-arg org-note-abort) (setq lines nil))
13868 (when lines
13869 (save-excursion
13870 (set-buffer (marker-buffer org-log-note-marker))
13871 (save-excursion
13872 (goto-char org-log-note-marker)
13873 (move-marker org-log-note-marker nil)
13874 (end-of-line 1)
13875 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13876 (indent-relative nil)
13877 (insert " - " (pop lines))
13878 (org-indent-line-function)
13879 (beginning-of-line 1)
13880 (looking-at "[ \t]*")
13881 (setq ind (concat (match-string 0) " "))
13882 (end-of-line 1)
13883 (while lines (insert "\n" ind (pop lines)))))))
13884 (set-window-configuration org-log-note-window-configuration)
13885 (with-current-buffer (marker-buffer org-log-note-return-to)
13886 (goto-char org-log-note-return-to))
13887 (move-marker org-log-note-return-to nil)
13888 (and org-log-post-message (message org-log-post-message)))
13890 ;; FIXME: what else would be useful?
13891 ;; - priority
13892 ;; - date
13894 (defun org-sparse-tree (&optional arg)
13895 "Create a sparse tree, prompt for the details.
13896 This command can create sparse trees. You first need to select the type
13897 of match used to create the tree:
13899 t Show entries with a specific TODO keyword.
13900 T Show entries selected by a tags match.
13901 p Enter a property name and its value (both with completion on existing
13902 names/values) and show entries with that property.
13903 r Show entries matching a regular expression"
13904 (interactive "P")
13905 (let (ans kwd value)
13906 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
13907 (setq ans (read-char-exclusive))
13908 (cond
13909 ((equal ans ?t)
13910 (org-show-todo-tree '(4)))
13911 ((equal ans ?T)
13912 (call-interactively 'org-tags-sparse-tree))
13913 ((member ans '(?p ?P))
13914 (setq kwd (completing-read "Property: "
13915 (mapcar 'list (org-buffer-property-keys))))
13916 (setq value (completing-read "Value: "
13917 (mapcar 'list (org-property-values kwd))))
13918 (unless (string-match "\\`{.*}\\'" value)
13919 (setq value (concat "\"" value "\"")))
13920 (org-tags-sparse-tree arg (concat kwd "=" value)))
13921 ((member ans '(?r ?R))
13922 (call-interactively 'org-occur))
13923 (t (error "No such sparse tree command \"%c\"" ans)))))
13925 (defvar org-occur-highlights nil)
13926 (make-variable-buffer-local 'org-occur-highlights)
13928 (defun org-occur (regexp &optional keep-previous callback)
13929 "Make a compact tree which shows all matches of REGEXP.
13930 The tree will show the lines where the regexp matches, and all higher
13931 headlines above the match. It will also show the heading after the match,
13932 to make sure editing the matching entry is easy.
13933 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13934 call to `org-occur' will be kept, to allow stacking of calls to this
13935 command.
13936 If CALLBACK is non-nil, it is a function which is called to confirm
13937 that the match should indeed be shown."
13938 (interactive "sRegexp: \nP")
13939 (or keep-previous (org-remove-occur-highlights nil nil t))
13940 (let ((cnt 0))
13941 (save-excursion
13942 (goto-char (point-min))
13943 (if (or (not keep-previous) ; do not want to keep
13944 (not org-occur-highlights)) ; no previous matches
13945 ;; hide everything
13946 (org-overview))
13947 (while (re-search-forward regexp nil t)
13948 (when (or (not callback)
13949 (save-match-data (funcall callback)))
13950 (setq cnt (1+ cnt))
13951 (when org-highlight-sparse-tree-matches
13952 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13953 (org-show-context 'occur-tree))))
13954 (when org-remove-highlights-with-change
13955 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13956 nil 'local))
13957 (unless org-sparse-tree-open-archived-trees
13958 (org-hide-archived-subtrees (point-min) (point-max)))
13959 (run-hooks 'org-occur-hook)
13960 (if (interactive-p)
13961 (message "%d match(es) for regexp %s" cnt regexp))
13962 cnt))
13964 (defun org-show-context (&optional key)
13965 "Make sure point and context and visible.
13966 How much context is shown depends upon the variables
13967 `org-show-hierarchy-above', `org-show-following-heading'. and
13968 `org-show-siblings'."
13969 (let ((heading-p (org-on-heading-p t))
13970 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13971 (following-p (org-get-alist-option org-show-following-heading key))
13972 (siblings-p (org-get-alist-option org-show-siblings key)))
13973 (catch 'exit
13974 ;; Show heading or entry text
13975 (if heading-p
13976 (org-flag-heading nil) ; only show the heading
13977 (and (or (org-invisible-p) (org-invisible-p2))
13978 (org-show-hidden-entry))) ; show entire entry
13979 (when following-p
13980 ;; Show next sibling, or heading below text
13981 (save-excursion
13982 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13983 (org-flag-heading nil))))
13984 (when siblings-p (org-show-siblings))
13985 (when hierarchy-p
13986 ;; show all higher headings, possibly with siblings
13987 (save-excursion
13988 (while (and (condition-case nil
13989 (progn (org-up-heading-all 1) t)
13990 (error nil))
13991 (not (bobp)))
13992 (org-flag-heading nil)
13993 (when siblings-p (org-show-siblings))))))))
13995 (defun org-reveal (&optional siblings)
13996 "Show current entry, hierarchy above it, and the following headline.
13997 This can be used to show a consistent set of context around locations
13998 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
13999 not t for the search context.
14001 With optional argument SIBLINGS, on each level of the hierarchy all
14002 siblings are shown. This repairs the tree structure to what it would
14003 look like when opened with hierarchical calls to `org-cycle'."
14004 (interactive "P")
14005 (let ((org-show-hierarchy-above t)
14006 (org-show-following-heading t)
14007 (org-show-siblings (if siblings t org-show-siblings)))
14008 (org-show-context nil)))
14010 (defun org-highlight-new-match (beg end)
14011 "Highlight from BEG to END and mark the highlight is an occur headline."
14012 (let ((ov (org-make-overlay beg end)))
14013 (org-overlay-put ov 'face 'secondary-selection)
14014 (push ov org-occur-highlights)))
14016 (defun org-remove-occur-highlights (&optional beg end noremove)
14017 "Remove the occur highlights from the buffer.
14018 BEG and END are ignored. If NOREMOVE is nil, remove this function
14019 from the `before-change-functions' in the current buffer."
14020 (interactive)
14021 (unless org-inhibit-highlight-removal
14022 (mapc 'org-delete-overlay org-occur-highlights)
14023 (setq org-occur-highlights nil)
14024 (unless noremove
14025 (remove-hook 'before-change-functions
14026 'org-remove-occur-highlights 'local))))
14028 ;;;; Priorities
14030 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14031 "Regular expression matching the priority indicator.")
14033 (defvar org-remove-priority-next-time nil)
14035 (defun org-priority-up ()
14036 "Increase the priority of the current item."
14037 (interactive)
14038 (org-priority 'up))
14040 (defun org-priority-down ()
14041 "Decrease the priority of the current item."
14042 (interactive)
14043 (org-priority 'down))
14045 (defun org-priority (&optional action)
14046 "Change the priority of an item by ARG.
14047 ACTION can be `set', `up', `down', or a character."
14048 (interactive)
14049 (setq action (or action 'set))
14050 (let (current new news have remove)
14051 (save-excursion
14052 (org-back-to-heading)
14053 (if (looking-at org-priority-regexp)
14054 (setq current (string-to-char (match-string 2))
14055 have t)
14056 (setq current org-default-priority))
14057 (cond
14058 ((or (eq action 'set) (integerp action))
14059 (if (integerp action)
14060 (setq new action)
14061 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14062 (setq new (read-char-exclusive)))
14063 (if (and (= (upcase org-highest-priority) org-highest-priority)
14064 (= (upcase org-lowest-priority) org-lowest-priority))
14065 (setq new (upcase new)))
14066 (cond ((equal new ?\ ) (setq remove t))
14067 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14068 (error "Priority must be between `%c' and `%c'"
14069 org-highest-priority org-lowest-priority))))
14070 ((eq action 'up)
14071 (if (and (not have) (eq last-command this-command))
14072 (setq new org-lowest-priority)
14073 (setq new (if (and org-priority-start-cycle-with-default (not have))
14074 org-default-priority (1- current)))))
14075 ((eq action 'down)
14076 (if (and (not have) (eq last-command this-command))
14077 (setq new org-highest-priority)
14078 (setq new (if (and org-priority-start-cycle-with-default (not have))
14079 org-default-priority (1+ current)))))
14080 (t (error "Invalid action")))
14081 (if (or (< (upcase new) org-highest-priority)
14082 (> (upcase new) org-lowest-priority))
14083 (setq remove t))
14084 (setq news (format "%c" new))
14085 (if have
14086 (if remove
14087 (replace-match "" t t nil 1)
14088 (replace-match news t t nil 2))
14089 (if remove
14090 (error "No priority cookie found in line")
14091 (looking-at org-todo-line-regexp)
14092 (if (match-end 2)
14093 (progn
14094 (goto-char (match-end 2))
14095 (insert " [#" news "]"))
14096 (goto-char (match-beginning 3))
14097 (insert "[#" news "] ")))))
14098 (org-preserve-lc (org-set-tags nil 'align))
14099 (if remove
14100 (message "Priority removed")
14101 (message "Priority of current item set to %s" news))))
14104 (defun org-get-priority (s)
14105 "Find priority cookie and return priority."
14106 (save-match-data
14107 (if (not (string-match org-priority-regexp s))
14108 (* 1000 (- org-lowest-priority org-default-priority))
14109 (* 1000 (- org-lowest-priority
14110 (string-to-char (match-string 2 s)))))))
14112 ;;;; Tags
14114 (defun org-scan-tags (action matcher &optional todo-only)
14115 "Scan headline tags with inheritance and produce output ACTION.
14116 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14117 evaluated, testing if a given set of tags qualifies a headline for
14118 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14119 are included in the output."
14120 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14121 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14122 (org-re
14123 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14124 (props (list 'face nil
14125 'done-face 'org-done
14126 'undone-face nil
14127 'mouse-face 'highlight
14128 'org-not-done-regexp org-not-done-regexp
14129 'org-todo-regexp org-todo-regexp
14130 'keymap org-agenda-keymap
14131 'help-echo
14132 (format "mouse-2 or RET jump to org file %s"
14133 (abbreviate-file-name buffer-file-name))))
14134 (case-fold-search nil)
14135 lspos
14136 tags tags-list tags-alist (llast 0) rtn level category i txt
14137 todo marker entry priority)
14138 (save-excursion
14139 (goto-char (point-min))
14140 (when (eq action 'sparse-tree)
14141 (org-overview)
14142 (org-remove-occur-highlights))
14143 (while (re-search-forward re nil t)
14144 (catch :skip
14145 (setq todo (if (match-end 1) (match-string 2))
14146 tags (if (match-end 4) (match-string 4)))
14147 (goto-char (setq lspos (1+ (match-beginning 0))))
14148 (setq level (org-reduced-level (funcall outline-level))
14149 category (org-get-category))
14150 (setq i llast llast level)
14151 ;; remove tag lists from same and sublevels
14152 (while (>= i level)
14153 (when (setq entry (assoc i tags-alist))
14154 (setq tags-alist (delete entry tags-alist)))
14155 (setq i (1- i)))
14156 ;; add the nex tags
14157 (when tags
14158 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14159 tags-alist
14160 (cons (cons level tags) tags-alist)))
14161 ;; compile tags for current headline
14162 (setq tags-list
14163 (if org-use-tag-inheritance
14164 (apply 'append (mapcar 'cdr tags-alist))
14165 tags))
14166 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14167 (eval matcher)
14168 (or (not org-agenda-skip-archived-trees)
14169 (not (member org-archive-tag tags-list))))
14170 (and (eq action 'agenda) (org-agenda-skip))
14171 ;; list this headline
14173 (if (eq action 'sparse-tree)
14174 (progn
14175 (and org-highlight-sparse-tree-matches
14176 (org-get-heading) (match-end 0)
14177 (org-highlight-new-match
14178 (match-beginning 0) (match-beginning 1)))
14179 (org-show-context 'tags-tree))
14180 (setq txt (org-format-agenda-item
14182 (concat
14183 (if org-tags-match-list-sublevels
14184 (make-string (1- level) ?.) "")
14185 (org-get-heading))
14186 category tags-list)
14187 priority (org-get-priority txt))
14188 (goto-char lspos)
14189 (setq marker (org-agenda-new-marker))
14190 (org-add-props txt props
14191 'org-marker marker 'org-hd-marker marker 'org-category category
14192 'priority priority 'type "tagsmatch")
14193 (push txt rtn))
14194 ;; if we are to skip sublevels, jump to end of subtree
14195 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14196 (when (and (eq action 'sparse-tree)
14197 (not org-sparse-tree-open-archived-trees))
14198 (org-hide-archived-subtrees (point-min) (point-max)))
14199 (nreverse rtn)))
14201 (defvar todo-only) ;; dynamically scoped
14203 (defun org-tags-sparse-tree (&optional todo-only match)
14204 "Create a sparse tree according to tags string MATCH.
14205 MATCH can contain positive and negative selection of tags, like
14206 \"+WORK+URGENT-WITHBOSS\".
14207 If optional argument TODO_ONLY is non-nil, only select lines that are
14208 also TODO lines."
14209 (interactive "P")
14210 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14212 (defvar org-cached-props nil)
14213 (defun org-cached-entry-get (pom property)
14214 (if org-use-property-inheritance
14215 ;; Caching is not possible, check it directly
14216 (org-entry-get pom property 'inherit)
14217 ;; Get all properties, so that we can do complicated checks easily
14218 (cdr (assoc property (or org-cached-props
14219 (setq org-cached-props
14220 (org-entry-properties pom)))))))
14222 (defun org-global-tags-completion-table (&optional files)
14223 "Return the list of all tags in all agenda buffer/files."
14224 (save-excursion
14225 (org-uniquify
14226 (apply 'append
14227 (mapcar
14228 (lambda (file)
14229 (set-buffer (find-file-noselect file))
14230 (org-get-buffer-tags))
14231 (if (and files (car files))
14232 files
14233 (org-agenda-files)))))))
14235 (defun org-make-tags-matcher (match)
14236 "Create the TAGS//TODO matcher form for the selection string MATCH."
14237 ;; todo-only is scoped dynamically into this function, and the function
14238 ;; may change it it the matcher asksk for it.
14239 (unless match
14240 ;; Get a new match request, with completion
14241 (let ((org-last-tags-completion-table
14242 (org-global-tags-completion-table)))
14243 (setq match (completing-read
14244 "Match: " 'org-tags-completion-function nil nil nil
14245 'org-tags-history))))
14247 ;; Parse the string and create a lisp form
14248 (let ((match0 match)
14249 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14250 minus tag mm
14251 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14252 orterms term orlist re-p level-p prop-p pn pv)
14253 (if (string-match "/+" match)
14254 ;; match contains also a todo-matching request
14255 (progn
14256 (setq tagsmatch (substring match 0 (match-beginning 0))
14257 todomatch (substring match (match-end 0)))
14258 (if (string-match "^!" todomatch)
14259 (setq todo-only t todomatch (substring todomatch 1)))
14260 (if (string-match "^\\s-*$" todomatch)
14261 (setq todomatch nil)))
14262 ;; only matching tags
14263 (setq tagsmatch match todomatch nil))
14265 ;; Make the tags matcher
14266 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14267 (setq tagsmatcher t)
14268 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14269 (while (setq term (pop orterms))
14270 (while (and (equal (substring term -1) "\\") orterms)
14271 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14272 (while (string-match re term)
14273 (setq minus (and (match-end 1)
14274 (equal (match-string 1 term) "-"))
14275 tag (match-string 2 term)
14276 re-p (equal (string-to-char tag) ?{)
14277 level-p (match-end 3)
14278 prop-p (match-end 4)
14279 mm (cond
14280 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14281 (level-p `(= level ,(string-to-number
14282 (match-string 3 term))))
14283 (prop-p
14284 (setq pn (match-string 4 term)
14285 pv (match-string 5 term)
14286 re-p (equal (string-to-char pv) ?{)
14287 pv (substring pv 1 -1))
14288 (if re-p
14289 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
14290 `(equal ,pv (org-cached-entry-get nil ,pn))))
14291 (t `(member ,(downcase tag) tags-list)))
14292 mm (if minus (list 'not mm) mm)
14293 term (substring term (match-end 0)))
14294 (push mm tagsmatcher))
14295 (push (if (> (length tagsmatcher) 1)
14296 (cons 'and tagsmatcher)
14297 (car tagsmatcher))
14298 orlist)
14299 (setq tagsmatcher nil))
14300 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14301 (setq tagsmatcher
14302 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14304 ;; Make the todo matcher
14305 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14306 (setq todomatcher t)
14307 (setq orterms (org-split-string todomatch "|") orlist nil)
14308 (while (setq term (pop orterms))
14309 (while (string-match re term)
14310 (setq minus (and (match-end 1)
14311 (equal (match-string 1 term) "-"))
14312 kwd (match-string 2 term)
14313 re-p (equal (string-to-char kwd) ?{)
14314 term (substring term (match-end 0))
14315 mm (if re-p
14316 `(string-match ,(substring kwd 1 -1) todo)
14317 (list 'equal 'todo kwd))
14318 mm (if minus (list 'not mm) mm))
14319 (push mm todomatcher))
14320 (push (if (> (length todomatcher) 1)
14321 (cons 'and todomatcher)
14322 (car todomatcher))
14323 orlist)
14324 (setq todomatcher nil))
14325 (setq todomatcher (if (> (length orlist) 1)
14326 (cons 'or orlist) (car orlist))))
14328 ;; Return the string and lisp forms of the matcher
14329 (setq matcher (if todomatcher
14330 (list 'and tagsmatcher todomatcher)
14331 tagsmatcher))
14332 (cons match0 matcher)))
14334 (defun org-match-any-p (re list)
14335 "Does re match any element of list?"
14336 (setq list (mapcar (lambda (x) (string-match re x)) list))
14337 (delq nil list))
14339 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14340 (defvar org-tags-overlay (org-make-overlay 1 1))
14341 (org-detach-overlay org-tags-overlay)
14343 (defun org-align-tags-here (to-col)
14344 ;; Assumes that this is a headline
14345 (let ((pos (point)) (col (current-column)) tags)
14346 (beginning-of-line 1)
14347 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14348 (< pos (match-beginning 2)))
14349 (progn
14350 (setq tags (match-string 2))
14351 (goto-char (match-beginning 1))
14352 (insert " ")
14353 (delete-region (point) (1+ (match-end 0)))
14354 (backward-char 1)
14355 (move-to-column
14356 (max (1+ (current-column))
14357 (1+ col)
14358 (if (> to-col 0)
14359 to-col
14360 (- (abs to-col) (length tags))))
14362 (insert tags)
14363 (move-to-column (min (current-column) col) t))
14364 (goto-char pos))))
14366 (defun org-set-tags (&optional arg just-align)
14367 "Set the tags for the current headline.
14368 With prefix ARG, realign all tags in headings in the current buffer."
14369 (interactive "P")
14370 (let* ((re (concat "^" outline-regexp))
14371 (current (org-get-tags-string))
14372 (col (current-column))
14373 (org-setting-tags t)
14374 table current-tags inherited-tags ; computed below when needed
14375 tags p0 c0 c1 rpl)
14376 (if arg
14377 (save-excursion
14378 (goto-char (point-min))
14379 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14380 (while (re-search-forward re nil t)
14381 (org-set-tags nil t)
14382 (end-of-line 1)))
14383 (message "All tags realigned to column %d" org-tags-column))
14384 (if just-align
14385 (setq tags current)
14386 ;; Get a new set of tags from the user
14387 (save-excursion
14388 (setq table (or org-tag-alist (org-get-buffer-tags))
14389 org-last-tags-completion-table table
14390 current-tags (org-split-string current ":")
14391 inherited-tags (nreverse
14392 (nthcdr (length current-tags)
14393 (nreverse (org-get-tags-at))))
14394 tags
14395 (if (or (eq t org-use-fast-tag-selection)
14396 (and org-use-fast-tag-selection
14397 (delq nil (mapcar 'cdr table))))
14398 (org-fast-tag-selection
14399 current-tags inherited-tags table
14400 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14401 (let ((org-add-colon-after-tag-completion t))
14402 (org-trim
14403 (org-without-partial-completion
14404 (completing-read "Tags: " 'org-tags-completion-function
14405 nil nil current 'org-tags-history)))))))
14406 (while (string-match "[-+&]+" tags)
14407 ;; No boolean logic, just a list
14408 (setq tags (replace-match ":" t t tags))))
14410 (if (string-match "\\`[\t ]*\\'" tags)
14411 (setq tags "")
14412 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14413 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14415 ;; Insert new tags at the correct column
14416 (beginning-of-line 1)
14417 (cond
14418 ((and (equal current "") (equal tags "")))
14419 ((re-search-forward
14420 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14421 (point-at-eol) t)
14422 (if (equal tags "")
14423 (setq rpl "")
14424 (goto-char (match-beginning 0))
14425 (setq c0 (current-column) p0 (point)
14426 c1 (max (1+ c0) (if (> org-tags-column 0)
14427 org-tags-column
14428 (- (- org-tags-column) (length tags))))
14429 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14430 (replace-match rpl t t)
14431 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14432 tags)
14433 (t (error "Tags alignment failed")))
14434 (move-to-column col)
14435 (unless just-align
14436 (run-hooks 'org-after-tags-change-hook)))))
14438 (defun org-change-tag-in-region (beg end tag off)
14439 "Add or remove TAG for each entry in the region.
14440 This works in the agenda, and also in an org-mode buffer."
14441 (interactive
14442 (list (region-beginning) (region-end)
14443 (let ((org-last-tags-completion-table
14444 (if (org-mode-p)
14445 (org-get-buffer-tags)
14446 (org-global-tags-completion-table))))
14447 (completing-read
14448 "Tag: " 'org-tags-completion-function nil nil nil
14449 'org-tags-history))
14450 (progn
14451 (message "[s]et or [r]emove? ")
14452 (equal (read-char-exclusive) ?r))))
14453 (if (fboundp 'deactivate-mark) (deactivate-mark))
14454 (let ((agendap (equal major-mode 'org-agenda-mode))
14455 l1 l2 m buf pos newhead (cnt 0))
14456 (goto-char end)
14457 (setq l2 (1- (org-current-line)))
14458 (goto-char beg)
14459 (setq l1 (org-current-line))
14460 (loop for l from l1 to l2 do
14461 (goto-line l)
14462 (setq m (get-text-property (point) 'org-hd-marker))
14463 (when (or (and (org-mode-p) (org-on-heading-p))
14464 (and agendap m))
14465 (setq buf (if agendap (marker-buffer m) (current-buffer))
14466 pos (if agendap m (point)))
14467 (with-current-buffer buf
14468 (save-excursion
14469 (save-restriction
14470 (goto-char pos)
14471 (setq cnt (1+ cnt))
14472 (org-toggle-tag tag (if off 'off 'on))
14473 (setq newhead (org-get-heading)))))
14474 (and agendap (org-agenda-change-all-lines newhead m))))
14475 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14477 (defun org-tags-completion-function (string predicate &optional flag)
14478 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14479 (confirm (lambda (x) (stringp (car x)))))
14480 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14481 (setq s1 (match-string 1 string)
14482 s2 (match-string 2 string))
14483 (setq s1 "" s2 string))
14484 (cond
14485 ((eq flag nil)
14486 ;; try completion
14487 (setq rtn (try-completion s2 ctable confirm))
14488 (if (stringp rtn)
14489 (setq rtn
14490 (concat s1 s2 (substring rtn (length s2))
14491 (if (and org-add-colon-after-tag-completion
14492 (assoc rtn ctable))
14493 ":" ""))))
14494 rtn)
14495 ((eq flag t)
14496 ;; all-completions
14497 (all-completions s2 ctable confirm)
14499 ((eq flag 'lambda)
14500 ;; exact match?
14501 (assoc s2 ctable)))
14504 (defun org-fast-tag-insert (kwd tags face &optional end)
14505 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14506 (insert (format "%-12s" (concat kwd ":"))
14507 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14508 (or end "")))
14510 (defun org-fast-tag-show-exit (flag)
14511 (save-excursion
14512 (goto-line 3)
14513 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14514 (replace-match ""))
14515 (when flag
14516 (end-of-line 1)
14517 (move-to-column (- (window-width) 19) t)
14518 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14520 (defun org-set-current-tags-overlay (current prefix)
14521 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14522 (if (featurep 'xemacs)
14523 (org-overlay-display org-tags-overlay (concat prefix s)
14524 'secondary-selection)
14525 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14526 (org-overlay-display org-tags-overlay (concat prefix s)))))
14528 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14529 "Fast tag selection with single keys.
14530 CURRENT is the current list of tags in the headline, INHERITED is the
14531 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14532 possibly with grouping information. TODO-TABLE is a similar table with
14533 TODO keywords, should these have keys assigned to them.
14534 If the keys are nil, a-z are automatically assigned.
14535 Returns the new tags string, or nil to not change the current settings."
14536 (let* ((fulltable (append table todo-table))
14537 (maxlen (apply 'max (mapcar
14538 (lambda (x)
14539 (if (stringp (car x)) (string-width (car x)) 0))
14540 fulltable)))
14541 (buf (current-buffer))
14542 (expert (eq org-fast-tag-selection-single-key 'expert))
14543 (buffer-tags nil)
14544 (fwidth (+ maxlen 3 1 3))
14545 (ncol (/ (- (window-width) 4) fwidth))
14546 (i-face 'org-done)
14547 (c-face 'org-todo)
14548 tg cnt e c char c1 c2 ntable tbl rtn
14549 ov-start ov-end ov-prefix
14550 (exit-after-next org-fast-tag-selection-single-key)
14551 (done-keywords org-done-keywords)
14552 groups ingroup)
14553 (save-excursion
14554 (beginning-of-line 1)
14555 (if (looking-at
14556 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14557 (setq ov-start (match-beginning 1)
14558 ov-end (match-end 1)
14559 ov-prefix "")
14560 (setq ov-start (1- (point-at-eol))
14561 ov-end (1+ ov-start))
14562 (skip-chars-forward "^\n\r")
14563 (setq ov-prefix
14564 (concat
14565 (buffer-substring (1- (point)) (point))
14566 (if (> (current-column) org-tags-column)
14568 (make-string (- org-tags-column (current-column)) ?\ ))))))
14569 (org-move-overlay org-tags-overlay ov-start ov-end)
14570 (save-window-excursion
14571 (if expert
14572 (set-buffer (get-buffer-create " *Org tags*"))
14573 (delete-other-windows)
14574 (split-window-vertically)
14575 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14576 (erase-buffer)
14577 (org-set-local 'org-done-keywords done-keywords)
14578 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14579 (org-fast-tag-insert "Current" current c-face "\n\n")
14580 (org-fast-tag-show-exit exit-after-next)
14581 (org-set-current-tags-overlay current ov-prefix)
14582 (setq tbl fulltable char ?a cnt 0)
14583 (while (setq e (pop tbl))
14584 (cond
14585 ((equal e '(:startgroup))
14586 (push '() groups) (setq ingroup t)
14587 (when (not (= cnt 0))
14588 (setq cnt 0)
14589 (insert "\n"))
14590 (insert "{ "))
14591 ((equal e '(:endgroup))
14592 (setq ingroup nil cnt 0)
14593 (insert "}\n"))
14595 (setq tg (car e) c2 nil)
14596 (if (cdr e)
14597 (setq c (cdr e))
14598 ;; automatically assign a character.
14599 (setq c1 (string-to-char
14600 (downcase (substring
14601 tg (if (= (string-to-char tg) ?@) 1 0)))))
14602 (if (or (rassoc c1 ntable) (rassoc c1 table))
14603 (while (or (rassoc char ntable) (rassoc char table))
14604 (setq char (1+ char)))
14605 (setq c2 c1))
14606 (setq c (or c2 char)))
14607 (if ingroup (push tg (car groups)))
14608 (setq tg (org-add-props tg nil 'face
14609 (cond
14610 ((not (assoc tg table))
14611 (org-get-todo-face tg))
14612 ((member tg current) c-face)
14613 ((member tg inherited) i-face)
14614 (t nil))))
14615 (if (and (= cnt 0) (not ingroup)) (insert " "))
14616 (insert "[" c "] " tg (make-string
14617 (- fwidth 4 (length tg)) ?\ ))
14618 (push (cons tg c) ntable)
14619 (when (= (setq cnt (1+ cnt)) ncol)
14620 (insert "\n")
14621 (if ingroup (insert " "))
14622 (setq cnt 0)))))
14623 (setq ntable (nreverse ntable))
14624 (insert "\n")
14625 (goto-char (point-min))
14626 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14627 (fit-window-to-buffer))
14628 (setq rtn
14629 (catch 'exit
14630 (while t
14631 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14632 (if groups " [!] no groups" " [!]groups")
14633 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14634 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14635 (cond
14636 ((= c ?\r) (throw 'exit t))
14637 ((= c ?!)
14638 (setq groups (not groups))
14639 (goto-char (point-min))
14640 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14641 ((= c ?\C-c)
14642 (if (not expert)
14643 (org-fast-tag-show-exit
14644 (setq exit-after-next (not exit-after-next)))
14645 (setq expert nil)
14646 (delete-other-windows)
14647 (split-window-vertically)
14648 (org-switch-to-buffer-other-window " *Org tags*")
14649 (and (fboundp 'fit-window-to-buffer)
14650 (fit-window-to-buffer))))
14651 ((or (= c ?\C-g)
14652 (and (= c ?q) (not (rassoc c ntable))))
14653 (org-detach-overlay org-tags-overlay)
14654 (setq quit-flag t))
14655 ((= c ?\ )
14656 (setq current nil)
14657 (if exit-after-next (setq exit-after-next 'now)))
14658 ((= c ?\t)
14659 (condition-case nil
14660 (setq tg (completing-read
14661 "Tag: "
14662 (or buffer-tags
14663 (with-current-buffer buf
14664 (org-get-buffer-tags)))))
14665 (quit (setq tg "")))
14666 (when (string-match "\\S-" tg)
14667 (add-to-list 'buffer-tags (list tg))
14668 (if (member tg current)
14669 (setq current (delete tg current))
14670 (push tg current)))
14671 (if exit-after-next (setq exit-after-next 'now)))
14672 ((setq e (rassoc c todo-table) tg (car e))
14673 (with-current-buffer buf
14674 (save-excursion (org-todo tg)))
14675 (if exit-after-next (setq exit-after-next 'now)))
14676 ((setq e (rassoc c ntable) tg (car e))
14677 (if (member tg current)
14678 (setq current (delete tg current))
14679 (loop for g in groups do
14680 (if (member tg g)
14681 (mapcar (lambda (x)
14682 (setq current (delete x current)))
14683 g)))
14684 (push tg current))
14685 (if exit-after-next (setq exit-after-next 'now))))
14687 ;; Create a sorted list
14688 (setq current
14689 (sort current
14690 (lambda (a b)
14691 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14692 (if (eq exit-after-next 'now) (throw 'exit t))
14693 (goto-char (point-min))
14694 (beginning-of-line 2)
14695 (delete-region (point) (point-at-eol))
14696 (org-fast-tag-insert "Current" current c-face)
14697 (org-set-current-tags-overlay current ov-prefix)
14698 (while (re-search-forward
14699 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14700 (setq tg (match-string 1))
14701 (add-text-properties
14702 (match-beginning 1) (match-end 1)
14703 (list 'face
14704 (cond
14705 ((member tg current) c-face)
14706 ((member tg inherited) i-face)
14707 (t (get-text-property (match-beginning 1) 'face))))))
14708 (goto-char (point-min)))))
14709 (org-detach-overlay org-tags-overlay)
14710 (if rtn
14711 (mapconcat 'identity current ":")
14712 nil))))
14714 (defun org-get-tags-string ()
14715 "Get the TAGS string in the current headline."
14716 (unless (org-on-heading-p t)
14717 (error "Not on a heading"))
14718 (save-excursion
14719 (beginning-of-line 1)
14720 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14721 (org-match-string-no-properties 1)
14722 "")))
14724 (defun org-get-tags ()
14725 "Get the list of tags specified in the current headline."
14726 (org-split-string (org-get-tags-string) ":"))
14728 (defun org-get-buffer-tags ()
14729 "Get a table of all tags used in the buffer, for completion."
14730 (let (tags)
14731 (save-excursion
14732 (goto-char (point-min))
14733 (while (re-search-forward
14734 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14735 (when (equal (char-after (point-at-bol 0)) ?*)
14736 (mapc (lambda (x) (add-to-list 'tags x))
14737 (org-split-string (org-match-string-no-properties 1) ":")))))
14738 (mapcar 'list tags)))
14741 ;;;; Properties
14743 ;;; Setting and retrieving properties
14745 (defconst org-special-properties
14746 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14747 "The special properties valid in Org-mode.
14749 These are properties that are not defined in the property drawer,
14750 but in some other way.")
14752 (defconst org-default-properties
14753 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
14754 "LOCATION" "LOGGING" "COLUMNS")
14755 "Some properties that are used by Org-mode for various purposes.
14756 Being in this list makes sure that they are offered for completion.")
14758 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14759 "Regular expression matching the first line of a property drawer.")
14761 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14762 "Regular expression matching the first line of a property drawer.")
14764 (defun org-property-action ()
14765 "Do an action on properties."
14766 (interactive)
14767 (let (c)
14768 (org-at-property-p)
14769 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14770 (setq c (read-char-exclusive))
14771 (cond
14772 ((equal c ?s)
14773 (call-interactively 'org-set-property))
14774 ((equal c ?d)
14775 (call-interactively 'org-delete-property))
14776 ((equal c ?D)
14777 (call-interactively 'org-delete-property-globally))
14778 ((equal c ?c)
14779 (call-interactively 'org-compute-property-at-point))
14780 (t (error "No such property action %c" c)))))
14782 (defun org-at-property-p ()
14783 "Is the cursor in a property line?"
14784 ;; FIXME: Does not check if we are actually in the drawer.
14785 ;; FIXME: also returns true on any drawers.....
14786 ;; This is used by C-c C-c for property action.
14787 (save-excursion
14788 (beginning-of-line 1)
14789 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14791 (defmacro org-with-point-at (pom &rest body)
14792 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14793 (declare (indent 1) (debug t))
14794 `(save-excursion
14795 (if (markerp pom) (set-buffer (marker-buffer pom)))
14796 (save-excursion
14797 (goto-char (or pom (point)))
14798 ,@body)))
14800 (defun org-get-property-block (&optional beg end force)
14801 "Return the (beg . end) range of the body of the property drawer.
14802 BEG and END can be beginning and end of subtree, if not given
14803 they will be found.
14804 If the drawer does not exist and FORCE is non-nil, create the drawer."
14805 (catch 'exit
14806 (save-excursion
14807 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14808 (end (or end (progn (outline-next-heading) (point)))))
14809 (goto-char beg)
14810 (if (re-search-forward org-property-start-re end t)
14811 (setq beg (1+ (match-end 0)))
14812 (if force
14813 (save-excursion
14814 (org-insert-property-drawer)
14815 (setq end (progn (outline-next-heading) (point))))
14816 (throw 'exit nil))
14817 (goto-char beg)
14818 (if (re-search-forward org-property-start-re end t)
14819 (setq beg (1+ (match-end 0)))))
14820 (if (re-search-forward org-property-end-re end t)
14821 (setq end (match-beginning 0))
14822 (or force (throw 'exit nil))
14823 (goto-char beg)
14824 (setq end beg)
14825 (org-indent-line-function)
14826 (insert ":END:\n"))
14827 (cons beg end)))))
14829 (defun org-entry-properties (&optional pom which)
14830 "Get all properties of the entry at point-or-marker POM.
14831 This includes the TODO keyword, the tags, time strings for deadline,
14832 scheduled, and clocking, and any additional properties defined in the
14833 entry. The return value is an alist, keys may occur multiple times
14834 if the property key was used several times.
14835 POM may also be nil, in which case the current entry is used.
14836 If WHICH is nil or `all', get all properties. If WHICH is
14837 `special' or `standard', only get that subclass."
14838 (setq which (or which 'all))
14839 (org-with-point-at pom
14840 (let ((clockstr (substring org-clock-string 0 -1))
14841 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14842 beg end range props sum-props key value)
14843 (save-excursion
14844 (when (condition-case nil (org-back-to-heading t) (error nil))
14845 (setq beg (point))
14846 (setq sum-props (get-text-property (point) 'org-summaries))
14847 (outline-next-heading)
14848 (setq end (point))
14849 (when (memq which '(all special))
14850 ;; Get the special properties, like TODO and tags
14851 (goto-char beg)
14852 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14853 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14854 (when (looking-at org-priority-regexp)
14855 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14856 (when (and (setq value (org-get-tags-string))
14857 (string-match "\\S-" value))
14858 (push (cons "TAGS" value) props))
14859 (when (setq value (org-get-tags-at))
14860 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14861 props))
14862 (while (re-search-forward org-keyword-time-regexp end t)
14863 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14864 (unless (member key excluded) (push key excluded))
14865 (push (cons key
14866 (if (equal key clockstr)
14867 (org-no-properties
14868 (org-trim
14869 (buffer-substring
14870 (match-beginning 2) (point-at-eol))))
14871 (org-match-string-no-properties 2)))
14872 props)))
14873 (when (memq which '(all standard))
14874 ;; Get the standard properties, like :PORP: ...
14875 (setq range (org-get-property-block beg end))
14876 (when range
14877 (goto-char (car range))
14878 (while (re-search-forward
14879 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14880 (cdr range) t)
14881 (setq key (org-match-string-no-properties 1)
14882 value (org-trim (or (org-match-string-no-properties 2) "")))
14883 (unless (member key excluded)
14884 (push (cons key (or value "")) props)))))
14885 (append sum-props (nreverse props)))))))
14887 (defun org-entry-get (pom property &optional inherit)
14888 "Get value of PROPERTY for entry at point-or-marker POM.
14889 If INHERIT is non-nil and the entry does not have the property,
14890 then also check higher levels of the hierarchy.
14891 If the property is present but empty, the return value is the empty string.
14892 If the property is not present at all, nil is returned."
14893 (org-with-point-at pom
14894 (if inherit
14895 (org-entry-get-with-inheritance property)
14896 (if (member property org-special-properties)
14897 ;; We need a special property. Use brute force, get all properties.
14898 (cdr (assoc property (org-entry-properties nil 'special)))
14899 (let ((range (org-get-property-block)))
14900 (if (and range
14901 (goto-char (car range))
14902 (re-search-forward
14903 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14904 (cdr range) t))
14905 ;; Found the property, return it.
14906 (if (match-end 1)
14907 (org-match-string-no-properties 1)
14908 "")))))))
14910 (defun org-entry-delete (pom property)
14911 "Delete the property PROPERTY from entry at point-or-marker POM."
14912 (org-with-point-at pom
14913 (if (member property org-special-properties)
14914 nil ; cannot delete these properties.
14915 (let ((range (org-get-property-block)))
14916 (if (and range
14917 (goto-char (car range))
14918 (re-search-forward
14919 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14920 (cdr range) t))
14921 (progn
14922 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14924 nil)))))
14926 ;; Multi-values properties are properties that contain multiple values
14927 ;; These values are assumed to be single words, separated by whitespace.
14928 (defun org-entry-add-to-multivalued-property (pom property value)
14929 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14930 (let* ((old (org-entry-get pom property))
14931 (values (and old (org-split-string old "[ \t]"))))
14932 (unless (member value values)
14933 (setq values (cons value values))
14934 (org-entry-put pom property
14935 (mapconcat 'identity values " ")))))
14937 (defun org-entry-remove-from-multivalued-property (pom property value)
14938 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14939 (let* ((old (org-entry-get pom property))
14940 (values (and old (org-split-string old "[ \t]"))))
14941 (when (member value values)
14942 (setq values (delete value values))
14943 (org-entry-put pom property
14944 (mapconcat 'identity values " ")))))
14946 (defun org-entry-member-in-multivalued-property (pom property value)
14947 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14948 (let* ((old (org-entry-get pom property))
14949 (values (and old (org-split-string old "[ \t]"))))
14950 (member value values)))
14952 (defvar org-entry-property-inherited-from (make-marker))
14954 (defun org-entry-get-with-inheritance (property)
14955 "Get entry property, and search higher levels if not present."
14956 (let (tmp)
14957 (save-excursion
14958 (save-restriction
14959 (widen)
14960 (catch 'ex
14961 (while t
14962 (when (setq tmp (org-entry-get nil property))
14963 (org-back-to-heading t)
14964 (move-marker org-entry-property-inherited-from (point))
14965 (throw 'ex tmp))
14966 (or (org-up-heading-safe) (throw 'ex nil)))))
14967 (or tmp (cdr (assoc property org-local-properties))
14968 (cdr (assoc property org-global-properties))))))
14970 (defun org-entry-put (pom property value)
14971 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14972 (org-with-point-at pom
14973 (org-back-to-heading t)
14974 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14975 range)
14976 (cond
14977 ((equal property "TODO")
14978 (when (and (stringp value) (string-match "\\S-" value)
14979 (not (member value org-todo-keywords-1)))
14980 (error "\"%s\" is not a valid TODO state" value))
14981 (if (or (not value)
14982 (not (string-match "\\S-" value)))
14983 (setq value 'none))
14984 (org-todo value)
14985 (org-set-tags nil 'align))
14986 ((equal property "PRIORITY")
14987 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
14988 (string-to-char value) ?\ ))
14989 (org-set-tags nil 'align))
14990 ((equal property "SCHEDULED")
14991 (if (re-search-forward org-scheduled-time-regexp end t)
14992 (cond
14993 ((eq value 'earlier) (org-timestamp-change -1 'day))
14994 ((eq value 'later) (org-timestamp-change 1 'day))
14995 (t (call-interactively 'org-schedule)))
14996 (call-interactively 'org-schedule)))
14997 ((equal property "DEADLINE")
14998 (if (re-search-forward org-deadline-time-regexp end t)
14999 (cond
15000 ((eq value 'earlier) (org-timestamp-change -1 'day))
15001 ((eq value 'later) (org-timestamp-change 1 'day))
15002 (t (call-interactively 'org-deadline)))
15003 (call-interactively 'org-deadline)))
15004 ((member property org-special-properties)
15005 (error "The %s property can not yet be set with `org-entry-put'"
15006 property))
15007 (t ; a non-special property
15008 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15009 (setq range (org-get-property-block beg end 'force))
15010 (goto-char (car range))
15011 (if (re-search-forward
15012 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15013 (progn
15014 (delete-region (match-beginning 1) (match-end 1))
15015 (goto-char (match-beginning 1)))
15016 (goto-char (cdr range))
15017 (insert "\n")
15018 (backward-char 1)
15019 (org-indent-line-function)
15020 (insert ":" property ":"))
15021 (and value (insert " " value))
15022 (org-indent-line-function)))))))
15024 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15025 "Get all property keys in the current buffer.
15026 With INCLUDE-SPECIALS, also list the special properties that relect things
15027 like tags and TODO state.
15028 With INCLUDE-DEFAULTS, also include properties that has special meaning
15029 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15030 (let (rtn range)
15031 (save-excursion
15032 (save-restriction
15033 (widen)
15034 (goto-char (point-min))
15035 (while (re-search-forward org-property-start-re nil t)
15036 (setq range (org-get-property-block))
15037 (goto-char (car range))
15038 (while (re-search-forward
15039 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15040 (cdr range) t)
15041 (add-to-list 'rtn (org-match-string-no-properties 1)))
15042 (outline-next-heading))))
15044 (when include-specials
15045 (setq rtn (append org-special-properties rtn)))
15047 (when include-defaults
15048 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15050 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15052 (defun org-property-values (key)
15053 "Return a list of all values of property KEY."
15054 (save-excursion
15055 (save-restriction
15056 (widen)
15057 (goto-char (point-min))
15058 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15059 values)
15060 (while (re-search-forward re nil t)
15061 (add-to-list 'values (org-trim (match-string 1))))
15062 (delete "" values)))))
15064 (defun org-insert-property-drawer ()
15065 "Insert a property drawer into the current entry."
15066 (interactive)
15067 (org-back-to-heading t)
15068 (looking-at outline-regexp)
15069 (let ((indent (- (match-end 0)(match-beginning 0)))
15070 (beg (point))
15071 (re (concat "^[ \t]*" org-keyword-time-regexp))
15072 end hiddenp)
15073 (outline-next-heading)
15074 (setq end (point))
15075 (goto-char beg)
15076 (while (re-search-forward re end t))
15077 (setq hiddenp (org-invisible-p))
15078 (end-of-line 1)
15079 (and (equal (char-after) ?\n) (forward-char 1))
15080 (org-skip-over-state-notes)
15081 (skip-chars-backward " \t\n\r")
15082 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15083 (beginning-of-line 0)
15084 (indent-to-column indent)
15085 (beginning-of-line 2)
15086 (indent-to-column indent)
15087 (beginning-of-line 0)
15088 (if hiddenp
15089 (save-excursion
15090 (org-back-to-heading t)
15091 (hide-entry))
15092 (org-flag-drawer t))))
15094 (defun org-set-property (property value)
15095 "In the current entry, set PROPERTY to VALUE.
15096 When called interactively, this will prompt for a property name, offering
15097 completion on existing and default properties. And then it will prompt
15098 for a value, offering competion either on allowed values (via an inherited
15099 xxx_ALL property) or on existing values in other instances of this property
15100 in the current file."
15101 (interactive
15102 (let* ((prop (completing-read
15103 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15104 (cur (org-entry-get nil prop))
15105 (allowed (org-property-get-allowed-values nil prop 'table))
15106 (existing (mapcar 'list (org-property-values prop)))
15107 (val (if allowed
15108 (completing-read "Value: " allowed nil 'req-match)
15109 (completing-read
15110 (concat "Value" (if (and cur (string-match "\\S-" cur))
15111 (concat "[" cur "]") "")
15112 ": ")
15113 existing nil nil "" nil cur))))
15114 (list prop (if (equal val "") cur val))))
15115 (unless (equal (org-entry-get nil property) value)
15116 (org-entry-put nil property value)))
15118 (defun org-delete-property (property)
15119 "In the current entry, delete PROPERTY."
15120 (interactive
15121 (let* ((prop (completing-read
15122 "Property: " (org-entry-properties nil 'standard))))
15123 (list prop)))
15124 (message (concat "Property " property
15125 (if (org-entry-delete nil property)
15126 " deleted"
15127 " was not present in the entry"))))
15129 (defun org-delete-property-globally (property)
15130 "Remove PROPERTY globally, from all entries."
15131 (interactive
15132 (let* ((prop (completing-read
15133 "Globally remove property: "
15134 (mapcar 'list (org-buffer-property-keys)))))
15135 (list prop)))
15136 (save-excursion
15137 (save-restriction
15138 (widen)
15139 (goto-char (point-min))
15140 (let ((cnt 0))
15141 (while (re-search-forward
15142 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15143 nil t)
15144 (setq cnt (1+ cnt))
15145 (replace-match ""))
15146 (message "Property \"%s\" removed from %d entries" property cnt)))))
15148 (defvar org-columns-current-fmt-compiled) ; defined below
15150 (defun org-compute-property-at-point ()
15151 "Compute the property at point.
15152 This looks for an enclosing column format, extracts the operator and
15153 then applies it to the proerty in the column format's scope."
15154 (interactive)
15155 (unless (org-at-property-p)
15156 (error "Not at a property"))
15157 (let ((prop (org-match-string-no-properties 2)))
15158 (org-columns-get-format-and-top-level)
15159 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15160 (error "No operator defined for property %s" prop))
15161 (org-columns-compute prop)))
15163 (defun org-property-get-allowed-values (pom property &optional table)
15164 "Get allowed values for the property PROPERTY.
15165 When TABLE is non-nil, return an alist that can directly be used for
15166 completion."
15167 (let (vals)
15168 (cond
15169 ((equal property "TODO")
15170 (setq vals (org-with-point-at pom
15171 (append org-todo-keywords-1 '("")))))
15172 ((equal property "PRIORITY")
15173 (let ((n org-lowest-priority))
15174 (while (>= n org-highest-priority)
15175 (push (char-to-string n) vals)
15176 (setq n (1- n)))))
15177 ((member property org-special-properties))
15179 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15181 (when (and vals (string-match "\\S-" vals))
15182 (setq vals (car (read-from-string (concat "(" vals ")"))))
15183 (setq vals (mapcar (lambda (x)
15184 (cond ((stringp x) x)
15185 ((numberp x) (number-to-string x))
15186 ((symbolp x) (symbol-name x))
15187 (t "???")))
15188 vals)))))
15189 (if table (mapcar 'list vals) vals)))
15191 (defun org-property-previous-allowed-value (&optional previous)
15192 "Switch to the next allowed value for this property."
15193 (interactive)
15194 (org-property-next-allowed-value t))
15196 (defun org-property-next-allowed-value (&optional previous)
15197 "Switch to the next allowed value for this property."
15198 (interactive)
15199 (unless (org-at-property-p)
15200 (error "Not at a property"))
15201 (let* ((key (match-string 2))
15202 (value (match-string 3))
15203 (allowed (or (org-property-get-allowed-values (point) key)
15204 (and (member value '("[ ]" "[-]" "[X]"))
15205 '("[ ]" "[X]"))))
15206 nval)
15207 (unless allowed
15208 (error "Allowed values for this property have not been defined"))
15209 (if previous (setq allowed (reverse allowed)))
15210 (if (member value allowed)
15211 (setq nval (car (cdr (member value allowed)))))
15212 (setq nval (or nval (car allowed)))
15213 (if (equal nval value)
15214 (error "Only one allowed value for this property"))
15215 (org-at-property-p)
15216 (replace-match (concat " :" key ": " nval) t t)
15217 (org-indent-line-function)
15218 (beginning-of-line 1)
15219 (skip-chars-forward " \t")))
15221 (defun org-find-entry-with-id (ident)
15222 "Locate the entry that contains the ID property with exact value IDENT.
15223 IDENT can be a string, a symbol or a number, this function will search for
15224 the string representation of it.
15225 Return the position where this entry starts, or nil if there is no such entry."
15226 (let ((id (cond
15227 ((stringp ident) ident)
15228 ((symbol-name ident) (symbol-name ident))
15229 ((numberp ident) (number-to-string ident))
15230 (t (error "IDENT %s must be a string, symbol or number" ident))))
15231 (case-fold-search nil))
15232 (save-excursion
15233 (save-restriction
15234 (goto-char (point-min))
15235 (when (re-search-forward
15236 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15237 nil t)
15238 (org-back-to-heading)
15239 (point))))))
15241 ;;; Column View
15243 (defvar org-columns-overlays nil
15244 "Holds the list of current column overlays.")
15246 (defvar org-columns-current-fmt nil
15247 "Local variable, holds the currently active column format.")
15248 (defvar org-columns-current-fmt-compiled nil
15249 "Local variable, holds the currently active column format.
15250 This is the compiled version of the format.")
15251 (defvar org-columns-current-widths nil
15252 "Loval variable, holds the currently widths of fields.")
15253 (defvar org-columns-current-maxwidths nil
15254 "Loval variable, holds the currently active maximum column widths.")
15255 (defvar org-columns-begin-marker (make-marker)
15256 "Points to the position where last a column creation command was called.")
15257 (defvar org-columns-top-level-marker (make-marker)
15258 "Points to the position where current columns region starts.")
15260 (defvar org-columns-map (make-sparse-keymap)
15261 "The keymap valid in column display.")
15263 (defun org-columns-content ()
15264 "Switch to contents view while in columns view."
15265 (interactive)
15266 (org-overview)
15267 (org-content))
15269 (org-defkey org-columns-map "c" 'org-columns-content)
15270 (org-defkey org-columns-map "o" 'org-overview)
15271 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15272 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15273 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15274 (org-defkey org-columns-map "v" 'org-columns-show-value)
15275 (org-defkey org-columns-map "q" 'org-columns-quit)
15276 (org-defkey org-columns-map "r" 'org-columns-redo)
15277 (org-defkey org-columns-map [left] 'backward-char)
15278 (org-defkey org-columns-map "\M-b" 'backward-char)
15279 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15280 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15281 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15282 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15283 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15284 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15285 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15286 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15287 (org-defkey org-columns-map "<" 'org-columns-narrow)
15288 (org-defkey org-columns-map ">" 'org-columns-widen)
15289 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15290 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15291 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15292 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15294 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15295 '("Column"
15296 ["Edit property" org-columns-edit-value t]
15297 ["Next allowed value" org-columns-next-allowed-value t]
15298 ["Previous allowed value" org-columns-previous-allowed-value t]
15299 ["Show full value" org-columns-show-value t]
15300 ["Edit allowed" org-columns-edit-allowed t]
15301 "--"
15302 ["Edit column attributes" org-columns-edit-attributes t]
15303 ["Increase column width" org-columns-widen t]
15304 ["Decrease column width" org-columns-narrow t]
15305 "--"
15306 ["Move column right" org-columns-move-right t]
15307 ["Move column left" org-columns-move-left t]
15308 ["Add column" org-columns-new t]
15309 ["Delete column" org-columns-delete t]
15310 "--"
15311 ["CONTENTS" org-columns-content t]
15312 ["OVERVIEW" org-overview t]
15313 ["Refresh columns display" org-columns-redo t]
15314 "--"
15315 ["Quit" org-columns-quit t]))
15317 (defun org-columns-new-overlay (beg end &optional string face)
15318 "Create a new column overlay and add it to the list."
15319 (let ((ov (org-make-overlay beg end)))
15320 (org-overlay-put ov 'face (or face 'secondary-selection))
15321 (org-overlay-display ov string face)
15322 (push ov org-columns-overlays)
15323 ov))
15325 (defun org-columns-display-here (&optional props)
15326 "Overlay the current line with column display."
15327 (interactive)
15328 (let* ((fmt org-columns-current-fmt-compiled)
15329 (beg (point-at-bol))
15330 (level-face (save-excursion
15331 (beginning-of-line 1)
15332 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15333 (org-get-level-face 2))))
15334 (color (list :foreground
15335 (face-attribute (or level-face 'default) :foreground)))
15336 props pom property ass width f string ov column val modval)
15337 ;; Check if the entry is in another buffer.
15338 (unless props
15339 (if (eq major-mode 'org-agenda-mode)
15340 (setq pom (or (get-text-property (point) 'org-hd-marker)
15341 (get-text-property (point) 'org-marker))
15342 props (if pom (org-entry-properties pom) nil))
15343 (setq props (org-entry-properties nil))))
15344 ;; Walk the format
15345 (while (setq column (pop fmt))
15346 (setq property (car column)
15347 ass (if (equal property "ITEM")
15348 (cons "ITEM"
15349 (save-match-data
15350 (org-no-properties
15351 (org-remove-tabs
15352 (buffer-substring-no-properties
15353 (point-at-bol) (point-at-eol))))))
15354 (assoc property props))
15355 width (or (cdr (assoc property org-columns-current-maxwidths))
15356 (nth 2 column)
15357 (length property))
15358 f (format "%%-%d.%ds | " width width)
15359 val (or (cdr ass) "")
15360 modval (if (equal property "ITEM")
15361 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15362 string (format f (or modval val)))
15363 ;; Create the overlay
15364 (org-unmodified
15365 (setq ov (org-columns-new-overlay
15366 beg (setq beg (1+ beg)) string
15367 (list color 'org-column)))
15368 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15369 (org-overlay-put ov 'keymap org-columns-map)
15370 (org-overlay-put ov 'org-columns-key property)
15371 (org-overlay-put ov 'org-columns-value (cdr ass))
15372 (org-overlay-put ov 'org-columns-value-modified modval)
15373 (org-overlay-put ov 'org-columns-pom pom)
15374 (org-overlay-put ov 'org-columns-format f))
15375 (if (or (not (char-after beg))
15376 (equal (char-after beg) ?\n))
15377 (let ((inhibit-read-only t))
15378 (save-excursion
15379 (goto-char beg)
15380 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15381 ;; Make the rest of the line disappear.
15382 (org-unmodified
15383 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15384 (org-overlay-put ov 'invisible t)
15385 (org-overlay-put ov 'keymap org-columns-map)
15386 (org-overlay-put ov 'intangible t)
15387 (push ov org-columns-overlays)
15388 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15389 (org-overlay-put ov 'keymap org-columns-map)
15390 (push ov org-columns-overlays)
15391 (let ((inhibit-read-only t))
15392 (put-text-property (max (point-min) (1- (point-at-bol)))
15393 (min (point-max) (1+ (point-at-eol)))
15394 'read-only "Type `e' to edit property")))))
15396 (defvar org-previous-header-line-format nil
15397 "The header line format before column view was turned on.")
15398 (defvar org-columns-inhibit-recalculation nil
15399 "Inhibit recomputing of columns on column view startup.")
15402 (defvar header-line-format)
15403 (defun org-columns-display-here-title ()
15404 "Overlay the newline before the current line with the table title."
15405 (interactive)
15406 (let ((fmt org-columns-current-fmt-compiled)
15407 string (title "")
15408 property width f column str widths)
15409 (while (setq column (pop fmt))
15410 (setq property (car column)
15411 str (or (nth 1 column) property)
15412 width (or (cdr (assoc property org-columns-current-maxwidths))
15413 (nth 2 column)
15414 (length str))
15415 widths (push width widths)
15416 f (format "%%-%d.%ds | " width width)
15417 string (format f str)
15418 title (concat title string)))
15419 (setq title (concat
15420 (org-add-props " " nil 'display '(space :align-to 0))
15421 (org-add-props title nil 'face '(:weight bold :underline t))))
15422 (org-set-local 'org-previous-header-line-format header-line-format)
15423 (org-set-local 'org-columns-current-widths (nreverse widths))
15424 (setq header-line-format title)))
15426 (defun org-columns-remove-overlays ()
15427 "Remove all currently active column overlays."
15428 (interactive)
15429 (when (marker-buffer org-columns-begin-marker)
15430 (with-current-buffer (marker-buffer org-columns-begin-marker)
15431 (when (local-variable-p 'org-previous-header-line-format)
15432 (setq header-line-format org-previous-header-line-format)
15433 (kill-local-variable 'org-previous-header-line-format))
15434 (move-marker org-columns-begin-marker nil)
15435 (move-marker org-columns-top-level-marker nil)
15436 (org-unmodified
15437 (mapc 'org-delete-overlay org-columns-overlays)
15438 (setq org-columns-overlays nil)
15439 (let ((inhibit-read-only t))
15440 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15442 (defun org-columns-cleanup-item (item fmt)
15443 "Remove from ITEM what is a column in the format FMT."
15444 (when (string-match org-complex-heading-regexp item)
15445 (concat
15446 (org-add-props (concat (match-string 1 item) " ") nil
15447 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15448 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15449 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15450 " " (match-string 4 item)
15451 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item))))))
15453 (defun org-columns-show-value ()
15454 "Show the full value of the property."
15455 (interactive)
15456 (let ((value (get-char-property (point) 'org-columns-value)))
15457 (message "Value is: %s" (or value ""))))
15459 (defun org-columns-quit ()
15460 "Remove the column overlays and in this way exit column editing."
15461 (interactive)
15462 (org-unmodified
15463 (org-columns-remove-overlays)
15464 (let ((inhibit-read-only t))
15465 (remove-text-properties (point-min) (point-max) '(read-only t))))
15466 (when (eq major-mode 'org-agenda-mode)
15467 (message
15468 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15470 (defun org-columns-check-computed ()
15471 "Check if this column value is computed.
15472 If yes, throw an error indicating that changing it does not make sense."
15473 (let ((val (get-char-property (point) 'org-columns-value)))
15474 (when (and (stringp val)
15475 (get-char-property 0 'org-computed val))
15476 (error "This value is computed from the entry's children"))))
15478 (defun org-columns-todo (&optional arg)
15479 "Change the TODO state during column view."
15480 (interactive "P")
15481 (org-columns-edit-value "TODO"))
15483 (defun org-columns-set-tags-or-toggle (&optional arg)
15484 "Toggle checkbox at point, or set tags for current headline."
15485 (interactive "P")
15486 (if (string-match "\\`\\[[ xX-]\\]\\'"
15487 (get-char-property (point) 'org-columns-value))
15488 (org-columns-next-allowed-value)
15489 (org-columns-edit-value "TAGS")))
15491 (defun org-columns-edit-value (&optional key)
15492 "Edit the value of the property at point in column view.
15493 Where possible, use the standard interface for changing this line."
15494 (interactive)
15495 (org-columns-check-computed)
15496 (let* ((external-key key)
15497 (col (current-column))
15498 (key (or key (get-char-property (point) 'org-columns-key)))
15499 (value (get-char-property (point) 'org-columns-value))
15500 (bol (point-at-bol)) (eol (point-at-eol))
15501 (pom (or (get-text-property bol 'org-hd-marker)
15502 (point))) ; keep despite of compiler waring
15503 (line-overlays
15504 (delq nil (mapcar (lambda (x)
15505 (and (eq (overlay-buffer x) (current-buffer))
15506 (>= (overlay-start x) bol)
15507 (<= (overlay-start x) eol)
15509 org-columns-overlays)))
15510 nval eval allowed)
15511 (cond
15512 ((equal key "ITEM")
15513 (setq eval '(org-with-point-at pom
15514 (org-edit-headline))))
15515 ((equal key "TODO")
15516 (setq eval '(org-with-point-at pom
15517 (let ((current-prefix-arg
15518 (if external-key current-prefix-arg '(4))))
15519 (call-interactively 'org-todo)))))
15520 ((equal key "PRIORITY")
15521 (setq eval '(org-with-point-at pom
15522 (call-interactively 'org-priority))))
15523 ((equal key "TAGS")
15524 (setq eval '(org-with-point-at pom
15525 (let ((org-fast-tag-selection-single-key
15526 (if (eq org-fast-tag-selection-single-key 'expert)
15527 t org-fast-tag-selection-single-key)))
15528 (call-interactively 'org-set-tags)))))
15529 ((equal key "DEADLINE")
15530 (setq eval '(org-with-point-at pom
15531 (call-interactively 'org-deadline))))
15532 ((equal key "SCHEDULED")
15533 (setq eval '(org-with-point-at pom
15534 (call-interactively 'org-schedule))))
15536 (setq allowed (org-property-get-allowed-values pom key 'table))
15537 (if allowed
15538 (setq nval (completing-read "Value: " allowed nil t))
15539 (setq nval (read-string "Edit: " value)))
15540 (setq nval (org-trim nval))
15541 (when (not (equal nval value))
15542 (setq eval '(org-entry-put pom key nval)))))
15543 (when eval
15544 (let ((inhibit-read-only t))
15545 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15546 (unwind-protect
15547 (progn
15548 (setq org-columns-overlays
15549 (org-delete-all line-overlays org-columns-overlays))
15550 (mapc 'org-delete-overlay line-overlays)
15551 (org-columns-eval eval))
15552 (org-columns-display-here))))
15553 (move-to-column col)
15554 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15555 (org-columns-update key))))
15557 (defun org-edit-headline () ; FIXME: this is not columns specific
15558 "Edit the current headline, the part without TODO keyword, TAGS."
15559 (org-back-to-heading)
15560 (when (looking-at org-todo-line-regexp)
15561 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15562 (txt (match-string 3))
15563 (post "")
15564 txt2)
15565 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15566 (setq post (match-string 0 txt)
15567 txt (substring txt 0 (match-beginning 0))))
15568 (setq txt2 (read-string "Edit: " txt))
15569 (when (not (equal txt txt2))
15570 (beginning-of-line 1)
15571 (insert pre txt2 post)
15572 (delete-region (point) (point-at-eol))
15573 (org-set-tags nil t)))))
15575 (defun org-columns-edit-allowed ()
15576 "Edit the list of allowed values for the current property."
15577 (interactive)
15578 (let* ((key (get-char-property (point) 'org-columns-key))
15579 (key1 (concat key "_ALL"))
15580 (allowed (org-entry-get (point) key1 t))
15581 nval)
15582 (setq nval (read-string "Allowed: " allowed))
15583 (org-entry-put
15584 (cond ((marker-position org-entry-property-inherited-from)
15585 org-entry-property-inherited-from)
15586 ((marker-position org-columns-top-level-marker)
15587 org-columns-top-level-marker))
15588 key1 nval)))
15590 (defun org-columns-eval (form)
15591 (let (hidep)
15592 (save-excursion
15593 (beginning-of-line 1)
15594 (condition-case nil (next-line 1) (error nil))
15595 (setq hidep (org-on-heading-p 1)))
15596 (eval form)
15597 (and hidep (hide-entry))))
15599 (defun org-columns-previous-allowed-value ()
15600 "Switch to the previous allowed value for this column."
15601 (interactive)
15602 (org-columns-next-allowed-value t))
15604 (defun org-columns-next-allowed-value (&optional previous)
15605 "Switch to the next allowed value for this column."
15606 (interactive)
15607 (org-columns-check-computed)
15608 (let* ((col (current-column))
15609 (key (get-char-property (point) 'org-columns-key))
15610 (value (get-char-property (point) 'org-columns-value))
15611 (bol (point-at-bol)) (eol (point-at-eol))
15612 (pom (or (get-text-property bol 'org-hd-marker)
15613 (point))) ; keep despite of compiler waring
15614 (line-overlays
15615 (delq nil (mapcar (lambda (x)
15616 (and (eq (overlay-buffer x) (current-buffer))
15617 (>= (overlay-start x) bol)
15618 (<= (overlay-start x) eol)
15620 org-columns-overlays)))
15621 (allowed (or (org-property-get-allowed-values pom key)
15622 (and (equal
15623 (nth 4 (assoc key org-columns-current-fmt-compiled))
15624 'checkbox) '("[ ]" "[X]"))))
15625 nval)
15626 (when (equal key "ITEM")
15627 (error "Cannot edit item headline from here"))
15628 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15629 (error "Allowed values for this property have not been defined"))
15630 (if (member key '("SCHEDULED" "DEADLINE"))
15631 (setq nval (if previous 'earlier 'later))
15632 (if previous (setq allowed (reverse allowed)))
15633 (if (member value allowed)
15634 (setq nval (car (cdr (member value allowed)))))
15635 (setq nval (or nval (car allowed)))
15636 (if (equal nval value)
15637 (error "Only one allowed value for this property")))
15638 (let ((inhibit-read-only t))
15639 (remove-text-properties (1- bol) eol '(read-only t))
15640 (unwind-protect
15641 (progn
15642 (setq org-columns-overlays
15643 (org-delete-all line-overlays org-columns-overlays))
15644 (mapc 'org-delete-overlay line-overlays)
15645 (org-columns-eval '(org-entry-put pom key nval)))
15646 (org-columns-display-here)))
15647 (move-to-column col)
15648 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15649 (org-columns-update key))))
15651 (defun org-verify-version (task)
15652 (cond
15653 ((eq task 'columns)
15654 (if (or (featurep 'xemacs)
15655 (< emacs-major-version 22))
15656 (error "Emacs 22 is required for the columns feature")))))
15658 ;; FIXME: does not yet work
15659 (defun org-columns-follow-link ()
15660 (let ((key (get-char-property (point) 'org-columns-key))
15661 (value (get-char-property (point) 'org-columns-value)))
15662 (if (or (string-match org-bracket-link-regexp value)
15663 (string-match org-angle-link-re value)
15664 (string-match org-plain-link-re value))
15665 (org-open-at-point) ; fixme
15666 (error "No link in this value"))))
15668 (defun org-columns-get-format-and-top-level ()
15669 (let (fmt)
15670 (when (condition-case nil (org-back-to-heading) (error nil))
15671 (move-marker org-entry-property-inherited-from nil)
15672 (setq fmt (org-entry-get nil "COLUMNS" t)))
15673 (setq fmt (or fmt org-columns-default-format))
15674 (org-set-local 'org-columns-current-fmt fmt)
15675 (org-columns-compile-format fmt)
15676 (if (marker-position org-entry-property-inherited-from)
15677 (move-marker org-columns-top-level-marker
15678 org-entry-property-inherited-from)
15679 (move-marker org-columns-top-level-marker (point)))
15680 fmt))
15682 (defun org-columns ()
15683 "Turn on column view on an org-mode file."
15684 (interactive)
15685 (org-verify-version 'columns)
15686 (org-columns-remove-overlays)
15687 (move-marker org-columns-begin-marker (point))
15688 (let (beg end fmt cache maxwidths)
15689 (setq fmt (org-columns-get-format-and-top-level))
15690 (save-excursion
15691 (goto-char org-columns-top-level-marker)
15692 (setq beg (point))
15693 (unless org-columns-inhibit-recalculation
15694 (org-columns-compute-all))
15695 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15696 (point-max)))
15697 (goto-char beg)
15698 ;; Get and cache the properties
15699 (while (re-search-forward (concat "^" outline-regexp) end t)
15700 (push (cons (org-current-line) (org-entry-properties)) cache))
15701 (when cache
15702 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15703 (org-set-local 'org-columns-current-maxwidths maxwidths)
15704 (org-columns-display-here-title)
15705 (mapc (lambda (x)
15706 (goto-line (car x))
15707 (org-columns-display-here (cdr x)))
15708 cache)))))
15710 (defun org-columns-new (&optional prop title width op fmt)
15711 "Insert a new column, to the leeft o the current column."
15712 (interactive)
15713 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15714 cell)
15715 (setq prop (completing-read
15716 "Property: " (mapcar 'list (org-buffer-property-keys t))
15717 nil nil prop))
15718 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15719 (setq width (read-string "Column width: " (if width (number-to-string width))))
15720 (if (string-match "\\S-" width)
15721 (setq width (string-to-number width))
15722 (setq width nil))
15723 (setq fmt (completing-read "Summary [none]: "
15724 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15725 nil t))
15726 (if (string-match "\\S-" fmt)
15727 (setq fmt (intern fmt))
15728 (setq fmt nil))
15729 (if (eq fmt 'none) (setq fmt nil))
15730 (if editp
15731 (progn
15732 (setcar editp prop)
15733 (setcdr editp (list title width nil fmt)))
15734 (setq cell (nthcdr (1- (current-column))
15735 org-columns-current-fmt-compiled))
15736 (setcdr cell (cons (list prop title width nil fmt)
15737 (cdr cell))))
15738 (org-columns-store-format)
15739 (org-columns-redo)))
15741 (defun org-columns-delete ()
15742 "Delete the column at point from columns view."
15743 (interactive)
15744 (let* ((n (current-column))
15745 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15746 (when (y-or-n-p
15747 (format "Are you sure you want to remove column \"%s\"? " title))
15748 (setq org-columns-current-fmt-compiled
15749 (delq (nth n org-columns-current-fmt-compiled)
15750 org-columns-current-fmt-compiled))
15751 (org-columns-store-format)
15752 (org-columns-redo)
15753 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15754 (backward-char 1)))))
15756 (defun org-columns-edit-attributes ()
15757 "Edit the attributes of the current column."
15758 (interactive)
15759 (let* ((n (current-column))
15760 (info (nth n org-columns-current-fmt-compiled)))
15761 (apply 'org-columns-new info)))
15763 (defun org-columns-widen (arg)
15764 "Make the column wider by ARG characters."
15765 (interactive "p")
15766 (let* ((n (current-column))
15767 (entry (nth n org-columns-current-fmt-compiled))
15768 (width (or (nth 2 entry)
15769 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15770 (setq width (max 1 (+ width arg)))
15771 (setcar (nthcdr 2 entry) width)
15772 (org-columns-store-format)
15773 (org-columns-redo)))
15775 (defun org-columns-narrow (arg)
15776 "Make the column nrrower by ARG characters."
15777 (interactive "p")
15778 (org-columns-widen (- arg)))
15780 (defun org-columns-move-right ()
15781 "Swap this column with the one to the right."
15782 (interactive)
15783 (let* ((n (current-column))
15784 (cell (nthcdr n org-columns-current-fmt-compiled))
15786 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15787 (error "Cannot shift this column further to the right"))
15788 (setq e (car cell))
15789 (setcar cell (car (cdr cell)))
15790 (setcdr cell (cons e (cdr (cdr cell))))
15791 (org-columns-store-format)
15792 (org-columns-redo)
15793 (forward-char 1)))
15795 (defun org-columns-move-left ()
15796 "Swap this column with the one to the left."
15797 (interactive)
15798 (let* ((n (current-column)))
15799 (when (= n 0)
15800 (error "Cannot shift this column further to the left"))
15801 (backward-char 1)
15802 (org-columns-move-right)
15803 (backward-char 1)))
15805 (defun org-columns-store-format ()
15806 "Store the text version of the current columns format in appropriate place.
15807 This is either in the COLUMNS property of the node starting the current column
15808 display, or in the #+COLUMNS line of the current buffer."
15809 (let (fmt (cnt 0))
15810 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15811 (org-set-local 'org-columns-current-fmt fmt)
15812 (if (marker-position org-columns-top-level-marker)
15813 (save-excursion
15814 (goto-char org-columns-top-level-marker)
15815 (if (and (org-at-heading-p)
15816 (org-entry-get nil "COLUMNS"))
15817 (org-entry-put nil "COLUMNS" fmt)
15818 (goto-char (point-min))
15819 ;; Overwrite all #+COLUMNS lines....
15820 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15821 (setq cnt (1+ cnt))
15822 (replace-match (concat "#+COLUMNS: " fmt) t t))
15823 (unless (> cnt 0)
15824 (goto-char (point-min))
15825 (or (org-on-heading-p t) (outline-next-heading))
15826 (let ((inhibit-read-only t))
15827 (insert-before-markers "#+COLUMNS: " fmt "\n")))
15828 (org-set-local 'org-columns-default-format fmt))))))
15830 (defvar org-overriding-columns-format nil
15831 "When set, overrides any other definition.")
15832 (defvar org-agenda-view-columns-initially nil
15833 "When set, switch to columns view immediately after creating the agenda.")
15835 (defun org-agenda-columns ()
15836 "Turn on column view in the agenda."
15837 (interactive)
15838 (org-verify-version 'columns)
15839 (org-columns-remove-overlays)
15840 (move-marker org-columns-begin-marker (point))
15841 (let (fmt cache maxwidths m)
15842 (cond
15843 ((and (local-variable-p 'org-overriding-columns-format)
15844 org-overriding-columns-format)
15845 (setq fmt org-overriding-columns-format))
15846 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15847 (setq fmt (org-entry-get m "COLUMNS" t)))
15848 ((and (boundp 'org-columns-current-fmt)
15849 (local-variable-p 'org-columns-current-fmt)
15850 org-columns-current-fmt)
15851 (setq fmt org-columns-current-fmt))
15852 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15853 (setq m (get-text-property m 'org-hd-marker))
15854 (setq fmt (org-entry-get m "COLUMNS" t))))
15855 (setq fmt (or fmt org-columns-default-format))
15856 (org-set-local 'org-columns-current-fmt fmt)
15857 (org-columns-compile-format fmt)
15858 (save-excursion
15859 ;; Get and cache the properties
15860 (goto-char (point-min))
15861 (while (not (eobp))
15862 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15863 (get-text-property (point) 'org-marker)))
15864 (push (cons (org-current-line) (org-entry-properties m)) cache))
15865 (beginning-of-line 2))
15866 (when cache
15867 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15868 (org-set-local 'org-columns-current-maxwidths maxwidths)
15869 (org-columns-display-here-title)
15870 (mapc (lambda (x)
15871 (goto-line (car x))
15872 (org-columns-display-here (cdr x)))
15873 cache)))))
15875 (defun org-columns-get-autowidth-alist (s cache)
15876 "Derive the maximum column widths from the format and the cache."
15877 (let ((start 0) rtn)
15878 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15879 (push (cons (match-string 1 s) 1) rtn)
15880 (setq start (match-end 0)))
15881 (mapc (lambda (x)
15882 (setcdr x (apply 'max
15883 (mapcar
15884 (lambda (y)
15885 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15886 cache))))
15887 rtn)
15888 rtn))
15890 (defun org-columns-compute-all ()
15891 "Compute all columns that have operators defined."
15892 (org-unmodified
15893 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15894 (let ((columns org-columns-current-fmt-compiled) col)
15895 (while (setq col (pop columns))
15896 (when (nth 3 col)
15897 (save-excursion
15898 (org-columns-compute (car col)))))))
15900 (defun org-columns-update (property)
15901 "Recompute PROPERTY, and update the columns display for it."
15902 (org-columns-compute property)
15903 (let (fmt val pos)
15904 (save-excursion
15905 (mapc (lambda (ov)
15906 (when (equal (org-overlay-get ov 'org-columns-key) property)
15907 (setq pos (org-overlay-start ov))
15908 (goto-char pos)
15909 (when (setq val (cdr (assoc property
15910 (get-text-property
15911 (point-at-bol) 'org-summaries))))
15912 (setq fmt (org-overlay-get ov 'org-columns-format))
15913 (org-overlay-put ov 'org-columns-value val)
15914 (org-overlay-put ov 'display (format fmt val)))))
15915 org-columns-overlays))))
15917 (defun org-columns-compute (property)
15918 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15919 (interactive)
15920 (let* ((re (concat "^" outline-regexp))
15921 (lmax 30) ; Does anyone use deeper levels???
15922 (lsum (make-vector lmax 0))
15923 (lflag (make-vector lmax nil))
15924 (level 0)
15925 (ass (assoc property org-columns-current-fmt-compiled))
15926 (format (nth 4 ass))
15927 (beg org-columns-top-level-marker)
15928 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15929 (save-excursion
15930 ;; Find the region to compute
15931 (goto-char beg)
15932 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15933 (goto-char end)
15934 ;; Walk the tree from the back and do the computations
15935 (while (re-search-backward re beg t)
15936 (setq sumpos (match-beginning 0)
15937 last-level level
15938 level (org-outline-level)
15939 val (org-entry-get nil property)
15940 valflag (and val (string-match "\\S-" val)))
15941 (cond
15942 ((< level last-level)
15943 ;; put the sum of lower levels here as a property
15944 (setq sum (aref lsum last-level) ; current sum
15945 flag (aref lflag last-level) ; any valid entries from children?
15946 str (org-column-number-to-string sum format)
15947 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15948 useval (if flag str1 (if valflag val ""))
15949 sum-alist (get-text-property sumpos 'org-summaries))
15950 (if (assoc property sum-alist)
15951 (setcdr (assoc property sum-alist) useval)
15952 (push (cons property useval) sum-alist)
15953 (org-unmodified
15954 (add-text-properties sumpos (1+ sumpos)
15955 (list 'org-summaries sum-alist))))
15956 (when val
15957 (org-entry-put nil property (if flag str val)))
15958 ;; add current to current level accumulator
15959 (when (or flag valflag)
15960 ;; FIXME: is this ok?????????
15961 (aset lsum level (+ (aref lsum level)
15962 (if flag sum (org-column-string-to-number
15963 (if flag str val) format))))
15964 (aset lflag level t))
15965 ;; clear accumulators for deeper levels
15966 (loop for l from (1+ level) to (1- lmax) do
15967 (aset lsum l 0)
15968 (aset lflag l nil)))
15969 ((>= level last-level)
15970 ;; add what we have here to the accumulator for this level
15971 (aset lsum level (+ (aref lsum level)
15972 (org-column-string-to-number (or val "0") format)))
15973 (and valflag (aset lflag level t)))
15974 (t (error "This should not happen")))))))
15976 (defun org-columns-redo ()
15977 "Construct the column display again."
15978 (interactive)
15979 (message "Recomputing columns...")
15980 (save-excursion
15981 (if (marker-position org-columns-begin-marker)
15982 (goto-char org-columns-begin-marker))
15983 (org-columns-remove-overlays)
15984 (if (org-mode-p)
15985 (call-interactively 'org-columns)
15986 (call-interactively 'org-agenda-columns)))
15987 (message "Recomputing columns...done"))
15989 (defun org-columns-not-in-agenda ()
15990 (if (eq major-mode 'org-agenda-mode)
15991 (error "This command is only allowed in Org-mode buffers")))
15994 (defun org-string-to-number (s)
15995 "Convert string to number, and interpret hh:mm:ss."
15996 (if (not (string-match ":" s))
15997 (string-to-number s)
15998 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
15999 (while l
16000 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16001 sum)))
16003 (defun org-column-number-to-string (n fmt)
16004 "Convert a computed column number to a string value, according to FMT."
16005 (cond
16006 ((eq fmt 'add_times)
16007 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16008 (format "%d:%02d" h m)))
16009 ((eq fmt 'checkbox)
16010 (cond ((= n (floor n)) "[X]")
16011 ((> n 1.) "[-]")
16012 (t "[ ]")))
16013 (t (number-to-string n))))
16015 (defun org-column-string-to-number (s fmt)
16016 "Convert a column value to a number that can be used for column computing."
16017 (cond
16018 ((string-match ":" s)
16019 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16020 (while l
16021 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16022 sum))
16023 ((eq fmt 'checkbox)
16024 (if (equal s "[X]") 1. 0.000001))
16025 (t (string-to-number s))))
16027 (defun org-columns-uncompile-format (cfmt)
16028 "Turn the compiled columns format back into a string representation."
16029 (let ((rtn "") e s prop title op width fmt)
16030 (while (setq e (pop cfmt))
16031 (setq prop (car e)
16032 title (nth 1 e)
16033 width (nth 2 e)
16034 op (nth 3 e)
16035 fmt (nth 4 e))
16036 (cond
16037 ((eq fmt 'add_times) (setq op ":"))
16038 ((eq fmt 'checkbox) (setq op "X"))
16039 ((eq fmt 'add_numbers) (setq op "+")))
16040 (if (equal title prop) (setq title nil))
16041 (setq s (concat "%" (if width (number-to-string width))
16042 prop
16043 (if title (concat "(" title ")"))
16044 (if op (concat "{" op "}"))))
16045 (setq rtn (concat rtn " " s)))
16046 (org-trim rtn)))
16048 (defun org-columns-compile-format (fmt)
16049 "Turn a column format string into an alist of specifications.
16050 The alist has one entry for each column in the format. The elements of
16051 that list are:
16052 property the property
16053 title the title field for the columns
16054 width the column width in characters, can be nil for automatic
16055 operator the operator if any
16056 format the output format for computed results, derived from operator"
16057 (let ((start 0) width prop title op f)
16058 (setq org-columns-current-fmt-compiled nil)
16059 (while (string-match
16060 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16061 fmt start)
16062 (setq start (match-end 0)
16063 width (match-string 1 fmt)
16064 prop (match-string 2 fmt)
16065 title (or (match-string 3 fmt) prop)
16066 op (match-string 4 fmt)
16067 f nil)
16068 (if width (setq width (string-to-number width)))
16069 (cond
16070 ((equal op "+") (setq f 'add_numbers))
16071 ((equal op ":") (setq f 'add_times))
16072 ((equal op "X") (setq f 'checkbox)))
16073 (push (list prop title width op f) org-columns-current-fmt-compiled))
16074 (setq org-columns-current-fmt-compiled
16075 (nreverse org-columns-current-fmt-compiled))))
16078 ;;; Dynamic block for Column view
16080 (defun org-columns-capture-view ()
16081 "Get the column view of the current buffer and return it as a list.
16082 The list will contains the title row and all other rows. Each row is
16083 a list of fields."
16084 (save-excursion
16085 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16086 (n (length title)) row tbl)
16087 (goto-char (point-min))
16088 (while (re-search-forward "^\\*+ " nil t)
16089 (when (get-char-property (match-beginning 0) 'org-columns-key)
16090 (setq row nil)
16091 (loop for i from 0 to (1- n) do
16092 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16093 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16095 row))
16096 (setq row (nreverse row))
16097 (push row tbl)))
16098 (append (list title 'hline) (nreverse tbl)))))
16100 (defun org-dblock-write:columnview (params)
16101 "Write the column view table.
16102 PARAMS is a property list of parameters:
16104 :width enforce same column widths with <N> specifiers.
16105 :id the :ID: property of the entry where the columns view
16106 should be built, as a string. When `local', call locally.
16107 When `global' call column view with the cursor at the beginning
16108 of the buffer (usually this means that the whole buffer switches
16109 to column view).
16110 :hlines When t, insert a hline before each item. When a number, insert
16111 a hline before each level <= that number.
16112 :vlines When t, make each column a colgroup to enforce vertical lines."
16113 (let ((pos (move-marker (make-marker) (point)))
16114 (hlines (plist-get params :hlines))
16115 (vlines (plist-get params :vlines))
16116 tbl id idpos nfields tmp)
16117 (save-excursion
16118 (save-restriction
16119 (when (setq id (plist-get params :id))
16120 (cond ((not id) nil)
16121 ((eq id 'global) (goto-char (point-min)))
16122 ((eq id 'local) nil)
16123 ((setq idpos (org-find-entry-with-id id))
16124 (goto-char idpos))
16125 (t (error "Cannot find entry with :ID: %s" id))))
16126 (org-columns)
16127 (setq tbl (org-columns-capture-view))
16128 (setq nfields (length (car tbl)))
16129 (org-columns-quit)))
16130 (goto-char pos)
16131 (move-marker pos nil)
16132 (when tbl
16133 (when (plist-get params :hlines)
16134 (setq tmp nil)
16135 (while tbl
16136 (if (eq (car tbl) 'hline)
16137 (push (pop tbl) tmp)
16138 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16139 (if (and (not (eq (car tmp) 'hline))
16140 (or (eq hlines t)
16141 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16142 (push 'hline tmp)))
16143 (push (pop tbl) tmp)))
16144 (setq tbl (nreverse tmp)))
16145 (when vlines
16146 (setq tbl (mapcar (lambda (x)
16147 (if (eq 'hline x) x (cons "" x)))
16148 tbl))
16149 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16150 (setq pos (point))
16151 (insert (org-listtable-to-string tbl))
16152 (when (plist-get params :width)
16153 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16154 org-columns-current-widths "|")))
16155 (goto-char pos)
16156 (org-table-align))))
16158 (defun org-listtable-to-string (tbl)
16159 "Convert a listtable TBL to a string that contains the Org-mode table.
16160 The table still need to be alligned. The resulting string has no leading
16161 and tailing newline characters."
16162 (mapconcat
16163 (lambda (x)
16164 (cond
16165 ((listp x)
16166 (concat "|" (mapconcat 'identity x "|") "|"))
16167 ((eq x 'hline) "|-|")
16168 (t (error "Garbage in listtable: %s" x))))
16169 tbl "\n"))
16171 (defun org-insert-columns-dblock ()
16172 "Create a dynamic block capturing a column view table."
16173 (interactive)
16174 (let ((defaults '(:name "columnview" :hlines 1))
16175 (id (completing-read
16176 "Capture columns (local, global, entry with :ID: property) [local]: "
16177 (append '(("global") ("local"))
16178 (mapcar 'list (org-property-values "ID"))))))
16179 (if (equal id "") (setq id 'local))
16180 (if (equal id "global") (setq id 'global))
16181 (setq defaults (append defaults (list :id id)))
16182 (org-create-dblock defaults)
16183 (org-update-dblock)))
16185 ;;;; Timestamps
16187 (defvar org-last-changed-timestamp nil)
16188 (defvar org-time-was-given) ; dynamically scoped parameter
16189 (defvar org-end-time-was-given) ; dynamically scoped parameter
16190 (defvar org-ts-what) ; dynamically scoped parameter
16192 (defun org-time-stamp (arg)
16193 "Prompt for a date/time and insert a time stamp.
16194 If the user specifies a time like HH:MM, or if this command is called
16195 with a prefix argument, the time stamp will contain date and time.
16196 Otherwise, only the date will be included. All parts of a date not
16197 specified by the user will be filled in from the current date/time.
16198 So if you press just return without typing anything, the time stamp
16199 will represent the current date/time. If there is already a timestamp
16200 at the cursor, it will be modified."
16201 (interactive "P")
16202 (let ((default-time
16203 ;; Default time is either today, or, when entering a range,
16204 ;; the range start.
16205 (if (or (org-at-timestamp-p t)
16206 (save-excursion
16207 (re-search-backward
16208 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16209 (- (point) 20) t)))
16210 (apply 'encode-time (org-parse-time-string (match-string 1)))
16211 (current-time)))
16212 org-time-was-given org-end-time-was-given time)
16213 (cond
16214 ((and (org-at-timestamp-p)
16215 (eq last-command 'org-time-stamp)
16216 (eq this-command 'org-time-stamp))
16217 (insert "--")
16218 (setq time (let ((this-command this-command))
16219 (org-read-date arg 'totime nil nil default-time)))
16220 (org-insert-time-stamp time (or org-time-was-given arg)))
16221 ((org-at-timestamp-p)
16222 (setq time (let ((this-command this-command))
16223 (org-read-date arg 'totime nil nil default-time)))
16224 (when (org-at-timestamp-p) ; just to get the match data
16225 (replace-match "")
16226 (setq org-last-changed-timestamp
16227 (org-insert-time-stamp
16228 time (or org-time-was-given arg)
16229 nil nil nil (list org-end-time-was-given))))
16230 (message "Timestamp updated"))
16232 (setq time (let ((this-command this-command))
16233 (org-read-date arg 'totime nil nil default-time)))
16234 (org-insert-time-stamp time (or org-time-was-given arg)
16235 nil nil nil (list org-end-time-was-given))))))
16237 (defun org-time-stamp-inactive (&optional arg)
16238 "Insert an inactive time stamp.
16239 An inactive time stamp is enclosed in square brackets instead of angle
16240 brackets. It is inactive in the sense that it does not trigger agenda entries,
16241 does not link to the calendar and cannot be changed with the S-cursor keys.
16242 So these are more for recording a certain time/date."
16243 (interactive "P")
16244 (let (org-time-was-given org-end-time-was-given time)
16245 (setq time (org-read-date arg 'totime))
16246 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16247 nil nil (list org-end-time-was-given))))
16249 (defvar org-date-ovl (org-make-overlay 1 1))
16250 (org-overlay-put org-date-ovl 'face 'org-warning)
16251 (org-detach-overlay org-date-ovl)
16253 (defvar org-ans1) ; dynamically scoped parameter
16254 (defvar org-ans2) ; dynamically scoped parameter
16256 (defvar org-plain-time-of-day-regexp) ; defined below
16257 (defun org-read-date (&optional with-time to-time from-string prompt
16258 default-time)
16259 "Read a date and make things smooth for the user.
16260 The prompt will suggest to enter an ISO date, but you can also enter anything
16261 which will at least partially be understood by `parse-time-string'.
16262 Unrecognized parts of the date will default to the current day, month, year,
16263 hour and minute. If this command is called to replace a timestamp at point,
16264 of to enter the second timestamp of a range, the default time is taken from the
16265 existing stamp. For example,
16266 3-2-5 --> 2003-02-05
16267 feb 15 --> currentyear-02-15
16268 sep 12 9 --> 2009-09-12
16269 12:45 --> today 12:45
16270 22 sept 0:34 --> currentyear-09-22 0:34
16271 12 --> currentyear-currentmonth-12
16272 Fri --> nearest Friday (today or later)
16273 etc.
16275 Furthermore you can specify a relative date by giving, as the *first* thing
16276 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16277 change in days weeks, months, years.
16278 With a single plus or minus, the date is relative to today. With a double
16279 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16280 +4d --> four days from today
16281 +4 --> same as above
16282 +2w --> two weeks from today
16283 ++5 --> five days from default date
16285 The function understands only English month and weekday abbreviations,
16286 but this can be configured with the variables `parse-time-months' and
16287 `parse-time-weekdays'.
16289 While prompting, a calendar is popped up - you can also select the
16290 date with the mouse (button 1). The calendar shows a period of three
16291 months. To scroll it to other months, use the keys `>' and `<'.
16292 If you don't like the calendar, turn it off with
16293 \(setq org-popup-calendar-for-date-prompt nil)
16295 With optional argument TO-TIME, the date will immediately be converted
16296 to an internal time.
16297 With an optional argument WITH-TIME, the prompt will suggest to also
16298 insert a time. Note that when WITH-TIME is not set, you can still
16299 enter a time, and this function will inform the calling routine about
16300 this change. The calling routine may then choose to change the format
16301 used to insert the time stamp into the buffer to include the time.
16302 With optional argument FROM-STRING, read fomr this string instead from
16303 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16304 the time/date that is used for everything that is not specified by the
16305 user."
16306 (require 'parse-time)
16307 (let* ((org-time-stamp-rounding-minutes
16308 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16309 (ct (org-current-time))
16310 (def (or default-time ct))
16311 (calendar-move-hook nil)
16312 (view-diary-entries-initially nil)
16313 (view-calendar-holidays-initially nil)
16314 (timestr (format-time-string
16315 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16316 (prompt (concat (if prompt (concat prompt " ") "")
16317 (format "Date and/or time (default [%s]): " timestr)))
16318 ans (org-ans0 "") org-ans1 org-ans2 deltan deltaw deltarel
16319 second minute hour day month year tl wday wday1 pm h2 m2)
16321 (cond
16322 (from-string (setq ans from-string))
16323 (org-popup-calendar-for-date-prompt
16324 (save-excursion
16325 (save-window-excursion
16326 (calendar)
16327 (calendar-forward-day (- (time-to-days def)
16328 (calendar-absolute-from-gregorian
16329 (calendar-current-date))))
16330 (org-eval-in-calendar nil t)
16331 (let* ((old-map (current-local-map))
16332 (map (copy-keymap calendar-mode-map))
16333 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16334 (org-defkey map (kbd "RET") 'org-calendar-select)
16335 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16336 'org-calendar-select-mouse)
16337 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16338 'org-calendar-select-mouse)
16339 (org-defkey minibuffer-local-map [(meta shift left)]
16340 (lambda () (interactive)
16341 (org-eval-in-calendar '(calendar-backward-month 1))))
16342 (org-defkey minibuffer-local-map [(meta shift right)]
16343 (lambda () (interactive)
16344 (org-eval-in-calendar '(calendar-forward-month 1))))
16345 (org-defkey minibuffer-local-map [(shift up)]
16346 (lambda () (interactive)
16347 (org-eval-in-calendar '(calendar-backward-week 1))))
16348 (org-defkey minibuffer-local-map [(shift down)]
16349 (lambda () (interactive)
16350 (org-eval-in-calendar '(calendar-forward-week 1))))
16351 (org-defkey minibuffer-local-map [(shift left)]
16352 (lambda () (interactive)
16353 (org-eval-in-calendar '(calendar-backward-day 1))))
16354 (org-defkey minibuffer-local-map [(shift right)]
16355 (lambda () (interactive)
16356 (org-eval-in-calendar '(calendar-forward-day 1))))
16357 (org-defkey minibuffer-local-map ">"
16358 (lambda () (interactive)
16359 (org-eval-in-calendar '(scroll-calendar-left 1))))
16360 (org-defkey minibuffer-local-map "<"
16361 (lambda () (interactive)
16362 (org-eval-in-calendar '(scroll-calendar-right 1))))
16363 (unwind-protect
16364 (progn
16365 (use-local-map map)
16366 (setq org-ans0 (read-string prompt "" nil nil))
16367 ;; org-ans0: from prompt
16368 ;; org-ans1: from mouse click
16369 ;; org-ans2: from calendar motion
16370 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16371 (use-local-map old-map))))))
16372 (t ; Naked prompt only
16373 (setq ans (read-string prompt "" nil timestr))))
16374 (org-detach-overlay org-date-ovl)
16376 (when (string-match
16377 "\\`[ \t]*\\([-+]\\)?\\([-+][0-9]+\\)\\([dwmy]?\\)\\([ \t\n]\\|$\\)"
16378 org-ans0)
16379 (setq deltan (string-to-number (match-string 2 ans))
16380 deltaw (match-string 3 ans)
16381 deltarel (match-end 1)))
16383 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16384 (when (string-match
16385 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16386 (setq year (if (match-end 2)
16387 (string-to-number (match-string 2 ans))
16388 (string-to-number (format-time-string "%Y")))
16389 month (string-to-number (match-string 3 ans))
16390 day (string-to-number (match-string 4 ans)))
16391 (if (< year 100) (setq year (+ 2000 year)))
16392 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16393 t nil ans)))
16394 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16395 ;; If there is a time with am/pm, and *no* time without it, we convert
16396 ;; so that matching will be successful.
16397 (loop for i from 1 to 2 do ; twice, for end time as well
16398 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16399 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16400 (setq hour (string-to-number (match-string 1 ans))
16401 minute (if (match-end 3)
16402 (string-to-number (match-string 3 ans))
16404 pm (equal ?p
16405 (string-to-char (downcase (match-string 4 ans)))))
16406 (if (and (= hour 12) (not pm))
16407 (setq hour 0)
16408 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16409 (setq ans (replace-match (format "%02d:%02d" hour minute)
16410 t t ans))))
16412 ;; Check if a time range is given as a duration
16413 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16414 (setq hour (string-to-number (match-string 1 ans))
16415 h2 (+ hour (string-to-number (match-string 3 ans)))
16416 minute (string-to-number (match-string 2 ans))
16417 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16418 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16420 ;; Check if there is a time range
16421 (when (and (boundp 'org-end-time-was-given)
16422 (string-match org-plain-time-of-day-regexp ans)
16423 (match-end 8))
16424 (setq org-end-time-was-given (match-string 8 ans))
16425 (setq ans (concat (substring ans 0 (match-beginning 7))
16426 (substring ans (match-end 7)))))
16428 (setq tl (parse-time-string ans)
16429 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
16430 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
16431 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
16432 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
16433 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
16434 second (or (nth 0 tl) 0)
16435 wday (nth 6 tl))
16436 (when deltan
16437 (unless deltarel
16438 (let ((now (decode-time (current-time))))
16439 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16440 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16441 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16442 ((equal deltaw "m") (setq month (+ month deltan)))
16443 ((equal deltaw "y") (setq year (+ year deltan)))))
16444 (when (and wday (not (nth 3 tl)))
16445 ;; Weekday was given, but no day, so pick that day in the week
16446 ;; on or after the derived date.
16447 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16448 (unless (equal wday wday1)
16449 (setq day (+ day (% (- wday wday1 -7) 7)))))
16450 (if (and (boundp 'org-time-was-given)
16451 (nth 2 tl))
16452 (setq org-time-was-given t))
16453 (if (< year 100) (setq year (+ 2000 year)))
16454 (if to-time
16455 (encode-time second minute hour day month year)
16456 (if (or (nth 1 tl) (nth 2 tl))
16457 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
16458 (format "%04d-%02d-%02d" year month day)))))
16460 (defun org-eval-in-calendar (form &optional keepdate)
16461 "Eval FORM in the calendar window and return to current window.
16462 Also, store the cursor date in variable org-ans2."
16463 (let ((sw (selected-window)))
16464 (select-window (get-buffer-window "*Calendar*"))
16465 (eval form)
16466 (when (and (not keepdate) (calendar-cursor-to-date))
16467 (let* ((date (calendar-cursor-to-date))
16468 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16469 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16470 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16471 (select-window sw)
16472 ;; Update the prompt to show new default date
16473 (save-excursion
16474 (goto-char (point-min))
16475 (when (and org-ans2
16476 (re-search-forward "\\[[-0-9]+\\]" nil t)
16477 (get-text-property (match-end 0) 'field))
16478 (let ((inhibit-read-only t))
16479 (replace-match (concat "[" org-ans2 "]") t t)
16480 (add-text-properties (point-min) (1+ (match-end 0))
16481 (text-properties-at (1+ (point-min)))))))))
16483 (defun org-calendar-select ()
16484 "Return to `org-read-date' with the date currently selected.
16485 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16486 (interactive)
16487 (when (calendar-cursor-to-date)
16488 (let* ((date (calendar-cursor-to-date))
16489 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16490 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16491 (if (active-minibuffer-window) (exit-minibuffer))))
16493 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16494 "Insert a date stamp for the date given by the internal TIME.
16495 WITH-HM means, use the stamp format that includes the time of the day.
16496 INACTIVE means use square brackets instead of angular ones, so that the
16497 stamp will not contribute to the agenda.
16498 PRE and POST are optional strings to be inserted before and after the
16499 stamp.
16500 The command returns the inserted time stamp."
16501 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16502 stamp)
16503 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16504 (insert-before-markers (or pre ""))
16505 (insert-before-markers (setq stamp (format-time-string fmt time)))
16506 (when (listp extra)
16507 (setq extra (car extra))
16508 (if (and (stringp extra)
16509 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16510 (setq extra (format "-%02d:%02d"
16511 (string-to-number (match-string 1 extra))
16512 (string-to-number (match-string 2 extra))))
16513 (setq extra nil)))
16514 (when extra
16515 (backward-char 1)
16516 (insert-before-markers extra)
16517 (forward-char 1))
16518 (insert-before-markers (or post ""))
16519 stamp))
16521 (defun org-toggle-time-stamp-overlays ()
16522 "Toggle the use of custom time stamp formats."
16523 (interactive)
16524 (setq org-display-custom-times (not org-display-custom-times))
16525 (unless org-display-custom-times
16526 (let ((p (point-min)) (bmp (buffer-modified-p)))
16527 (while (setq p (next-single-property-change p 'display))
16528 (if (and (get-text-property p 'display)
16529 (eq (get-text-property p 'face) 'org-date))
16530 (remove-text-properties
16531 p (setq p (next-single-property-change p 'display))
16532 '(display t))))
16533 (set-buffer-modified-p bmp)))
16534 (if (featurep 'xemacs)
16535 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16536 (org-restart-font-lock)
16537 (setq org-table-may-need-update t)
16538 (if org-display-custom-times
16539 (message "Time stamps are overlayed with custom format")
16540 (message "Time stamp overlays removed")))
16542 (defun org-display-custom-time (beg end)
16543 "Overlay modified time stamp format over timestamp between BED and END."
16544 (let* ((ts (buffer-substring beg end))
16545 t1 w1 with-hm tf time str w2 (off 0))
16546 (save-match-data
16547 (setq t1 (org-parse-time-string ts t))
16548 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16549 (setq off (- (match-end 0) (match-beginning 0)))))
16550 (setq end (- end off))
16551 (setq w1 (- end beg)
16552 with-hm (and (nth 1 t1) (nth 2 t1))
16553 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16554 time (org-fix-decoded-time t1)
16555 str (org-add-props
16556 (format-time-string
16557 (substring tf 1 -1) (apply 'encode-time time))
16558 nil 'mouse-face 'highlight)
16559 w2 (length str))
16560 (if (not (= w2 w1))
16561 (add-text-properties (1+ beg) (+ 2 beg)
16562 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16563 (if (featurep 'xemacs)
16564 (progn
16565 (put-text-property beg end 'invisible t)
16566 (put-text-property beg end 'end-glyph (make-glyph str)))
16567 (put-text-property beg end 'display str))))
16569 (defun org-translate-time (string)
16570 "Translate all timestamps in STRING to custom format.
16571 But do this only if the variable `org-display-custom-times' is set."
16572 (when org-display-custom-times
16573 (save-match-data
16574 (let* ((start 0)
16575 (re org-ts-regexp-both)
16576 t1 with-hm inactive tf time str beg end)
16577 (while (setq start (string-match re string start))
16578 (setq beg (match-beginning 0)
16579 end (match-end 0)
16580 t1 (save-match-data
16581 (org-parse-time-string (substring string beg end) t))
16582 with-hm (and (nth 1 t1) (nth 2 t1))
16583 inactive (equal (substring string beg (1+ beg)) "[")
16584 tf (funcall (if with-hm 'cdr 'car)
16585 org-time-stamp-custom-formats)
16586 time (org-fix-decoded-time t1)
16587 str (format-time-string
16588 (concat
16589 (if inactive "[" "<") (substring tf 1 -1)
16590 (if inactive "]" ">"))
16591 (apply 'encode-time time))
16592 string (replace-match str t t string)
16593 start (+ start (length str)))))))
16594 string)
16596 (defun org-fix-decoded-time (time)
16597 "Set 0 instead of nil for the first 6 elements of time.
16598 Don't touch the rest."
16599 (let ((n 0))
16600 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16602 (defun org-days-to-time (timestamp-string)
16603 "Difference between TIMESTAMP-STRING and now in days."
16604 (- (time-to-days (org-time-string-to-time timestamp-string))
16605 (time-to-days (current-time))))
16607 (defun org-deadline-close (timestamp-string &optional ndays)
16608 "Is the time in TIMESTAMP-STRING close to the current date?"
16609 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16610 (and (< (org-days-to-time timestamp-string) ndays)
16611 (not (org-entry-is-done-p))))
16613 (defun org-get-wdays (ts)
16614 "Get the deadline lead time appropriate for timestring TS."
16615 (cond
16616 ((<= org-deadline-warning-days 0)
16617 ;; 0 or negative, enforce this value no matter what
16618 (- org-deadline-warning-days))
16619 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16620 ;; lead time is specified.
16621 (floor (* (string-to-number (match-string 1 ts))
16622 (cdr (assoc (match-string 2 ts)
16623 '(("d" . 1) ("w" . 7)
16624 ("m" . 30.4) ("y" . 365.25)))))))
16625 ;; go for the default.
16626 (t org-deadline-warning-days)))
16628 (defun org-calendar-select-mouse (ev)
16629 "Return to `org-read-date' with the date currently selected.
16630 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16631 (interactive "e")
16632 (mouse-set-point ev)
16633 (when (calendar-cursor-to-date)
16634 (let* ((date (calendar-cursor-to-date))
16635 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16636 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16637 (if (active-minibuffer-window) (exit-minibuffer))))
16639 (defun org-check-deadlines (ndays)
16640 "Check if there are any deadlines due or past due.
16641 A deadline is considered due if it happens within `org-deadline-warning-days'
16642 days from today's date. If the deadline appears in an entry marked DONE,
16643 it is not shown. The prefix arg NDAYS can be used to test that many
16644 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16645 (interactive "P")
16646 (let* ((org-warn-days
16647 (cond
16648 ((equal ndays '(4)) 100000)
16649 (ndays (prefix-numeric-value ndays))
16650 (t (abs org-deadline-warning-days))))
16651 (case-fold-search nil)
16652 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16653 (callback
16654 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16656 (message "%d deadlines past-due or due within %d days"
16657 (org-occur regexp nil callback)
16658 org-warn-days)))
16660 (defun org-evaluate-time-range (&optional to-buffer)
16661 "Evaluate a time range by computing the difference between start and end.
16662 Normally the result is just printed in the echo area, but with prefix arg
16663 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16664 If the time range is actually in a table, the result is inserted into the
16665 next column.
16666 For time difference computation, a year is assumed to be exactly 365
16667 days in order to avoid rounding problems."
16668 (interactive "P")
16670 (org-clock-update-time-maybe)
16671 (save-excursion
16672 (unless (org-at-date-range-p t)
16673 (goto-char (point-at-bol))
16674 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16675 (if (not (org-at-date-range-p t))
16676 (error "Not at a time-stamp range, and none found in current line")))
16677 (let* ((ts1 (match-string 1))
16678 (ts2 (match-string 2))
16679 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16680 (match-end (match-end 0))
16681 (time1 (org-time-string-to-time ts1))
16682 (time2 (org-time-string-to-time ts2))
16683 (t1 (time-to-seconds time1))
16684 (t2 (time-to-seconds time2))
16685 (diff (abs (- t2 t1)))
16686 (negative (< (- t2 t1) 0))
16687 ;; (ys (floor (* 365 24 60 60)))
16688 (ds (* 24 60 60))
16689 (hs (* 60 60))
16690 (fy "%dy %dd %02d:%02d")
16691 (fy1 "%dy %dd")
16692 (fd "%dd %02d:%02d")
16693 (fd1 "%dd")
16694 (fh "%02d:%02d")
16695 y d h m align)
16696 (if havetime
16697 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16699 d (floor (/ diff ds)) diff (mod diff ds)
16700 h (floor (/ diff hs)) diff (mod diff hs)
16701 m (floor (/ diff 60)))
16702 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16704 d (floor (+ (/ diff ds) 0.5))
16705 h 0 m 0))
16706 (if (not to-buffer)
16707 (message (org-make-tdiff-string y d h m))
16708 (when (org-at-table-p)
16709 (goto-char match-end)
16710 (setq align t)
16711 (and (looking-at " *|") (goto-char (match-end 0))))
16712 (if (looking-at
16713 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16714 (replace-match ""))
16715 (if negative (insert " -"))
16716 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16717 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16718 (insert " " (format fh h m))))
16719 (if align (org-table-align))
16720 (message "Time difference inserted")))))
16722 (defun org-make-tdiff-string (y d h m)
16723 (let ((fmt "")
16724 (l nil))
16725 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16726 l (push y l)))
16727 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16728 l (push d l)))
16729 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16730 l (push h l)))
16731 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16732 l (push m l)))
16733 (apply 'format fmt (nreverse l))))
16735 (defun org-time-string-to-time (s)
16736 (apply 'encode-time (org-parse-time-string s)))
16738 (defun org-time-string-to-absolute (s &optional daynr)
16739 "Convert a time stamp to an absolute day number.
16740 If there is a specifyer for a cyclic time stamp, get the closest date to
16741 DAYNR."
16742 (cond
16743 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16744 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16745 daynr
16746 (+ daynr 1000)))
16747 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16748 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16749 (time-to-days (current-time))) (match-string 0 s)))
16750 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16752 (defun org-time-from-absolute (d)
16753 "Return the time corresponding to date D.
16754 D may be an absolute day number, or a calendar-type list (month day year)."
16755 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16756 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16758 (defun org-calendar-holiday ()
16759 "List of holidays, for Diary display in Org-mode."
16760 (let ((hl (check-calendar-holidays date)))
16761 (if hl (mapconcat 'identity hl "; "))))
16763 (defun org-diary-sexp-entry (sexp entry date)
16764 "Process a SEXP diary ENTRY for DATE."
16765 (require 'diary-lib)
16766 (let ((result (if calendar-debug-sexp
16767 (let ((stack-trace-on-error t))
16768 (eval (car (read-from-string sexp))))
16769 (condition-case nil
16770 (eval (car (read-from-string sexp)))
16771 (error
16772 (beep)
16773 (message "Bad sexp at line %d in %s: %s"
16774 (org-current-line)
16775 (buffer-file-name) sexp)
16776 (sleep-for 2))))))
16777 (cond ((stringp result) result)
16778 ((and (consp result)
16779 (stringp (cdr result))) (cdr result))
16780 (result entry)
16781 (t nil))))
16783 (defun org-diary-to-ical-string (frombuf)
16784 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16785 This uses the icalendar.el library."
16786 (let* ((tmpdir (if (featurep 'xemacs)
16787 (temp-directory)
16788 temporary-file-directory))
16789 (tmpfile (make-temp-name
16790 (expand-file-name "orgics" tmpdir)))
16791 buf rtn b e)
16792 (save-excursion
16793 (set-buffer frombuf)
16794 (icalendar-export-region (point-min) (point-max) tmpfile)
16795 (setq buf (find-buffer-visiting tmpfile))
16796 (set-buffer buf)
16797 (goto-char (point-min))
16798 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16799 (setq b (match-beginning 0)))
16800 (goto-char (point-max))
16801 (if (re-search-backward "^END:VEVENT" nil t)
16802 (setq e (match-end 0)))
16803 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16804 (kill-buffer buf)
16805 (kill-buffer frombuf)
16806 (delete-file tmpfile)
16807 rtn))
16809 (defun org-closest-date (start current change)
16810 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16811 ;; Make the proper lists from the dates
16812 (catch 'exit
16813 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16814 dn dw sday cday n1 n2
16815 d m y y1 y2 date1 date2 nmonths nm ny m2)
16817 (setq start (org-date-to-gregorian start)
16818 current (org-date-to-gregorian
16819 (if org-agenda-repeating-timestamp-show-all
16820 current
16821 (time-to-days (current-time))))
16822 sday (calendar-absolute-from-gregorian start)
16823 cday (calendar-absolute-from-gregorian current))
16825 (if (<= cday sday) (throw 'exit sday))
16827 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16828 (setq dn (string-to-number (match-string 1 change))
16829 dw (cdr (assoc (match-string 2 change) a1)))
16830 (error "Invalid change specifyer: %s" change))
16831 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16832 (cond
16833 ((eq dw 'day)
16834 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16835 n2 (+ n1 dn)))
16836 ((eq dw 'year)
16837 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16838 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16839 (setq date1 (list m d y1)
16840 n1 (calendar-absolute-from-gregorian date1)
16841 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16842 n2 (calendar-absolute-from-gregorian date2)))
16843 ((eq dw 'month)
16844 ;; approx number of month between the tow dates
16845 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16846 ;; How often does dn fit in there?
16847 (setq d (nth 1 start) m (car start) y (nth 2 start)
16848 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16849 m (+ m nm)
16850 ny (floor (/ m 12))
16851 y (+ y ny)
16852 m (- m (* ny 12)))
16853 (while (> m 12) (setq m (- m 12) y (1+ y)))
16854 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16855 (setq m2 (+ m dn) y2 y)
16856 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16857 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16858 (while (< n2 cday)
16859 (setq n1 n2 m m2 y y2)
16860 (setq m2 (+ m dn) y2 y)
16861 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16862 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16864 (if org-agenda-repeating-timestamp-show-all
16865 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16866 (if (= cday n1) n1 n2)))))
16868 (defun org-date-to-gregorian (date)
16869 "Turn any specification of DATE into a gregorian date for the calendar."
16870 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16871 ((and (listp date) (= (length date) 3)) date)
16872 ((stringp date)
16873 (setq date (org-parse-time-string date))
16874 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16875 ((listp date)
16876 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16878 (defun org-parse-time-string (s &optional nodefault)
16879 "Parse the standard Org-mode time string.
16880 This should be a lot faster than the normal `parse-time-string'.
16881 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16882 hour and minute fields will be nil if not given."
16883 (if (string-match org-ts-regexp0 s)
16884 (list 0
16885 (if (or (match-beginning 8) (not nodefault))
16886 (string-to-number (or (match-string 8 s) "0")))
16887 (if (or (match-beginning 7) (not nodefault))
16888 (string-to-number (or (match-string 7 s) "0")))
16889 (string-to-number (match-string 4 s))
16890 (string-to-number (match-string 3 s))
16891 (string-to-number (match-string 2 s))
16892 nil nil nil)
16893 (make-list 9 0)))
16895 (defun org-timestamp-up (&optional arg)
16896 "Increase the date item at the cursor by one.
16897 If the cursor is on the year, change the year. If it is on the month or
16898 the day, change that.
16899 With prefix ARG, change by that many units."
16900 (interactive "p")
16901 (org-timestamp-change (prefix-numeric-value arg)))
16903 (defun org-timestamp-down (&optional arg)
16904 "Decrease the date item at the cursor by one.
16905 If the cursor is on the year, change the year. If it is on the month or
16906 the day, change that.
16907 With prefix ARG, change by that many units."
16908 (interactive "p")
16909 (org-timestamp-change (- (prefix-numeric-value arg))))
16911 (defun org-timestamp-up-day (&optional arg)
16912 "Increase the date in the time stamp by one day.
16913 With prefix ARG, change that many days."
16914 (interactive "p")
16915 (if (and (not (org-at-timestamp-p t))
16916 (org-on-heading-p))
16917 (org-todo 'up)
16918 (org-timestamp-change (prefix-numeric-value arg) 'day)))
16920 (defun org-timestamp-down-day (&optional arg)
16921 "Decrease the date in the time stamp by one day.
16922 With prefix ARG, change that many days."
16923 (interactive "p")
16924 (if (and (not (org-at-timestamp-p t))
16925 (org-on-heading-p))
16926 (org-todo 'down)
16927 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
16929 (defsubst org-pos-in-match-range (pos n)
16930 (and (match-beginning n)
16931 (<= (match-beginning n) pos)
16932 (>= (match-end n) pos)))
16934 (defun org-at-timestamp-p (&optional inactive-ok)
16935 "Determine if the cursor is in or at a timestamp."
16936 (interactive)
16937 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
16938 (pos (point))
16939 (ans (or (looking-at tsr)
16940 (save-excursion
16941 (skip-chars-backward "^[<\n\r\t")
16942 (if (> (point) (point-min)) (backward-char 1))
16943 (and (looking-at tsr)
16944 (> (- (match-end 0) pos) -1))))))
16945 (and ans
16946 (boundp 'org-ts-what)
16947 (setq org-ts-what
16948 (cond
16949 ((= pos (match-beginning 0)) 'bracket)
16950 ((= pos (1- (match-end 0))) 'bracket)
16951 ((org-pos-in-match-range pos 2) 'year)
16952 ((org-pos-in-match-range pos 3) 'month)
16953 ((org-pos-in-match-range pos 7) 'hour)
16954 ((org-pos-in-match-range pos 8) 'minute)
16955 ((or (org-pos-in-match-range pos 4)
16956 (org-pos-in-match-range pos 5)) 'day)
16957 ((and (> pos (or (match-end 8) (match-end 5)))
16958 (< pos (match-end 0)))
16959 (- pos (or (match-end 8) (match-end 5))))
16960 (t 'day))))
16961 ans))
16963 (defun org-toggle-timestamp-type ()
16965 (interactive)
16966 (when (org-at-timestamp-p t)
16967 (save-excursion
16968 (goto-char (match-beginning 0))
16969 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
16970 (goto-char (1- (match-end 0)))
16971 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
16972 (message "Timestamp is now %sactive"
16973 (if (equal (char-before) ?>) "in" ""))))
16975 (defun org-timestamp-change (n &optional what)
16976 "Change the date in the time stamp at point.
16977 The date will be changed by N times WHAT. WHAT can be `day', `month',
16978 `year', `minute', `second'. If WHAT is not given, the cursor position
16979 in the timestamp determines what will be changed."
16980 (let ((pos (point))
16981 with-hm inactive
16982 org-ts-what
16983 extra
16984 ts time time0)
16985 (if (not (org-at-timestamp-p t))
16986 (error "Not at a timestamp"))
16987 (if (and (not what) (eq org-ts-what 'bracket))
16988 (org-toggle-timestamp-type)
16989 (if (and (not what) (not (eq org-ts-what 'day))
16990 org-display-custom-times
16991 (get-text-property (point) 'display)
16992 (not (get-text-property (1- (point)) 'display)))
16993 (setq org-ts-what 'day))
16994 (setq org-ts-what (or what org-ts-what)
16995 inactive (= (char-after (match-beginning 0)) ?\[)
16996 ts (match-string 0))
16997 (replace-match "")
16998 (if (string-match
16999 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17001 (setq extra (match-string 1 ts)))
17002 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17003 (setq with-hm t))
17004 (setq time0 (org-parse-time-string ts))
17005 (setq time
17006 (encode-time (or (car time0) 0)
17007 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17008 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17009 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17010 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17011 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17012 (nthcdr 6 time0)))
17013 (when (integerp org-ts-what)
17014 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17015 (if (eq what 'calendar)
17016 (let ((cal-date (org-get-date-from-calendar)))
17017 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17018 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17019 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17020 (setcar time0 (or (car time0) 0))
17021 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17022 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17023 (setq time (apply 'encode-time time0))))
17024 (setq org-last-changed-timestamp
17025 (org-insert-time-stamp time with-hm inactive nil nil extra))
17026 (org-clock-update-time-maybe)
17027 (goto-char pos)
17028 ;; Try to recenter the calendar window, if any
17029 (if (and org-calendar-follow-timestamp-change
17030 (get-buffer-window "*Calendar*" t)
17031 (memq org-ts-what '(day month year)))
17032 (org-recenter-calendar (time-to-days time))))))
17034 ;; FIXME: does not yet work for lead times
17035 (defun org-modify-ts-extra (s pos n)
17036 "Change the different parts of the lead-time and repeat fields in timestamp."
17037 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17038 ng h m new)
17039 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17040 (cond
17041 ((or (org-pos-in-match-range pos 2)
17042 (org-pos-in-match-range pos 3))
17043 (setq m (string-to-number (match-string 3 s))
17044 h (string-to-number (match-string 2 s)))
17045 (if (org-pos-in-match-range pos 2)
17046 (setq h (+ h n))
17047 (setq m (+ m n)))
17048 (if (< m 0) (setq m (+ m 60) h (1- h)))
17049 (if (> m 59) (setq m (- m 60) h (1+ h)))
17050 (setq h (min 24 (max 0 h)))
17051 (setq ng 1 new (format "-%02d:%02d" h m)))
17052 ((org-pos-in-match-range pos 6)
17053 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17054 ((org-pos-in-match-range pos 5)
17055 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17057 (when ng
17058 (setq s (concat
17059 (substring s 0 (match-beginning ng))
17061 (substring s (match-end ng))))))
17064 (defun org-recenter-calendar (date)
17065 "If the calendar is visible, recenter it to DATE."
17066 (let* ((win (selected-window))
17067 (cwin (get-buffer-window "*Calendar*" t))
17068 (calendar-move-hook nil))
17069 (when cwin
17070 (select-window cwin)
17071 (calendar-goto-date (if (listp date) date
17072 (calendar-gregorian-from-absolute date)))
17073 (select-window win))))
17075 (defun org-goto-calendar (&optional arg)
17076 "Go to the Emacs calendar at the current date.
17077 If there is a time stamp in the current line, go to that date.
17078 A prefix ARG can be used to force the current date."
17079 (interactive "P")
17080 (let ((tsr org-ts-regexp) diff
17081 (calendar-move-hook nil)
17082 (view-calendar-holidays-initially nil)
17083 (view-diary-entries-initially nil))
17084 (if (or (org-at-timestamp-p)
17085 (save-excursion
17086 (beginning-of-line 1)
17087 (looking-at (concat ".*" tsr))))
17088 (let ((d1 (time-to-days (current-time)))
17089 (d2 (time-to-days
17090 (org-time-string-to-time (match-string 1)))))
17091 (setq diff (- d2 d1))))
17092 (calendar)
17093 (calendar-goto-today)
17094 (if (and diff (not arg)) (calendar-forward-day diff))))
17096 (defun org-get-date-from-calendar ()
17097 "Return a list (month day year) of date at point in calendar."
17098 (with-current-buffer "*Calendar*"
17099 (save-match-data
17100 (calendar-cursor-to-date))))
17102 (defun org-date-from-calendar ()
17103 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17104 If there is already a time stamp at the cursor position, update it."
17105 (interactive)
17106 (if (org-at-timestamp-p t)
17107 (org-timestamp-change 0 'calendar)
17108 (let ((cal-date (org-get-date-from-calendar)))
17109 (org-insert-time-stamp
17110 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17112 ;; Make appt aware of appointments from the agenda
17113 ;;;###autoload
17114 (defun org-agenda-to-appt (&optional filter)
17115 "Activate appointments found in `org-agenda-files'.
17116 When prefixed, prompt for a regular expression and use it as a
17117 filter: only add entries if they match this regular expression.
17119 FILTER can be a string. In this case, use this string as a
17120 regular expression to filter results.
17122 FILTER can also be an alist, with the car of each cell being
17123 either 'headline or 'category. For example:
17125 '((headline \"IMPORTANT\")
17126 (category \"Work\"))
17128 will only add headlines containing IMPORTANT or headlines
17129 belonging to the category \"Work\"."
17130 (interactive "P")
17131 (require 'calendar)
17132 (if (equal filter '(4))
17133 (setq filter (read-from-minibuffer "Regexp filter: ")))
17134 (let* ((cnt 0) ; count added events
17135 (today (org-date-to-gregorian
17136 (time-to-days (current-time))))
17137 (files (org-agenda-files)) entries file)
17138 ;; Get all entries which may contain an appt
17139 (while (setq file (pop files))
17140 (setq entries
17141 (append entries
17142 (org-agenda-get-day-entries
17143 file today
17144 :timestamp :scheduled :deadline))))
17145 (setq entries (delq nil entries))
17146 ;; Map thru entries and find if they pass thru the filter
17147 (mapc
17148 (lambda(x)
17149 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17150 (cat (get-text-property 1 'org-category x))
17151 (tod (get-text-property 1 'time-of-day x))
17152 (ok (or (null filter)
17153 (and (stringp filter) (string-match filter evt))
17154 (and (listp filter)
17155 (or (string-match
17156 (cadr (assoc 'category filter)) cat)
17157 (string-match
17158 (cadr (assoc 'headline filter)) evt))))))
17159 ;; FIXME Shall we remove text-properties for the appt text?
17160 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17161 (when (and ok tod)
17162 (setq tod (number-to-string tod)
17163 tod (when (string-match
17164 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17165 (concat (match-string 1 tod) ":"
17166 (match-string 2 tod))))
17167 (appt-add tod evt)
17168 (setq cnt (1+ cnt))))) entries)
17169 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17171 ;;; The clock for measuring work time.
17173 (defvar org-mode-line-string "")
17174 (put 'org-mode-line-string 'risky-local-variable t)
17176 (defvar org-mode-line-timer nil)
17177 (defvar org-clock-heading "")
17178 (defvar org-clock-start-time "")
17180 (defun org-update-mode-line ()
17181 (let* ((delta (- (time-to-seconds (current-time))
17182 (time-to-seconds org-clock-start-time)))
17183 (h (floor delta 3600))
17184 (m (floor (- delta (* 3600 h)) 60)))
17185 (setq org-mode-line-string
17186 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17187 'help-echo "Org-mode clock is running"))
17188 (force-mode-line-update)))
17190 (defvar org-clock-marker (make-marker)
17191 "Marker recording the last clock-in.")
17192 (defvar org-clock-mode-line-entry nil
17193 "Information for the modeline about the running clock.")
17195 (defun org-clock-in ()
17196 "Start the clock on the current item.
17197 If necessary, clock-out of the currently active clock."
17198 (interactive)
17199 (org-clock-out t)
17200 (let (ts)
17201 (save-excursion
17202 (org-back-to-heading t)
17203 (if (looking-at org-todo-line-regexp)
17204 (setq org-clock-heading (match-string 3))
17205 (setq org-clock-heading "???"))
17206 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17207 (org-clock-find-position)
17209 (insert "\n") (backward-char 1)
17210 (indent-relative)
17211 (insert org-clock-string " ")
17212 (setq org-clock-start-time (current-time))
17213 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17214 (move-marker org-clock-marker (point) (buffer-base-buffer))
17215 (or global-mode-string (setq global-mode-string '("")))
17216 (or (memq 'org-mode-line-string global-mode-string)
17217 (setq global-mode-string
17218 (append global-mode-string '(org-mode-line-string))))
17219 (org-update-mode-line)
17220 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17221 (message "Clock started at %s" ts))))
17223 (defun org-clock-find-position ()
17224 "Find the location where the next clock line should be inserted."
17225 (org-back-to-heading t)
17226 (catch 'exit
17227 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17228 (re (concat "^[ \t]*" org-clock-string))
17229 (cnt 0)
17230 first last)
17231 (goto-char beg)
17232 (when (eobp) (newline) (setq end (max (point) end)))
17233 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17234 ;; we seem to have a CLOCK drawer, so go there.
17235 (beginning-of-line 2)
17236 (throw 'exit t))
17237 ;; Lets count the CLOCK lines
17238 (goto-char beg)
17239 (while (re-search-forward re end t)
17240 (setq first (or first (match-beginning 0))
17241 last (match-beginning 0)
17242 cnt (1+ cnt)))
17243 (when (and (integerp org-clock-into-drawer)
17244 (>= (1+ cnt) org-clock-into-drawer))
17245 ;; Wrap current entries into a new drawer
17246 (goto-char last)
17247 (beginning-of-line 2)
17248 (if (org-at-item-p) (org-end-of-item))
17249 (insert ":END:\n")
17250 (beginning-of-line 0)
17251 (org-indent-line-function)
17252 (goto-char first)
17253 (insert ":CLOCK:\n")
17254 (beginning-of-line 0)
17255 (org-indent-line-function)
17256 (org-flag-drawer t)
17257 (beginning-of-line 2)
17258 (throw 'exit nil))
17260 (goto-char beg)
17261 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17262 (not (equal (match-string 1) org-clock-string)))
17263 ;; Planning info, skip to after it
17264 (beginning-of-line 2)
17265 (or (bolp) (newline)))
17266 (when (eq t org-clock-into-drawer)
17267 (insert ":CLOCK:\n:END:\n")
17268 (beginning-of-line -1)
17269 (org-indent-line-function)
17270 (org-flag-drawer t)
17271 (beginning-of-line 2)
17272 (org-indent-line-function)))))
17274 (defun org-clock-out (&optional fail-quietly)
17275 "Stop the currently running clock.
17276 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17277 (interactive)
17278 (catch 'exit
17279 (if (not (marker-buffer org-clock-marker))
17280 (if fail-quietly (throw 'exit t) (error "No active clock")))
17281 (let (ts te s h m)
17282 (save-excursion
17283 (set-buffer (marker-buffer org-clock-marker))
17284 (goto-char org-clock-marker)
17285 (beginning-of-line 1)
17286 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17287 (equal (match-string 1) org-clock-string))
17288 (setq ts (match-string 2))
17289 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17290 (goto-char (match-end 0))
17291 (delete-region (point) (point-at-eol))
17292 (insert "--")
17293 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17294 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17295 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17296 h (floor (/ s 3600))
17297 s (- s (* 3600 h))
17298 m (floor (/ s 60))
17299 s (- s (* 60 s)))
17300 (insert " => " (format "%2d:%02d" h m))
17301 (move-marker org-clock-marker nil)
17302 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17303 (org-log-done (org-parse-local-options logging 'org-log-done))
17304 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17305 (org-add-log-maybe 'clock-out))
17306 (when org-mode-line-timer
17307 (cancel-timer org-mode-line-timer)
17308 (setq org-mode-line-timer nil))
17309 (setq global-mode-string
17310 (delq 'org-mode-line-string global-mode-string))
17311 (force-mode-line-update)
17312 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17314 (defun org-clock-cancel ()
17315 "Cancel the running clock be removing the start timestamp."
17316 (interactive)
17317 (if (not (marker-buffer org-clock-marker))
17318 (error "No active clock"))
17319 (save-excursion
17320 (set-buffer (marker-buffer org-clock-marker))
17321 (goto-char org-clock-marker)
17322 (delete-region (1- (point-at-bol)) (point-at-eol)))
17323 (message "Clock canceled"))
17325 (defun org-clock-goto (&optional delete-windows)
17326 "Go to the currently clocked-in entry."
17327 (interactive "P")
17328 (if (not (marker-buffer org-clock-marker))
17329 (error "No active clock"))
17330 (switch-to-buffer-other-window
17331 (marker-buffer org-clock-marker))
17332 (if delete-windows (delete-other-windows))
17333 (goto-char org-clock-marker)
17334 (org-show-entry)
17335 (org-back-to-heading)
17336 (recenter))
17338 (defvar org-clock-file-total-minutes nil
17339 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17340 (make-variable-buffer-local 'org-clock-file-total-minutes)
17342 (defun org-clock-sum (&optional tstart tend)
17343 "Sum the times for each subtree.
17344 Puts the resulting times in minutes as a text property on each headline."
17345 (interactive)
17346 (let* ((bmp (buffer-modified-p))
17347 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17348 org-clock-string
17349 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17350 (lmax 30)
17351 (ltimes (make-vector lmax 0))
17352 (t1 0)
17353 (level 0)
17354 ts te dt
17355 time)
17356 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17357 (save-excursion
17358 (goto-char (point-max))
17359 (while (re-search-backward re nil t)
17360 (cond
17361 ((match-end 2)
17362 ;; Two time stamps
17363 (setq ts (match-string 2)
17364 te (match-string 3)
17365 ts (time-to-seconds
17366 (apply 'encode-time (org-parse-time-string ts)))
17367 te (time-to-seconds
17368 (apply 'encode-time (org-parse-time-string te)))
17369 ts (if tstart (max ts tstart) ts)
17370 te (if tend (min te tend) te)
17371 dt (- te ts)
17372 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17373 ((match-end 4)
17374 ;; A naket time
17375 (setq t1 (+ t1 (string-to-number (match-string 5))
17376 (* 60 (string-to-number (match-string 4))))))
17377 (t ;; A headline
17378 (setq level (- (match-end 1) (match-beginning 1)))
17379 (when (or (> t1 0) (> (aref ltimes level) 0))
17380 (loop for l from 0 to level do
17381 (aset ltimes l (+ (aref ltimes l) t1)))
17382 (setq t1 0 time (aref ltimes level))
17383 (loop for l from level to (1- lmax) do
17384 (aset ltimes l 0))
17385 (goto-char (match-beginning 0))
17386 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17387 (setq org-clock-file-total-minutes (aref ltimes 0)))
17388 (set-buffer-modified-p bmp)))
17390 (defun org-clock-display (&optional total-only)
17391 "Show subtree times in the entire buffer.
17392 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17393 in the echo area."
17394 (interactive)
17395 (org-remove-clock-overlays)
17396 (let (time h m p)
17397 (org-clock-sum)
17398 (unless total-only
17399 (save-excursion
17400 (goto-char (point-min))
17401 (while (or (and (equal (setq p (point)) (point-min))
17402 (get-text-property p :org-clock-minutes))
17403 (setq p (next-single-property-change
17404 (point) :org-clock-minutes)))
17405 (goto-char p)
17406 (when (setq time (get-text-property p :org-clock-minutes))
17407 (org-put-clock-overlay time (funcall outline-level))))
17408 (setq h (/ org-clock-file-total-minutes 60)
17409 m (- org-clock-file-total-minutes (* 60 h)))
17410 ;; Arrange to remove the overlays upon next change.
17411 (when org-remove-highlights-with-change
17412 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17413 nil 'local))))
17414 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17416 (defvar org-clock-overlays nil)
17417 (make-variable-buffer-local 'org-clock-overlays)
17419 (defun org-put-clock-overlay (time &optional level)
17420 "Put an overlays on the current line, displaying TIME.
17421 If LEVEL is given, prefix time with a corresponding number of stars.
17422 This creates a new overlay and stores it in `org-clock-overlays', so that it
17423 will be easy to remove."
17424 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17425 (l (if level (org-get-legal-level level 0) 0))
17426 (off 0)
17427 ov tx)
17428 (move-to-column c)
17429 (unless (eolp) (skip-chars-backward "^ \t"))
17430 (skip-chars-backward " \t")
17431 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17432 tx (concat (buffer-substring (1- (point)) (point))
17433 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17434 (org-add-props (format "%s %2d:%02d%s"
17435 (make-string l ?*) h m
17436 (make-string (- 10 l) ?\ ))
17437 '(face secondary-selection))
17438 ""))
17439 (if (not (featurep 'xemacs))
17440 (org-overlay-put ov 'display tx)
17441 (org-overlay-put ov 'invisible t)
17442 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17443 (push ov org-clock-overlays)))
17445 (defun org-remove-clock-overlays (&optional beg end noremove)
17446 "Remove the occur highlights from the buffer.
17447 BEG and END are ignored. If NOREMOVE is nil, remove this function
17448 from the `before-change-functions' in the current buffer."
17449 (interactive)
17450 (unless org-inhibit-highlight-removal
17451 (mapc 'org-delete-overlay org-clock-overlays)
17452 (setq org-clock-overlays nil)
17453 (unless noremove
17454 (remove-hook 'before-change-functions
17455 'org-remove-clock-overlays 'local))))
17457 (defun org-clock-out-if-current ()
17458 "Clock out if the current entry contains the running clock.
17459 This is used to stop the clock after a TODO entry is marked DONE,
17460 and is only done if the variable `org-clock-out-when-done' is not nil."
17461 (when (and org-clock-out-when-done
17462 (member state org-done-keywords)
17463 (equal (marker-buffer org-clock-marker) (current-buffer))
17464 (< (point) org-clock-marker)
17465 (> (save-excursion (outline-next-heading) (point))
17466 org-clock-marker))
17467 ;; Clock out, but don't accept a logging message for this.
17468 (let ((org-log-done (if (and (listp org-log-done)
17469 (member 'clock-out org-log-done))
17470 '(done)
17471 org-log-done)))
17472 (org-clock-out))))
17474 (add-hook 'org-after-todo-state-change-hook
17475 'org-clock-out-if-current)
17477 (defun org-check-running-clock ()
17478 "Check if the current buffer contains the running clock.
17479 If yes, offer to stop it and to save the buffer with the changes."
17480 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17481 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17482 (buffer-name))))
17483 (org-clock-out)
17484 (when (y-or-n-p "Save changed buffer?")
17485 (save-buffer))))
17487 (defun org-clock-report (&optional arg)
17488 "Create a table containing a report about clocked time.
17489 If the cursor is inside an existing clocktable block, then the table
17490 will be updated. If not, a new clocktable will be inserted.
17491 When called with a prefix argument, move to the first clock table in the
17492 buffer and update it."
17493 (interactive "P")
17494 (org-remove-clock-overlays)
17495 (when arg (org-find-dblock "clocktable"))
17496 (if (org-in-clocktable-p)
17497 (goto-char (org-in-clocktable-p))
17498 (org-create-dblock (list :name "clocktable"
17499 :maxlevel 2 :scope 'file)))
17500 (org-update-dblock))
17502 (defun org-in-clocktable-p ()
17503 "Check if the cursor is in a clocktable."
17504 (let ((pos (point)) start)
17505 (save-excursion
17506 (end-of-line 1)
17507 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17508 (setq start (match-beginning 0))
17509 (re-search-forward "^#\\+END:.*" nil t)
17510 (>= (match-end 0) pos)
17511 start))))
17513 (defun org-clock-update-time-maybe ()
17514 "If this is a CLOCK line, update it and return t.
17515 Otherwise, return nil."
17516 (interactive)
17517 (save-excursion
17518 (beginning-of-line 1)
17519 (skip-chars-forward " \t")
17520 (when (looking-at org-clock-string)
17521 (let ((re (concat "[ \t]*" org-clock-string
17522 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
17523 "\\([ \t]*=>.*\\)?"))
17524 ts te h m s)
17525 (if (not (looking-at re))
17527 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
17528 (end-of-line 1)
17529 (setq ts (match-string 1)
17530 te (match-string 2))
17531 (setq s (- (time-to-seconds
17532 (apply 'encode-time (org-parse-time-string te)))
17533 (time-to-seconds
17534 (apply 'encode-time (org-parse-time-string ts))))
17535 h (floor (/ s 3600))
17536 s (- s (* 3600 h))
17537 m (floor (/ s 60))
17538 s (- s (* 60 s)))
17539 (insert " => " (format "%2d:%02d" h m))
17540 t)))))
17542 (defun org-clock-special-range (key &optional time as-strings)
17543 "Return two times bordering a special time range.
17544 Key is a symbol specifying the range and can be one of `today', `yesterday',
17545 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
17546 A week starts Monday 0:00 and ends Sunday 24:00.
17547 The range is determined relative to TIME. TIME defaults to the current time.
17548 The return value is a cons cell with two internal times like the ones
17549 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
17550 the returned times will be formatted strings."
17551 (let* ((tm (decode-time (or time (current-time))))
17552 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
17553 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
17554 (dow (nth 6 tm))
17555 s1 m1 h1 d1 month1 y1 diff ts te fm)
17556 (cond
17557 ((eq key 'today)
17558 (setq h 0 m 0 h1 24 m1 0))
17559 ((eq key 'yesterday)
17560 (setq d (1- d) h 0 m 0 h1 24 m1 0))
17561 ((eq key 'thisweek)
17562 (setq diff (if (= dow 0) 6 (1- dow))
17563 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17564 ((eq key 'lastweek)
17565 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
17566 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17567 ((eq key 'thismonth)
17568 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
17569 ((eq key 'lastmonth)
17570 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
17571 ((eq key 'thisyear)
17572 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
17573 ((eq key 'lastyear)
17574 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17575 (t (error "No such time block %s" key)))
17576 (setq ts (encode-time s m h d month y)
17577 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17578 (or d1 d) (or month1 month) (or y1 y)))
17579 (setq fm (cdr org-time-stamp-formats))
17580 (if as-strings
17581 (cons (format-time-string fm ts) (format-time-string fm te))
17582 (cons ts te))))
17584 (defun org-dblock-write:clocktable (params)
17585 "Write the standard clocktable."
17586 (let ((hlchars '((1 . "*") (2 . "/")))
17587 (emph nil)
17588 (ins (make-marker))
17589 (total-time nil)
17590 ipos time h m p level hlc hdl maxlevel
17591 ts te cc block beg end pos scope tbl tostring multifile)
17592 (setq scope (plist-get params :scope)
17593 tostring (plist-get params :tostring)
17594 multifile (plist-get params :multifile)
17595 maxlevel (or (plist-get params :maxlevel) 3)
17596 emph (plist-get params :emphasize)
17597 ts (plist-get params :tstart)
17598 te (plist-get params :tend)
17599 block (plist-get params :block))
17600 (when block
17601 (setq cc (org-clock-special-range block nil t)
17602 ts (car cc) te (cdr cc)))
17603 (if ts (setq ts (time-to-seconds
17604 (apply 'encode-time (org-parse-time-string ts)))))
17605 (if te (setq te (time-to-seconds
17606 (apply 'encode-time (org-parse-time-string te)))))
17607 (move-marker ins (point))
17608 (setq ipos (point))
17610 ;; Get the right scope
17611 (setq pos (point))
17612 (save-restriction
17613 (cond
17614 ((not scope))
17615 ((eq scope 'file) (widen))
17616 ((eq scope 'subtree) (org-narrow-to-subtree))
17617 ((eq scope 'tree)
17618 (while (org-up-heading-safe))
17619 (org-narrow-to-subtree))
17620 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17621 (symbol-name scope)))
17622 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17623 (catch 'exit
17624 (while (org-up-heading-safe)
17625 (looking-at outline-regexp)
17626 (if (<= (org-reduced-level (funcall outline-level)) level)
17627 (throw 'exit nil))))
17628 (org-narrow-to-subtree))
17629 ((or (listp scope) (eq scope 'agenda))
17630 (let* ((files (if (listp scope) scope (org-agenda-files)))
17631 (scope 'agenda)
17632 (p1 (copy-sequence params))
17633 file)
17634 (plist-put p1 :tostring t)
17635 (plist-put p1 :multifile t)
17636 (plist-put p1 :scope 'file)
17637 (org-prepare-agenda-buffers files)
17638 (while (setq file (pop files))
17639 (with-current-buffer (find-buffer-visiting file)
17640 (push (org-clocktable-add-file
17641 file (org-dblock-write:clocktable p1)) tbl)
17642 (setq total-time (+ (or total-time 0)
17643 org-clock-file-total-minutes)))))))
17644 (goto-char pos)
17646 (unless (eq scope 'agenda)
17647 (org-clock-sum ts te)
17648 (goto-char (point-min))
17649 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17650 (goto-char p)
17651 (when (setq time (get-text-property p :org-clock-minutes))
17652 (save-excursion
17653 (beginning-of-line 1)
17654 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17655 (setq level (org-reduced-level
17656 (- (match-end 1) (match-beginning 1))))
17657 (<= level maxlevel))
17658 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17659 hdl (match-string 2)
17660 h (/ time 60)
17661 m (- time (* 60 h)))
17662 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17663 (push (concat
17664 "| " (int-to-string level) "|" hlc hdl hlc " |"
17665 (make-string (1- level) ?|)
17666 hlc (format "%d:%02d" h m) hlc
17667 " |") tbl))))))
17668 (setq tbl (nreverse tbl))
17669 (if tostring
17670 (if tbl (mapconcat 'identity tbl "\n") nil)
17671 (goto-char ins)
17672 (insert-before-markers
17673 "Clock summary at ["
17674 (substring
17675 (format-time-string (cdr org-time-stamp-formats))
17676 1 -1)
17677 "]."
17678 (if block
17679 (format " Considered range is /%s/." block)
17681 "\n\n"
17682 (if (eq scope 'agenda) "|File" "")
17683 "|L|Headline|Time|\n")
17684 (setq total-time (or total-time org-clock-file-total-minutes)
17685 h (/ total-time 60)
17686 m (- total-time (* 60 h)))
17687 (insert-before-markers
17688 "|-\n|"
17689 (if (eq scope 'agenda) "|" "")
17690 "|"
17691 "*Total time*| "
17692 (format "*%d:%02d*" h m)
17693 "|\n|-\n")
17694 (setq tbl (delq nil tbl))
17695 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17696 (equal (substring (car tbl) 0 2) "|-"))
17697 (pop tbl))
17698 (insert-before-markers (mapconcat
17699 'identity (delq nil tbl)
17700 (if (eq scope 'agenda) "\n|-\n" "\n")))
17701 (backward-delete-char 1)
17702 (goto-char ipos)
17703 (skip-chars-forward "^|")
17704 (org-table-align)))))
17706 (defun org-clocktable-add-file (file table)
17707 (if table
17708 (let ((lines (org-split-string table "\n"))
17709 (ff (file-name-nondirectory file)))
17710 (mapconcat 'identity
17711 (mapcar (lambda (x)
17712 (if (string-match org-table-dataline-regexp x)
17713 (concat "|" ff x)
17715 lines)
17716 "\n"))))
17718 ;; FIXME: I don't think anybody uses this, ask David
17719 (defun org-collect-clock-time-entries ()
17720 "Return an internal list with clocking information.
17721 This list has one entry for each CLOCK interval.
17722 FIXME: describe the elements."
17723 (interactive)
17724 (let ((re (concat "^[ \t]*" org-clock-string
17725 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17726 rtn beg end next cont level title total closedp leafp
17727 clockpos titlepos h m donep)
17728 (save-excursion
17729 (org-clock-sum)
17730 (goto-char (point-min))
17731 (while (re-search-forward re nil t)
17732 (setq clockpos (match-beginning 0)
17733 beg (match-string 1) end (match-string 2)
17734 cont (match-end 0))
17735 (setq beg (apply 'encode-time (org-parse-time-string beg))
17736 end (apply 'encode-time (org-parse-time-string end)))
17737 (org-back-to-heading t)
17738 (setq donep (org-entry-is-done-p))
17739 (setq titlepos (point)
17740 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17741 h (/ total 60) m (- total (* 60 h))
17742 total (cons h m))
17743 (looking-at "\\(\\*+\\) +\\(.*\\)")
17744 (setq level (- (match-end 1) (match-beginning 1))
17745 title (org-match-string-no-properties 2))
17746 (save-excursion (outline-next-heading) (setq next (point)))
17747 (setq closedp (re-search-forward org-closed-time-regexp next t))
17748 (goto-char next)
17749 (setq leafp (and (looking-at "^\\*+ ")
17750 (<= (- (match-end 0) (point)) level)))
17751 (push (list beg end clockpos closedp donep
17752 total title titlepos level leafp)
17753 rtn)
17754 (goto-char cont)))
17755 (nreverse rtn)))
17757 ;;;; Agenda, and Diary Integration
17759 ;;; Define the Org-agenda-mode
17761 (defvar org-agenda-mode-map (make-sparse-keymap)
17762 "Keymap for `org-agenda-mode'.")
17764 (defvar org-agenda-menu) ; defined later in this file.
17765 (defvar org-agenda-follow-mode nil)
17766 (defvar org-agenda-show-log nil)
17767 (defvar org-agenda-redo-command nil)
17768 (defvar org-agenda-mode-hook nil)
17769 (defvar org-agenda-type nil)
17770 (defvar org-agenda-force-single-file nil)
17772 (defun org-agenda-mode ()
17773 "Mode for time-sorted view on action items in Org-mode files.
17775 The following commands are available:
17777 \\{org-agenda-mode-map}"
17778 (interactive)
17779 (kill-all-local-variables)
17780 (setq org-agenda-undo-list nil
17781 org-agenda-pending-undo-list nil)
17782 (setq major-mode 'org-agenda-mode)
17783 ;; Keep global-font-lock-mode from turning on font-lock-mode
17784 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17785 (setq mode-name "Org-Agenda")
17786 (use-local-map org-agenda-mode-map)
17787 (easy-menu-add org-agenda-menu)
17788 (if org-startup-truncated (setq truncate-lines t))
17789 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17790 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17791 ;; Make sure properties are removed when copying text
17792 (when (boundp 'buffer-substring-filters)
17793 (org-set-local 'buffer-substring-filters
17794 (cons (lambda (x)
17795 (set-text-properties 0 (length x) nil x) x)
17796 buffer-substring-filters)))
17797 (unless org-agenda-keep-modes
17798 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17799 org-agenda-show-log nil))
17800 (easy-menu-change
17801 '("Agenda") "Agenda Files"
17802 (append
17803 (list
17804 (vector
17805 (if (get 'org-agenda-files 'org-restrict)
17806 "Restricted to single file"
17807 "Edit File List")
17808 '(org-edit-agenda-file-list)
17809 (not (get 'org-agenda-files 'org-restrict)))
17810 "--")
17811 (mapcar 'org-file-menu-entry (org-agenda-files))))
17812 (org-agenda-set-mode-name)
17813 (apply
17814 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17815 (list 'org-agenda-mode-hook)))
17817 (substitute-key-definition 'undo 'org-agenda-undo
17818 org-agenda-mode-map global-map)
17819 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17820 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17821 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17822 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17823 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17824 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17825 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17826 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17827 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17828 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17829 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17830 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17831 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17832 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17833 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17834 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17835 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17836 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17837 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17838 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17839 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17840 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17841 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17842 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17843 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17844 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17845 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17846 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17847 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17849 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17850 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17851 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17852 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17853 (while l (org-defkey org-agenda-mode-map
17854 (int-to-string (pop l)) 'digit-argument)))
17856 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17857 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17858 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17859 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17860 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17861 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17862 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17863 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17864 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17865 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17866 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17867 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17868 (org-defkey org-agenda-mode-map "n" 'next-line)
17869 (org-defkey org-agenda-mode-map "p" 'previous-line)
17870 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17871 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17872 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17873 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17874 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17875 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17876 (eval-after-load "calendar"
17877 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17878 'org-calendar-goto-agenda))
17879 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17880 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17881 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17882 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17883 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17884 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17885 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17886 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17887 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17888 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17889 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17890 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17891 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17892 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17893 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17894 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17895 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17896 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17897 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17898 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17899 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17900 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17902 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17903 "Local keymap for agenda entries from Org-mode.")
17905 (org-defkey org-agenda-keymap
17906 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17907 (org-defkey org-agenda-keymap
17908 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17909 (when org-agenda-mouse-1-follows-link
17910 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17911 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17912 '("Agenda"
17913 ("Agenda Files")
17914 "--"
17915 ["Show" org-agenda-show t]
17916 ["Go To (other window)" org-agenda-goto t]
17917 ["Go To (this window)" org-agenda-switch-to t]
17918 ["Follow Mode" org-agenda-follow-mode
17919 :style toggle :selected org-agenda-follow-mode :active t]
17920 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
17921 "--"
17922 ["Cycle TODO" org-agenda-todo t]
17923 ["Archive subtree" org-agenda-archive t]
17924 ["Delete subtree" org-agenda-kill t]
17925 "--"
17926 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
17927 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
17928 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
17929 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
17930 "--"
17931 ("Tags and Properties"
17932 ["Show all Tags" org-agenda-show-tags t]
17933 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
17934 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
17935 "--"
17936 ["Column View" org-columns t])
17937 ("Date/Schedule"
17938 ["Schedule" org-agenda-schedule t]
17939 ["Set Deadline" org-agenda-deadline t]
17940 "--"
17941 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
17942 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
17943 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
17944 ("Clock"
17945 ["Clock in" org-agenda-clock-in t]
17946 ["Clock out" org-agenda-clock-out t]
17947 ["Clock cancel" org-agenda-clock-cancel t]
17948 ["Goto running clock" org-clock-goto t])
17949 ("Priority"
17950 ["Set Priority" org-agenda-priority t]
17951 ["Increase Priority" org-agenda-priority-up t]
17952 ["Decrease Priority" org-agenda-priority-down t]
17953 ["Show Priority" org-agenda-show-priority t])
17954 ("Calendar/Diary"
17955 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
17956 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
17957 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
17958 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
17959 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
17960 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
17961 "--"
17962 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
17963 "--"
17964 ("View"
17965 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
17966 :style radio :selected (equal org-agenda-ndays 1)]
17967 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
17968 :style radio :selected (equal org-agenda-ndays 7)]
17969 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
17970 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
17971 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
17972 :style radio :selected (member org-agenda-ndays '(365 366))]
17973 "--"
17974 ["Show Logbook entries" org-agenda-log-mode
17975 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
17976 ["Include Diary" org-agenda-toggle-diary
17977 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
17978 ["Use Time Grid" org-agenda-toggle-time-grid
17979 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
17980 ["Write view to file" org-write-agenda t]
17981 ["Rebuild buffer" org-agenda-redo t]
17982 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
17983 "--"
17984 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
17985 "--"
17986 ["Quit" org-agenda-quit t]
17987 ["Exit and Release Buffers" org-agenda-exit t]
17990 ;;; Agenda undo
17992 (defvar org-agenda-allow-remote-undo t
17993 "Non-nil means, allow remote undo from the agenda buffer.")
17994 (defvar org-agenda-undo-list nil
17995 "List of undoable operations in the agenda since last refresh.")
17996 (defvar org-agenda-undo-has-started-in nil
17997 "Buffers that have already seen `undo-start' in the current undo sequence.")
17998 (defvar org-agenda-pending-undo-list nil
17999 "In a series of undo commands, this is the list of remaning undo items.")
18001 (defmacro org-if-unprotected (&rest body)
18002 "Execute BODY if there is no `org-protected' text property at point."
18003 (declare (debug t))
18004 `(unless (get-text-property (point) 'org-protected)
18005 ,@body))
18007 (defmacro org-with-remote-undo (_buffer &rest _body)
18008 "Execute BODY while recording undo information in two buffers."
18009 (declare (indent 1) (debug t))
18010 `(let ((_cline (org-current-line))
18011 (_cmd this-command)
18012 (_buf1 (current-buffer))
18013 (_buf2 ,_buffer)
18014 (_undo1 buffer-undo-list)
18015 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18016 _c1 _c2)
18017 ,@_body
18018 (when org-agenda-allow-remote-undo
18019 (setq _c1 (org-verify-change-for-undo
18020 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18021 _c2 (org-verify-change-for-undo
18022 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18023 (when (or _c1 _c2)
18024 ;; make sure there are undo boundaries
18025 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18026 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18027 ;; remember which buffer to undo
18028 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18029 org-agenda-undo-list)))))
18031 (defun org-agenda-undo ()
18032 "Undo a remote editing step in the agenda.
18033 This undoes changes both in the agenda buffer and in the remote buffer
18034 that have been changed along."
18035 (interactive)
18036 (or org-agenda-allow-remote-undo
18037 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18038 (if (not (eq this-command last-command))
18039 (setq org-agenda-undo-has-started-in nil
18040 org-agenda-pending-undo-list org-agenda-undo-list))
18041 (if (not org-agenda-pending-undo-list)
18042 (error "No further undo information"))
18043 (let* ((entry (pop org-agenda-pending-undo-list))
18044 buf line cmd rembuf)
18045 (setq cmd (pop entry) line (pop entry))
18046 (setq rembuf (nth 2 entry))
18047 (org-with-remote-undo rembuf
18048 (while (bufferp (setq buf (pop entry)))
18049 (if (pop entry)
18050 (with-current-buffer buf
18051 (let ((last-undo-buffer buf)
18052 (inhibit-read-only t))
18053 (unless (memq buf org-agenda-undo-has-started-in)
18054 (push buf org-agenda-undo-has-started-in)
18055 (make-local-variable 'pending-undo-list)
18056 (undo-start))
18057 (while (and pending-undo-list
18058 (listp pending-undo-list)
18059 (not (car pending-undo-list)))
18060 (pop pending-undo-list))
18061 (undo-more 1))))))
18062 (goto-line line)
18063 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18065 (defun org-verify-change-for-undo (l1 l2)
18066 "Verify that a real change occurred between the undo lists L1 and L2."
18067 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18068 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18069 (not (eq l1 l2)))
18071 ;;; Agenda dispatch
18073 (defvar org-agenda-restrict nil)
18074 (defvar org-agenda-restrict-begin (make-marker))
18075 (defvar org-agenda-restrict-end (make-marker))
18076 (defvar org-agenda-last-dispatch-buffer nil)
18078 ;;;###autoload
18079 (defun org-agenda (arg &optional keys restriction)
18080 "Dispatch agenda commands to collect entries to the agenda buffer.
18081 Prompts for a command to execute. Any prefix arg will be passed
18082 on to the selected command. The default selections are:
18084 a Call `org-agenda-list' to display the agenda for current day or week.
18085 t Call `org-todo-list' to display the global todo list.
18086 T Call `org-todo-list' to display the global todo list, select only
18087 entries with a specific TODO keyword (the user gets a prompt).
18088 m Call `org-tags-view' to display headlines with tags matching
18089 a condition (the user is prompted for the condition).
18090 M Like `m', but select only TODO entries, no ordinary headlines.
18091 L Create a timeline for the current buffer.
18092 e Export views to associated files.
18094 More commands can be added by configuring the variable
18095 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18096 searches can be pre-defined in this way.
18098 If the current buffer is in Org-mode and visiting a file, you can also
18099 first press `<' once to indicate that the agenda should be temporarily
18100 \(until the next use of \\[org-agenda]) restricted to the current file.
18101 Pressing `<' twice means to restrict to the current subtree or region
18102 \(if active)."
18103 (interactive "P")
18104 (catch 'exit
18105 (let* ((prefix-descriptions nil)
18106 (org-agenda-custom-commands
18107 ;; normalize different versions
18108 (delq nil
18109 (mapcar
18110 (lambda (x)
18111 (cond ((stringp (cdr x))
18112 (push x prefix-descriptions)
18113 nil)
18114 ((stringp (nth 1 x)) x)
18115 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18116 (t (cons (car x) (cons "" (cdr x))))))
18117 org-agenda-custom-commands)))
18118 (buf (current-buffer))
18119 (bfn (buffer-file-name (buffer-base-buffer)))
18120 entry key type match lprops ans)
18121 ;; Turn off restriction
18122 (put 'org-agenda-files 'org-restrict nil)
18123 (setq org-agenda-restrict nil)
18124 (move-marker org-agenda-restrict-begin nil)
18125 (move-marker org-agenda-restrict-end nil)
18126 ;; Delete old local properties
18127 (put 'org-agenda-redo-command 'org-lprops nil)
18128 ;; Remember where this call originated
18129 (setq org-agenda-last-dispatch-buffer (current-buffer))
18130 (unless keys
18131 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18132 keys (car ans)
18133 restriction (cdr ans)))
18134 ;; Estabish the restriction, if any
18135 (when restriction
18136 (put 'org-agenda-files 'org-restrict (list bfn))
18137 (cond
18138 ((eq restriction 'region)
18139 (setq org-agenda-restrict t)
18140 (move-marker org-agenda-restrict-begin (region-beginning))
18141 (move-marker org-agenda-restrict-end (region-end)))
18142 ((eq restriction 'subtree)
18143 (save-excursion
18144 (setq org-agenda-restrict t)
18145 (org-back-to-heading t)
18146 (move-marker org-agenda-restrict-begin (point))
18147 (move-marker org-agenda-restrict-end
18148 (progn (org-end-of-subtree t)))))))
18150 (require 'calendar) ; FIXME: can we avoid this for some commands?
18151 ;; For example the todo list should not need it (but does...)
18152 (cond
18153 ((setq entry (assoc keys org-agenda-custom-commands))
18154 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18155 (progn
18156 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18157 (put 'org-agenda-redo-command 'org-lprops lprops)
18158 (cond
18159 ((eq type 'agenda)
18160 (org-let lprops '(org-agenda-list current-prefix-arg)))
18161 ((eq type 'alltodo)
18162 (org-let lprops '(org-todo-list current-prefix-arg)))
18163 ((eq type 'stuck)
18164 (org-let lprops '(org-agenda-list-stuck-projects
18165 current-prefix-arg)))
18166 ((eq type 'tags)
18167 (org-let lprops '(org-tags-view current-prefix-arg match)))
18168 ((eq type 'tags-todo)
18169 (org-let lprops '(org-tags-view '(4) match)))
18170 ((eq type 'todo)
18171 (org-let lprops '(org-todo-list match)))
18172 ((eq type 'tags-tree)
18173 (org-check-for-org-mode)
18174 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18175 ((eq type 'todo-tree)
18176 (org-check-for-org-mode)
18177 (org-let lprops
18178 '(org-occur (concat "^" outline-regexp "[ \t]*"
18179 (regexp-quote match) "\\>"))))
18180 ((eq type 'occur-tree)
18181 (org-check-for-org-mode)
18182 (org-let lprops '(org-occur match)))
18183 ((functionp type)
18184 (org-let lprops '(funcall type match)))
18185 ((fboundp type)
18186 (org-let lprops '(funcall type match)))
18187 (t (error "Invalid custom agenda command type %s" type))))
18188 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18189 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18190 ((equal keys "a") (call-interactively 'org-agenda-list))
18191 ((equal keys "t") (call-interactively 'org-todo-list))
18192 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18193 ((equal keys "m") (call-interactively 'org-tags-view))
18194 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18195 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18196 ((equal keys "L")
18197 (unless (org-mode-p)
18198 (error "This is not an Org-mode file"))
18199 (unless restriction
18200 (put 'org-agenda-files 'org-restrict (list bfn))
18201 (org-call-with-arg 'org-timeline arg)))
18202 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18203 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18204 ((equal keys "!") (customize-variable 'org-stuck-projects))
18205 (t (error "Invalid agenda key"))))))
18207 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18208 "The user interface for selecting an agenda command."
18209 (catch 'exit
18210 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18211 (restrict-ok (and bfn (org-mode-p)))
18212 (region-p (org-region-active-p))
18213 (custom org-agenda-custom-commands)
18214 (selstring "")
18215 restriction
18216 c entry key type match prefixes rmheader header-end custom1 desc)
18217 (save-window-excursion
18218 (delete-other-windows)
18219 (org-switch-to-buffer-other-window " *Agenda Commands*")
18220 (erase-buffer)
18221 (insert (eval-when-compile
18222 (let ((header
18223 "Press key for an agenda command: < Buffer,subtree/region restriction
18224 -------------------------------- C Configure custom agenda commands
18225 a Agenda for current week or day e Export agenda views
18226 t List of all TODO entries T Entries with special TODO kwd
18227 m Match a TAGS query M Like m, but only TODO entries
18228 L Timeline for current buffer # List stuck projects (!=configure)
18229 / Multi-occur
18231 (start 0))
18232 (while (string-match
18233 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18234 header start)
18235 (setq start (match-end 0))
18236 (add-text-properties (match-beginning 2) (match-end 2)
18237 '(face bold) header))
18238 header)))
18239 (setq header-end (move-marker (make-marker) (point)))
18240 (while t
18241 (setq custom1 custom)
18242 (when (eq rmheader t)
18243 (goto-line 1)
18244 (re-search-forward ":" nil t)
18245 (delete-region (match-end 0) (line-end-position))
18246 (forward-char 1)
18247 (looking-at "-+")
18248 (delete-region (match-end 0) (line-end-position))
18249 (move-marker header-end (match-end 0)))
18250 (goto-char header-end)
18251 (delete-region (point) (point-max))
18252 (while (setq entry (pop custom1))
18253 (setq key (car entry) desc (nth 1 entry)
18254 type (nth 2 entry) match (nth 3 entry))
18255 (if (> (length key) 1)
18256 (add-to-list 'prefixes (string-to-char key))
18257 (insert
18258 (format
18259 "\n%-4s%-14s: %s"
18260 (org-add-props (copy-sequence key)
18261 '(face bold))
18262 (cond
18263 ((string-match "\\S-" desc) desc)
18264 ((eq type 'agenda) "Agenda for current week or day")
18265 ((eq type 'alltodo) "List of all TODO entries")
18266 ((eq type 'stuck) "List of stuck projects")
18267 ((eq type 'todo) "TODO keyword")
18268 ((eq type 'tags) "Tags query")
18269 ((eq type 'tags-todo) "Tags (TODO)")
18270 ((eq type 'tags-tree) "Tags tree")
18271 ((eq type 'todo-tree) "TODO kwd tree")
18272 ((eq type 'occur-tree) "Occur tree")
18273 ((functionp type) (if (symbolp type)
18274 (symbol-name type)
18275 "Lambda expression"))
18276 (t "???"))
18277 (cond
18278 ((stringp match)
18279 (org-add-props match nil 'face 'org-warning))
18280 (match
18281 (format "set of %d commands" (length match)))
18282 (t ""))))))
18283 (when prefixes
18284 (mapcar (lambda (x)
18285 (insert
18286 (format "\n%s %s"
18287 (org-add-props (char-to-string x)
18288 nil 'face 'bold)
18289 (or (cdr (assoc (concat selstring (char-to-string x))
18290 prefix-descriptions))
18291 "Prefix key"))))
18292 prefixes))
18293 (goto-char (point-min))
18294 (if (and (fboundp 'fit-window-to-buffer)
18295 (not (pos-visible-in-window-p (point-max))))
18296 (fit-window-to-buffer))
18297 (message "Press key for agenda command%s:"
18298 (if restrict-ok
18299 (if restriction
18300 (format " (restricted to %s)" restriction)
18301 " (unrestricted)")
18302 ""))
18303 (setq c (read-char-exclusive))
18304 (message "")
18305 (cond
18306 ((assoc (char-to-string c) custom)
18307 (setq selstring (concat selstring (char-to-string c)))
18308 (throw 'exit (cons selstring restriction)))
18309 ((memq c prefixes)
18310 (setq selstring (concat selstring (char-to-string c))
18311 prefixes nil
18312 rmheader (or rmheader t)
18313 custom (delq nil (mapcar
18314 (lambda (x)
18315 (if (or (= (length (car x)) 1)
18316 (/= (string-to-char (car x)) c))
18318 (cons (substring (car x) 1) (cdr x))))
18319 custom))))
18320 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18321 (message "Restriction is only possible in Org-mode buffers")
18322 (ding) (sit-for 1))
18323 ((eq c ?1)
18324 (setq restriction 'buffer))
18325 ((eq c ?0)
18326 (setq restriction (if region-p 'region 'subtree)))
18327 ((eq c ?<)
18328 (setq restriction
18329 (cond
18330 ((eq restriction 'buffer)
18331 (if region-p 'region 'subtree))
18332 ((memq restriction '(subtree region))
18333 nil)
18334 (t 'buffer))))
18335 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18336 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18337 ((equal c ?q) (error "Abort"))
18338 (t (error "Invalid key %c" c))))))))
18340 (defun org-run-agenda-series (name series)
18341 (org-prepare-agenda name)
18342 (let* ((org-agenda-multi t)
18343 (redo (list 'org-run-agenda-series name (list 'quote series)))
18344 (cmds (car series))
18345 (gprops (nth 1 series))
18346 match ;; The byte compiler incorrectly complains about this. Keep it!
18347 cmd type lprops)
18348 (while (setq cmd (pop cmds))
18349 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18350 (cond
18351 ((eq type 'agenda)
18352 (org-let2 gprops lprops
18353 '(call-interactively 'org-agenda-list)))
18354 ((eq type 'alltodo)
18355 (org-let2 gprops lprops
18356 '(call-interactively 'org-todo-list)))
18357 ((eq type 'stuck)
18358 (org-let2 gprops lprops
18359 '(call-interactively 'org-agenda-list-stuck-projects)))
18360 ((eq type 'tags)
18361 (org-let2 gprops lprops
18362 '(org-tags-view current-prefix-arg match)))
18363 ((eq type 'tags-todo)
18364 (org-let2 gprops lprops
18365 '(org-tags-view '(4) match)))
18366 ((eq type 'todo)
18367 (org-let2 gprops lprops
18368 '(org-todo-list match)))
18369 ((fboundp type)
18370 (org-let2 gprops lprops
18371 '(funcall type match)))
18372 (t (error "Invalid type in command series"))))
18373 (widen)
18374 (setq org-agenda-redo-command redo)
18375 (goto-char (point-min)))
18376 (org-finalize-agenda))
18378 ;;;###autoload
18379 (defmacro org-batch-agenda (cmd-key &rest parameters)
18380 "Run an agenda command in batch mode and send the result to STDOUT.
18381 If CMD-KEY is a string of length 1, it is used as a key in
18382 `org-agenda-custom-commands' and triggers this command. If it is a
18383 longer string is is used as a tags/todo match string.
18384 Paramters are alternating variable names and values that will be bound
18385 before running the agenda command."
18386 (let (pars)
18387 (while parameters
18388 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18389 (if (> (length cmd-key) 2)
18390 (eval (list 'let (nreverse pars)
18391 (list 'org-tags-view nil cmd-key)))
18392 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18393 (set-buffer org-agenda-buffer-name)
18394 (princ (org-encode-for-stdout (buffer-string)))))
18396 (defun org-encode-for-stdout (string)
18397 (if (fboundp 'encode-coding-string)
18398 (encode-coding-string string buffer-file-coding-system)
18399 string))
18401 (defvar org-agenda-info nil)
18403 ;;;###autoload
18404 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18405 "Run an agenda command in batch mode and send the result to STDOUT.
18406 If CMD-KEY is a string of length 1, it is used as a key in
18407 `org-agenda-custom-commands' and triggers this command. If it is a
18408 longer string is is used as a tags/todo match string.
18409 Paramters are alternating variable names and values that will be bound
18410 before running the agenda command.
18412 The output gives a line for each selected agenda item. Each
18413 item is a list of comma-separated values, like this:
18415 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18417 category The category of the item
18418 head The headline, without TODO kwd, TAGS and PRIORITY
18419 type The type of the agenda entry, can be
18420 todo selected in TODO match
18421 tagsmatch selected in tags match
18422 diary imported from diary
18423 deadline a deadline on given date
18424 scheduled scheduled on given date
18425 timestamp entry has timestamp on given date
18426 closed entry was closed on given date
18427 upcoming-deadline warning about deadline
18428 past-scheduled forwarded scheduled item
18429 block entry has date block including g. date
18430 todo The todo keyword, if any
18431 tags All tags including inherited ones, separated by colons
18432 date The relevant date, like 2007-2-14
18433 time The time, like 15:00-16:50
18434 extra Sting with extra planning info
18435 priority-l The priority letter if any was given
18436 priority-n The computed numerical priority
18437 agenda-day The day in the agenda where this is listed"
18439 (let (pars)
18440 (while parameters
18441 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18442 (push (list 'org-agenda-remove-tags t) pars)
18443 (if (> (length cmd-key) 2)
18444 (eval (list 'let (nreverse pars)
18445 (list 'org-tags-view nil cmd-key)))
18446 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18447 (set-buffer org-agenda-buffer-name)
18448 (let* ((lines (org-split-string (buffer-string) "\n"))
18449 line)
18450 (while (setq line (pop lines))
18451 (catch 'next
18452 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18453 (setq org-agenda-info
18454 (org-fix-agenda-info (text-properties-at 0 line)))
18455 (princ
18456 (org-encode-for-stdout
18457 (mapconcat 'org-agenda-export-csv-mapper
18458 '(org-category txt type todo tags date time-of-day extra
18459 priority-letter priority agenda-day)
18460 ",")))
18461 (princ "\n"))))))
18463 (defun org-fix-agenda-info (props)
18464 "Make sure all properties on an agenda item have a canonical form,
18465 so the the export commands caneasily use it."
18466 (let (tmp re)
18467 (when (setq tmp (plist-get props 'tags))
18468 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18469 (when (setq tmp (plist-get props 'date))
18470 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18471 (let ((calendar-date-display-form '(year "-" month "-" day)))
18472 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18474 (setq tmp (calendar-date-string tmp)))
18475 (setq props (plist-put props 'date tmp)))
18476 (when (setq tmp (plist-get props 'day))
18477 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18478 (let ((calendar-date-display-form '(year "-" month "-" day)))
18479 (setq tmp (calendar-date-string tmp)))
18480 (setq props (plist-put props 'day tmp))
18481 (setq props (plist-put props 'agenda-day tmp)))
18482 (when (setq tmp (plist-get props 'txt))
18483 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18484 (plist-put props 'priority-letter (match-string 1 tmp))
18485 (setq tmp (replace-match "" t t tmp)))
18486 (when (and (setq re (plist-get props 'org-todo-regexp))
18487 (setq re (concat "\\`\\.*" re " ?"))
18488 (string-match re tmp))
18489 (plist-put props 'todo (match-string 1 tmp))
18490 (setq tmp (replace-match "" t t tmp)))
18491 (plist-put props 'txt tmp)))
18492 props)
18494 (defun org-agenda-export-csv-mapper (prop)
18495 (let ((res (plist-get org-agenda-info prop)))
18496 (setq res
18497 (cond
18498 ((not res) "")
18499 ((stringp res) res)
18500 (t (prin1-to-string res))))
18501 (while (string-match "," res)
18502 (setq res (replace-match ";" t t res)))
18503 (org-trim res)))
18506 ;;;###autoload
18507 (defun org-store-agenda-views (&rest parameters)
18508 (interactive)
18509 (eval (list 'org-batch-store-agenda-views)))
18511 ;; FIXME, why is this a macro?????
18512 ;;;###autoload
18513 (defmacro org-batch-store-agenda-views (&rest parameters)
18514 "Run all custom agenda commands that have a file argument."
18515 (let ((cmds org-agenda-custom-commands)
18516 (pop-up-frames nil)
18517 (dir default-directory)
18518 pars cmd thiscmdkey files opts)
18519 (while parameters
18520 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18521 (setq pars (reverse pars))
18522 (save-window-excursion
18523 (while cmds
18524 (setq cmd (pop cmds)
18525 thiscmdkey (car cmd)
18526 opts (nth 3 cmd)
18527 files (nth 4 cmd))
18528 (if (stringp files) (setq files (list files)))
18529 (when files
18530 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18531 (list 'org-agenda nil thiscmdkey)))
18532 (set-buffer org-agenda-buffer-name)
18533 (while files
18534 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18535 (list 'org-write-agenda
18536 (expand-file-name (pop files) dir) t))))
18537 (and (get-buffer org-agenda-buffer-name)
18538 (kill-buffer org-agenda-buffer-name)))))))
18540 (defun org-write-agenda (file &optional nosettings)
18541 "Write the current buffer (an agenda view) as a file.
18542 Depending on the extension of the file name, plain text (.txt),
18543 HTML (.html or .htm) or Postscript (.ps) is produced.
18544 If NOSETTINGS is given, do not scope the settings of
18545 `org-agenda-exporter-settings' into the export commands. This is used when
18546 the settings have already been scoped and we do not wish to overrule other,
18547 higher priority settings."
18548 (interactive "FWrite agenda to file: ")
18549 (if (not (file-writable-p file))
18550 (error "Cannot write agenda to file %s" file))
18551 (cond
18552 ((string-match "\\.html?\\'" file) (require 'htmlize))
18553 ((string-match "\\.ps\\'" file) (require 'ps-print)))
18554 (org-let (if nosettings nil org-agenda-exporter-settings)
18555 '(save-excursion
18556 (save-window-excursion
18557 (cond
18558 ((string-match "\\.html?\\'" file)
18559 (set-buffer (htmlize-buffer (current-buffer)))
18561 (when (and org-agenda-export-html-style
18562 (string-match "<style>" org-agenda-export-html-style))
18563 ;; replace <style> section with org-agenda-export-html-style
18564 (goto-char (point-min))
18565 (kill-region (- (search-forward "<style") 6)
18566 (search-forward "</style>"))
18567 (insert org-agenda-export-html-style))
18568 (write-file file)
18569 (kill-buffer (current-buffer))
18570 (message "HTML written to %s" file))
18571 ((string-match "\\.ps\\'" file)
18572 (ps-print-buffer-with-faces file)
18573 (message "Postscript written to %s" file))
18575 (let ((bs (buffer-string)))
18576 (find-file file)
18577 (insert bs)
18578 (save-buffer 0)
18579 (kill-buffer (current-buffer))
18580 (message "Plain text written to %s" file))))))
18581 (set-buffer org-agenda-buffer-name)))
18583 (defmacro org-no-read-only (&rest body)
18584 "Inhibit read-only for BODY."
18585 `(let ((inhibit-read-only t)) ,@body))
18587 (defun org-check-for-org-mode ()
18588 "Make sure current buffer is in org-mode. Error if not."
18589 (or (org-mode-p)
18590 (error "Cannot execute org-mode agenda command on buffer in %s."
18591 major-mode)))
18593 (defun org-fit-agenda-window ()
18594 "Fit the window to the buffer size."
18595 (and (memq org-agenda-window-setup '(reorganize-frame))
18596 (fboundp 'fit-window-to-buffer)
18597 (fit-window-to-buffer
18599 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
18600 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
18602 ;;; Agenda file list
18604 (defun org-agenda-files (&optional unrestricted)
18605 "Get the list of agenda files.
18606 Optional UNRESTRICTED means return the full list even if a restriction
18607 is currently in place."
18608 (let ((files
18609 (cond
18610 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18611 ((stringp org-agenda-files) (org-read-agenda-file-list))
18612 ((listp org-agenda-files) org-agenda-files)
18613 (t (error "Invalid value of `org-agenda-files'")))))
18614 (if org-agenda-skip-unavailable-files
18615 (delq nil
18616 (mapcar (function
18617 (lambda (file)
18618 (and (file-readable-p file) file)))
18619 files))
18620 files))) ; `org-check-agenda-file' will remove them from the list
18622 (defun org-edit-agenda-file-list ()
18623 "Edit the list of agenda files.
18624 Depending on setup, this either uses customize to edit the variable
18625 `org-agenda-files', or it visits the file that is holding the list. In the
18626 latter case, the buffer is set up in a way that saving it automatically kills
18627 the buffer and restores the previous window configuration."
18628 (interactive)
18629 (if (stringp org-agenda-files)
18630 (let ((cw (current-window-configuration)))
18631 (find-file org-agenda-files)
18632 (org-set-local 'org-window-configuration cw)
18633 (org-add-hook 'after-save-hook
18634 (lambda ()
18635 (set-window-configuration
18636 (prog1 org-window-configuration
18637 (kill-buffer (current-buffer))))
18638 (org-install-agenda-files-menu)
18639 (message "New agenda file list installed"))
18640 nil 'local)
18641 (message (substitute-command-keys
18642 "Edit list and finish with \\[save-buffer]")))
18643 (customize-variable 'org-agenda-files)))
18645 (defun org-store-new-agenda-file-list (list)
18646 "Set new value for the agenda file list and save it correcly."
18647 (if (stringp org-agenda-files)
18648 (let ((f org-agenda-files) b)
18649 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
18650 (with-temp-file f
18651 (insert (mapconcat 'identity list "\n") "\n")))
18652 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
18653 (setq org-agenda-files list)
18654 (customize-save-variable 'org-agenda-files org-agenda-files))))
18656 (defun org-read-agenda-file-list ()
18657 "Read the list of agenda files from a file."
18658 (when (stringp org-agenda-files)
18659 (with-temp-buffer
18660 (insert-file-contents org-agenda-files)
18661 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
18664 ;;;###autoload
18665 (defun org-cycle-agenda-files ()
18666 "Cycle through the files in `org-agenda-files'.
18667 If the current buffer visits an agenda file, find the next one in the list.
18668 If the current buffer does not, find the first agenda file."
18669 (interactive)
18670 (let* ((fs (org-agenda-files t))
18671 (files (append fs (list (car fs))))
18672 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18673 file)
18674 (unless files (error "No agenda files"))
18675 (catch 'exit
18676 (while (setq file (pop files))
18677 (if (equal (file-truename file) tcf)
18678 (when (car files)
18679 (find-file (car files))
18680 (throw 'exit t))))
18681 (find-file (car fs)))
18682 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18684 (defun org-agenda-file-to-front (&optional to-end)
18685 "Move/add the current file to the top of the agenda file list.
18686 If the file is not present in the list, it is added to the front. If it is
18687 present, it is moved there. With optional argument TO-END, add/move to the
18688 end of the list."
18689 (interactive "P")
18690 (let ((org-agenda-skip-unavailable-files nil)
18691 (file-alist (mapcar (lambda (x)
18692 (cons (file-truename x) x))
18693 (org-agenda-files t)))
18694 (ctf (file-truename buffer-file-name))
18695 x had)
18696 (setq x (assoc ctf file-alist) had x)
18698 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18699 (if to-end
18700 (setq file-alist (append (delq x file-alist) (list x)))
18701 (setq file-alist (cons x (delq x file-alist))))
18702 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18703 (org-install-agenda-files-menu)
18704 (message "File %s to %s of agenda file list"
18705 (if had "moved" "added") (if to-end "end" "front"))))
18707 (defun org-remove-file (&optional file)
18708 "Remove current file from the list of files in variable `org-agenda-files'.
18709 These are the files which are being checked for agenda entries.
18710 Optional argument FILE means, use this file instead of the current."
18711 (interactive)
18712 (let* ((org-agenda-skip-unavailable-files nil)
18713 (file (or file buffer-file-name))
18714 (true-file (file-truename file))
18715 (afile (abbreviate-file-name file))
18716 (files (delq nil (mapcar
18717 (lambda (x)
18718 (if (equal true-file
18719 (file-truename x))
18720 nil x))
18721 (org-agenda-files t)))))
18722 (if (not (= (length files) (length (org-agenda-files t))))
18723 (progn
18724 (org-store-new-agenda-file-list files)
18725 (org-install-agenda-files-menu)
18726 (message "Removed file: %s" afile))
18727 (message "File was not in list: %s" afile))))
18729 (defun org-file-menu-entry (file)
18730 (vector file (list 'find-file file) t))
18732 (defun org-check-agenda-file (file)
18733 "Make sure FILE exists. If not, ask user what to do."
18734 (when (not (file-exists-p file))
18735 (message "non-existent file %s. [R]emove from list or [A]bort?"
18736 (abbreviate-file-name file))
18737 (let ((r (downcase (read-char-exclusive))))
18738 (cond
18739 ((equal r ?r)
18740 (org-remove-file file)
18741 (throw 'nextfile t))
18742 (t (error "Abort"))))))
18744 ;;; Agenda prepare and finalize
18746 (defvar org-agenda-multi nil) ; dynammically scoped
18747 (defvar org-agenda-buffer-name "*Org Agenda*")
18748 (defvar org-pre-agenda-window-conf nil)
18749 (defvar org-agenda-name nil)
18750 (defun org-prepare-agenda (&optional name)
18751 (setq org-todo-keywords-for-agenda nil)
18752 (setq org-done-keywords-for-agenda nil)
18753 (if org-agenda-multi
18754 (progn
18755 (setq buffer-read-only nil)
18756 (goto-char (point-max))
18757 (unless (or (bobp) org-agenda-compact-blocks)
18758 (insert "\n" (make-string (window-width) ?=) "\n"))
18759 (narrow-to-region (point) (point-max)))
18760 (org-agenda-maybe-reset-markers 'force)
18761 (org-prepare-agenda-buffers (org-agenda-files))
18762 (setq org-todo-keywords-for-agenda
18763 (org-uniquify org-todo-keywords-for-agenda))
18764 (setq org-done-keywords-for-agenda
18765 (org-uniquify org-done-keywords-for-agenda))
18766 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18767 (awin (get-buffer-window abuf)))
18768 (cond
18769 ((equal (current-buffer) abuf) nil)
18770 (awin (select-window awin))
18771 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18772 ((equal org-agenda-window-setup 'current-window)
18773 (switch-to-buffer abuf))
18774 ((equal org-agenda-window-setup 'other-window)
18775 (org-switch-to-buffer-other-window abuf))
18776 ((equal org-agenda-window-setup 'other-frame)
18777 (switch-to-buffer-other-frame abuf))
18778 ((equal org-agenda-window-setup 'reorganize-frame)
18779 (delete-other-windows)
18780 (org-switch-to-buffer-other-window abuf))))
18781 (setq buffer-read-only nil)
18782 (erase-buffer)
18783 (org-agenda-mode)
18784 (and name (not org-agenda-name)
18785 (org-set-local 'org-agenda-name name)))
18786 (setq buffer-read-only nil))
18788 (defun org-finalize-agenda ()
18789 "Finishing touch for the agenda buffer, called just before displaying it."
18790 (unless org-agenda-multi
18791 (save-excursion
18792 (let ((inhibit-read-only t))
18793 (goto-char (point-min))
18794 (while (org-activate-bracket-links (point-max))
18795 (add-text-properties (match-beginning 0) (match-end 0)
18796 '(face org-link)))
18797 (org-agenda-align-tags)
18798 (unless org-agenda-with-colors
18799 (remove-text-properties (point-min) (point-max) '(face nil))))
18800 (if (and (boundp 'org-overriding-columns-format)
18801 org-overriding-columns-format)
18802 (org-set-local 'org-overriding-columns-format
18803 org-overriding-columns-format))
18804 (if (and (boundp 'org-agenda-view-columns-initially)
18805 org-agenda-view-columns-initially)
18806 (org-agenda-columns))
18807 (when org-agenda-fontify-priorities
18808 (org-fontify-priorities))
18809 (run-hooks 'org-finalize-agenda-hook))))
18811 (defun org-fontify-priorities ()
18812 "Make highest priority lines bold, and lowest italic."
18813 (interactive)
18814 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18815 (org-delete-overlay o)))
18816 (overlays-in (point-min) (point-max)))
18817 (save-excursion
18818 (let ((ovs (org-overlays-in (point-min) (point-max)))
18819 (inhibit-read-only t)
18820 b e p ov h l)
18821 (goto-char (point-min))
18822 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18823 (setq h (or (get-char-property (point) 'org-highest-priority)
18824 org-highest-priority)
18825 l (or (get-char-property (point) 'org-lowest-priority)
18826 org-lowest-priority)
18827 p (string-to-char (match-string 1))
18828 b (match-beginning 0) e (line-end-position)
18829 ov (org-make-overlay b e))
18830 (org-overlay-put
18831 ov 'face
18832 (cond ((listp org-agenda-fontify-priorities)
18833 (cdr (assoc p org-agenda-fontify-priorities)))
18834 ((equal p l) 'italic)
18835 ((equal p h) 'bold)))
18836 (org-overlay-put ov 'org-type 'org-priority)))))
18838 (defun org-prepare-agenda-buffers (files)
18839 "Create buffers for all agenda files, protect archived trees and comments."
18840 (interactive)
18841 (let ((pa '(:org-archived t))
18842 (pc '(:org-comment t))
18843 (pall '(:org-archived t :org-comment t))
18844 (inhibit-read-only t)
18845 (rea (concat ":" org-archive-tag ":"))
18846 bmp file re)
18847 (save-excursion
18848 (save-restriction
18849 (while (setq file (pop files))
18850 (org-check-agenda-file file)
18851 (set-buffer (org-get-agenda-file-buffer file))
18852 (widen)
18853 (setq bmp (buffer-modified-p))
18854 (org-refresh-category-properties)
18855 (setq org-todo-keywords-for-agenda
18856 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18857 (setq org-done-keywords-for-agenda
18858 (append org-done-keywords-for-agenda org-done-keywords))
18859 (save-excursion
18860 (remove-text-properties (point-min) (point-max) pall)
18861 (when org-agenda-skip-archived-trees
18862 (goto-char (point-min))
18863 (while (re-search-forward rea nil t)
18864 (if (org-on-heading-p t)
18865 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18866 (goto-char (point-min))
18867 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18868 (while (re-search-forward re nil t)
18869 (add-text-properties
18870 (match-beginning 0) (org-end-of-subtree t) pc)))
18871 (set-buffer-modified-p bmp))))))
18873 (defvar org-agenda-skip-function nil
18874 "Function to be called at each match during agenda construction.
18875 If this function returns nil, the current match should not be skipped.
18876 Otherwise, the function must return a position from where the search
18877 should be continued.
18878 This may also be a Lisp form, it will be evaluated.
18879 Never set this variable using `setq' or so, because then it will apply
18880 to all future agenda commands. Instead, bind it with `let' to scope
18881 it dynamically into the agenda-constructing command. A good way to set
18882 it is through options in org-agenda-custom-commands.")
18884 (defun org-agenda-skip ()
18885 "Throw to `:skip' in places that should be skipped.
18886 Also moves point to the end of the skipped region, so that search can
18887 continue from there."
18888 (let ((p (point-at-bol)) to fp)
18889 (and org-agenda-skip-archived-trees
18890 (get-text-property p :org-archived)
18891 (org-end-of-subtree t)
18892 (throw :skip t))
18893 (and (get-text-property p :org-comment)
18894 (org-end-of-subtree t)
18895 (throw :skip t))
18896 (if (equal (char-after p) ?#) (throw :skip t))
18897 (when (and (or (setq fp (functionp org-agenda-skip-function))
18898 (consp org-agenda-skip-function))
18899 (setq to (save-excursion
18900 (save-match-data
18901 (if fp
18902 (funcall org-agenda-skip-function)
18903 (eval org-agenda-skip-function))))))
18904 (goto-char to)
18905 (throw :skip t))))
18907 (defvar org-agenda-markers nil
18908 "List of all currently active markers created by `org-agenda'.")
18909 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
18910 "Creation time of the last agenda marker.")
18912 (defun org-agenda-new-marker (&optional pos)
18913 "Return a new agenda marker.
18914 Org-mode keeps a list of these markers and resets them when they are
18915 no longer in use."
18916 (let ((m (copy-marker (or pos (point)))))
18917 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
18918 (push m org-agenda-markers)
18921 (defun org-agenda-maybe-reset-markers (&optional force)
18922 "Reset markers created by `org-agenda'. But only if they are old enough."
18923 (if (or (and force (not org-agenda-multi))
18924 (> (- (time-to-seconds (current-time))
18925 org-agenda-last-marker-time)
18927 (while org-agenda-markers
18928 (move-marker (pop org-agenda-markers) nil))))
18930 (defvar org-agenda-new-buffers nil
18931 "Buffers created to visit agenda files.")
18933 (defun org-get-agenda-file-buffer (file)
18934 "Get a buffer visiting FILE. If the buffer needs to be created, add
18935 it to the list of buffers which might be released later."
18936 (let ((buf (org-find-base-buffer-visiting file)))
18937 (if buf
18938 buf ; just return it
18939 ;; Make a new buffer and remember it
18940 (setq buf (find-file-noselect file))
18941 (if buf (push buf org-agenda-new-buffers))
18942 buf)))
18944 (defun org-release-buffers (blist)
18945 "Release all buffers in list, asking the user for confirmation when needed.
18946 When a buffer is unmodified, it is just killed. When modified, it is saved
18947 \(if the user agrees) and then killed."
18948 (let (buf file)
18949 (while (setq buf (pop blist))
18950 (setq file (buffer-file-name buf))
18951 (when (and (buffer-modified-p buf)
18952 file
18953 (y-or-n-p (format "Save file %s? " file)))
18954 (with-current-buffer buf (save-buffer)))
18955 (kill-buffer buf))))
18957 (defun org-get-category (&optional pos)
18958 "Get the category applying to position POS."
18959 (get-text-property (or pos (point)) 'org-category))
18961 ;;; Agenda timeline
18963 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
18965 (defun org-timeline (&optional include-all)
18966 "Show a time-sorted view of the entries in the current org file.
18967 Only entries with a time stamp of today or later will be listed. With
18968 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
18969 under the current date.
18970 If the buffer contains an active region, only check the region for
18971 dates."
18972 (interactive "P")
18973 (require 'calendar)
18974 (org-compile-prefix-format 'timeline)
18975 (org-set-sorting-strategy 'timeline)
18976 (let* ((dopast t)
18977 (dotodo include-all)
18978 (doclosed org-agenda-show-log)
18979 (entry buffer-file-name)
18980 (date (calendar-current-date))
18981 (beg (if (org-region-active-p) (region-beginning) (point-min)))
18982 (end (if (org-region-active-p) (region-end) (point-max)))
18983 (day-numbers (org-get-all-dates beg end 'no-ranges
18984 t doclosed ; always include today
18985 org-timeline-show-empty-dates))
18986 (org-deadline-warning-days 0)
18987 (org-agenda-only-exact-dates t)
18988 (today (time-to-days (current-time)))
18989 (past t)
18990 args
18991 s e rtn d emptyp)
18992 (setq org-agenda-redo-command
18993 (list 'progn
18994 (list 'org-switch-to-buffer-other-window (current-buffer))
18995 (list 'org-timeline (list 'quote include-all))))
18996 (if (not dopast)
18997 ;; Remove past dates from the list of dates.
18998 (setq day-numbers (delq nil (mapcar (lambda(x)
18999 (if (>= x today) x nil))
19000 day-numbers))))
19001 (org-prepare-agenda (concat "Timeline "
19002 (file-name-nondirectory buffer-file-name)))
19003 (if doclosed (push :closed args))
19004 (push :timestamp args)
19005 (push :deadline args)
19006 (push :scheduled args)
19007 (push :sexp args)
19008 (if dotodo (push :todo args))
19009 (while (setq d (pop day-numbers))
19010 (if (and (listp d) (eq (car d) :omitted))
19011 (progn
19012 (setq s (point))
19013 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19014 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19015 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19016 (if (and (>= d today)
19017 dopast
19018 past)
19019 (progn
19020 (setq past nil)
19021 (insert (make-string 79 ?-) "\n")))
19022 (setq date (calendar-gregorian-from-absolute d))
19023 (setq s (point))
19024 (setq rtn (and (not emptyp)
19025 (apply 'org-agenda-get-day-entries entry
19026 date args)))
19027 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19028 (progn
19029 (insert
19030 (if (stringp org-agenda-format-date)
19031 (format-time-string org-agenda-format-date
19032 (org-time-from-absolute date))
19033 (funcall org-agenda-format-date date))
19034 "\n")
19035 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19036 (put-text-property s (1- (point)) 'org-date-line t)
19037 (if (equal d today)
19038 (put-text-property s (1- (point)) 'org-today t))
19039 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19040 (put-text-property s (1- (point)) 'day d)))))
19041 (goto-char (point-min))
19042 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19043 (point-min)))
19044 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19045 (org-finalize-agenda)
19046 (setq buffer-read-only t)))
19048 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19049 "Return a list of all relevant day numbers from BEG to END buffer positions.
19050 If NO-RANGES is non-nil, include only the start and end dates of a range,
19051 not every single day in the range. If FORCE-TODAY is non-nil, make
19052 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19053 inactive time stamps (those in square brackets) are included.
19054 When EMPTY is non-nil, also include days without any entries."
19055 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19056 dates dates1 date day day1 day2 ts1 ts2)
19057 (if force-today
19058 (setq dates (list (time-to-days (current-time)))))
19059 (save-excursion
19060 (goto-char beg)
19061 (while (re-search-forward re end t)
19062 (setq day (time-to-days (org-time-string-to-time
19063 (substring (match-string 1) 0 10))))
19064 (or (memq day dates) (push day dates)))
19065 (unless no-ranges
19066 (goto-char beg)
19067 (while (re-search-forward org-tr-regexp end t)
19068 (setq ts1 (substring (match-string 1) 0 10)
19069 ts2 (substring (match-string 2) 0 10)
19070 day1 (time-to-days (org-time-string-to-time ts1))
19071 day2 (time-to-days (org-time-string-to-time ts2)))
19072 (while (< (setq day1 (1+ day1)) day2)
19073 (or (memq day1 dates) (push day1 dates)))))
19074 (setq dates (sort dates '<))
19075 (when empty
19076 (while (setq day (pop dates))
19077 (setq day2 (car dates))
19078 (push day dates1)
19079 (when (and day2 empty)
19080 (if (or (eq empty t)
19081 (and (numberp empty) (<= (- day2 day) empty)))
19082 (while (< (setq day (1+ day)) day2)
19083 (push (list day) dates1))
19084 (push (cons :omitted (- day2 day)) dates1))))
19085 (setq dates (nreverse dates1)))
19086 dates)))
19088 ;;; Agenda Daily/Weekly
19090 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19091 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19092 (defvar org-agenda-last-arguments nil
19093 "The arguments of the previous call to org-agenda")
19094 (defvar org-starting-day nil) ; local variable in the agenda buffer
19095 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19096 (defvar org-include-all-loc nil) ; local variable
19097 (defvar org-agenda-remove-date nil) ; dynamically scoped
19099 ;;;###autoload
19100 (defun org-agenda-list (&optional include-all start-day ndays)
19101 "Produce a weekly view from all files in variable `org-agenda-files'.
19102 The view will be for the current week, but from the overview buffer you
19103 will be able to go to other weeks.
19104 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
19105 also be shown, under the current date.
19106 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
19107 on the days are also shown. See the variable `org-log-done' for how
19108 to turn on logging.
19109 START-DAY defaults to TODAY, or to the most recent match for the weekday
19110 given in `org-agenda-start-on-weekday'.
19111 NDAYS defaults to `org-agenda-ndays'."
19112 (interactive "P")
19113 (setq ndays (or ndays org-agenda-ndays)
19114 start-day (or start-day org-agenda-start-day))
19115 (if org-agenda-overriding-arguments
19116 (setq include-all (car org-agenda-overriding-arguments)
19117 start-day (nth 1 org-agenda-overriding-arguments)
19118 ndays (nth 2 org-agenda-overriding-arguments)))
19119 (if (stringp start-day)
19120 ;; Convert to an absolute day number
19121 (setq start-day (time-to-days (org-read-date nil t start-day))))
19122 (setq org-agenda-last-arguments (list include-all start-day ndays))
19123 (org-compile-prefix-format 'agenda)
19124 (org-set-sorting-strategy 'agenda)
19125 (require 'calendar)
19126 (let* ((org-agenda-start-on-weekday
19127 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19128 org-agenda-start-on-weekday nil))
19129 (thefiles (org-agenda-files))
19130 (files thefiles)
19131 (today (time-to-days (current-time)))
19132 (sd (or start-day today))
19133 (start (if (or (null org-agenda-start-on-weekday)
19134 (< org-agenda-ndays 7))
19136 (let* ((nt (calendar-day-of-week
19137 (calendar-gregorian-from-absolute sd)))
19138 (n1 org-agenda-start-on-weekday)
19139 (d (- nt n1)))
19140 (- sd (+ (if (< d 0) 7 0) d)))))
19141 (day-numbers (list start))
19142 (day-cnt 0)
19143 (inhibit-redisplay (not debug-on-error))
19144 s e rtn rtnall file date d start-pos end-pos todayp nd)
19145 (setq org-agenda-redo-command
19146 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19147 ;; Make the list of days
19148 (setq ndays (or ndays org-agenda-ndays)
19149 nd ndays)
19150 (while (> ndays 1)
19151 (push (1+ (car day-numbers)) day-numbers)
19152 (setq ndays (1- ndays)))
19153 (setq day-numbers (nreverse day-numbers))
19154 (org-prepare-agenda "Day/Week")
19155 (org-set-local 'org-starting-day (car day-numbers))
19156 (org-set-local 'org-include-all-loc include-all)
19157 (org-set-local 'org-agenda-span
19158 (org-agenda-ndays-to-span nd))
19159 (when (and (or include-all org-agenda-include-all-todo)
19160 (member today day-numbers))
19161 (setq files thefiles
19162 rtnall nil)
19163 (while (setq file (pop files))
19164 (catch 'nextfile
19165 (org-check-agenda-file file)
19166 (setq date (calendar-gregorian-from-absolute today)
19167 rtn (org-agenda-get-day-entries
19168 file date :todo))
19169 (setq rtnall (append rtnall rtn))))
19170 (when rtnall
19171 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19172 (add-text-properties (point-min) (1- (point))
19173 (list 'face 'org-agenda-structure))
19174 (insert (org-finalize-agenda-entries rtnall) "\n")))
19175 (unless org-agenda-compact-blocks
19176 (setq s (point))
19177 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19178 "-agenda:\n")
19179 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19180 'org-date-line t)))
19181 (while (setq d (pop day-numbers))
19182 (setq date (calendar-gregorian-from-absolute d)
19183 s (point))
19184 (if (or (setq todayp (= d today))
19185 (and (not start-pos) (= d sd)))
19186 (setq start-pos (point))
19187 (if (and start-pos (not end-pos))
19188 (setq end-pos (point))))
19189 (setq files thefiles
19190 rtnall nil)
19191 (while (setq file (pop files))
19192 (catch 'nextfile
19193 (org-check-agenda-file file)
19194 (if org-agenda-show-log
19195 (setq rtn (org-agenda-get-day-entries
19196 file date
19197 :deadline :scheduled :timestamp :sexp :closed))
19198 (setq rtn (org-agenda-get-day-entries
19199 file date
19200 :deadline :scheduled :sexp :timestamp)))
19201 (setq rtnall (append rtnall rtn))))
19202 (if org-agenda-include-diary
19203 (progn
19204 (require 'diary-lib)
19205 (setq rtn (org-get-entries-from-diary date))
19206 (setq rtnall (append rtnall rtn))))
19207 (if (or rtnall org-agenda-show-all-dates)
19208 (progn
19209 (setq day-cnt (1+ day-cnt))
19210 (insert
19211 (if (stringp org-agenda-format-date)
19212 (format-time-string org-agenda-format-date
19213 (org-time-from-absolute date))
19214 (funcall org-agenda-format-date date))
19215 "\n")
19216 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19217 (put-text-property s (1- (point)) 'org-date-line t)
19218 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19219 (if todayp (put-text-property s (1- (point)) 'org-today t))
19220 (if rtnall (insert
19221 (org-finalize-agenda-entries
19222 (org-agenda-add-time-grid-maybe
19223 rtnall nd todayp))
19224 "\n"))
19225 (put-text-property s (1- (point)) 'day d)
19226 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19227 (goto-char (point-min))
19228 (org-fit-agenda-window)
19229 (unless (and (pos-visible-in-window-p (point-min))
19230 (pos-visible-in-window-p (point-max)))
19231 (goto-char (1- (point-max)))
19232 (recenter -1)
19233 (if (not (pos-visible-in-window-p (or start-pos 1)))
19234 (progn
19235 (goto-char (or start-pos 1))
19236 (recenter 1))))
19237 (goto-char (or start-pos 1))
19238 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19239 (org-finalize-agenda)
19240 (setq buffer-read-only t)
19241 (message "")))
19243 (defun org-agenda-ndays-to-span (n)
19244 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19246 ;;; Agenda TODO list
19248 (defvar org-select-this-todo-keyword nil)
19249 (defvar org-last-arg nil)
19251 ;;;###autoload
19252 (defun org-todo-list (arg)
19253 "Show all TODO entries from all agenda file in a single list.
19254 The prefix arg can be used to select a specific TODO keyword and limit
19255 the list to these. When using \\[universal-argument], you will be prompted
19256 for a keyword. A numeric prefix directly selects the Nth keyword in
19257 `org-todo-keywords-1'."
19258 (interactive "P")
19259 (require 'calendar)
19260 (org-compile-prefix-format 'todo)
19261 (org-set-sorting-strategy 'todo)
19262 (org-prepare-agenda "TODO")
19263 (let* ((today (time-to-days (current-time)))
19264 (date (calendar-gregorian-from-absolute today))
19265 (kwds org-todo-keywords-for-agenda)
19266 (completion-ignore-case t)
19267 (org-select-this-todo-keyword
19268 (if (stringp arg) arg
19269 (and arg (integerp arg) (> arg 0)
19270 (nth (1- arg) kwds))))
19271 rtn rtnall files file pos)
19272 (when (equal arg '(4))
19273 (setq org-select-this-todo-keyword
19274 (completing-read "Keyword (or KWD1|K2D2|...): "
19275 (mapcar 'list kwds) nil nil)))
19276 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19277 (org-set-local 'org-last-arg arg)
19278 (setq org-agenda-redo-command
19279 '(org-todo-list (or current-prefix-arg org-last-arg)))
19280 (setq files (org-agenda-files)
19281 rtnall nil)
19282 (while (setq file (pop files))
19283 (catch 'nextfile
19284 (org-check-agenda-file file)
19285 (setq rtn (org-agenda-get-day-entries file date :todo))
19286 (setq rtnall (append rtnall rtn))))
19287 (if org-agenda-overriding-header
19288 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19289 nil 'face 'org-agenda-structure) "\n")
19290 (insert "Global list of TODO items of type: ")
19291 (add-text-properties (point-min) (1- (point))
19292 (list 'face 'org-agenda-structure))
19293 (setq pos (point))
19294 (insert (or org-select-this-todo-keyword "ALL") "\n")
19295 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19296 (setq pos (point))
19297 (unless org-agenda-multi
19298 (insert "Available with `N r': (0)ALL")
19299 (let ((n 0) s)
19300 (mapc (lambda (x)
19301 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19302 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19303 (insert "\n "))
19304 (insert " " s))
19305 kwds))
19306 (insert "\n"))
19307 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19308 (when rtnall
19309 (insert (org-finalize-agenda-entries rtnall) "\n"))
19310 (goto-char (point-min))
19311 (org-fit-agenda-window)
19312 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19313 (org-finalize-agenda)
19314 (setq buffer-read-only t)))
19316 ;;; Agenda tags match
19318 ;;;###autoload
19319 (defun org-tags-view (&optional todo-only match)
19320 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19321 The prefix arg TODO-ONLY limits the search to TODO entries."
19322 (interactive "P")
19323 (org-compile-prefix-format 'tags)
19324 (org-set-sorting-strategy 'tags)
19325 (let* ((org-tags-match-list-sublevels
19326 (if todo-only t org-tags-match-list-sublevels))
19327 (completion-ignore-case t)
19328 rtn rtnall files file pos matcher
19329 buffer)
19330 (setq matcher (org-make-tags-matcher match)
19331 match (car matcher) matcher (cdr matcher))
19332 (org-prepare-agenda (concat "TAGS " match))
19333 (setq org-agenda-redo-command
19334 (list 'org-tags-view (list 'quote todo-only)
19335 (list 'if 'current-prefix-arg nil match)))
19336 (setq files (org-agenda-files)
19337 rtnall nil)
19338 (while (setq file (pop files))
19339 (catch 'nextfile
19340 (org-check-agenda-file file)
19341 (setq buffer (if (file-exists-p file)
19342 (org-get-agenda-file-buffer file)
19343 (error "No such file %s" file)))
19344 (if (not buffer)
19345 ;; If file does not exist, merror message to agenda
19346 (setq rtn (list
19347 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19348 rtnall (append rtnall rtn))
19349 (with-current-buffer buffer
19350 (unless (org-mode-p)
19351 (error "Agenda file %s is not in `org-mode'" file))
19352 (save-excursion
19353 (save-restriction
19354 (if org-agenda-restrict
19355 (narrow-to-region org-agenda-restrict-begin
19356 org-agenda-restrict-end)
19357 (widen))
19358 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19359 (setq rtnall (append rtnall rtn))))))))
19360 (if org-agenda-overriding-header
19361 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19362 nil 'face 'org-agenda-structure) "\n")
19363 (insert "Headlines with TAGS match: ")
19364 (add-text-properties (point-min) (1- (point))
19365 (list 'face 'org-agenda-structure))
19366 (setq pos (point))
19367 (insert match "\n")
19368 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19369 (setq pos (point))
19370 (unless org-agenda-multi
19371 (insert "Press `C-u r' to search again with new search string\n"))
19372 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19373 (when rtnall
19374 (insert (org-finalize-agenda-entries rtnall) "\n"))
19375 (goto-char (point-min))
19376 (org-fit-agenda-window)
19377 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19378 (org-finalize-agenda)
19379 (setq buffer-read-only t)))
19381 ;;; Agenda Finding stuck projects
19383 (defvar org-agenda-skip-regexp nil
19384 "Regular expression used in skipping subtrees for the agenda.
19385 This is basically a temporary global variable that can be set and then
19386 used by user-defined selections using `org-agenda-skip-function'.")
19388 (defvar org-agenda-overriding-header nil
19389 "When this is set during todo and tags searches, will replace header.")
19391 (defun org-agenda-skip-subtree-when-regexp-matches ()
19392 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19393 If yes, it returns the end position of this tree, causing agenda commands
19394 to skip this subtree. This is a function that can be put into
19395 `org-agenda-skip-function' for the duration of a command."
19396 (let ((end (save-excursion (org-end-of-subtree t)))
19397 skip)
19398 (save-excursion
19399 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19400 (and skip end)))
19402 (defun org-agenda-skip-entry-if (&rest conditions)
19403 "Skip entry if any of CONDITIONS is true.
19404 See `org-agenda-skip-if for details."
19405 (org-agenda-skip-if nil conditions))
19406 (defun org-agenda-skip-subtree-if (&rest conditions)
19407 "Skip entry if any of CONDITIONS is true.
19408 See `org-agenda-skip-if for details."
19409 (org-agenda-skip-if t conditions))
19411 (defun org-agenda-skip-if (subtree conditions)
19412 "Checks current entity for CONDITIONS.
19413 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19414 the entry, i.e. the text before the next heading is checked.
19416 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19417 from different tests. Valid conditions are:
19419 scheduled Check if there is a scheduled cookie
19420 notscheduled Check if there is no scheduled cookie
19421 deadline Check if there is a deadline
19422 notdeadline Check if there is no deadline
19423 regexp Check if regexp matches
19424 notregexp Check if regexp does not match.
19426 The regexp is taken from the conditions list, it must com right after the
19427 `regexp' of `notregexp' element.
19429 If any of these conditions is met, this function returns the end point of
19430 the entity, causing the search to continue from there. This is a function
19431 that can be put into `org-agenda-skip-function' for the duration of a command."
19432 (let (beg end m r)
19433 (org-back-to-heading t)
19434 (setq beg (point)
19435 end (if subtree
19436 (progn (org-end-of-subtree t) (point))
19437 (progn (outline-next-heading) (1- (point)))))
19438 (goto-char beg)
19439 (and
19441 (and (memq 'scheduled conditions)
19442 (re-search-forward org-scheduled-time-regexp end t))
19443 (and (memq 'notscheduled conditions)
19444 (not (re-search-forward org-scheduled-time-regexp end t)))
19445 (and (memq 'deadline conditions)
19446 (re-search-forward org-deadline-time-regexp end t))
19447 (and (memq 'notdeadline conditions)
19448 (not (re-search-forward org-deadline-time-regexp end t)))
19449 (and (setq m (memq 'regexp conditions))
19450 (stringp (setq r (nth 1 m)))
19451 (re-search-forward (nth 1 m) end t))
19452 (and (setq m (memq 'notregexp conditions))
19453 (stringp (setq r (nth 1 m)))
19454 (not (re-search-forward (nth 1 m) end t))))
19455 end)))
19457 (defun org-agenda-list-stuck-projects (&rest ignore)
19458 "Create agenda view for projects that are stuck.
19459 Stuck projects are project that have no next actions. For the definitions
19460 of what a project is and how to check if it stuck, customize the variable
19461 `org-stuck-projects'.
19462 MATCH is being ignored."
19463 (interactive)
19464 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19465 ;; FIXME: we could have used org-agenda-skip-if here.
19466 (org-agenda-overriding-header "List of stuck projects: ")
19467 (matcher (nth 0 org-stuck-projects))
19468 (todo (nth 1 org-stuck-projects))
19469 (todo-wds (if (member "*" todo)
19470 (progn
19471 (org-prepare-agenda-buffers (org-agenda-files))
19472 (org-delete-all
19473 org-done-keywords-for-agenda
19474 (copy-sequence org-todo-keywords-for-agenda)))
19475 todo))
19476 (todo-re (concat "^\\*+[ \t]+\\("
19477 (mapconcat 'identity todo-wds "\\|")
19478 "\\)\\>"))
19479 (tags (nth 2 org-stuck-projects))
19480 (tags-re (if (member "*" tags)
19481 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
19482 (concat "^\\*+ .*:\\("
19483 (mapconcat 'identity tags "\\|")
19484 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
19485 (gen-re (nth 3 org-stuck-projects))
19486 (re-list
19487 (delq nil
19488 (list
19489 (if todo todo-re)
19490 (if tags tags-re)
19491 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
19492 gen-re)))))
19493 (setq org-agenda-skip-regexp
19494 (if re-list
19495 (mapconcat 'identity re-list "\\|")
19496 (error "No information how to identify unstuck projects")))
19497 (org-tags-view nil matcher)
19498 (with-current-buffer org-agenda-buffer-name
19499 (setq org-agenda-redo-command
19500 '(org-agenda-list-stuck-projects
19501 (or current-prefix-arg org-last-arg))))))
19503 ;;; Diary integration
19505 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
19507 (defun org-get-entries-from-diary (date)
19508 "Get the (Emacs Calendar) diary entries for DATE."
19509 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
19510 (diary-display-hook '(fancy-diary-display))
19511 (pop-up-frames nil)
19512 (list-diary-entries-hook
19513 (cons 'org-diary-default-entry list-diary-entries-hook))
19514 (diary-file-name-prefix-function nil) ; turn this feature off
19515 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
19516 entries
19517 (org-disable-agenda-to-diary t))
19518 (save-excursion
19519 (save-window-excursion
19520 (funcall (if (fboundp 'diary-list-entries)
19521 'diary-list-entries 'list-diary-entries)
19522 date 1)))
19523 (if (not (get-buffer fancy-diary-buffer))
19524 (setq entries nil)
19525 (with-current-buffer fancy-diary-buffer
19526 (setq buffer-read-only nil)
19527 (if (zerop (buffer-size))
19528 ;; No entries
19529 (setq entries nil)
19530 ;; Omit the date and other unnecessary stuff
19531 (org-agenda-cleanup-fancy-diary)
19532 ;; Add prefix to each line and extend the text properties
19533 (if (zerop (buffer-size))
19534 (setq entries nil)
19535 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
19536 (set-buffer-modified-p nil)
19537 (kill-buffer fancy-diary-buffer)))
19538 (when entries
19539 (setq entries (org-split-string entries "\n"))
19540 (setq entries
19541 (mapcar
19542 (lambda (x)
19543 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
19544 ;; Extend the text properties to the beginning of the line
19545 (org-add-props x (text-properties-at (1- (length x)) x)
19546 'type "diary" 'date date))
19547 entries)))))
19549 (defun org-agenda-cleanup-fancy-diary ()
19550 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
19551 This gets rid of the date, the underline under the date, and
19552 the dummy entry installed by `org-mode' to ensure non-empty diary for each
19553 date. It also removes lines that contain only whitespace."
19554 (goto-char (point-min))
19555 (if (looking-at ".*?:[ \t]*")
19556 (progn
19557 (replace-match "")
19558 (re-search-forward "\n=+$" nil t)
19559 (replace-match "")
19560 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
19561 (re-search-forward "\n=+$" nil t)
19562 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
19563 (goto-char (point-min))
19564 (while (re-search-forward "^ +\n" nil t)
19565 (replace-match ""))
19566 (goto-char (point-min))
19567 (if (re-search-forward "^Org-mode dummy\n?" nil t)
19568 (replace-match "")))
19570 ;; Make sure entries from the diary have the right text properties.
19571 (eval-after-load "diary-lib"
19572 '(if (boundp 'diary-modify-entry-list-string-function)
19573 ;; We can rely on the hook, nothing to do
19575 ;; Hook not avaiable, must use advice to make this work
19576 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
19577 "Make the position visible."
19578 (if (and org-disable-agenda-to-diary ;; called from org-agenda
19579 (stringp string)
19580 buffer-file-name)
19581 (setq string (org-modify-diary-entry-string string))))))
19583 (defun org-modify-diary-entry-string (string)
19584 "Add text properties to string, allowing org-mode to act on it."
19585 (org-add-props string nil
19586 'mouse-face 'highlight
19587 'keymap org-agenda-keymap
19588 'help-echo (if buffer-file-name
19589 (format "mouse-2 or RET jump to diary file %s"
19590 (abbreviate-file-name buffer-file-name))
19592 'org-agenda-diary-link t
19593 'org-marker (org-agenda-new-marker (point-at-bol))))
19595 (defun org-diary-default-entry ()
19596 "Add a dummy entry to the diary.
19597 Needed to avoid empty dates which mess up holiday display."
19598 ;; Catch the error if dealing with the new add-to-diary-alist
19599 (when org-disable-agenda-to-diary
19600 (condition-case nil
19601 (add-to-diary-list original-date "Org-mode dummy" "")
19602 (error
19603 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
19605 ;;;###autoload
19606 (defun org-diary (&rest args)
19607 "Return diary information from org-files.
19608 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
19609 It accesses org files and extracts information from those files to be
19610 listed in the diary. The function accepts arguments specifying what
19611 items should be listed. The following arguments are allowed:
19613 :timestamp List the headlines of items containing a date stamp or
19614 date range matching the selected date. Deadlines will
19615 also be listed, on the expiration day.
19617 :sexp List entries resulting from diary-like sexps.
19619 :deadline List any deadlines past due, or due within
19620 `org-deadline-warning-days'. The listing occurs only
19621 in the diary for *today*, not at any other date. If
19622 an entry is marked DONE, it is no longer listed.
19624 :scheduled List all items which are scheduled for the given date.
19625 The diary for *today* also contains items which were
19626 scheduled earlier and are not yet marked DONE.
19628 :todo List all TODO items from the org-file. This may be a
19629 long list - so this is not turned on by default.
19630 Like deadlines, these entries only show up in the
19631 diary for *today*, not at any other date.
19633 The call in the diary file should look like this:
19635 &%%(org-diary) ~/path/to/some/orgfile.org
19637 Use a separate line for each org file to check. Or, if you omit the file name,
19638 all files listed in `org-agenda-files' will be checked automatically:
19640 &%%(org-diary)
19642 If you don't give any arguments (as in the example above), the default
19643 arguments (:deadline :scheduled :timestamp :sexp) are used.
19644 So the example above may also be written as
19646 &%%(org-diary :deadline :timestamp :sexp :scheduled)
19648 The function expects the lisp variables `entry' and `date' to be provided
19649 by the caller, because this is how the calendar works. Don't use this
19650 function from a program - use `org-agenda-get-day-entries' instead."
19651 (org-agenda-maybe-reset-markers)
19652 (org-compile-prefix-format 'agenda)
19653 (org-set-sorting-strategy 'agenda)
19654 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19655 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
19656 (list entry)
19657 (org-agenda-files t)))
19658 file rtn results)
19659 (org-prepare-agenda-buffers files)
19660 ;; If this is called during org-agenda, don't return any entries to
19661 ;; the calendar. Org Agenda will list these entries itself.
19662 (if org-disable-agenda-to-diary (setq files nil))
19663 (while (setq file (pop files))
19664 (setq rtn (apply 'org-agenda-get-day-entries file date args))
19665 (setq results (append results rtn)))
19666 (if results
19667 (concat (org-finalize-agenda-entries results) "\n"))))
19669 ;;; Agenda entry finders
19671 (defun org-agenda-get-day-entries (file date &rest args)
19672 "Does the work for `org-diary' and `org-agenda'.
19673 FILE is the path to a file to be checked for entries. DATE is date like
19674 the one returned by `calendar-current-date'. ARGS are symbols indicating
19675 which kind of entries should be extracted. For details about these, see
19676 the documentation of `org-diary'."
19677 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19678 (let* ((org-startup-folded nil)
19679 (org-startup-align-all-tables nil)
19680 (buffer (if (file-exists-p file)
19681 (org-get-agenda-file-buffer file)
19682 (error "No such file %s" file)))
19683 arg results rtn)
19684 (if (not buffer)
19685 ;; If file does not exist, make sure an error message ends up in diary
19686 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19687 (with-current-buffer buffer
19688 (unless (org-mode-p)
19689 (error "Agenda file %s is not in `org-mode'" file))
19690 (let ((case-fold-search nil))
19691 (save-excursion
19692 (save-restriction
19693 (if org-agenda-restrict
19694 (narrow-to-region org-agenda-restrict-begin
19695 org-agenda-restrict-end)
19696 (widen))
19697 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19698 (while (setq arg (pop args))
19699 (cond
19700 ((and (eq arg :todo)
19701 (equal date (calendar-current-date)))
19702 (setq rtn (org-agenda-get-todos))
19703 (setq results (append results rtn)))
19704 ((eq arg :timestamp)
19705 (setq rtn (org-agenda-get-blocks))
19706 (setq results (append results rtn))
19707 (setq rtn (org-agenda-get-timestamps))
19708 (setq results (append results rtn)))
19709 ((eq arg :sexp)
19710 (setq rtn (org-agenda-get-sexps))
19711 (setq results (append results rtn)))
19712 ((eq arg :scheduled)
19713 (setq rtn (org-agenda-get-scheduled))
19714 (setq results (append results rtn)))
19715 ((eq arg :closed)
19716 (setq rtn (org-agenda-get-closed))
19717 (setq results (append results rtn)))
19718 ((eq arg :deadline)
19719 (setq rtn (org-agenda-get-deadlines))
19720 (setq results (append results rtn))))))))
19721 results))))
19723 ;; FIXME: this works only if the cursor is *not* at the
19724 ;; beginning of the entry
19725 ;(defun org-entry-is-done-p ()
19726 ; "Is the current entry marked DONE?"
19727 ; (save-excursion
19728 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
19729 ; (looking-at org-nl-done-regexp))))
19731 (defun org-entry-is-todo-p ()
19732 (member (org-get-todo-state) org-not-done-keywords))
19734 (defun org-entry-is-done-p ()
19735 (member (org-get-todo-state) org-done-keywords))
19737 (defun org-get-todo-state ()
19738 (save-excursion
19739 (org-back-to-heading t)
19740 (and (looking-at org-todo-line-regexp)
19741 (match-end 2)
19742 (match-string 2))))
19744 (defun org-at-date-range-p (&optional inactive-ok)
19745 "Is the cursor inside a date range?"
19746 (interactive)
19747 (save-excursion
19748 (catch 'exit
19749 (let ((pos (point)))
19750 (skip-chars-backward "^[<\r\n")
19751 (skip-chars-backward "<[")
19752 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19753 (>= (match-end 0) pos)
19754 (throw 'exit t))
19755 (skip-chars-backward "^<[\r\n")
19756 (skip-chars-backward "<[")
19757 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19758 (>= (match-end 0) pos)
19759 (throw 'exit t)))
19760 nil)))
19762 (defun org-agenda-get-todos ()
19763 "Return the TODO information for agenda display."
19764 (let* ((props (list 'face nil
19765 'done-face 'org-done
19766 'org-not-done-regexp org-not-done-regexp
19767 'org-todo-regexp org-todo-regexp
19768 'mouse-face 'highlight
19769 'keymap org-agenda-keymap
19770 'help-echo
19771 (format "mouse-2 or RET jump to org file %s"
19772 (abbreviate-file-name buffer-file-name))))
19773 ;; FIXME: get rid of the \n at some point but watch out
19774 (regexp (concat "^\\*+[ \t]+\\("
19775 (if org-select-this-todo-keyword
19776 (if (equal org-select-this-todo-keyword "*")
19777 org-todo-regexp
19778 (concat "\\<\\("
19779 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19780 "\\)\\>"))
19781 org-not-done-regexp)
19782 "[^\n\r]*\\)"))
19783 marker priority category tags
19784 ee txt beg end)
19785 (goto-char (point-min))
19786 (while (re-search-forward regexp nil t)
19787 (catch :skip
19788 (save-match-data
19789 (beginning-of-line)
19790 (setq beg (point) end (progn (outline-next-heading) (point)))
19791 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
19792 (re-search-forward org-ts-regexp end t))
19793 (and org-agenda-todo-ignore-scheduled (goto-char beg)
19794 (re-search-forward org-scheduled-time-regexp end t))
19795 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19796 (re-search-forward org-deadline-time-regexp end t)
19797 (org-deadline-close (match-string 1))))
19798 (goto-char (1+ beg))
19799 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19800 (throw :skip nil)))
19801 (goto-char beg)
19802 (org-agenda-skip)
19803 (goto-char (match-beginning 1))
19804 (setq marker (org-agenda-new-marker (match-beginning 0))
19805 category (org-get-category)
19806 tags (org-get-tags-at (point))
19807 txt (org-format-agenda-item "" (match-string 1) category tags)
19808 priority (1+ (org-get-priority txt)))
19809 (org-add-props txt props
19810 'org-marker marker 'org-hd-marker marker
19811 'priority priority 'org-category category
19812 'type "todo")
19813 (push txt ee)
19814 (if org-agenda-todo-list-sublevels
19815 (goto-char (match-end 1))
19816 (org-end-of-subtree 'invisible))))
19817 (nreverse ee)))
19819 (defconst org-agenda-no-heading-message
19820 "No heading for this item in buffer or region.")
19822 (defun org-agenda-get-timestamps ()
19823 "Return the date stamp information for agenda display."
19824 (let* ((props (list 'face nil
19825 'org-not-done-regexp org-not-done-regexp
19826 'org-todo-regexp org-todo-regexp
19827 'mouse-face 'highlight
19828 'keymap org-agenda-keymap
19829 'help-echo
19830 (format "mouse-2 or RET jump to org file %s"
19831 (abbreviate-file-name buffer-file-name))))
19832 (d1 (calendar-absolute-from-gregorian date))
19833 (remove-re
19834 (concat
19835 (regexp-quote
19836 (format-time-string
19837 "<%Y-%m-%d"
19838 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19839 ".*?>"))
19840 (regexp
19841 (concat
19842 (regexp-quote
19843 (substring
19844 (format-time-string
19845 (car org-time-stamp-formats)
19846 (apply 'encode-time ; DATE bound by calendar
19847 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19848 0 11))
19849 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
19850 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
19851 marker hdmarker deadlinep scheduledp donep tmp priority category
19852 ee txt timestr tags b0 b3 e3)
19853 (goto-char (point-min))
19854 (while (re-search-forward regexp nil t)
19855 (setq b0 (match-beginning 0)
19856 b3 (match-beginning 3) e3 (match-end 3))
19857 (catch :skip
19858 (and (org-at-date-range-p) (throw :skip nil))
19859 (org-agenda-skip)
19860 (if (and (match-end 1)
19861 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
19862 (throw :skip nil))
19863 (if (and e3
19864 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
19865 (throw :skip nil))
19866 (setq marker (org-agenda-new-marker b0)
19867 category (org-get-category b0)
19868 tmp (buffer-substring (max (point-min)
19869 (- b0 org-ds-keyword-length))
19871 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19872 deadlinep (string-match org-deadline-regexp tmp)
19873 scheduledp (string-match org-scheduled-regexp tmp)
19874 donep (org-entry-is-done-p))
19875 (if (or scheduledp deadlinep) (throw :skip t))
19876 (if (string-match ">" timestr)
19877 ;; substring should only run to end of time stamp
19878 (setq timestr (substring timestr 0 (match-end 0))))
19879 (save-excursion
19880 (if (re-search-backward "^\\*+ " nil t)
19881 (progn
19882 (goto-char (match-beginning 0))
19883 (setq hdmarker (org-agenda-new-marker)
19884 tags (org-get-tags-at))
19885 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19886 (setq txt (org-format-agenda-item
19887 nil (match-string 1) category tags timestr nil
19888 remove-re)))
19889 (setq txt org-agenda-no-heading-message))
19890 (setq priority (org-get-priority txt))
19891 (org-add-props txt props
19892 'org-marker marker 'org-hd-marker hdmarker)
19893 (org-add-props txt nil 'priority priority
19894 'org-category category 'date date
19895 'type "timestamp")
19896 (push txt ee))
19897 (outline-next-heading)))
19898 (nreverse ee)))
19900 (defun org-agenda-get-sexps ()
19901 "Return the sexp information for agenda display."
19902 (require 'diary-lib)
19903 (let* ((props (list 'face nil
19904 'mouse-face 'highlight
19905 'keymap org-agenda-keymap
19906 'help-echo
19907 (format "mouse-2 or RET jump to org file %s"
19908 (abbreviate-file-name buffer-file-name))))
19909 (regexp "^&?%%(")
19910 marker category ee txt tags entry result beg b sexp sexp-entry)
19911 (goto-char (point-min))
19912 (while (re-search-forward regexp nil t)
19913 (catch :skip
19914 (org-agenda-skip)
19915 (setq beg (match-beginning 0))
19916 (goto-char (1- (match-end 0)))
19917 (setq b (point))
19918 (forward-sexp 1)
19919 (setq sexp (buffer-substring b (point)))
19920 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
19921 (org-trim (match-string 1))
19922 ""))
19923 (setq result (org-diary-sexp-entry sexp sexp-entry date))
19924 (when result
19925 (setq marker (org-agenda-new-marker beg)
19926 category (org-get-category beg))
19928 (if (string-match "\\S-" result)
19929 (setq txt result)
19930 (setq txt "SEXP entry returned empty string"))
19932 (setq txt (org-format-agenda-item
19933 "" txt category tags 'time))
19934 (org-add-props txt props 'org-marker marker)
19935 (org-add-props txt nil
19936 'org-category category 'date date
19937 'type "sexp")
19938 (push txt ee))))
19939 (nreverse ee)))
19941 (defun org-agenda-get-closed ()
19942 "Return the logged TODO entries for agenda display."
19943 (let* ((props (list 'mouse-face 'highlight
19944 'org-not-done-regexp org-not-done-regexp
19945 'org-todo-regexp org-todo-regexp
19946 'keymap org-agenda-keymap
19947 'help-echo
19948 (format "mouse-2 or RET jump to org file %s"
19949 (abbreviate-file-name buffer-file-name))))
19950 (regexp (concat
19951 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
19952 (regexp-quote
19953 (substring
19954 (format-time-string
19955 (car org-time-stamp-formats)
19956 (apply 'encode-time ; DATE bound by calendar
19957 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19958 1 11))))
19959 marker hdmarker priority category tags closedp
19960 ee txt timestr)
19961 (goto-char (point-min))
19962 (while (re-search-forward regexp nil t)
19963 (catch :skip
19964 (org-agenda-skip)
19965 (setq marker (org-agenda-new-marker (match-beginning 0))
19966 closedp (equal (match-string 1) org-closed-string)
19967 category (org-get-category (match-beginning 0))
19968 timestr (buffer-substring (match-beginning 0) (point-at-eol))
19969 ;; donep (org-entry-is-done-p)
19971 (if (string-match "\\]" timestr)
19972 ;; substring should only run to end of time stamp
19973 (setq timestr (substring timestr 0 (match-end 0))))
19974 (save-excursion
19975 (if (re-search-backward "^\\*+ " nil t)
19976 (progn
19977 (goto-char (match-beginning 0))
19978 (setq hdmarker (org-agenda-new-marker)
19979 tags (org-get-tags-at))
19980 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19981 (setq txt (org-format-agenda-item
19982 (if closedp "Closed: " "Clocked: ")
19983 (match-string 1) category tags timestr)))
19984 (setq txt org-agenda-no-heading-message))
19985 (setq priority 100000)
19986 (org-add-props txt props
19987 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
19988 'priority priority 'org-category category
19989 'type "closed" 'date date
19990 'undone-face 'org-warning 'done-face 'org-done)
19991 (push txt ee))
19992 (outline-next-heading)))
19993 (nreverse ee)))
19995 (defun org-agenda-get-deadlines ()
19996 "Return the deadline information for agenda display."
19997 (let* ((props (list 'mouse-face 'highlight
19998 'org-not-done-regexp org-not-done-regexp
19999 'org-todo-regexp org-todo-regexp
20000 'keymap org-agenda-keymap
20001 'help-echo
20002 (format "mouse-2 or RET jump to org file %s"
20003 (abbreviate-file-name buffer-file-name))))
20004 (regexp org-deadline-time-regexp)
20005 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20006 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20007 d2 diff dfrac wdays pos pos1 category tags
20008 ee txt head face s upcomingp donep timestr)
20009 (goto-char (point-min))
20010 (while (re-search-forward regexp nil t)
20011 (catch :skip
20012 (org-agenda-skip)
20013 (setq s (match-string 1)
20014 pos (1- (match-beginning 1))
20015 d2 (org-time-string-to-absolute (match-string 1) d1)
20016 diff (- d2 d1)
20017 wdays (org-get-wdays s)
20018 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20019 upcomingp (and todayp (> diff 0)))
20020 ;; When to show a deadline in the calendar:
20021 ;; If the expiration is within wdays warning time.
20022 ;; Past-due deadlines are only shown on the current date
20023 (if (or (and (<= diff wdays)
20024 (and todayp (not org-agenda-only-exact-dates)))
20025 (= diff 0))
20026 (save-excursion
20027 (setq category (org-get-category))
20028 (if (re-search-backward "^\\*+[ \t]+" nil t)
20029 (progn
20030 (goto-char (match-end 0))
20031 (setq pos1 (match-beginning 0))
20032 (setq tags (org-get-tags-at pos1))
20033 (setq head (buffer-substring-no-properties
20034 (point)
20035 (progn (skip-chars-forward "^\r\n")
20036 (point))))
20037 (setq donep (string-match org-looking-at-done-regexp head))
20038 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20039 (setq timestr
20040 (concat (substring s (match-beginning 1)) " "))
20041 (setq timestr 'time))
20042 (if (and donep
20043 (or org-agenda-skip-deadline-if-done
20044 (not (= diff 0))))
20045 (setq txt nil)
20046 (setq txt (org-format-agenda-item
20047 (if (= diff 0)
20048 (car org-agenda-deadline-leaders)
20049 (format (nth 1 org-agenda-deadline-leaders)
20050 diff))
20051 head category tags timestr))))
20052 (setq txt org-agenda-no-heading-message))
20053 (when txt
20054 (setq face (org-agenda-deadline-face dfrac))
20055 (org-add-props txt props
20056 'org-marker (org-agenda-new-marker pos)
20057 'org-hd-marker (org-agenda-new-marker pos1)
20058 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20059 (org-get-priority txt))
20060 'org-category category
20061 'type (if upcomingp "upcoming-deadline" "deadline")
20062 'date (if upcomingp date d2)
20063 'face (if donep 'org-done face)
20064 'undone-face face 'done-face 'org-done)
20065 (push txt ee))))))
20066 (nreverse ee)))
20068 (defun org-agenda-deadline-face (fraction)
20069 "Return the face to displaying a deadline item.
20070 FRACTION is what fraction of the head-warning time has passed."
20071 (let ((faces org-agenda-deadline-faces) f)
20072 (catch 'exit
20073 (while (setq f (pop faces))
20074 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20076 (defun org-agenda-get-scheduled ()
20077 "Return the scheduled information for agenda display."
20078 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20079 'org-todo-regexp org-todo-regexp
20080 'done-face 'org-done
20081 'mouse-face 'highlight
20082 'keymap org-agenda-keymap
20083 'help-echo
20084 (format "mouse-2 or RET jump to org file %s"
20085 (abbreviate-file-name buffer-file-name))))
20086 (regexp org-scheduled-time-regexp)
20087 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20088 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20089 d2 diff pos pos1 category tags
20090 ee txt head pastschedp donep face timestr s)
20091 (goto-char (point-min))
20092 (while (re-search-forward regexp nil t)
20093 (catch :skip
20094 (org-agenda-skip)
20095 (setq s (match-string 1)
20096 pos (1- (match-beginning 1))
20097 d2 (org-time-string-to-absolute (match-string 1) d1)
20098 diff (- d2 d1))
20099 (setq pastschedp (and todayp (< diff 0)))
20100 ;; When to show a scheduled item in the calendar:
20101 ;; If it is on or past the date.
20102 (if (or (and (< diff 0)
20103 (and todayp (not org-agenda-only-exact-dates)))
20104 (= diff 0))
20105 (save-excursion
20106 (setq category (org-get-category))
20107 (if (re-search-backward "^\\*+[ \t]+" nil t)
20108 (progn
20109 (goto-char (match-end 0))
20110 (setq pos1 (match-beginning 0))
20111 (setq tags (org-get-tags-at))
20112 (setq head (buffer-substring-no-properties
20113 (point)
20114 (progn (skip-chars-forward "^\r\n") (point))))
20115 (setq donep (string-match org-looking-at-done-regexp head))
20116 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20117 (setq timestr
20118 (concat (substring s (match-beginning 1)) " "))
20119 (setq timestr 'time))
20120 (if (and donep
20121 (or org-agenda-skip-scheduled-if-done
20122 (not (= diff 0))))
20123 (setq txt nil)
20124 (setq txt (org-format-agenda-item
20125 (if (= diff 0)
20126 (car org-agenda-scheduled-leaders)
20127 (format (nth 1 org-agenda-scheduled-leaders)
20128 (- 1 diff)))
20129 head category tags timestr))))
20130 (setq txt org-agenda-no-heading-message))
20131 (when txt
20132 (setq face (if pastschedp
20133 'org-scheduled-previously
20134 'org-scheduled-today))
20135 (org-add-props txt props
20136 'undone-face face
20137 'face (if donep 'org-done face)
20138 'org-marker (org-agenda-new-marker pos)
20139 'org-hd-marker (org-agenda-new-marker pos1)
20140 'type (if pastschedp "past-scheduled" "scheduled")
20141 'date (if pastschedp d2 date)
20142 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20143 'org-category category)
20144 (push txt ee))))))
20145 (nreverse ee)))
20147 (defun org-agenda-get-blocks ()
20148 "Return the date-range information for agenda display."
20149 (let* ((props (list 'face nil
20150 'org-not-done-regexp org-not-done-regexp
20151 'org-todo-regexp org-todo-regexp
20152 'mouse-face 'highlight
20153 'keymap org-agenda-keymap
20154 'help-echo
20155 (format "mouse-2 or RET jump to org file %s"
20156 (abbreviate-file-name buffer-file-name))))
20157 (regexp org-tr-regexp)
20158 (d0 (calendar-absolute-from-gregorian date))
20159 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
20160 (goto-char (point-min))
20161 (while (re-search-forward regexp nil t)
20162 (catch :skip
20163 (org-agenda-skip)
20164 (setq pos (point))
20165 (setq timestr (match-string 0)
20166 s1 (match-string 1)
20167 s2 (match-string 2)
20168 d1 (time-to-days (org-time-string-to-time s1))
20169 d2 (time-to-days (org-time-string-to-time s2)))
20170 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20171 ;; Only allow days between the limits, because the normal
20172 ;; date stamps will catch the limits.
20173 (save-excursion
20174 (setq marker (org-agenda-new-marker (point)))
20175 (setq category (org-get-category))
20176 (if (re-search-backward "^\\*+ " nil t)
20177 (progn
20178 (goto-char (match-beginning 0))
20179 (setq hdmarker (org-agenda-new-marker (point)))
20180 (setq tags (org-get-tags-at))
20181 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20182 (setq txt (org-format-agenda-item
20183 (format (if (= d1 d2) "" "(%d/%d): ")
20184 (1+ (- d0 d1)) (1+ (- d2 d1)))
20185 (match-string 1) category tags
20186 (if (= d0 d1) timestr))))
20187 (setq txt org-agenda-no-heading-message))
20188 (org-add-props txt props
20189 'org-marker marker 'org-hd-marker hdmarker
20190 'type "block" 'date date
20191 'priority (org-get-priority txt) 'org-category category)
20192 (push txt ee)))
20193 (goto-char pos)))
20194 ;; Sort the entries by expiration date.
20195 (nreverse ee)))
20197 ;;; Agenda presentation and sorting
20199 (defconst org-plain-time-of-day-regexp
20200 (concat
20201 "\\(\\<[012]?[0-9]"
20202 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20203 "\\(--?"
20204 "\\(\\<[012]?[0-9]"
20205 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20206 "\\)?")
20207 "Regular expression to match a plain time or time range.
20208 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20209 groups carry important information:
20210 0 the full match
20211 1 the first time, range or not
20212 8 the second time, if it is a range.")
20214 (defconst org-plain-time-extension-regexp
20215 (concat
20216 "\\(\\<[012]?[0-9]"
20217 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20218 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20219 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20220 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20221 groups carry important information:
20222 0 the full match
20223 7 hours of duration
20224 9 minutes of duration")
20226 (defconst org-stamp-time-of-day-regexp
20227 (concat
20228 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20229 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20230 "\\(--?"
20231 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20232 "Regular expression to match a timestamp time or time range.
20233 After a match, the following groups carry important information:
20234 0 the full match
20235 1 date plus weekday, for backreferencing to make sure both times on same day
20236 2 the first time, range or not
20237 4 the second time, if it is a range.")
20239 (defvar org-prefix-has-time nil
20240 "A flag, set by `org-compile-prefix-format'.
20241 The flag is set if the currently compiled format contains a `%t'.")
20242 (defvar org-prefix-has-tag nil
20243 "A flag, set by `org-compile-prefix-format'.
20244 The flag is set if the currently compiled format contains a `%T'.")
20246 (defun org-format-agenda-item (extra txt &optional category tags dotime
20247 noprefix remove-re)
20248 "Format TXT to be inserted into the agenda buffer.
20249 In particular, it adds the prefix and corresponding text properties. EXTRA
20250 must be a string and replaces the `%s' specifier in the prefix format.
20251 CATEGORY (string, symbol or nil) may be used to overrule the default
20252 category taken from local variable or file name. It will replace the `%c'
20253 specifier in the format. DOTIME, when non-nil, indicates that a
20254 time-of-day should be extracted from TXT for sorting of this entry, and for
20255 the `%t' specifier in the format. When DOTIME is a string, this string is
20256 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20257 only the correctly processes TXT should be returned - this is used by
20258 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20259 Any match of REMOVE-RE will be removed from TXT."
20260 (save-match-data
20261 ;; Diary entries sometimes have extra whitespace at the beginning
20262 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20263 (let* ((category (or category
20264 org-category
20265 (if buffer-file-name
20266 (file-name-sans-extension
20267 (file-name-nondirectory buffer-file-name))
20268 "")))
20269 (tag (if tags (nth (1- (length tags)) tags) ""))
20270 time ; time and tag are needed for the eval of the prefix format
20271 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20272 (time-of-day (and dotime (org-get-time-of-day ts)))
20273 stamp plain s0 s1 s2 rtn srp)
20274 (when (and dotime time-of-day org-prefix-has-time)
20275 ;; Extract starting and ending time and move them to prefix
20276 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20277 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20278 (setq s0 (match-string 0 ts)
20279 srp (and stamp (match-end 3))
20280 s1 (match-string (if plain 1 2) ts)
20281 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20283 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20284 ;; them, we might want to remove them there to avoid duplication.
20285 ;; The user can turn this off with a variable.
20286 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20287 (string-match (concat (regexp-quote s0) " *") txt)
20288 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20289 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20290 (= (match-beginning 0) 0)
20292 (setq txt (replace-match "" nil nil txt))))
20293 ;; Normalize the time(s) to 24 hour
20294 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20295 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20297 (when (and s1 (not s2) org-agenda-default-appointment-duration
20298 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20299 (let ((m (+ (string-to-number (match-string 2 s1))
20300 (* 60 (string-to-number (match-string 1 s1)))
20301 org-agenda-default-appointment-duration))
20303 (setq h (/ m 60) m (- m (* h 60)))
20304 (setq s2 (format "%02d:%02d" h m))))
20306 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20307 txt)
20308 ;; Tags are in the string
20309 (if (or (eq org-agenda-remove-tags t)
20310 (and org-agenda-remove-tags
20311 org-prefix-has-tag))
20312 (setq txt (replace-match "" t t txt))
20313 (setq txt (replace-match
20314 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20315 (match-string 2 txt))
20316 t t txt))))
20318 (when remove-re
20319 (while (string-match remove-re txt)
20320 (setq txt (replace-match "" t t txt))))
20322 ;; Create the final string
20323 (if noprefix
20324 (setq rtn txt)
20325 ;; Prepare the variables needed in the eval of the compiled format
20326 (setq time (cond (s2 (concat s1 "-" s2))
20327 (s1 (concat s1 "......"))
20328 (t ""))
20329 extra (or extra "")
20330 category (if (symbolp category) (symbol-name category) category))
20331 ;; Evaluate the compiled format
20332 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20334 ;; And finally add the text properties
20335 (org-add-props rtn nil
20336 'org-category (downcase category) 'tags tags
20337 'org-highest-priority org-highest-priority
20338 'org-lowest-priority org-lowest-priority
20339 'prefix-length (- (length rtn) (length txt))
20340 'time-of-day time-of-day
20341 'txt txt
20342 'time time
20343 'extra extra
20344 'dotime dotime))))
20346 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20347 (defvar org-agenda-sorting-strategy-selected nil)
20349 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20350 (catch 'exit
20351 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20352 ((and todayp (member 'today (car org-agenda-time-grid))))
20353 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20354 ((member 'weekly (car org-agenda-time-grid)))
20355 (t (throw 'exit list)))
20356 (let* ((have (delq nil (mapcar
20357 (lambda (x) (get-text-property 1 'time-of-day x))
20358 list)))
20359 (string (nth 1 org-agenda-time-grid))
20360 (gridtimes (nth 2 org-agenda-time-grid))
20361 (req (car org-agenda-time-grid))
20362 (remove (member 'remove-match req))
20363 new time)
20364 (if (and (member 'require-timed req) (not have))
20365 ;; don't show empty grid
20366 (throw 'exit list))
20367 (while (setq time (pop gridtimes))
20368 (unless (and remove (member time have))
20369 (setq time (int-to-string time))
20370 (push (org-format-agenda-item
20371 nil string "" nil
20372 (concat (substring time 0 -2) ":" (substring time -2)))
20373 new)
20374 (put-text-property
20375 1 (length (car new)) 'face 'org-time-grid (car new))))
20376 (if (member 'time-up org-agenda-sorting-strategy-selected)
20377 (append new list)
20378 (append list new)))))
20380 (defun org-compile-prefix-format (key)
20381 "Compile the prefix format into a Lisp form that can be evaluated.
20382 The resulting form is returned and stored in the variable
20383 `org-prefix-format-compiled'."
20384 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20385 (let ((s (cond
20386 ((stringp org-agenda-prefix-format)
20387 org-agenda-prefix-format)
20388 ((assq key org-agenda-prefix-format)
20389 (cdr (assq key org-agenda-prefix-format)))
20390 (t " %-12:c%?-12t% s")))
20391 (start 0)
20392 varform vars var e c f opt)
20393 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20394 s start)
20395 (setq var (cdr (assoc (match-string 4 s)
20396 '(("c" . category) ("t" . time) ("s" . extra)
20397 ("T" . tag))))
20398 c (or (match-string 3 s) "")
20399 opt (match-beginning 1)
20400 start (1+ (match-beginning 0)))
20401 (if (equal var 'time) (setq org-prefix-has-time t))
20402 (if (equal var 'tag) (setq org-prefix-has-tag t))
20403 (setq f (concat "%" (match-string 2 s) "s"))
20404 (if opt
20405 (setq varform
20406 `(if (equal "" ,var)
20408 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20409 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20410 (setq s (replace-match "%s" t nil s))
20411 (push varform vars))
20412 (setq vars (nreverse vars))
20413 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20415 (defun org-set-sorting-strategy (key)
20416 (if (symbolp (car org-agenda-sorting-strategy))
20417 ;; the old format
20418 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20419 (setq org-agenda-sorting-strategy-selected
20420 (or (cdr (assq key org-agenda-sorting-strategy))
20421 (cdr (assq 'agenda org-agenda-sorting-strategy))
20422 '(time-up category-keep priority-down)))))
20424 (defun org-get-time-of-day (s &optional string mod24)
20425 "Check string S for a time of day.
20426 If found, return it as a military time number between 0 and 2400.
20427 If not found, return nil.
20428 The optional STRING argument forces conversion into a 5 character wide string
20429 HH:MM."
20430 (save-match-data
20431 (when
20432 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20433 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20434 (let* ((h (string-to-number (match-string 1 s)))
20435 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20436 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20437 (am-p (equal ampm "am"))
20438 (h1 (cond ((not ampm) h)
20439 ((= h 12) (if am-p 0 12))
20440 (t (+ h (if am-p 0 12)))))
20441 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20442 (mod h1 24) h1))
20443 (t0 (+ (* 100 h2) m))
20444 (t1 (concat (if (>= h1 24) "+" " ")
20445 (if (< t0 100) "0" "")
20446 (if (< t0 10) "0" "")
20447 (int-to-string t0))))
20448 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20450 (defun org-finalize-agenda-entries (list &optional nosort)
20451 "Sort and concatenate the agenda items."
20452 (setq list (mapcar 'org-agenda-highlight-todo list))
20453 (if nosort
20454 list
20455 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20457 (defun org-agenda-highlight-todo (x)
20458 (let (re pl)
20459 (if (eq x 'line)
20460 (save-excursion
20461 (beginning-of-line 1)
20462 (setq re (get-text-property (point) 'org-todo-regexp))
20463 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20464 (and (looking-at (concat "[ \t]*\\.*" re))
20465 (add-text-properties (match-beginning 0) (match-end 0)
20466 (list 'face (org-get-todo-face 0)))))
20467 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20468 pl (get-text-property 0 'prefix-length x))
20469 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20470 (add-text-properties
20471 (or (match-end 1) (match-end 0)) (match-end 0)
20472 (list 'face (org-get-todo-face (match-string 2 x)))
20474 x)))
20476 (defsubst org-cmp-priority (a b)
20477 "Compare the priorities of string A and B."
20478 (let ((pa (or (get-text-property 1 'priority a) 0))
20479 (pb (or (get-text-property 1 'priority b) 0)))
20480 (cond ((> pa pb) +1)
20481 ((< pa pb) -1)
20482 (t nil))))
20484 (defsubst org-cmp-category (a b)
20485 "Compare the string values of categories of strings A and B."
20486 (let ((ca (or (get-text-property 1 'org-category a) ""))
20487 (cb (or (get-text-property 1 'org-category b) "")))
20488 (cond ((string-lessp ca cb) -1)
20489 ((string-lessp cb ca) +1)
20490 (t nil))))
20492 (defsubst org-cmp-tag (a b)
20493 "Compare the string values of categories of strings A and B."
20494 (let ((ta (car (last (get-text-property 1 'tags a))))
20495 (tb (car (last (get-text-property 1 'tags b)))))
20496 (cond ((not ta) +1)
20497 ((not tb) -1)
20498 ((string-lessp ta tb) -1)
20499 ((string-lessp tb ta) +1)
20500 (t nil))))
20502 (defsubst org-cmp-time (a b)
20503 "Compare the time-of-day values of strings A and B."
20504 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
20505 (ta (or (get-text-property 1 'time-of-day a) def))
20506 (tb (or (get-text-property 1 'time-of-day b) def)))
20507 (cond ((< ta tb) -1)
20508 ((< tb ta) +1)
20509 (t nil))))
20511 (defun org-entries-lessp (a b)
20512 "Predicate for sorting agenda entries."
20513 ;; The following variables will be used when the form is evaluated.
20514 ;; So even though the compiler complains, keep them.
20515 (let* ((time-up (org-cmp-time a b))
20516 (time-down (if time-up (- time-up) nil))
20517 (priority-up (org-cmp-priority a b))
20518 (priority-down (if priority-up (- priority-up) nil))
20519 (category-up (org-cmp-category a b))
20520 (category-down (if category-up (- category-up) nil))
20521 (category-keep (if category-up +1 nil))
20522 (tag-up (org-cmp-tag a b))
20523 (tag-down (if tag-up (- tag-up) nil)))
20524 (cdr (assoc
20525 (eval (cons 'or org-agenda-sorting-strategy-selected))
20526 '((-1 . t) (1 . nil) (nil . nil))))))
20528 ;;; Agenda commands
20530 (defun org-agenda-check-type (error &rest types)
20531 "Check if agenda buffer is of allowed type.
20532 If ERROR is non-nil, throw an error, otherwise just return nil."
20533 (if (memq org-agenda-type types)
20535 (if error
20536 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
20537 nil)))
20539 (defun org-agenda-quit ()
20540 "Exit agenda by removing the window or the buffer."
20541 (interactive)
20542 (let ((buf (current-buffer)))
20543 (if (not (one-window-p)) (delete-window))
20544 (kill-buffer buf)
20545 (org-agenda-maybe-reset-markers 'force)
20546 (org-columns-remove-overlays))
20547 ;; Maybe restore the pre-agenda window configuration.
20548 (and org-agenda-restore-windows-after-quit
20549 (not (eq org-agenda-window-setup 'other-frame))
20550 org-pre-agenda-window-conf
20551 (set-window-configuration org-pre-agenda-window-conf)))
20553 (defun org-agenda-exit ()
20554 "Exit agenda by removing the window or the buffer.
20555 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
20556 Org-mode buffers visited directly by the user will not be touched."
20557 (interactive)
20558 (org-release-buffers org-agenda-new-buffers)
20559 (setq org-agenda-new-buffers nil)
20560 (org-agenda-quit))
20562 (defun org-save-all-org-buffers ()
20563 "Save all Org-mode buffers without user confirmation."
20564 (interactive)
20565 (message "Saving all Org-mode buffers...")
20566 (save-some-buffers t 'org-mode-p)
20567 (message "Saving all Org-mode buffers... done"))
20569 (defun org-agenda-redo ()
20570 "Rebuild Agenda.
20571 When this is the global TODO list, a prefix argument will be interpreted."
20572 (interactive)
20573 (let* ((org-agenda-keep-modes t)
20574 (line (org-current-line))
20575 (window-line (- line (org-current-line (window-start))))
20576 (lprops (get 'org-agenda-redo-command 'org-lprops)))
20577 (message "Rebuilding agenda buffer...")
20578 (org-let lprops '(eval org-agenda-redo-command))
20579 (setq org-agenda-undo-list nil
20580 org-agenda-pending-undo-list nil)
20581 (message "Rebuilding agenda buffer...done")
20582 (goto-line line)
20583 (recenter window-line)))
20585 (defun org-agenda-goto-date (date)
20586 "Jump to DATE in agenda."
20587 (interactive (list (org-read-date)))
20588 (org-agenda-list nil date))
20590 (defun org-agenda-goto-today ()
20591 "Go to today."
20592 (interactive)
20593 (org-agenda-check-type t 'timeline 'agenda)
20594 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
20595 (cond
20596 (tdpos (goto-char tdpos))
20597 ((eq org-agenda-type 'agenda)
20598 (let* ((sd (time-to-days (current-time)))
20599 (comp (org-agenda-compute-time-span sd org-agenda-span))
20600 (org-agenda-overriding-arguments org-agenda-last-arguments))
20601 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
20602 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
20603 (org-agenda-redo)
20604 (org-agenda-find-same-or-today-or-agenda)))
20605 (t (error "Cannot find today")))))
20607 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
20608 (goto-char
20609 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
20610 (text-property-any (point-min) (point-max) 'org-today t)
20611 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
20612 (point-min))))
20614 (defun org-agenda-later (arg)
20615 "Go forward in time by thee current span.
20616 With prefix ARG, go forward that many times the current span."
20617 (interactive "p")
20618 (org-agenda-check-type t 'agenda)
20619 (let* ((span org-agenda-span)
20620 (sd org-starting-day)
20621 (greg (calendar-gregorian-from-absolute sd))
20622 (cnt (get-text-property (point) 'org-day-cnt))
20623 greg2 nd)
20624 (cond
20625 ((eq span 'day)
20626 (setq sd (+ arg sd) nd 1))
20627 ((eq span 'week)
20628 (setq sd (+ (* 7 arg) sd) nd 7))
20629 ((eq span 'month)
20630 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
20631 sd (calendar-absolute-from-gregorian greg2))
20632 (setcar greg2 (1+ (car greg2)))
20633 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
20634 ((eq span 'year)
20635 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
20636 sd (calendar-absolute-from-gregorian greg2))
20637 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
20638 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
20639 (let ((org-agenda-overriding-arguments
20640 (list (car org-agenda-last-arguments) sd nd t)))
20641 (org-agenda-redo)
20642 (org-agenda-find-same-or-today-or-agenda cnt))))
20644 (defun org-agenda-earlier (arg)
20645 "Go backward in time by the current span.
20646 With prefix ARG, go backward that many times the current span."
20647 (interactive "p")
20648 (org-agenda-later (- arg)))
20650 (defun org-agenda-day-view ()
20651 "Switch to daily view for agenda."
20652 (interactive)
20653 (setq org-agenda-ndays 1)
20654 (org-agenda-change-time-span 'day))
20655 (defun org-agenda-week-view ()
20656 "Switch to daily view for agenda."
20657 (interactive)
20658 (setq org-agenda-ndays 7)
20659 (org-agenda-change-time-span 'week))
20660 (defun org-agenda-month-view ()
20661 "Switch to daily view for agenda."
20662 (interactive)
20663 (org-agenda-change-time-span 'month))
20664 (defun org-agenda-year-view ()
20665 "Switch to daily view for agenda."
20666 (interactive)
20667 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
20668 (org-agenda-change-time-span 'year)
20669 (error "Abort")))
20671 (defun org-agenda-change-time-span (span)
20672 "Change the agenda view to SPAN.
20673 SPAN may be `day', `week', `month', `year'."
20674 (org-agenda-check-type t 'agenda)
20675 (if (equal org-agenda-span span)
20676 (error "Viewing span is already \"%s\"" span))
20677 (let* ((sd (or (get-text-property (point) 'day)
20678 org-starting-day))
20679 (computed (org-agenda-compute-time-span sd span))
20680 (org-agenda-overriding-arguments
20681 (list (car org-agenda-last-arguments)
20682 (car computed) (cdr computed) t)))
20683 (org-agenda-redo)
20684 (org-agenda-find-same-or-today-or-agenda))
20685 (org-agenda-set-mode-name)
20686 (message "Switched to %s view" span))
20688 (defun org-agenda-compute-time-span (sd span)
20689 "Compute starting date and number of days for agenda.
20690 SPAN may be `day', `week', `month', `year'. The return value
20691 is a cons cell with the starting date and the number of days,
20692 so that the date SD will be in that range."
20693 (let* ((greg (calendar-gregorian-from-absolute sd))
20695 (cond
20696 ((eq span 'day)
20697 (setq nd 1))
20698 ((eq span 'week)
20699 (let* ((nt (calendar-day-of-week
20700 (calendar-gregorian-from-absolute sd)))
20701 (d (if org-agenda-start-on-weekday
20702 (- nt org-agenda-start-on-weekday)
20703 0)))
20704 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20705 (setq nd 7)))
20706 ((eq span 'month)
20707 (setq sd (calendar-absolute-from-gregorian
20708 (list (car greg) 1 (nth 2 greg)))
20709 nd (- (calendar-absolute-from-gregorian
20710 (list (1+ (car greg)) 1 (nth 2 greg)))
20711 sd)))
20712 ((eq span 'year)
20713 (setq sd (calendar-absolute-from-gregorian
20714 (list 1 1 (nth 2 greg)))
20715 nd (- (calendar-absolute-from-gregorian
20716 (list 1 1 (1+ (nth 2 greg))))
20717 sd))))
20718 (cons sd nd)))
20720 ;; FIXME: does not work if user makes date format that starts with a blank
20721 (defun org-agenda-next-date-line (&optional arg)
20722 "Jump to the next line indicating a date in agenda buffer."
20723 (interactive "p")
20724 (org-agenda-check-type t 'agenda 'timeline)
20725 (beginning-of-line 1)
20726 (if (looking-at "^\\S-") (forward-char 1))
20727 (if (not (re-search-forward "^\\S-" nil t arg))
20728 (progn
20729 (backward-char 1)
20730 (error "No next date after this line in this buffer")))
20731 (goto-char (match-beginning 0)))
20733 (defun org-agenda-previous-date-line (&optional arg)
20734 "Jump to the previous line indicating a date in agenda buffer."
20735 (interactive "p")
20736 (org-agenda-check-type t 'agenda 'timeline)
20737 (beginning-of-line 1)
20738 (if (not (re-search-backward "^\\S-" nil t arg))
20739 (error "No previous date before this line in this buffer")))
20741 ;; Initialize the highlight
20742 (defvar org-hl (org-make-overlay 1 1))
20743 (org-overlay-put org-hl 'face 'highlight)
20745 (defun org-highlight (begin end &optional buffer)
20746 "Highlight a region with overlay."
20747 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20748 org-hl begin end (or buffer (current-buffer))))
20750 (defun org-unhighlight ()
20751 "Detach overlay INDEX."
20752 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20754 ;; FIXME this is currently not used.
20755 (defun org-highlight-until-next-command (beg end &optional buffer)
20756 (org-highlight beg end buffer)
20757 (add-hook 'pre-command-hook 'org-unhighlight-once))
20758 (defun org-unhighlight-once ()
20759 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20760 (org-unhighlight))
20762 (defun org-agenda-follow-mode ()
20763 "Toggle follow mode in an agenda buffer."
20764 (interactive)
20765 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20766 (org-agenda-set-mode-name)
20767 (message "Follow mode is %s"
20768 (if org-agenda-follow-mode "on" "off")))
20770 (defun org-agenda-log-mode ()
20771 "Toggle log mode in an agenda buffer."
20772 (interactive)
20773 (org-agenda-check-type t 'agenda 'timeline)
20774 (setq org-agenda-show-log (not org-agenda-show-log))
20775 (org-agenda-set-mode-name)
20776 (org-agenda-redo)
20777 (message "Log mode is %s"
20778 (if org-agenda-show-log "on" "off")))
20780 (defun org-agenda-toggle-diary ()
20781 "Toggle diary inclusion in an agenda buffer."
20782 (interactive)
20783 (org-agenda-check-type t 'agenda)
20784 (setq org-agenda-include-diary (not org-agenda-include-diary))
20785 (org-agenda-redo)
20786 (org-agenda-set-mode-name)
20787 (message "Diary inclusion turned %s"
20788 (if org-agenda-include-diary "on" "off")))
20790 (defun org-agenda-toggle-time-grid ()
20791 "Toggle time grid in an agenda buffer."
20792 (interactive)
20793 (org-agenda-check-type t 'agenda)
20794 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20795 (org-agenda-redo)
20796 (org-agenda-set-mode-name)
20797 (message "Time-grid turned %s"
20798 (if org-agenda-use-time-grid "on" "off")))
20800 (defun org-agenda-set-mode-name ()
20801 "Set the mode name to indicate all the small mode settings."
20802 (setq mode-name
20803 (concat "Org-Agenda"
20804 (if (equal org-agenda-ndays 1) " Day" "")
20805 (if (equal org-agenda-ndays 7) " Week" "")
20806 (if org-agenda-follow-mode " Follow" "")
20807 (if org-agenda-include-diary " Diary" "")
20808 (if org-agenda-use-time-grid " Grid" "")
20809 (if org-agenda-show-log " Log" "")))
20810 (force-mode-line-update))
20812 (defun org-agenda-post-command-hook ()
20813 (and (eolp) (not (bolp)) (backward-char 1))
20814 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20815 (if (and org-agenda-follow-mode
20816 (get-text-property (point) 'org-marker))
20817 (org-agenda-show)))
20819 (defun org-agenda-show-priority ()
20820 "Show the priority of the current item.
20821 This priority is composed of the main priority given with the [#A] cookies,
20822 and by additional input from the age of a schedules or deadline entry."
20823 (interactive)
20824 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20825 (message "Priority is %d" (if pri pri -1000))))
20827 (defun org-agenda-show-tags ()
20828 "Show the tags applicable to the current item."
20829 (interactive)
20830 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20831 (if tags
20832 (message "Tags are :%s:"
20833 (org-no-properties (mapconcat 'identity tags ":")))
20834 (message "No tags associated with this line"))))
20836 (defun org-agenda-goto (&optional highlight)
20837 "Go to the Org-mode file which contains the item at point."
20838 (interactive)
20839 (let* ((marker (or (get-text-property (point) 'org-marker)
20840 (org-agenda-error)))
20841 (buffer (marker-buffer marker))
20842 (pos (marker-position marker)))
20843 (switch-to-buffer-other-window buffer)
20844 (widen)
20845 (goto-char pos)
20846 (when (org-mode-p)
20847 (org-show-context 'agenda)
20848 (save-excursion
20849 (and (outline-next-heading)
20850 (org-flag-heading nil)))) ; show the next heading
20851 (run-hooks 'org-agenda-after-show-hook)
20852 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
20854 (defvar org-agenda-after-show-hook nil
20855 "Normal hook run after an item has been shown from the agenda.
20856 Point is in the buffer where the item originated.")
20858 (defun org-agenda-kill ()
20859 "Kill the entry or subtree belonging to the current agenda entry."
20860 (interactive)
20861 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20862 (let* ((marker (or (get-text-property (point) 'org-marker)
20863 (org-agenda-error)))
20864 (buffer (marker-buffer marker))
20865 (pos (marker-position marker))
20866 (type (get-text-property (point) 'type))
20867 dbeg dend (n 0) conf)
20868 (org-with-remote-undo buffer
20869 (with-current-buffer buffer
20870 (save-excursion
20871 (goto-char pos)
20872 (if (and (org-mode-p) (not (member type '("sexp"))))
20873 (setq dbeg (progn (org-back-to-heading t) (point))
20874 dend (org-end-of-subtree t t))
20875 (setq dbeg (point-at-bol)
20876 dend (min (point-max) (1+ (point-at-eol)))))
20877 (goto-char dbeg)
20878 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20879 (setq conf (or (eq t org-agenda-confirm-kill)
20880 (and (numberp org-agenda-confirm-kill)
20881 (> n org-agenda-confirm-kill))))
20882 (and conf
20883 (not (y-or-n-p
20884 (format "Delete entry with %d lines in buffer \"%s\"? "
20885 n (buffer-name buffer))))
20886 (error "Abort"))
20887 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20888 (with-current-buffer buffer (delete-region dbeg dend))
20889 (message "Agenda item and source killed"))))
20891 (defun org-agenda-archive ()
20892 "Kill the entry or subtree belonging to the current agenda entry."
20893 (interactive)
20894 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20895 (let* ((marker (or (get-text-property (point) 'org-marker)
20896 (org-agenda-error)))
20897 (buffer (marker-buffer marker))
20898 (pos (marker-position marker)))
20899 (org-with-remote-undo buffer
20900 (with-current-buffer buffer
20901 (if (org-mode-p)
20902 (save-excursion
20903 (goto-char pos)
20904 (org-remove-subtree-entries-from-agenda)
20905 (org-back-to-heading t)
20906 (org-archive-subtree))
20907 (error "Archiving works only in Org-mode files"))))))
20909 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
20910 "Remove all lines in the agenda that correspond to a given subtree.
20911 The subtree is the one in buffer BUF, starting at BEG and ending at END.
20912 If this information is not given, the function uses the tree at point."
20913 (let ((buf (or buf (current-buffer))) m p)
20914 (save-excursion
20915 (unless (and beg end)
20916 (org-back-to-heading t)
20917 (setq beg (point))
20918 (org-end-of-subtree t)
20919 (setq end (point)))
20920 (set-buffer (get-buffer org-agenda-buffer-name))
20921 (save-excursion
20922 (goto-char (point-max))
20923 (beginning-of-line 1)
20924 (while (not (bobp))
20925 (when (and (setq m (get-text-property (point) 'org-marker))
20926 (equal buf (marker-buffer m))
20927 (setq p (marker-position m))
20928 (>= p beg)
20929 (<= p end))
20930 (let ((inhibit-read-only t))
20931 (delete-region (point-at-bol) (1+ (point-at-eol)))))
20932 (beginning-of-line 0))))))
20934 (defun org-agenda-open-link ()
20935 "Follow the link in the current line, if any."
20936 (interactive)
20937 (save-excursion
20938 (save-restriction
20939 (narrow-to-region (point-at-bol) (point-at-eol))
20940 (org-open-at-point))))
20942 (defun org-agenda-switch-to (&optional delete-other-windows)
20943 "Go to the Org-mode file which contains the item at point."
20944 (interactive)
20945 (let* ((marker (or (get-text-property (point) 'org-marker)
20946 (org-agenda-error)))
20947 (buffer (marker-buffer marker))
20948 (pos (marker-position marker)))
20949 (switch-to-buffer buffer)
20950 (and delete-other-windows (delete-other-windows))
20951 (widen)
20952 (goto-char pos)
20953 (when (org-mode-p)
20954 (org-show-context 'agenda)
20955 (save-excursion
20956 (and (outline-next-heading)
20957 (org-flag-heading nil)))))) ; show the next heading
20959 (defun org-agenda-goto-mouse (ev)
20960 "Go to the Org-mode file which contains the item at the mouse click."
20961 (interactive "e")
20962 (mouse-set-point ev)
20963 (org-agenda-goto))
20965 (defun org-agenda-show ()
20966 "Display the Org-mode file which contains the item at point."
20967 (interactive)
20968 (let ((win (selected-window)))
20969 (org-agenda-goto t)
20970 (select-window win)))
20972 (defun org-agenda-recenter (arg)
20973 "Display the Org-mode file which contains the item at point and recenter."
20974 (interactive "P")
20975 (let ((win (selected-window)))
20976 (org-agenda-goto t)
20977 (recenter arg)
20978 (select-window win)))
20980 (defun org-agenda-show-mouse (ev)
20981 "Display the Org-mode file which contains the item at the mouse click."
20982 (interactive "e")
20983 (mouse-set-point ev)
20984 (org-agenda-show))
20986 (defun org-agenda-check-no-diary ()
20987 "Check if the entry is a diary link and abort if yes."
20988 (if (get-text-property (point) 'org-agenda-diary-link)
20989 (org-agenda-error)))
20991 (defun org-agenda-error ()
20992 (error "Command not allowed in this line"))
20994 (defun org-agenda-tree-to-indirect-buffer ()
20995 "Show the subtree corresponding to the current entry in an indirect buffer.
20996 This calls the command `org-tree-to-indirect-buffer' from the original
20997 Org-mode buffer.
20998 With numerical prefix arg ARG, go up to this level and then take that tree.
20999 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21000 dedicated frame)."
21001 (interactive)
21002 (org-agenda-check-no-diary)
21003 (let* ((marker (or (get-text-property (point) 'org-marker)
21004 (org-agenda-error)))
21005 (buffer (marker-buffer marker))
21006 (pos (marker-position marker)))
21007 (with-current-buffer buffer
21008 (save-excursion
21009 (goto-char pos)
21010 (call-interactively 'org-tree-to-indirect-buffer)))))
21012 (defvar org-last-heading-marker (make-marker)
21013 "Marker pointing to the headline that last changed its TODO state
21014 by a remote command from the agenda.")
21016 (defun org-agenda-todo-nextset ()
21017 "Switch TODO entry to next sequence."
21018 (interactive)
21019 (org-agenda-todo 'nextset))
21021 (defun org-agenda-todo-previousset ()
21022 "Switch TODO entry to previous sequence."
21023 (interactive)
21024 (org-agenda-todo 'previousset))
21026 (defun org-agenda-todo (&optional arg)
21027 "Cycle TODO state of line at point, also in Org-mode file.
21028 This changes the line at point, all other lines in the agenda referring to
21029 the same tree node, and the headline of the tree node in the Org-mode file."
21030 (interactive "P")
21031 (org-agenda-check-no-diary)
21032 (let* ((col (current-column))
21033 (marker (or (get-text-property (point) 'org-marker)
21034 (org-agenda-error)))
21035 (buffer (marker-buffer marker))
21036 (pos (marker-position marker))
21037 (hdmarker (get-text-property (point) 'org-hd-marker))
21038 (inhibit-read-only t)
21039 newhead)
21040 (org-with-remote-undo buffer
21041 (with-current-buffer buffer
21042 (widen)
21043 (goto-char pos)
21044 (org-show-context 'agenda)
21045 (save-excursion
21046 (and (outline-next-heading)
21047 (org-flag-heading nil))) ; show the next heading
21048 (org-todo arg)
21049 (and (bolp) (forward-char 1))
21050 (setq newhead (org-get-heading))
21051 (save-excursion
21052 (org-back-to-heading)
21053 (move-marker org-last-heading-marker (point))))
21054 (beginning-of-line 1)
21055 (save-excursion
21056 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21057 (move-to-column col))))
21059 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21060 "Change all lines in the agenda buffer which match HDMARKER.
21061 The new content of the line will be NEWHEAD (as modified by
21062 `org-format-agenda-item'). HDMARKER is checked with
21063 `equal' against all `org-hd-marker' text properties in the file.
21064 If FIXFACE is non-nil, the face of each item is modified acording to
21065 the new TODO state."
21066 (let* ((inhibit-read-only t)
21067 props m pl undone-face done-face finish new dotime cat tags)
21068 (save-excursion
21069 (goto-char (point-max))
21070 (beginning-of-line 1)
21071 (while (not finish)
21072 (setq finish (bobp))
21073 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21074 (equal m hdmarker))
21075 (setq props (text-properties-at (point))
21076 dotime (get-text-property (point) 'dotime)
21077 cat (get-text-property (point) 'org-category)
21078 tags (get-text-property (point) 'tags)
21079 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21080 pl (get-text-property (point) 'prefix-length)
21081 undone-face (get-text-property (point) 'undone-face)
21082 done-face (get-text-property (point) 'done-face))
21083 (move-to-column pl)
21084 (cond
21085 ((equal new "")
21086 (beginning-of-line 1)
21087 (and (looking-at ".*\n?") (replace-match "")))
21088 ((looking-at ".*")
21089 (replace-match new t t)
21090 (beginning-of-line 1)
21091 (add-text-properties (point-at-bol) (point-at-eol) props)
21092 (when fixface
21093 (add-text-properties
21094 (point-at-bol) (point-at-eol)
21095 (list 'face
21096 (if org-last-todo-state-is-todo
21097 undone-face done-face))))
21098 (org-agenda-highlight-todo 'line)
21099 (beginning-of-line 1))
21100 (t (error "Line update did not work"))))
21101 (beginning-of-line 0)))
21102 (org-finalize-agenda)))
21104 (defun org-agenda-align-tags (&optional line)
21105 "Align all tags in agenda items to `org-agenda-tags-column'."
21106 (let ((inhibit-read-only t) l c)
21107 (save-excursion
21108 (goto-char (if line (point-at-bol) (point-min)))
21109 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21110 (if line (point-at-eol) nil) t)
21111 (add-text-properties
21112 (match-beginning 2) (match-end 2)
21113 (list 'face (list 'org-tag (get-text-property
21114 (match-beginning 2) 'face))))
21115 (setq l (- (match-end 2) (match-beginning 2))
21116 c (if (< org-agenda-tags-column 0)
21117 (- (abs org-agenda-tags-column) l)
21118 org-agenda-tags-column))
21119 (delete-region (match-beginning 1) (match-end 1))
21120 (goto-char (match-beginning 1))
21121 (insert (org-add-props
21122 (make-string (max 1 (- c (current-column))) ?\ )
21123 (text-properties-at (point))))))))
21125 (defun org-agenda-priority-up ()
21126 "Increase the priority of line at point, also in Org-mode file."
21127 (interactive)
21128 (org-agenda-priority 'up))
21130 (defun org-agenda-priority-down ()
21131 "Decrease the priority of line at point, also in Org-mode file."
21132 (interactive)
21133 (org-agenda-priority 'down))
21135 (defun org-agenda-priority (&optional force-direction)
21136 "Set the priority of line at point, also in Org-mode file.
21137 This changes the line at point, all other lines in the agenda referring to
21138 the same tree node, and the headline of the tree node in the Org-mode file."
21139 (interactive)
21140 (org-agenda-check-no-diary)
21141 (let* ((marker (or (get-text-property (point) 'org-marker)
21142 (org-agenda-error)))
21143 (hdmarker (get-text-property (point) 'org-hd-marker))
21144 (buffer (marker-buffer hdmarker))
21145 (pos (marker-position hdmarker))
21146 (inhibit-read-only t)
21147 newhead)
21148 (org-with-remote-undo buffer
21149 (with-current-buffer buffer
21150 (widen)
21151 (goto-char pos)
21152 (org-show-context 'agenda)
21153 (save-excursion
21154 (and (outline-next-heading)
21155 (org-flag-heading nil))) ; show the next heading
21156 (funcall 'org-priority force-direction)
21157 (end-of-line 1)
21158 (setq newhead (org-get-heading)))
21159 (org-agenda-change-all-lines newhead hdmarker)
21160 (beginning-of-line 1))))
21162 (defun org-get-tags-at (&optional pos)
21163 "Get a list of all headline tags applicable at POS.
21164 POS defaults to point. If tags are inherited, the list contains
21165 the targets in the same sequence as the headlines appear, i.e.
21166 the tags of the current headline come last."
21167 (interactive)
21168 (let (tags lastpos)
21169 (save-excursion
21170 (save-restriction
21171 (widen)
21172 (goto-char (or pos (point)))
21173 (save-match-data
21174 (org-back-to-heading t)
21175 (condition-case nil
21176 (while (not (equal lastpos (point)))
21177 (setq lastpos (point))
21178 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21179 (setq tags (append (org-split-string
21180 (org-match-string-no-properties 1) ":")
21181 tags)))
21182 (or org-use-tag-inheritance (error ""))
21183 (org-up-heading-all 1))
21184 (error nil))))
21185 tags)))
21187 ;; FIXME: should fix the tags property of the agenda line.
21188 (defun org-agenda-set-tags ()
21189 "Set tags for the current headline."
21190 (interactive)
21191 (org-agenda-check-no-diary)
21192 (if (and (org-region-active-p) (interactive-p))
21193 (call-interactively 'org-change-tag-in-region)
21194 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21195 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21196 (org-agenda-error)))
21197 (buffer (marker-buffer hdmarker))
21198 (pos (marker-position hdmarker))
21199 (inhibit-read-only t)
21200 newhead)
21201 (org-with-remote-undo buffer
21202 (with-current-buffer buffer
21203 (widen)
21204 (goto-char pos)
21205 (save-excursion
21206 (org-show-context 'agenda))
21207 (save-excursion
21208 (and (outline-next-heading)
21209 (org-flag-heading nil))) ; show the next heading
21210 (goto-char pos)
21211 (call-interactively 'org-set-tags)
21212 (end-of-line 1)
21213 (setq newhead (org-get-heading)))
21214 (org-agenda-change-all-lines newhead hdmarker)
21215 (beginning-of-line 1)))))
21217 (defun org-agenda-toggle-archive-tag ()
21218 "Toggle the archive tag for the current entry."
21219 (interactive)
21220 (org-agenda-check-no-diary)
21221 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21222 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21223 (org-agenda-error)))
21224 (buffer (marker-buffer hdmarker))
21225 (pos (marker-position hdmarker))
21226 (inhibit-read-only t)
21227 newhead)
21228 (org-with-remote-undo buffer
21229 (with-current-buffer buffer
21230 (widen)
21231 (goto-char pos)
21232 (org-show-context 'agenda)
21233 (save-excursion
21234 (and (outline-next-heading)
21235 (org-flag-heading nil))) ; show the next heading
21236 (call-interactively 'org-toggle-archive-tag)
21237 (end-of-line 1)
21238 (setq newhead (org-get-heading)))
21239 (org-agenda-change-all-lines newhead hdmarker)
21240 (beginning-of-line 1))))
21242 (defun org-agenda-date-later (arg &optional what)
21243 "Change the date of this item to one day later."
21244 (interactive "p")
21245 (org-agenda-check-type t 'agenda 'timeline)
21246 (org-agenda-check-no-diary)
21247 (let* ((marker (or (get-text-property (point) 'org-marker)
21248 (org-agenda-error)))
21249 (buffer (marker-buffer marker))
21250 (pos (marker-position marker)))
21251 (org-with-remote-undo buffer
21252 (with-current-buffer buffer
21253 (widen)
21254 (goto-char pos)
21255 (if (not (org-at-timestamp-p))
21256 (error "Cannot find time stamp"))
21257 (org-timestamp-change arg (or what 'day)))
21258 (org-agenda-show-new-time marker org-last-changed-timestamp))
21259 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21261 (defun org-agenda-date-earlier (arg &optional what)
21262 "Change the date of this item to one day earlier."
21263 (interactive "p")
21264 (org-agenda-date-later (- arg) what))
21266 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21267 "Show new date stamp via text properties."
21268 ;; We use text properties to make this undoable
21269 (let ((inhibit-read-only t))
21270 (setq stamp (concat " " prefix " => " stamp))
21271 (save-excursion
21272 (goto-char (point-max))
21273 (while (not (bobp))
21274 (when (equal marker (get-text-property (point) 'org-marker))
21275 (move-to-column (- (window-width) (length stamp)) t)
21276 (if (featurep 'xemacs)
21277 ;; Use `duplicable' property to trigger undo recording
21278 (let ((ex (make-extent nil nil))
21279 (gl (make-glyph stamp)))
21280 (set-glyph-face gl 'secondary-selection)
21281 (set-extent-properties
21282 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21283 (insert-extent ex (1- (point)) (point-at-eol)))
21284 (add-text-properties
21285 (1- (point)) (point-at-eol)
21286 (list 'display (org-add-props stamp nil
21287 'face 'secondary-selection))))
21288 (beginning-of-line 1))
21289 (beginning-of-line 0)))))
21291 (defun org-agenda-date-prompt (arg)
21292 "Change the date of this item. Date is prompted for, with default today.
21293 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21294 be used to request time specification in the time stamp."
21295 (interactive "P")
21296 (org-agenda-check-type t 'agenda 'timeline)
21297 (org-agenda-check-no-diary)
21298 (let* ((marker (or (get-text-property (point) 'org-marker)
21299 (org-agenda-error)))
21300 (buffer (marker-buffer marker))
21301 (pos (marker-position marker)))
21302 (org-with-remote-undo buffer
21303 (with-current-buffer buffer
21304 (widen)
21305 (goto-char pos)
21306 (if (not (org-at-timestamp-p))
21307 (error "Cannot find time stamp"))
21308 (org-time-stamp arg)
21309 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21311 (defun org-agenda-schedule (arg)
21312 "Schedule the item at point."
21313 (interactive "P")
21314 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21315 (org-agenda-check-no-diary)
21316 (let* ((marker (or (get-text-property (point) 'org-marker)
21317 (org-agenda-error)))
21318 (buffer (marker-buffer marker))
21319 (pos (marker-position marker))
21320 (org-insert-labeled-timestamps-at-point nil)
21322 (org-with-remote-undo buffer
21323 (with-current-buffer buffer
21324 (widen)
21325 (goto-char pos)
21326 (setq ts (org-schedule arg)))
21327 (org-agenda-show-new-time marker ts "S"))
21328 (message "Item scheduled for %s" ts)))
21330 (defun org-agenda-deadline (arg)
21331 "Schedule the item at point."
21332 (interactive "P")
21333 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21334 (org-agenda-check-no-diary)
21335 (let* ((marker (or (get-text-property (point) 'org-marker)
21336 (org-agenda-error)))
21337 (buffer (marker-buffer marker))
21338 (pos (marker-position marker))
21339 (org-insert-labeled-timestamps-at-point nil)
21341 (org-with-remote-undo buffer
21342 (with-current-buffer buffer
21343 (widen)
21344 (goto-char pos)
21345 (setq ts (org-deadline arg)))
21346 (org-agenda-show-new-time marker ts "S"))
21347 (message "Deadline for this item set to %s" ts)))
21349 (defun org-get-heading (&optional no-tags)
21350 "Return the heading of the current entry, without the stars."
21351 (save-excursion
21352 (org-back-to-heading t)
21353 (if (looking-at
21354 (if no-tags
21355 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21356 "\\*+[ \t]+\\([^\r\n]*\\)"))
21357 (match-string 1) "")))
21359 (defun org-agenda-clock-in (&optional arg)
21360 "Start the clock on the currently selected item."
21361 (interactive "P")
21362 (org-agenda-check-no-diary)
21363 (let* ((marker (or (get-text-property (point) 'org-marker)
21364 (org-agenda-error)))
21365 (pos (marker-position marker)))
21366 (org-with-remote-undo (marker-buffer marker)
21367 (with-current-buffer (marker-buffer marker)
21368 (widen)
21369 (goto-char pos)
21370 (org-clock-in)))))
21372 (defun org-agenda-clock-out (&optional arg)
21373 "Stop the currently running clock."
21374 (interactive "P")
21375 (unless (marker-buffer org-clock-marker)
21376 (error "No running clock"))
21377 (org-with-remote-undo (marker-buffer org-clock-marker)
21378 (org-clock-out)))
21380 (defun org-agenda-clock-cancel (&optional arg)
21381 "Cancel the currently running clock."
21382 (interactive "P")
21383 (unless (marker-buffer org-clock-marker)
21384 (error "No running clock"))
21385 (org-with-remote-undo (marker-buffer org-clock-marker)
21386 (org-clock-cancel)))
21388 (defun org-agenda-diary-entry ()
21389 "Make a diary entry, like the `i' command from the calendar.
21390 All the standard commands work: block, weekly etc."
21391 (interactive)
21392 (org-agenda-check-type t 'agenda 'timeline)
21393 (require 'diary-lib)
21394 (let* ((char (progn
21395 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21396 (read-char-exclusive)))
21397 (cmd (cdr (assoc char
21398 '((?d . insert-diary-entry)
21399 (?w . insert-weekly-diary-entry)
21400 (?m . insert-monthly-diary-entry)
21401 (?y . insert-yearly-diary-entry)
21402 (?a . insert-anniversary-diary-entry)
21403 (?b . insert-block-diary-entry)
21404 (?c . insert-cyclic-diary-entry)))))
21405 (oldf (symbol-function 'calendar-cursor-to-date))
21406 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21407 (point (point))
21408 (mark (or (mark t) (point))))
21409 (unless cmd
21410 (error "No command associated with <%c>" char))
21411 (unless (and (get-text-property point 'day)
21412 (or (not (equal ?b char))
21413 (get-text-property mark 'day)))
21414 (error "Don't know which date to use for diary entry"))
21415 ;; We implement this by hacking the `calendar-cursor-to-date' function
21416 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21417 (let ((calendar-mark-ring
21418 (list (calendar-gregorian-from-absolute
21419 (or (get-text-property mark 'day)
21420 (get-text-property point 'day))))))
21421 (unwind-protect
21422 (progn
21423 (fset 'calendar-cursor-to-date
21424 (lambda (&optional error)
21425 (calendar-gregorian-from-absolute
21426 (get-text-property point 'day))))
21427 (call-interactively cmd))
21428 (fset 'calendar-cursor-to-date oldf)))))
21431 (defun org-agenda-execute-calendar-command (cmd)
21432 "Execute a calendar command from the agenda, with the date associated to
21433 the cursor position."
21434 (org-agenda-check-type t 'agenda 'timeline)
21435 (require 'diary-lib)
21436 (unless (get-text-property (point) 'day)
21437 (error "Don't know which date to use for calendar command"))
21438 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21439 (point (point))
21440 (date (calendar-gregorian-from-absolute
21441 (get-text-property point 'day)))
21442 ;; the following 3 vars are needed in the calendar
21443 (displayed-day (extract-calendar-day date))
21444 (displayed-month (extract-calendar-month date))
21445 (displayed-year (extract-calendar-year date)))
21446 (unwind-protect
21447 (progn
21448 (fset 'calendar-cursor-to-date
21449 (lambda (&optional error)
21450 (calendar-gregorian-from-absolute
21451 (get-text-property point 'day))))
21452 (call-interactively cmd))
21453 (fset 'calendar-cursor-to-date oldf))))
21455 (defun org-agenda-phases-of-moon ()
21456 "Display the phases of the moon for the 3 months around the cursor date."
21457 (interactive)
21458 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
21460 (defun org-agenda-holidays ()
21461 "Display the holidays for the 3 months around the cursor date."
21462 (interactive)
21463 (org-agenda-execute-calendar-command 'list-calendar-holidays))
21465 (defun org-agenda-sunrise-sunset (arg)
21466 "Display sunrise and sunset for the cursor date.
21467 Latitude and longitude can be specified with the variables
21468 `calendar-latitude' and `calendar-longitude'. When called with prefix
21469 argument, latitude and longitude will be prompted for."
21470 (interactive "P")
21471 (let ((calendar-longitude (if arg nil calendar-longitude))
21472 (calendar-latitude (if arg nil calendar-latitude))
21473 (calendar-location-name
21474 (if arg "the given coordinates" calendar-location-name)))
21475 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
21477 (defun org-agenda-goto-calendar ()
21478 "Open the Emacs calendar with the date at the cursor."
21479 (interactive)
21480 (org-agenda-check-type t 'agenda 'timeline)
21481 (let* ((day (or (get-text-property (point) 'day)
21482 (error "Don't know which date to open in calendar")))
21483 (date (calendar-gregorian-from-absolute day))
21484 (calendar-move-hook nil)
21485 (view-calendar-holidays-initially nil)
21486 (view-diary-entries-initially nil))
21487 (calendar)
21488 (calendar-goto-date date)))
21490 (defun org-calendar-goto-agenda ()
21491 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
21492 This is a command that has to be installed in `calendar-mode-map'."
21493 (interactive)
21494 (org-agenda-list nil (calendar-absolute-from-gregorian
21495 (calendar-cursor-to-date))
21496 nil))
21498 (defun org-agenda-convert-date ()
21499 (interactive)
21500 (org-agenda-check-type t 'agenda 'timeline)
21501 (let ((day (get-text-property (point) 'day))
21502 date s)
21503 (unless day
21504 (error "Don't know which date to convert"))
21505 (setq date (calendar-gregorian-from-absolute day))
21506 (setq s (concat
21507 "Gregorian: " (calendar-date-string date) "\n"
21508 "ISO: " (calendar-iso-date-string date) "\n"
21509 "Day of Yr: " (calendar-day-of-year-string date) "\n"
21510 "Julian: " (calendar-julian-date-string date) "\n"
21511 "Astron. JD: " (calendar-astro-date-string date)
21512 " (Julian date number at noon UTC)\n"
21513 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
21514 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
21515 "French: " (calendar-french-date-string date) "\n"
21516 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
21517 "Mayan: " (calendar-mayan-date-string date) "\n"
21518 "Coptic: " (calendar-coptic-date-string date) "\n"
21519 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
21520 "Persian: " (calendar-persian-date-string date) "\n"
21521 "Chinese: " (calendar-chinese-date-string date) "\n"))
21522 (with-output-to-temp-buffer "*Dates*"
21523 (princ s))
21524 (if (fboundp 'fit-window-to-buffer)
21525 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
21528 ;;;; Embedded LaTeX
21530 (defvar org-cdlatex-mode-map (make-sparse-keymap)
21531 "Keymap for the minor `org-cdlatex-mode'.")
21533 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
21534 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
21535 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
21536 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
21537 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
21539 (defvar org-cdlatex-texmathp-advice-is-done nil
21540 "Flag remembering if we have applied the advice to texmathp already.")
21542 (define-minor-mode org-cdlatex-mode
21543 "Toggle the minor `org-cdlatex-mode'.
21544 This mode supports entering LaTeX environment and math in LaTeX fragments
21545 in Org-mode.
21546 \\{org-cdlatex-mode-map}"
21547 nil " OCDL" nil
21548 (when org-cdlatex-mode (require 'cdlatex))
21549 (unless org-cdlatex-texmathp-advice-is-done
21550 (setq org-cdlatex-texmathp-advice-is-done t)
21551 (defadvice texmathp (around org-math-always-on activate)
21552 "Always return t in org-mode buffers.
21553 This is because we want to insert math symbols without dollars even outside
21554 the LaTeX math segments. If Orgmode thinks that point is actually inside
21555 en embedded LaTeX fragement, let texmathp do its job.
21556 \\[org-cdlatex-mode-map]"
21557 (interactive)
21558 (let (p)
21559 (cond
21560 ((not (org-mode-p)) ad-do-it)
21561 ((eq this-command 'cdlatex-math-symbol)
21562 (setq ad-return-value t
21563 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
21565 (let ((p (org-inside-LaTeX-fragment-p)))
21566 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
21567 (setq ad-return-value t
21568 texmathp-why '("Org-mode embedded math" . 0))
21569 (if p ad-do-it)))))))))
21571 (defun turn-on-org-cdlatex ()
21572 "Unconditionally turn on `org-cdlatex-mode'."
21573 (org-cdlatex-mode 1))
21575 (defun org-inside-LaTeX-fragment-p ()
21576 "Test if point is inside a LaTeX fragment.
21577 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
21578 sequence appearing also before point.
21579 Even though the matchers for math are configurable, this function assumes
21580 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
21581 delimiters are skipped when they have been removed by customization.
21582 The return value is nil, or a cons cell with the delimiter and
21583 and the position of this delimiter.
21585 This function does a reasonably good job, but can locally be fooled by
21586 for example currency specifications. For example it will assume being in
21587 inline math after \"$22.34\". The LaTeX fragment formatter will only format
21588 fragments that are properly closed, but during editing, we have to live
21589 with the uncertainty caused by missing closing delimiters. This function
21590 looks only before point, not after."
21591 (catch 'exit
21592 (let ((pos (point))
21593 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
21594 (lim (progn
21595 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
21596 (point)))
21597 dd-on str (start 0) m re)
21598 (goto-char pos)
21599 (when dodollar
21600 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
21601 re (nth 1 (assoc "$" org-latex-regexps)))
21602 (while (string-match re str start)
21603 (cond
21604 ((= (match-end 0) (length str))
21605 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
21606 ((= (match-end 0) (- (length str) 5))
21607 (throw 'exit nil))
21608 (t (setq start (match-end 0))))))
21609 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
21610 (goto-char pos)
21611 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
21612 (and (match-beginning 2) (throw 'exit nil))
21613 ;; count $$
21614 (while (re-search-backward "\\$\\$" lim t)
21615 (setq dd-on (not dd-on)))
21616 (goto-char pos)
21617 (if dd-on (cons "$$" m))))))
21620 (defun org-try-cdlatex-tab ()
21621 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
21622 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
21623 - inside a LaTeX fragment, or
21624 - after the first word in a line, where an abbreviation expansion could
21625 insert a LaTeX environment."
21626 (when org-cdlatex-mode
21627 (cond
21628 ((save-excursion
21629 (skip-chars-backward "a-zA-Z0-9*")
21630 (skip-chars-backward " \t")
21631 (bolp))
21632 (cdlatex-tab) t)
21633 ((org-inside-LaTeX-fragment-p)
21634 (cdlatex-tab) t)
21635 (t nil))))
21637 (defun org-cdlatex-underscore-caret (&optional arg)
21638 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
21639 Revert to the normal definition outside of these fragments."
21640 (interactive "P")
21641 (if (org-inside-LaTeX-fragment-p)
21642 (call-interactively 'cdlatex-sub-superscript)
21643 (let (org-cdlatex-mode)
21644 (call-interactively (key-binding (vector last-input-event))))))
21646 (defun org-cdlatex-math-modify (&optional arg)
21647 "Execute `cdlatex-math-modify' in LaTeX fragments.
21648 Revert to the normal definition outside of these fragments."
21649 (interactive "P")
21650 (if (org-inside-LaTeX-fragment-p)
21651 (call-interactively 'cdlatex-math-modify)
21652 (let (org-cdlatex-mode)
21653 (call-interactively (key-binding (vector last-input-event))))))
21655 (defvar org-latex-fragment-image-overlays nil
21656 "List of overlays carrying the images of latex fragments.")
21657 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
21659 (defun org-remove-latex-fragment-image-overlays ()
21660 "Remove all overlays with LaTeX fragment images in current buffer."
21661 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
21662 (setq org-latex-fragment-image-overlays nil))
21664 (defun org-preview-latex-fragment (&optional subtree)
21665 "Preview the LaTeX fragment at point, or all locally or globally.
21666 If the cursor is in a LaTeX fragment, create the image and overlay
21667 it over the source code. If there is no fragment at point, display
21668 all fragments in the current text, from one headline to the next. With
21669 prefix SUBTREE, display all fragments in the current subtree. With a
21670 double prefix `C-u C-u', or when the cursor is before the first headline,
21671 display all fragments in the buffer.
21672 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
21673 (interactive "P")
21674 (org-remove-latex-fragment-image-overlays)
21675 (save-excursion
21676 (save-restriction
21677 (let (beg end at msg)
21678 (cond
21679 ((or (equal subtree '(16))
21680 (not (save-excursion
21681 (re-search-backward (concat "^" outline-regexp) nil t))))
21682 (setq beg (point-min) end (point-max)
21683 msg "Creating images for buffer...%s"))
21684 ((equal subtree '(4))
21685 (org-back-to-heading)
21686 (setq beg (point) end (org-end-of-subtree t)
21687 msg "Creating images for subtree...%s"))
21689 (if (setq at (org-inside-LaTeX-fragment-p))
21690 (goto-char (max (point-min) (- (cdr at) 2)))
21691 (org-back-to-heading))
21692 (setq beg (point) end (progn (outline-next-heading) (point))
21693 msg (if at "Creating image...%s"
21694 "Creating images for entry...%s"))))
21695 (message msg "")
21696 (narrow-to-region beg end)
21697 (goto-char beg)
21698 (org-format-latex
21699 (concat "ltxpng/" (file-name-sans-extension
21700 (file-name-nondirectory
21701 buffer-file-name)))
21702 default-directory 'overlays msg at 'forbuffer)
21703 (message msg "done. Use `C-c C-c' to remove images.")))))
21705 (defvar org-latex-regexps
21706 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21707 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21708 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21709 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21710 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21711 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21712 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21713 "Regular expressions for matching embedded LaTeX.")
21715 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21716 "Replace LaTeX fragments with links to an image, and produce images."
21717 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21718 (let* ((prefixnodir (file-name-nondirectory prefix))
21719 (absprefix (expand-file-name prefix dir))
21720 (todir (file-name-directory absprefix))
21721 (opt org-format-latex-options)
21722 (matchers (plist-get opt :matchers))
21723 (re-list org-latex-regexps)
21724 (cnt 0) txt link beg end re e checkdir
21725 m n block linkfile movefile ov)
21726 ;; Check if there are old images files with this prefix, and remove them
21727 (when (file-directory-p todir)
21728 (mapc 'delete-file
21729 (directory-files
21730 todir 'full
21731 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21732 ;; Check the different regular expressions
21733 (while (setq e (pop re-list))
21734 (setq m (car e) re (nth 1 e) n (nth 2 e)
21735 block (if (nth 3 e) "\n\n" ""))
21736 (when (member m matchers)
21737 (goto-char (point-min))
21738 (while (re-search-forward re nil t)
21739 (when (or (not at) (equal (cdr at) (match-beginning n)))
21740 (setq txt (match-string n)
21741 beg (match-beginning n) end (match-end n)
21742 cnt (1+ cnt)
21743 linkfile (format "%s_%04d.png" prefix cnt)
21744 movefile (format "%s_%04d.png" absprefix cnt)
21745 link (concat block "[[file:" linkfile "]]" block))
21746 (if msg (message msg cnt))
21747 (goto-char beg)
21748 (unless checkdir ; make sure the directory exists
21749 (setq checkdir t)
21750 (or (file-directory-p todir) (make-directory todir)))
21751 (org-create-formula-image
21752 txt movefile opt forbuffer)
21753 (if overlays
21754 (progn
21755 (setq ov (org-make-overlay beg end))
21756 (if (featurep 'xemacs)
21757 (progn
21758 (org-overlay-put ov 'invisible t)
21759 (org-overlay-put
21760 ov 'end-glyph
21761 (make-glyph (vector 'png :file movefile))))
21762 (org-overlay-put
21763 ov 'display
21764 (list 'image :type 'png :file movefile :ascent 'center)))
21765 (push ov org-latex-fragment-image-overlays)
21766 (goto-char end))
21767 (delete-region beg end)
21768 (insert link))))))))
21770 ;; This function borrows from Ganesh Swami's latex2png.el
21771 (defun org-create-formula-image (string tofile options buffer)
21772 (let* ((tmpdir (if (featurep 'xemacs)
21773 (temp-directory)
21774 temporary-file-directory))
21775 (texfilebase (make-temp-name
21776 (expand-file-name "orgtex" tmpdir)))
21777 (texfile (concat texfilebase ".tex"))
21778 (dvifile (concat texfilebase ".dvi"))
21779 (pngfile (concat texfilebase ".png"))
21780 (fnh (face-attribute 'default :height nil))
21781 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21782 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21783 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21784 "Black"))
21785 (bg (or (plist-get options (if buffer :background :html-background))
21786 "Transparent")))
21787 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21788 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21789 (with-temp-file texfile
21790 (insert org-format-latex-header
21791 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21792 (let ((dir default-directory))
21793 (condition-case nil
21794 (progn
21795 (cd tmpdir)
21796 (call-process "latex" nil nil nil texfile))
21797 (error nil))
21798 (cd dir))
21799 (if (not (file-exists-p dvifile))
21800 (progn (message "Failed to create dvi file from %s" texfile) nil)
21801 (call-process "dvipng" nil nil nil
21802 "-E" "-fg" fg "-bg" bg
21803 "-D" dpi
21804 ;;"-x" scale "-y" scale
21805 "-T" "tight"
21806 "-o" pngfile
21807 dvifile)
21808 (if (not (file-exists-p pngfile))
21809 (progn (message "Failed to create png file from %s" texfile) nil)
21810 ;; Use the requested file name and clean up
21811 (copy-file pngfile tofile 'replace)
21812 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21813 (delete-file (concat texfilebase e)))
21814 pngfile))))
21816 (defun org-dvipng-color (attr)
21817 "Return an rgb color specification for dvipng."
21818 (apply 'format "rgb %s %s %s"
21819 (mapcar 'org-normalize-color
21820 (color-values (face-attribute 'default attr nil)))))
21822 (defun org-normalize-color (value)
21823 "Return string to be used as color value for an RGB component."
21824 (format "%g" (/ value 65535.0)))
21826 ;;;; Exporting
21828 ;;; Variables, constants, and parameter plists
21830 (defconst org-level-max 20)
21832 (defvar org-export-html-preamble nil
21833 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21834 (defvar org-export-html-postamble nil
21835 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21836 (defvar org-export-html-auto-preamble t
21837 "Should default preamble be inserted? Set by publishing functions.")
21838 (defvar org-export-html-auto-postamble t
21839 "Should default postamble be inserted? Set by publishing functions.")
21840 (defvar org-current-export-file nil) ; dynamically scoped parameter
21841 (defvar org-current-export-dir nil) ; dynamically scoped parameter
21844 (defconst org-export-plist-vars
21845 '((:language . org-export-default-language)
21846 (:customtime . org-display-custom-times)
21847 (:headline-levels . org-export-headline-levels)
21848 (:section-numbers . org-export-with-section-numbers)
21849 (:table-of-contents . org-export-with-toc)
21850 (:preserve-breaks . org-export-preserve-breaks)
21851 (:archived-trees . org-export-with-archived-trees)
21852 (:emphasize . org-export-with-emphasize)
21853 (:sub-superscript . org-export-with-sub-superscripts)
21854 (:footnotes . org-export-with-footnotes)
21855 (:drawers . org-export-with-drawers)
21856 (:tags . org-export-with-tags)
21857 (:TeX-macros . org-export-with-TeX-macros)
21858 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
21859 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
21860 (:fixed-width . org-export-with-fixed-width)
21861 (:timestamps . org-export-with-timestamps)
21862 (:author-info . org-export-author-info)
21863 (:time-stamp-file . org-export-time-stamp-file)
21864 (:tables . org-export-with-tables)
21865 (:table-auto-headline . org-export-highlight-first-table-line)
21866 (:style . org-export-html-style)
21867 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
21868 (:convert-org-links . org-export-html-link-org-files-as-html)
21869 (:inline-images . org-export-html-inline-images)
21870 (:html-extension . org-export-html-extension)
21871 (:expand-quoted-html . org-export-html-expand)
21872 (:timestamp . org-export-html-with-timestamp)
21873 (:publishing-directory . org-export-publishing-directory)
21874 (:preamble . org-export-html-preamble)
21875 (:postamble . org-export-html-postamble)
21876 (:auto-preamble . org-export-html-auto-preamble)
21877 (:auto-postamble . org-export-html-auto-postamble)
21878 (:author . user-full-name)
21879 (:email . user-mail-address)))
21881 (defun org-default-export-plist ()
21882 "Return the property list with default settings for the export variables."
21883 (let ((l org-export-plist-vars) rtn e)
21884 (while (setq e (pop l))
21885 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21886 rtn))
21888 (defun org-infile-export-plist ()
21889 "Return the property list with file-local settings for export."
21890 (save-excursion
21891 (goto-char 0)
21892 (let ((re (org-make-options-regexp
21893 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
21894 p key val text options)
21895 (while (re-search-forward re nil t)
21896 (setq key (org-match-string-no-properties 1)
21897 val (org-match-string-no-properties 2))
21898 (cond
21899 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
21900 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
21901 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
21902 ((string-equal key "DATE") (setq p (plist-put p :date val)))
21903 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
21904 ((string-equal key "TEXT")
21905 (setq text (if text (concat text "\n" val) val)))
21906 ((string-equal key "OPTIONS") (setq options val))))
21907 (setq p (plist-put p :text text))
21908 (when options
21909 (let ((op '(("H" . :headline-levels)
21910 ("num" . :section-numbers)
21911 ("toc" . :table-of-contents)
21912 ("\\n" . :preserve-breaks)
21913 ("@" . :expand-quoted-html)
21914 (":" . :fixed-width)
21915 ("|" . :tables)
21916 ("^" . :sub-superscript)
21917 ("f" . :footnotes)
21918 ("d" . :drawers)
21919 ("tags" . :tags)
21920 ("*" . :emphasize)
21921 ("TeX" . :TeX-macros)
21922 ("LaTeX" . :LaTeX-fragments)
21923 ("skip" . :skip-before-1st-heading)
21924 ("author" . :author-info)
21925 ("timestamp" . :time-stamp-file)))
21927 (while (setq o (pop op))
21928 (if (string-match (concat (regexp-quote (car o))
21929 ":\\([^ \t\n\r;,.]*\\)")
21930 options)
21931 (setq p (plist-put p (cdr o)
21932 (car (read-from-string
21933 (match-string 1 options)))))))))
21934 p)))
21936 (defun org-export-directory (type plist)
21937 (let* ((val (plist-get plist :publishing-directory))
21938 (dir (if (listp val)
21939 (or (cdr (assoc type val)) ".")
21940 val)))
21941 dir))
21943 (defun org-skip-comments (lines)
21944 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
21945 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
21946 (re2 "^\\(\\*+\\)[ \t\n\r]")
21947 (case-fold-search nil)
21948 rtn line level)
21949 (while (setq line (pop lines))
21950 (cond
21951 ((and (string-match re1 line)
21952 (setq level (- (match-end 1) (match-beginning 1))))
21953 ;; Beginning of a COMMENT subtree. Skip it.
21954 (while (and (setq line (pop lines))
21955 (or (not (string-match re2 line))
21956 (> (- (match-end 1) (match-beginning 1)) level))))
21957 (setq lines (cons line lines)))
21958 ((string-match "^#" line)
21959 ;; an ordinary comment line
21961 ((and org-export-table-remove-special-lines
21962 (string-match "^[ \t]*|" line)
21963 (or (string-match "^[ \t]*| *[!_^] *|" line)
21964 (and (string-match "| *<[0-9]+> *|" line)
21965 (not (string-match "| *[^ <|]" line)))))
21966 ;; a special table line that should be removed
21968 (t (setq rtn (cons line rtn)))))
21969 (nreverse rtn)))
21971 (defun org-export (&optional arg)
21972 (interactive)
21973 (let ((help "[t] insert the export option template
21974 \[v] limit export to visible part of outline tree
21976 \[a] export as ASCII
21978 \[h] export as HTML
21979 \[H] export as HTML to temporary buffer
21980 \[R] export region as HTML
21981 \[b] export as HTML and browse immediately
21982 \[x] export as XOXO
21984 \[l] export as LaTeX
21985 \[L] export as LaTeX to temporary buffer
21987 \[i] export current file as iCalendar file
21988 \[I] export all agenda files as iCalendar files
21989 \[c] export agenda files into combined iCalendar file
21991 \[F] publish current file
21992 \[P] publish current project
21993 \[X] publish... (project will be prompted for)
21994 \[A] publish all projects")
21995 (cmds
21996 '((?t . org-insert-export-options-template)
21997 (?v . org-export-visible)
21998 (?a . org-export-as-ascii)
21999 (?h . org-export-as-html)
22000 (?b . org-export-as-html-and-open)
22001 (?H . org-export-as-html-to-buffer)
22002 (?R . org-export-region-as-html)
22003 (?x . org-export-as-xoxo)
22004 (?l . org-export-as-latex)
22005 (?L . org-export-as-latex-to-buffer)
22006 (?i . org-export-icalendar-this-file)
22007 (?I . org-export-icalendar-all-agenda-files)
22008 (?c . org-export-icalendar-combine-agenda-files)
22009 (?F . org-publish-current-file)
22010 (?P . org-publish-current-project)
22011 (?X . org-publish)
22012 (?A . org-publish-all)))
22013 r1 r2 ass)
22014 (save-window-excursion
22015 (delete-other-windows)
22016 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22017 (princ help))
22018 (message "Select command: ")
22019 (setq r1 (read-char-exclusive)))
22020 (setq r2 (if (< r1 27) (+ r1 96) r1))
22021 (if (setq ass (assq r2 cmds))
22022 (call-interactively (cdr ass))
22023 (error "No command associated with key %c" r1))))
22025 (defconst org-html-entities
22026 '(("nbsp")
22027 ("iexcl")
22028 ("cent")
22029 ("pound")
22030 ("curren")
22031 ("yen")
22032 ("brvbar")
22033 ("vert" . "&#124;")
22034 ("sect")
22035 ("uml")
22036 ("copy")
22037 ("ordf")
22038 ("laquo")
22039 ("not")
22040 ("shy")
22041 ("reg")
22042 ("macr")
22043 ("deg")
22044 ("plusmn")
22045 ("sup2")
22046 ("sup3")
22047 ("acute")
22048 ("micro")
22049 ("para")
22050 ("middot")
22051 ("odot"."o")
22052 ("star"."*")
22053 ("cedil")
22054 ("sup1")
22055 ("ordm")
22056 ("raquo")
22057 ("frac14")
22058 ("frac12")
22059 ("frac34")
22060 ("iquest")
22061 ("Agrave")
22062 ("Aacute")
22063 ("Acirc")
22064 ("Atilde")
22065 ("Auml")
22066 ("Aring") ("AA"."&Aring;")
22067 ("AElig")
22068 ("Ccedil")
22069 ("Egrave")
22070 ("Eacute")
22071 ("Ecirc")
22072 ("Euml")
22073 ("Igrave")
22074 ("Iacute")
22075 ("Icirc")
22076 ("Iuml")
22077 ("ETH")
22078 ("Ntilde")
22079 ("Ograve")
22080 ("Oacute")
22081 ("Ocirc")
22082 ("Otilde")
22083 ("Ouml")
22084 ("times")
22085 ("Oslash")
22086 ("Ugrave")
22087 ("Uacute")
22088 ("Ucirc")
22089 ("Uuml")
22090 ("Yacute")
22091 ("THORN")
22092 ("szlig")
22093 ("agrave")
22094 ("aacute")
22095 ("acirc")
22096 ("atilde")
22097 ("auml")
22098 ("aring")
22099 ("aelig")
22100 ("ccedil")
22101 ("egrave")
22102 ("eacute")
22103 ("ecirc")
22104 ("euml")
22105 ("igrave")
22106 ("iacute")
22107 ("icirc")
22108 ("iuml")
22109 ("eth")
22110 ("ntilde")
22111 ("ograve")
22112 ("oacute")
22113 ("ocirc")
22114 ("otilde")
22115 ("ouml")
22116 ("divide")
22117 ("oslash")
22118 ("ugrave")
22119 ("uacute")
22120 ("ucirc")
22121 ("uuml")
22122 ("yacute")
22123 ("thorn")
22124 ("yuml")
22125 ("fnof")
22126 ("Alpha")
22127 ("Beta")
22128 ("Gamma")
22129 ("Delta")
22130 ("Epsilon")
22131 ("Zeta")
22132 ("Eta")
22133 ("Theta")
22134 ("Iota")
22135 ("Kappa")
22136 ("Lambda")
22137 ("Mu")
22138 ("Nu")
22139 ("Xi")
22140 ("Omicron")
22141 ("Pi")
22142 ("Rho")
22143 ("Sigma")
22144 ("Tau")
22145 ("Upsilon")
22146 ("Phi")
22147 ("Chi")
22148 ("Psi")
22149 ("Omega")
22150 ("alpha")
22151 ("beta")
22152 ("gamma")
22153 ("delta")
22154 ("epsilon")
22155 ("varepsilon"."&epsilon;")
22156 ("zeta")
22157 ("eta")
22158 ("theta")
22159 ("iota")
22160 ("kappa")
22161 ("lambda")
22162 ("mu")
22163 ("nu")
22164 ("xi")
22165 ("omicron")
22166 ("pi")
22167 ("rho")
22168 ("sigmaf") ("varsigma"."&sigmaf;")
22169 ("sigma")
22170 ("tau")
22171 ("upsilon")
22172 ("phi")
22173 ("chi")
22174 ("psi")
22175 ("omega")
22176 ("thetasym") ("vartheta"."&thetasym;")
22177 ("upsih")
22178 ("piv")
22179 ("bull") ("bullet"."&bull;")
22180 ("hellip") ("dots"."&hellip;")
22181 ("prime")
22182 ("Prime")
22183 ("oline")
22184 ("frasl")
22185 ("weierp")
22186 ("image")
22187 ("real")
22188 ("trade")
22189 ("alefsym")
22190 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22191 ("uarr") ("uparrow"."&uarr;")
22192 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22193 ("darr")("downarrow"."&darr;")
22194 ("harr") ("leftrightarrow"."&harr;")
22195 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22196 ("lArr") ("Leftarrow"."&lArr;")
22197 ("uArr") ("Uparrow"."&uArr;")
22198 ("rArr") ("Rightarrow"."&rArr;")
22199 ("dArr") ("Downarrow"."&dArr;")
22200 ("hArr") ("Leftrightarrow"."&hArr;")
22201 ("forall")
22202 ("part") ("partial"."&part;")
22203 ("exist") ("exists"."&exist;")
22204 ("empty") ("emptyset"."&empty;")
22205 ("nabla")
22206 ("isin") ("in"."&isin;")
22207 ("notin")
22208 ("ni")
22209 ("prod")
22210 ("sum")
22211 ("minus")
22212 ("lowast") ("ast"."&lowast;")
22213 ("radic")
22214 ("prop") ("proptp"."&prop;")
22215 ("infin") ("infty"."&infin;")
22216 ("ang") ("angle"."&ang;")
22217 ("and") ("vee"."&and;")
22218 ("or") ("wedge"."&or;")
22219 ("cap")
22220 ("cup")
22221 ("int")
22222 ("there4")
22223 ("sim")
22224 ("cong") ("simeq"."&cong;")
22225 ("asymp")("approx"."&asymp;")
22226 ("ne") ("neq"."&ne;")
22227 ("equiv")
22228 ("le")
22229 ("ge")
22230 ("sub") ("subset"."&sub;")
22231 ("sup") ("supset"."&sup;")
22232 ("nsub")
22233 ("sube")
22234 ("supe")
22235 ("oplus")
22236 ("otimes")
22237 ("perp")
22238 ("sdot") ("cdot"."&sdot;")
22239 ("lceil")
22240 ("rceil")
22241 ("lfloor")
22242 ("rfloor")
22243 ("lang")
22244 ("rang")
22245 ("loz") ("Diamond"."&loz;")
22246 ("spades") ("spadesuit"."&spades;")
22247 ("clubs") ("clubsuit"."&clubs;")
22248 ("hearts") ("diamondsuit"."&hearts;")
22249 ("diams") ("diamondsuit"."&diams;")
22250 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22251 ("quot")
22252 ("amp")
22253 ("lt")
22254 ("gt")
22255 ("OElig")
22256 ("oelig")
22257 ("Scaron")
22258 ("scaron")
22259 ("Yuml")
22260 ("circ")
22261 ("tilde")
22262 ("ensp")
22263 ("emsp")
22264 ("thinsp")
22265 ("zwnj")
22266 ("zwj")
22267 ("lrm")
22268 ("rlm")
22269 ("ndash")
22270 ("mdash")
22271 ("lsquo")
22272 ("rsquo")
22273 ("sbquo")
22274 ("ldquo")
22275 ("rdquo")
22276 ("bdquo")
22277 ("dagger")
22278 ("Dagger")
22279 ("permil")
22280 ("lsaquo")
22281 ("rsaquo")
22282 ("euro")
22284 ("arccos"."arccos")
22285 ("arcsin"."arcsin")
22286 ("arctan"."arctan")
22287 ("arg"."arg")
22288 ("cos"."cos")
22289 ("cosh"."cosh")
22290 ("cot"."cot")
22291 ("coth"."coth")
22292 ("csc"."csc")
22293 ("deg"."deg")
22294 ("det"."det")
22295 ("dim"."dim")
22296 ("exp"."exp")
22297 ("gcd"."gcd")
22298 ("hom"."hom")
22299 ("inf"."inf")
22300 ("ker"."ker")
22301 ("lg"."lg")
22302 ("lim"."lim")
22303 ("liminf"."liminf")
22304 ("limsup"."limsup")
22305 ("ln"."ln")
22306 ("log"."log")
22307 ("max"."max")
22308 ("min"."min")
22309 ("Pr"."Pr")
22310 ("sec"."sec")
22311 ("sin"."sin")
22312 ("sinh"."sinh")
22313 ("sup"."sup")
22314 ("tan"."tan")
22315 ("tanh"."tanh")
22317 "Entities for TeX->HTML translation.
22318 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22319 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22320 In that case, \"\\ent\" will be translated to \"&other;\".
22321 The list contains HTML entities for Latin-1, Greek and other symbols.
22322 It is supplemented by a number of commonly used TeX macros with appropriate
22323 translations. There is currently no way for users to extend this.")
22325 ;;; General functions for all backends
22327 (defun org-cleaned-string-for-export (string &rest parameters)
22328 "Cleanup a buffer STRING so that links can be created safely."
22329 (interactive)
22330 (let* ((re-radio (and org-target-link-regexp
22331 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22332 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22333 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22334 (re-archive (concat ":" org-archive-tag ":"))
22335 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22336 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22337 (htmlp (plist-get parameters :for-html))
22338 (asciip (plist-get parameters :for-ascii))
22339 (latexp (plist-get parameters :for-LaTeX))
22340 (commentsp (plist-get parameters :comments))
22341 (archived-trees (plist-get parameters :archived-trees))
22342 (inhibit-read-only t)
22343 (outline-regexp "\\*+ ")
22344 a b xx
22345 rtn p)
22346 (with-current-buffer (get-buffer-create " org-mode-tmp")
22347 (erase-buffer)
22348 (insert string)
22349 ;; Remove license-to-kill stuff
22350 (while (setq p (text-property-any (point-min) (point-max)
22351 :org-license-to-kill t))
22352 (delete-region p (next-single-property-change p :org-license-to-kill)))
22354 (let ((org-inhibit-startup t)) (org-mode))
22355 (untabify (point-min) (point-max))
22357 ;; Get the correct stuff before the first headline
22358 (when (plist-get parameters :skip-before-1st-heading)
22359 (goto-char (point-min))
22360 (when (re-search-forward "^\\*+[ \t]" nil t)
22361 (delete-region (point-min) (match-beginning 0))
22362 (goto-char (point-min))
22363 (insert "\n")))
22364 (when (plist-get parameters :add-text)
22365 (goto-char (point-min))
22366 (insert (plist-get parameters :add-text) "\n"))
22368 ;; Get rid of archived trees
22369 (when (not (eq archived-trees t))
22370 (goto-char (point-min))
22371 (while (re-search-forward re-archive nil t)
22372 (if (not (org-on-heading-p t))
22373 (org-end-of-subtree t)
22374 (beginning-of-line 1)
22375 (setq a (if archived-trees
22376 (1+ (point-at-eol)) (point))
22377 b (org-end-of-subtree t))
22378 (if (> b a) (delete-region a b)))))
22380 ;; Get rid of drawers
22381 (unless (eq t org-export-with-drawers)
22382 (goto-char (point-min))
22383 (let ((re (concat "^[ \t]*:\\("
22384 (mapconcat 'identity
22385 (if (listp org-export-with-drawers)
22386 org-export-with-drawers
22387 org-drawers)
22388 "\\|")
22389 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22390 (while (re-search-forward re nil t)
22391 (replace-match ""))))
22393 ;; Find targets in comments and move them out of comments,
22394 ;; but mark them as targets that should be invisible
22395 (goto-char (point-min))
22396 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22397 (replace-match "\\1(INVISIBLE)"))
22399 ;; Protect backend specific stuff, throw away the others.
22400 (goto-char (point-min))
22401 (let ((formatters
22402 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22403 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22404 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22405 fmt)
22406 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22407 (add-text-properties (match-beginning 0) (match-end 0)
22408 '(org-protected t)))
22409 (while formatters
22410 (setq fmt (pop formatters))
22411 (when (car fmt)
22412 (goto-char (point-min))
22413 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22414 ":[ \t]*\\(.*\\)") nil t)
22415 (replace-match "\\1" t)
22416 (add-text-properties
22417 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22418 '(org-protected t))))
22419 (goto-char (point-min))
22420 (while (re-search-forward
22421 (concat "^#\\+"
22422 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22423 (cadddr fmt) "\\>.*\n?") nil t)
22424 (if (car fmt)
22425 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22426 '(org-protected t))
22427 (delete-region (match-beginning 0) (match-end 0))))))
22429 ;; Protect quoted subtrees
22430 (goto-char (point-min))
22431 (while (re-search-forward re-quote nil t)
22432 (goto-char (match-beginning 0))
22433 (end-of-line 1)
22434 (add-text-properties (point) (org-end-of-subtree t)
22435 '(org-protected t)))
22437 ;; Remove subtrees that are commented
22438 (goto-char (point-min))
22439 (while (re-search-forward re-commented nil t)
22440 (goto-char (match-beginning 0))
22441 (delete-region (point) (org-end-of-subtree t)))
22443 ;; Remove special table lines
22444 (when org-export-table-remove-special-lines
22445 (goto-char (point-min))
22446 (while (re-search-forward "^[ \t]*|" nil t)
22447 (beginning-of-line 1)
22448 (if (or (looking-at "[ \t]*| *[!_^] *|")
22449 (and (looking-at ".*?| *<[0-9]+> *|")
22450 (not (looking-at ".*?| *[^ <|]"))))
22451 (delete-region (max (point-min) (1- (point-at-bol)))
22452 (point-at-eol))
22453 (end-of-line 1))))
22455 ;; Specific LaTeX stuff
22456 (when latexp
22457 (require 'org-export-latex nil)
22458 (org-export-latex-cleaned-string))
22460 ;; Specific HTML stuff
22461 (when htmlp
22462 ;; Convert LaTeX fragments to images
22463 (when (plist-get parameters :LaTeX-fragments)
22464 (org-format-latex
22465 (concat "ltxpng/" (file-name-sans-extension
22466 (file-name-nondirectory
22467 org-current-export-file)))
22468 org-current-export-dir nil "Creating LaTeX image %s"))
22469 (message "Exporting..."))
22471 ;; Remove or replace comments
22472 (goto-char (point-min))
22473 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
22474 (if commentsp
22475 (progn (add-text-properties
22476 (match-beginning 0) (match-end 0) '(org-protected t))
22477 (replace-match (format commentsp (match-string 1)) t t))
22478 (replace-match "")))
22480 ;; Find matches for radio targets and turn them into internal links
22481 (goto-char (point-min))
22482 (when re-radio
22483 (while (re-search-forward re-radio nil t)
22484 (org-if-unprotected
22485 (replace-match "\\1[[\\2]]"))))
22487 ;; Find all links that contain a newline and put them into a single line
22488 (goto-char (point-min))
22489 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
22490 (org-if-unprotected
22491 (replace-match "\\1 \\3")
22492 (goto-char (match-beginning 0))))
22495 ;; Normalize links: Convert angle and plain links into bracket links
22496 ;; Expand link abbreviations
22497 (goto-char (point-min))
22498 (while (re-search-forward re-plain-link nil t)
22499 (goto-char (1- (match-end 0)))
22500 (org-if-unprotected
22501 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22502 ":" (match-string 3) "]]")))
22503 ;; added 'org-link face to links
22504 (put-text-property 0 (length s) 'face 'org-link s)
22505 (replace-match s t t))))
22506 (goto-char (point-min))
22507 (while (re-search-forward re-angle-link nil t)
22508 (goto-char (1- (match-end 0)))
22509 (org-if-unprotected
22510 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22511 ":" (match-string 3) "]]")))
22512 (put-text-property 0 (length s) 'face 'org-link s)
22513 (replace-match s t t))))
22514 (goto-char (point-min))
22515 (while (re-search-forward org-bracket-link-regexp nil t)
22516 (org-if-unprotected
22517 (let* ((s (concat "[[" (setq xx (save-match-data
22518 (org-link-expand-abbrev (match-string 1))))
22520 (if (match-end 3)
22521 (match-string 2)
22522 (concat "[" xx "]"))
22523 "]")))
22524 (put-text-property 0 (length s) 'face 'org-link s)
22525 (replace-match s t t))))
22527 ;; Find multiline emphasis and put them into single line
22528 (when (plist-get parameters :emph-multiline)
22529 (goto-char (point-min))
22530 (while (re-search-forward org-emph-re nil t)
22531 (if (not (= (char-after (match-beginning 3))
22532 (char-after (match-beginning 4))))
22533 (org-if-unprotected
22534 (subst-char-in-region (match-beginning 0) (match-end 0)
22535 ?\n ?\ t)
22536 (goto-char (1- (match-end 0))))
22537 (goto-char (1+ (match-beginning 0))))))
22539 (setq rtn (buffer-string)))
22540 (kill-buffer " org-mode-tmp")
22541 rtn))
22543 (defun org-export-grab-title-from-buffer ()
22544 "Get a title for the current document, from looking at the buffer."
22545 (let ((inhibit-read-only t))
22546 (save-excursion
22547 (goto-char (point-min))
22548 (let ((end (save-excursion (outline-next-heading) (point))))
22549 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
22550 ;; Mark the line so that it will not be exported as normal text.
22551 (org-unmodified
22552 (add-text-properties (match-beginning 0) (match-end 0)
22553 (list :org-license-to-kill t)))
22554 ;; Return the title string
22555 (org-trim (match-string 0)))))))
22557 (defun org-export-get-title-from-subtree ()
22558 "Return subtree title and exclude it from export."
22559 (let (title (m (mark)))
22560 (save-excursion
22561 (goto-char (region-beginning))
22562 (when (and (org-at-heading-p)
22563 (>= (org-end-of-subtree t t) (region-end)))
22564 ;; This is a subtree, we take the title from the first heading
22565 (goto-char (region-beginning))
22566 (looking-at org-todo-line-regexp)
22567 (setq title (match-string 3))
22568 (org-unmodified
22569 (add-text-properties (point) (1+ (point-at-eol))
22570 (list :org-license-to-kill t)))))
22571 title))
22573 (defun org-solidify-link-text (s &optional alist)
22574 "Take link text and make a safe target out of it."
22575 (save-match-data
22576 (let* ((rtn
22577 (mapconcat
22578 'identity
22579 (org-split-string s "[ \t\r\n]+") "--"))
22580 (a (assoc rtn alist)))
22581 (or (cdr a) rtn))))
22583 (defun org-get-min-level (lines)
22584 "Get the minimum level in LINES."
22585 (let ((re "^\\(\\*+\\) ") l min)
22586 (catch 'exit
22587 (while (setq l (pop lines))
22588 (if (string-match re l)
22589 (throw 'exit (org-tr-level (length (match-string 1 l))))))
22590 1)))
22592 ;; Variable holding the vector with section numbers
22593 (defvar org-section-numbers (make-vector org-level-max 0))
22595 (defun org-init-section-numbers ()
22596 "Initialize the vector for the section numbers."
22597 (let* ((level -1)
22598 (numbers (nreverse (org-split-string "" "\\.")))
22599 (depth (1- (length org-section-numbers)))
22600 (i depth) number-string)
22601 (while (>= i 0)
22602 (if (> i level)
22603 (aset org-section-numbers i 0)
22604 (setq number-string (or (car numbers) "0"))
22605 (if (string-match "\\`[A-Z]\\'" number-string)
22606 (aset org-section-numbers i
22607 (- (string-to-char number-string) ?A -1))
22608 (aset org-section-numbers i (string-to-number number-string)))
22609 (pop numbers))
22610 (setq i (1- i)))))
22612 (defun org-section-number (&optional level)
22613 "Return a string with the current section number.
22614 When LEVEL is non-nil, increase section numbers on that level."
22615 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
22616 (when level
22617 (when (> level -1)
22618 (aset org-section-numbers
22619 level (1+ (aref org-section-numbers level))))
22620 (setq idx (1+ level))
22621 (while (<= idx depth)
22622 (if (not (= idx 1))
22623 (aset org-section-numbers idx 0))
22624 (setq idx (1+ idx))))
22625 (setq idx 0)
22626 (while (<= idx depth)
22627 (setq n (aref org-section-numbers idx))
22628 (setq string (concat string (if (not (string= string "")) "." "")
22629 (int-to-string n)))
22630 (setq idx (1+ idx)))
22631 (save-match-data
22632 (if (string-match "\\`\\([@0]\\.\\)+" string)
22633 (setq string (replace-match "" t nil string)))
22634 (if (string-match "\\(\\.0\\)+\\'" string)
22635 (setq string (replace-match "" t nil string))))
22636 string))
22638 ;;; ASCII export
22640 (defvar org-last-level nil) ; dynamically scoped variable
22641 (defvar org-min-level nil) ; dynamically scoped variable
22642 (defvar org-levels-open nil) ; dynamically scoped parameter
22643 (defvar org-ascii-current-indentation nil) ; For communication
22645 (defun org-export-as-ascii (arg)
22646 "Export the outline as a pretty ASCII file.
22647 If there is an active region, export only the region.
22648 The prefix ARG specifies how many levels of the outline should become
22649 underlined headlines. The default is 3."
22650 (interactive "P")
22651 (setq-default org-todo-line-regexp org-todo-line-regexp)
22652 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22653 (org-infile-export-plist)))
22654 (region-p (org-region-active-p))
22655 (subtree-p
22656 (when region-p
22657 (save-excursion
22658 (goto-char (region-beginning))
22659 (and (org-at-heading-p)
22660 (>= (org-end-of-subtree t t) (region-end))))))
22661 (custom-times org-display-custom-times)
22662 (org-ascii-current-indentation '(0 . 0))
22663 (level 0) line txt
22664 (umax nil)
22665 (umax-toc nil)
22666 (case-fold-search nil)
22667 (filename (concat (file-name-as-directory
22668 (org-export-directory :ascii opt-plist))
22669 (file-name-sans-extension
22670 (or (and subtree-p
22671 (org-entry-get (region-beginning)
22672 "EXPORT_FILE_NAME" t))
22673 (file-name-nondirectory buffer-file-name)))
22674 ".txt"))
22675 (filename (if (equal (file-truename filename)
22676 (file-truename buffer-file-name))
22677 (concat filename ".txt")
22678 filename))
22679 (buffer (find-file-noselect filename))
22680 (org-levels-open (make-vector org-level-max nil))
22681 (odd org-odd-levels-only)
22682 (date (plist-get opt-plist :date))
22683 (author (plist-get opt-plist :author))
22684 (title (or (and subtree-p (org-export-get-title-from-subtree))
22685 (plist-get opt-plist :title)
22686 (and (not
22687 (plist-get opt-plist :skip-before-1st-heading))
22688 (org-export-grab-title-from-buffer))
22689 (file-name-sans-extension
22690 (file-name-nondirectory buffer-file-name))))
22691 (email (plist-get opt-plist :email))
22692 (language (plist-get opt-plist :language))
22693 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22694 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22695 (todo nil)
22696 (lang-words nil)
22697 (region
22698 (buffer-substring
22699 (if (org-region-active-p) (region-beginning) (point-min))
22700 (if (org-region-active-p) (region-end) (point-max))))
22701 (lines (org-split-string
22702 (org-cleaned-string-for-export
22703 region
22704 :for-ascii t
22705 :skip-before-1st-heading
22706 (plist-get opt-plist :skip-before-1st-heading)
22707 :archived-trees
22708 (plist-get opt-plist :archived-trees)
22709 :add-text (plist-get opt-plist :text))
22710 "\n"))
22711 thetoc have-headings first-heading-pos
22712 table-open table-buffer)
22714 (let ((inhibit-read-only t))
22715 (org-unmodified
22716 (remove-text-properties (point-min) (point-max)
22717 '(:org-license-to-kill t))))
22719 (setq org-min-level (org-get-min-level lines))
22720 (setq org-last-level org-min-level)
22721 (org-init-section-numbers)
22723 (find-file-noselect filename)
22725 (setq lang-words (or (assoc language org-export-language-setup)
22726 (assoc "en" org-export-language-setup)))
22727 (switch-to-buffer-other-window buffer)
22728 (erase-buffer)
22729 (fundamental-mode)
22730 ;; create local variables for all options, to make sure all called
22731 ;; functions get the correct information
22732 (mapcar (lambda (x)
22733 (set (make-local-variable (cdr x))
22734 (plist-get opt-plist (car x))))
22735 org-export-plist-vars)
22736 (org-set-local 'org-odd-levels-only odd)
22737 (setq umax (if arg (prefix-numeric-value arg)
22738 org-export-headline-levels))
22739 (setq umax-toc (if (integerp org-export-with-toc)
22740 (min org-export-with-toc umax)
22741 umax))
22743 ;; File header
22744 (if title (org-insert-centered title ?=))
22745 (insert "\n")
22746 (if (and (or author email)
22747 org-export-author-info)
22748 (insert (concat (nth 1 lang-words) ": " (or author "")
22749 (if email (concat " <" email ">") "")
22750 "\n")))
22752 (cond
22753 ((and date (string-match "%" date))
22754 (setq date (format-time-string date (current-time))))
22755 (date)
22756 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22758 (if (and date org-export-time-stamp-file)
22759 (insert (concat (nth 2 lang-words) ": " date"\n")))
22761 (insert "\n\n")
22763 (if org-export-with-toc
22764 (progn
22765 (push (concat (nth 3 lang-words) "\n") thetoc)
22766 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22767 (mapcar '(lambda (line)
22768 (if (string-match org-todo-line-regexp
22769 line)
22770 ;; This is a headline
22771 (progn
22772 (setq have-headings t)
22773 (setq level (- (match-end 1) (match-beginning 1))
22774 level (org-tr-level level)
22775 txt (match-string 3 line)
22776 todo
22777 (or (and org-export-mark-todo-in-toc
22778 (match-beginning 2)
22779 (not (member (match-string 2 line)
22780 org-done-keywords)))
22781 ; TODO, not DONE
22782 (and org-export-mark-todo-in-toc
22783 (= level umax-toc)
22784 (org-search-todo-below
22785 line lines level))))
22786 (setq txt (org-html-expand-for-ascii txt))
22788 (while (string-match org-bracket-link-regexp txt)
22789 (setq txt
22790 (replace-match
22791 (match-string (if (match-end 2) 3 1) txt)
22792 t t txt)))
22794 (if (and (memq org-export-with-tags '(not-in-toc nil))
22795 (string-match
22796 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22797 txt))
22798 (setq txt (replace-match "" t t txt)))
22799 (if (string-match quote-re0 txt)
22800 (setq txt (replace-match "" t t txt)))
22802 (if org-export-with-section-numbers
22803 (setq txt (concat (org-section-number level)
22804 " " txt)))
22805 (if (<= level umax-toc)
22806 (progn
22807 (push
22808 (concat
22809 (make-string
22810 (* (max 0 (- level org-min-level)) 4) ?\ )
22811 (format (if todo "%s (*)\n" "%s\n") txt))
22812 thetoc)
22813 (setq org-last-level level))
22814 ))))
22815 lines)
22816 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22818 (org-init-section-numbers)
22819 (while (setq line (pop lines))
22820 ;; Remove the quoted HTML tags.
22821 (setq line (org-html-expand-for-ascii line))
22822 ;; Remove targets
22823 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22824 (setq line (replace-match "" t t line)))
22825 ;; Replace internal links
22826 (while (string-match org-bracket-link-regexp line)
22827 (setq line (replace-match
22828 (if (match-end 3) "[\\3]" "[\\1]")
22829 t nil line)))
22830 (when custom-times
22831 (setq line (org-translate-time line)))
22832 (cond
22833 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22834 ;; a Headline
22835 (setq first-heading-pos (or first-heading-pos (point)))
22836 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22837 txt (match-string 2 line))
22838 (org-ascii-level-start level txt umax lines))
22840 ((and org-export-with-tables
22841 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22842 (if (not table-open)
22843 ;; New table starts
22844 (setq table-open t table-buffer nil))
22845 ;; Accumulate lines
22846 (setq table-buffer (cons line table-buffer))
22847 (when (or (not lines)
22848 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22849 (car lines))))
22850 (setq table-open nil
22851 table-buffer (nreverse table-buffer))
22852 (insert (mapconcat
22853 (lambda (x)
22854 (org-fix-indentation x org-ascii-current-indentation))
22855 (org-format-table-ascii table-buffer)
22856 "\n") "\n")))
22858 (setq line (org-fix-indentation line org-ascii-current-indentation))
22859 (if (and org-export-with-fixed-width
22860 (string-match "^\\([ \t]*\\)\\(:\\)" line))
22861 (setq line (replace-match "\\1" nil nil line)))
22862 (insert line "\n"))))
22864 (normal-mode)
22866 ;; insert the table of contents
22867 (when thetoc
22868 (goto-char (point-min))
22869 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
22870 (progn
22871 (goto-char (match-beginning 0))
22872 (replace-match ""))
22873 (goto-char first-heading-pos))
22874 (mapc 'insert thetoc)
22875 (or (looking-at "[ \t]*\n[ \t]*\n")
22876 (insert "\n\n")))
22878 ;; Convert whitespace place holders
22879 (goto-char (point-min))
22880 (let (beg end)
22881 (while (setq beg (next-single-property-change (point) 'org-whitespace))
22882 (setq end (next-single-property-change beg 'org-whitespace))
22883 (goto-char beg)
22884 (delete-region beg end)
22885 (insert (make-string (- end beg) ?\ ))))
22887 (save-buffer)
22888 ;; remove display and invisible chars
22889 (let (beg end)
22890 (goto-char (point-min))
22891 (while (setq beg (next-single-property-change (point) 'display))
22892 (setq end (next-single-property-change beg 'display))
22893 (delete-region beg end)
22894 (goto-char beg)
22895 (insert "=>"))
22896 (goto-char (point-min))
22897 (while (setq beg (next-single-property-change (point) 'org-cwidth))
22898 (setq end (next-single-property-change beg 'org-cwidth))
22899 (delete-region beg end)
22900 (goto-char beg)))
22901 (goto-char (point-min))))
22903 (defun org-search-todo-below (line lines level)
22904 "Search the subtree below LINE for any TODO entries."
22905 (let ((rest (cdr (memq line lines)))
22906 (re org-todo-line-regexp)
22907 line lv todo)
22908 (catch 'exit
22909 (while (setq line (pop rest))
22910 (if (string-match re line)
22911 (progn
22912 (setq lv (- (match-end 1) (match-beginning 1))
22913 todo (and (match-beginning 2)
22914 (not (member (match-string 2 line)
22915 org-done-keywords))))
22916 ; TODO, not DONE
22917 (if (<= lv level) (throw 'exit nil))
22918 (if todo (throw 'exit t))))))))
22920 (defun org-html-expand-for-ascii (line)
22921 "Handle quoted HTML for ASCII export."
22922 (if org-export-html-expand
22923 (while (string-match "@<[^<>\n]*>" line)
22924 ;; We just remove the tags for now.
22925 (setq line (replace-match "" nil nil line))))
22926 line)
22928 (defun org-insert-centered (s &optional underline)
22929 "Insert the string S centered and underline it with character UNDERLINE."
22930 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
22931 (insert (make-string ind ?\ ) s "\n")
22932 (if underline
22933 (insert (make-string ind ?\ )
22934 (make-string (string-width s) underline)
22935 "\n"))))
22937 (defun org-ascii-level-start (level title umax &optional lines)
22938 "Insert a new level in ASCII export."
22939 (let (char (n (- level umax 1)) (ind 0))
22940 (if (> level umax)
22941 (progn
22942 (insert (make-string (* 2 n) ?\ )
22943 (char-to-string (nth (% n (length org-export-ascii-bullets))
22944 org-export-ascii-bullets))
22945 " " title "\n")
22946 ;; find the indentation of the next non-empty line
22947 (catch 'stop
22948 (while lines
22949 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
22950 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
22951 (throw 'stop (setq ind (org-get-indentation (car lines)))))
22952 (pop lines)))
22953 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
22954 (if (or (not (equal (char-before) ?\n))
22955 (not (equal (char-before (1- (point))) ?\n)))
22956 (insert "\n"))
22957 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
22958 (unless org-export-with-tags
22959 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
22960 (setq title (replace-match "" t t title))))
22961 (if org-export-with-section-numbers
22962 (setq title (concat (org-section-number level) " " title)))
22963 (insert title "\n" (make-string (string-width title) char) "\n")
22964 (setq org-ascii-current-indentation '(0 . 0)))))
22966 (defun org-export-visible (type arg)
22967 "Create a copy of the visible part of the current buffer, and export it.
22968 The copy is created in a temporary buffer and removed after use.
22969 TYPE is the final key (as a string) that also select the export command in
22970 the `C-c C-e' export dispatcher.
22971 As a special case, if the you type SPC at the prompt, the temporary
22972 org-mode file will not be removed but presented to you so that you can
22973 continue to use it. The prefix arg ARG is passed through to the exporting
22974 command."
22975 (interactive
22976 (list (progn
22977 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
22978 (read-char-exclusive))
22979 current-prefix-arg))
22980 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
22981 (error "Invalid export key"))
22982 (let* ((binding (cdr (assoc type
22983 '((?a . org-export-as-ascii)
22984 (?\C-a . org-export-as-ascii)
22985 (?b . org-export-as-html-and-open)
22986 (?\C-b . org-export-as-html-and-open)
22987 (?h . org-export-as-html)
22988 (?H . org-export-as-html-to-buffer)
22989 (?R . org-export-region-as-html)
22990 (?x . org-export-as-xoxo)))))
22991 (keepp (equal type ?\ ))
22992 (file buffer-file-name)
22993 (buffer (get-buffer-create "*Org Export Visible*"))
22994 s e)
22995 ;; Need to hack the drawers here.
22996 (save-excursion
22997 (goto-char (point-min))
22998 (while (re-search-forward org-drawer-regexp nil t)
22999 (goto-char (match-beginning 1))
23000 (or (org-invisible-p) (org-flag-drawer nil))))
23001 (with-current-buffer buffer (erase-buffer))
23002 (save-excursion
23003 (setq s (goto-char (point-min)))
23004 (while (not (= (point) (point-max)))
23005 (goto-char (org-find-invisible))
23006 (append-to-buffer buffer s (point))
23007 (setq s (goto-char (org-find-visible))))
23008 (org-cycle-hide-drawers 'all)
23009 (goto-char (point-min))
23010 (unless keepp
23011 ;; Copy all comment lines to the end, to make sure #+ settings are
23012 ;; still available for the second export step. Kind of a hack, but
23013 ;; does do the trick.
23014 (if (looking-at "#[^\r\n]*")
23015 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23016 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23017 (append-to-buffer buffer (1+ (match-beginning 0))
23018 (min (point-max) (1+ (match-end 0))))))
23019 (set-buffer buffer)
23020 (let ((buffer-file-name file)
23021 (org-inhibit-startup t))
23022 (org-mode)
23023 (show-all)
23024 (unless keepp (funcall binding arg))))
23025 (if (not keepp)
23026 (kill-buffer buffer)
23027 (switch-to-buffer-other-window buffer)
23028 (goto-char (point-min)))))
23030 (defun org-find-visible ()
23031 (let ((s (point)))
23032 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23033 (get-char-property s 'invisible)))
23035 (defun org-find-invisible ()
23036 (let ((s (point)))
23037 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23038 (not (get-char-property s 'invisible))))
23041 ;;; HTML export
23043 (defun org-get-current-options ()
23044 "Return a string with current options as keyword options.
23045 Does include HTML export options as well as TODO and CATEGORY stuff."
23046 (format
23047 "#+TITLE: %s
23048 #+AUTHOR: %s
23049 #+EMAIL: %s
23050 #+LANGUAGE: %s
23051 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23052 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23053 #+CATEGORY: %s
23054 #+SEQ_TODO: %s
23055 #+TYP_TODO: %s
23056 #+PRIORITIES: %c %c %c
23057 #+DRAWERS: %s
23058 #+STARTUP: %s %s %s %s %s
23059 #+TAGS: %s
23060 #+ARCHIVE: %s
23061 #+LINK: %s
23063 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23064 org-export-headline-levels
23065 org-export-with-section-numbers
23066 org-export-with-toc
23067 org-export-preserve-breaks
23068 org-export-html-expand
23069 org-export-with-fixed-width
23070 org-export-with-tables
23071 org-export-with-sub-superscripts
23072 org-export-with-footnotes
23073 org-export-with-emphasize
23074 org-export-with-TeX-macros
23075 org-export-with-LaTeX-fragments
23076 org-export-skip-text-before-1st-heading
23077 org-export-with-drawers
23078 org-export-with-tags
23079 (file-name-nondirectory buffer-file-name)
23080 "TODO FEEDBACK VERIFY DONE"
23081 "Me Jason Marie DONE"
23082 org-highest-priority org-lowest-priority org-default-priority
23083 (mapconcat 'identity org-drawers " ")
23084 (cdr (assoc org-startup-folded
23085 '((nil . "showall") (t . "overview") (content . "content"))))
23086 (if org-odd-levels-only "odd" "oddeven")
23087 (if org-hide-leading-stars "hidestars" "showstars")
23088 (if org-startup-align-all-tables "align" "noalign")
23089 (cond ((eq t org-log-done) "logdone")
23090 ((not org-log-done) "nologging")
23091 ((listp org-log-done)
23092 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23093 org-log-done " ")))
23094 (or (mapconcat (lambda (x)
23095 (cond
23096 ((equal '(:startgroup) x) "{")
23097 ((equal '(:endgroup) x) "}")
23098 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23099 (t (car x))))
23100 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23101 org-archive-location
23102 "org file:~/org/%s.org"
23105 (defun org-insert-export-options-template ()
23106 "Insert into the buffer a template with information for exporting."
23107 (interactive)
23108 (if (not (bolp)) (newline))
23109 (let ((s (org-get-current-options)))
23110 (and (string-match "#\\+CATEGORY" s)
23111 (setq s (substring s 0 (match-beginning 0))))
23112 (insert s)))
23114 (defun org-toggle-fixed-width-section (arg)
23115 "Toggle the fixed-width export.
23116 If there is no active region, the QUOTE keyword at the current headline is
23117 inserted or removed. When present, it causes the text between this headline
23118 and the next to be exported as fixed-width text, and unmodified.
23119 If there is an active region, this command adds or removes a colon as the
23120 first character of this line. If the first character of a line is a colon,
23121 this line is also exported in fixed-width font."
23122 (interactive "P")
23123 (let* ((cc 0)
23124 (regionp (org-region-active-p))
23125 (beg (if regionp (region-beginning) (point)))
23126 (end (if regionp (region-end)))
23127 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23128 (re "[ \t]*\\(:\\)")
23129 off)
23130 (if regionp
23131 (save-excursion
23132 (goto-char beg)
23133 (setq cc (current-column))
23134 (beginning-of-line 1)
23135 (setq off (looking-at re))
23136 (while (> nlines 0)
23137 (setq nlines (1- nlines))
23138 (beginning-of-line 1)
23139 (cond
23140 (arg
23141 (move-to-column cc t)
23142 (insert ":\n")
23143 (forward-line -1))
23144 ((and off (looking-at re))
23145 (replace-match "" t t nil 1))
23146 ((not off) (move-to-column cc t) (insert ":")))
23147 (forward-line 1)))
23148 (save-excursion
23149 (org-back-to-heading)
23150 (if (looking-at (concat outline-regexp
23151 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23152 (replace-match "" t t nil 1)
23153 (if (looking-at outline-regexp)
23154 (progn
23155 (goto-char (match-end 0))
23156 (insert org-quote-string " "))))))))
23158 (defun org-export-as-html-and-open (arg)
23159 "Export the outline as HTML and immediately open it with a browser.
23160 If there is an active region, export only the region.
23161 The prefix ARG specifies how many levels of the outline should become
23162 headlines. The default is 3. Lower levels will become bulleted lists."
23163 (interactive "P")
23164 (org-export-as-html arg 'hidden)
23165 (org-open-file buffer-file-name))
23167 (defun org-export-as-html-batch ()
23168 "Call `org-export-as-html', may be used in batch processing as
23169 emacs --batch
23170 --load=$HOME/lib/emacs/org.el
23171 --eval \"(setq org-export-headline-levels 2)\"
23172 --visit=MyFile --funcall org-export-as-html-batch"
23173 (org-export-as-html org-export-headline-levels 'hidden))
23175 (defun org-export-as-html-to-buffer (arg)
23176 "Call `org-exort-as-html` with output to a temporary buffer.
23177 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23178 (interactive "P")
23179 (org-export-as-html arg nil nil "*Org HTML Export*")
23180 (switch-to-buffer-other-window "*Org HTML Export*"))
23182 (defun org-replace-region-by-html (beg end)
23183 "Assume the current region has org-mode syntax, and convert it to HTML.
23184 This can be used in any buffer. For example, you could write an
23185 itemized list in org-mode syntax in an HTML buffer and then use this
23186 command to convert it."
23187 (interactive "r")
23188 (let (reg html buf pop-up-frames)
23189 (save-window-excursion
23190 (if (org-mode-p)
23191 (setq html (org-export-region-as-html
23192 beg end t 'string))
23193 (setq reg (buffer-substring beg end)
23194 buf (get-buffer-create "*Org tmp*"))
23195 (with-current-buffer buf
23196 (erase-buffer)
23197 (insert reg)
23198 (org-mode)
23199 (setq html (org-export-region-as-html
23200 (point-min) (point-max) t 'string)))
23201 (kill-buffer buf)))
23202 (delete-region beg end)
23203 (insert html)))
23205 (defun org-export-region-as-html (beg end &optional body-only buffer)
23206 "Convert region from BEG to END in org-mode buffer to HTML.
23207 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23208 contents, and only produce the region of converted text, useful for
23209 cut-and-paste operations.
23210 If BUFFER is a buffer or a string, use/create that buffer as a target
23211 of the converted HTML. If BUFFER is the symbol `string', return the
23212 produced HTML as a string and leave not buffer behind. For example,
23213 a Lisp program could call this function in the following way:
23215 (setq html (org-export-region-as-html beg end t 'string))
23217 When called interactively, the output buffer is selected, and shown
23218 in a window. A non-interactive call will only retunr the buffer."
23219 (interactive "r\nP")
23220 (when (interactive-p)
23221 (setq buffer "*Org HTML Export*"))
23222 (let ((transient-mark-mode t) (zmacs-regions t)
23223 rtn)
23224 (goto-char end)
23225 (set-mark (point)) ;; to activate the region
23226 (goto-char beg)
23227 (setq rtn (org-export-as-html
23228 nil nil nil
23229 buffer body-only))
23230 (if (fboundp 'deactivate-mark) (deactivate-mark))
23231 (if (and (interactive-p) (bufferp rtn))
23232 (switch-to-buffer-other-window rtn)
23233 rtn)))
23235 (defun org-export-as-html (arg &optional hidden ext-plist
23236 to-buffer body-only)
23237 "Export the outline as a pretty HTML file.
23238 If there is an active region, export only the region. The prefix
23239 ARG specifies how many levels of the outline should become
23240 headlines. The default is 3. Lower levels will become bulleted
23241 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23242 EXT-PLIST is a property list with external parameters overriding
23243 org-mode's default settings, but still inferior to file-local
23244 settings. When TO-BUFFER is non-nil, create a buffer with that
23245 name and export to that buffer. If TO-BUFFER is the symbol `string',
23246 don't leave any buffer behind but just return the resulting HTML as
23247 a string. When BODY-ONLY is set, don't produce the file header and footer,
23248 simply return the content of <body>...</body>, without even
23249 the body tags themselves."
23250 (interactive "P")
23252 ;; Make sure we have a file name when we need it.
23253 (when (and (not (or to-buffer body-only))
23254 (not buffer-file-name))
23255 (if (buffer-base-buffer)
23256 (org-set-local 'buffer-file-name
23257 (with-current-buffer (buffer-base-buffer)
23258 buffer-file-name))
23259 (error "Need a file name to be able to export.")))
23261 (message "Exporting...")
23262 (setq-default org-todo-line-regexp org-todo-line-regexp)
23263 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23264 (setq-default org-done-keywords org-done-keywords)
23265 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23266 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23267 ext-plist
23268 (org-infile-export-plist)))
23270 (style (plist-get opt-plist :style))
23271 (link-validate (plist-get opt-plist :link-validation-function))
23272 valid thetoc have-headings first-heading-pos
23273 (odd org-odd-levels-only)
23274 (region-p (org-region-active-p))
23275 (subtree-p
23276 (when region-p
23277 (save-excursion
23278 (goto-char (region-beginning))
23279 (and (org-at-heading-p)
23280 (>= (org-end-of-subtree t t) (region-end))))))
23281 ;; The following two are dynamically scoped into other
23282 ;; routines below.
23283 (org-current-export-dir (org-export-directory :html opt-plist))
23284 (org-current-export-file buffer-file-name)
23285 (level 0) (line "") (origline "") txt todo
23286 (umax nil)
23287 (umax-toc nil)
23288 (filename (if to-buffer nil
23289 (concat (file-name-as-directory
23290 (org-export-directory :html opt-plist))
23291 (file-name-sans-extension
23292 (or (and subtree-p
23293 (org-entry-get (region-beginning)
23294 "EXPORT_FILE_NAME" t))
23295 (file-name-nondirectory buffer-file-name)))
23296 "." org-export-html-extension)))
23297 (current-dir (if buffer-file-name
23298 (file-name-directory buffer-file-name)
23299 default-directory))
23300 (buffer (if to-buffer
23301 (cond
23302 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23303 (t (get-buffer-create to-buffer)))
23304 (find-file-noselect filename)))
23305 (org-levels-open (make-vector org-level-max nil))
23306 (date (plist-get opt-plist :date))
23307 (author (plist-get opt-plist :author))
23308 (title (or (and subtree-p (org-export-get-title-from-subtree))
23309 (plist-get opt-plist :title)
23310 (and (not
23311 (plist-get opt-plist :skip-before-1st-heading))
23312 (org-export-grab-title-from-buffer))
23313 (and buffer-file-name
23314 (file-name-sans-extension
23315 (file-name-nondirectory buffer-file-name)))
23316 "UNTITLED"))
23317 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23318 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23319 (inquote nil)
23320 (infixed nil)
23321 (in-local-list nil)
23322 (local-list-num nil)
23323 (local-list-indent nil)
23324 (llt org-plain-list-ordered-item-terminator)
23325 (email (plist-get opt-plist :email))
23326 (language (plist-get opt-plist :language))
23327 (lang-words nil)
23328 (target-alist nil) tg
23329 (head-count 0) cnt
23330 (start 0)
23331 (coding-system (and (boundp 'buffer-file-coding-system)
23332 buffer-file-coding-system))
23333 (coding-system-for-write (or org-export-html-coding-system
23334 coding-system))
23335 (save-buffer-coding-system (or org-export-html-coding-system
23336 coding-system))
23337 (charset (and coding-system-for-write
23338 (fboundp 'coding-system-get)
23339 (coding-system-get coding-system-for-write
23340 'mime-charset)))
23341 (region
23342 (buffer-substring
23343 (if region-p (region-beginning) (point-min))
23344 (if region-p (region-end) (point-max))))
23345 (lines
23346 (org-split-string
23347 (org-cleaned-string-for-export
23348 region
23349 :emph-multiline t
23350 :for-html t
23351 :skip-before-1st-heading
23352 (plist-get opt-plist :skip-before-1st-heading)
23353 :archived-trees
23354 (plist-get opt-plist :archived-trees)
23355 :add-text
23356 (plist-get opt-plist :text)
23357 :LaTeX-fragments
23358 (plist-get opt-plist :LaTeX-fragments))
23359 "[\r\n]"))
23360 table-open type
23361 table-buffer table-orig-buffer
23362 ind start-is-num starter didclose
23363 rpl path desc descp desc1 desc2 link
23366 (let ((inhibit-read-only t))
23367 (org-unmodified
23368 (remove-text-properties (point-min) (point-max)
23369 '(:org-license-to-kill t))))
23371 (message "Exporting...")
23373 (setq org-min-level (org-get-min-level lines))
23374 (setq org-last-level org-min-level)
23375 (org-init-section-numbers)
23377 (cond
23378 ((and date (string-match "%" date))
23379 (setq date (format-time-string date (current-time))))
23380 (date)
23381 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23383 ;; Get the language-dependent settings
23384 (setq lang-words (or (assoc language org-export-language-setup)
23385 (assoc "en" org-export-language-setup)))
23387 ;; Switch to the output buffer
23388 (set-buffer buffer)
23389 (erase-buffer)
23390 (fundamental-mode)
23392 (and (fboundp 'set-buffer-file-coding-system)
23393 (set-buffer-file-coding-system coding-system-for-write))
23395 (let ((case-fold-search nil)
23396 (org-odd-levels-only odd))
23397 ;; create local variables for all options, to make sure all called
23398 ;; functions get the correct information
23399 (mapcar (lambda (x)
23400 (set (make-local-variable (cdr x))
23401 (plist-get opt-plist (car x))))
23402 org-export-plist-vars)
23403 (setq umax (if arg (prefix-numeric-value arg)
23404 org-export-headline-levels))
23405 (setq umax-toc (if (integerp org-export-with-toc)
23406 (min org-export-with-toc umax)
23407 umax))
23408 (unless body-only
23409 ;; File header
23410 (insert (format
23411 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23412 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23413 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23414 lang=\"%s\" xml:lang=\"%s\">
23415 <head>
23416 <title>%s</title>
23417 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
23418 <meta name=\"generator\" content=\"Org-mode\"/>
23419 <meta name=\"generated\" content=\"%s\"/>
23420 <meta name=\"author\" content=\"%s\"/>
23422 </head><body>
23424 language language (org-html-expand title)
23425 (or charset "iso-8859-1") date author style))
23427 (insert (or (plist-get opt-plist :preamble) ""))
23429 (when (plist-get opt-plist :auto-preamble)
23430 (if title (insert (format org-export-html-title-format
23431 (org-html-expand title))))))
23433 (if (and org-export-with-toc (not body-only))
23434 (progn
23435 (push (format "<h%d>%s</h%d>\n"
23436 org-export-html-toplevel-hlevel
23437 (nth 3 lang-words)
23438 org-export-html-toplevel-hlevel)
23439 thetoc)
23440 (push "<ul>\n<li>" thetoc)
23441 (setq lines
23442 (mapcar '(lambda (line)
23443 (if (string-match org-todo-line-regexp line)
23444 ;; This is a headline
23445 (progn
23446 (setq have-headings t)
23447 (setq level (- (match-end 1) (match-beginning 1))
23448 level (org-tr-level level)
23449 txt (save-match-data
23450 (org-html-expand
23451 (org-export-cleanup-toc-line
23452 (match-string 3 line))))
23453 todo
23454 (or (and org-export-mark-todo-in-toc
23455 (match-beginning 2)
23456 (not (member (match-string 2 line)
23457 org-done-keywords)))
23458 ; TODO, not DONE
23459 (and org-export-mark-todo-in-toc
23460 (= level umax-toc)
23461 (org-search-todo-below
23462 line lines level))))
23463 (if (string-match
23464 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
23465 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
23466 (if (string-match quote-re0 txt)
23467 (setq txt (replace-match "" t t txt)))
23468 (if org-export-with-section-numbers
23469 (setq txt (concat (org-section-number level)
23470 " " txt)))
23471 (if (<= level (max umax umax-toc))
23472 (setq head-count (+ head-count 1)))
23473 (if (<= level umax-toc)
23474 (progn
23475 (if (> level org-last-level)
23476 (progn
23477 (setq cnt (- level org-last-level))
23478 (while (>= (setq cnt (1- cnt)) 0)
23479 (push "\n<ul>\n<li>" thetoc))
23480 (push "\n" thetoc)))
23481 (if (< level org-last-level)
23482 (progn
23483 (setq cnt (- org-last-level level))
23484 (while (>= (setq cnt (1- cnt)) 0)
23485 (push "</li>\n</ul>" thetoc))
23486 (push "\n" thetoc)))
23487 ;; Check for targets
23488 (while (string-match org-target-regexp line)
23489 (setq tg (match-string 1 line)
23490 line (replace-match
23491 (concat "@<span class=\"target\">" tg "@</span> ")
23492 t t line))
23493 (push (cons (org-solidify-link-text tg)
23494 (format "sec-%d" head-count))
23495 target-alist))
23496 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
23497 (setq txt (replace-match "" t t txt)))
23498 (push
23499 (format
23500 (if todo
23501 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
23502 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
23503 head-count txt) thetoc)
23505 (setq org-last-level level))
23507 line)
23508 lines))
23509 (while (> org-last-level (1- org-min-level))
23510 (setq org-last-level (1- org-last-level))
23511 (push "</li>\n</ul>\n" thetoc))
23512 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23514 (setq head-count 0)
23515 (org-init-section-numbers)
23517 (while (setq line (pop lines) origline line)
23518 (catch 'nextline
23520 ;; end of quote section?
23521 (when (and inquote (string-match "^\\*+ " line))
23522 (insert "</pre>\n")
23523 (setq inquote nil))
23524 ;; inside a quote section?
23525 (when inquote
23526 (insert (org-html-protect line) "\n")
23527 (throw 'nextline nil))
23529 ;; verbatim lines
23530 (when (and org-export-with-fixed-width
23531 (string-match "^[ \t]*:\\(.*\\)" line))
23532 (when (not infixed)
23533 (setq infixed t)
23534 (insert "<pre>\n"))
23535 (insert (org-html-protect (match-string 1 line)) "\n")
23536 (when (and lines
23537 (not (string-match "^[ \t]*\\(:.*\\)"
23538 (car lines))))
23539 (setq infixed nil)
23540 (insert "</pre>\n"))
23541 (throw 'nextline nil))
23543 ;; Protected HTML
23544 (when (get-text-property 0 'org-protected line)
23545 (let (par)
23546 (when (re-search-backward
23547 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
23548 (setq par (match-string 1))
23549 (replace-match "\\2\n"))
23550 (insert line "\n")
23551 (while (and lines
23552 (get-text-property 0 'org-protected (car lines)))
23553 (insert (pop lines) "\n"))
23554 (and par (insert "<p>\n")))
23555 (throw 'nextline nil))
23557 ;; Horizontal line
23558 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
23559 (insert "\n<hr/>\n")
23560 (throw 'nextline nil))
23562 ;; make targets to anchors
23563 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
23564 (cond
23565 ((match-end 2)
23566 (setq line (replace-match
23567 (concat "@<a name=\""
23568 (org-solidify-link-text (match-string 1 line))
23569 "\">\\nbsp@</a>")
23570 t t line)))
23571 ((and org-export-with-toc (equal (string-to-char line) ?*))
23572 (setq line (replace-match
23573 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
23574 ; (concat "@<i>" (match-string 1 line) "@</i> ")
23575 t t line)))
23577 (setq line (replace-match
23578 (concat "@<a name=\""
23579 (org-solidify-link-text (match-string 1 line))
23580 "\" class=\"target\">" (match-string 1 line) "@</a> ")
23581 t t line)))))
23583 (setq line (org-html-handle-time-stamps line))
23585 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
23586 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
23587 ;; Also handle sub_superscripts and checkboxes
23588 (setq line (org-html-expand line))
23590 ;; Format the links
23591 (setq start 0)
23592 (while (string-match org-bracket-link-analytic-regexp line start)
23593 (setq start (match-beginning 0))
23594 (setq type (if (match-end 2) (match-string 2 line) "internal"))
23595 (setq path (match-string 3 line))
23596 (setq desc1 (if (match-end 5) (match-string 5 line))
23597 desc2 (if (match-end 2) (concat type ":" path) path)
23598 descp (and desc1 (not (equal desc1 desc2)))
23599 desc (or desc1 desc2))
23600 ;; Make an image out of the description if that is so wanted
23601 (when (and descp (org-file-image-p desc))
23602 (save-match-data
23603 (if (string-match "^file:" desc)
23604 (setq desc (substring desc (match-end 0)))))
23605 (setq desc (concat "<img src=\"" desc "\"/>")))
23606 ;; FIXME: do we need to unescape here somewhere?
23607 (cond
23608 ((equal type "internal")
23609 (setq rpl
23610 (concat
23611 "<a href=\"#"
23612 (org-solidify-link-text
23613 (save-match-data (org-link-unescape path)) target-alist)
23614 "\">" desc "</a>")))
23615 ((member type '("http" "https"))
23616 ;; standard URL, just check if we need to inline an image
23617 (if (and (or (eq t org-export-html-inline-images)
23618 (and org-export-html-inline-images (not descp)))
23619 (org-file-image-p path))
23620 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
23621 (setq link (concat type ":" path))
23622 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
23623 ((member type '("ftp" "mailto" "news"))
23624 ;; standard URL
23625 (setq link (concat type ":" path))
23626 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
23627 ((string= type "file")
23628 ;; FILE link
23629 (let* ((filename path)
23630 (abs-p (file-name-absolute-p filename))
23631 thefile file-is-image-p search)
23632 (save-match-data
23633 (if (string-match "::\\(.*\\)" filename)
23634 (setq search (match-string 1 filename)
23635 filename (replace-match "" t nil filename)))
23636 (setq valid
23637 (if (functionp link-validate)
23638 (funcall link-validate filename current-dir)
23640 (setq file-is-image-p (org-file-image-p filename))
23641 (setq thefile (if abs-p (expand-file-name filename) filename))
23642 (when (and org-export-html-link-org-files-as-html
23643 (string-match "\\.org$" thefile))
23644 (setq thefile (concat (substring thefile 0
23645 (match-beginning 0))
23646 "." org-export-html-extension))
23647 (if (and search
23648 ;; make sure this is can be used as target search
23649 (not (string-match "^[0-9]*$" search))
23650 (not (string-match "^\\*" search))
23651 (not (string-match "^/.*/$" search)))
23652 (setq thefile (concat thefile "#"
23653 (org-solidify-link-text
23654 (org-link-unescape search)))))
23655 (when (string-match "^file:" desc)
23656 (setq desc (replace-match "" t t desc))
23657 (if (string-match "\\.org$" desc)
23658 (setq desc (replace-match "" t t desc))))))
23659 (setq rpl (if (and file-is-image-p
23660 (or (eq t org-export-html-inline-images)
23661 (and org-export-html-inline-images
23662 (not descp))))
23663 (concat "<img src=\"" thefile "\"/>")
23664 (concat "<a href=\"" thefile "\">" desc "</a>")))
23665 (if (not valid) (setq rpl desc))))
23666 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
23667 (setq rpl (concat "<i>&lt;" type ":"
23668 (save-match-data (org-link-unescape path))
23669 "&gt;</i>"))))
23670 (setq line (replace-match rpl t t line)
23671 start (+ start (length rpl))))
23673 ;; TODO items
23674 (if (and (string-match org-todo-line-regexp line)
23675 (match-beginning 2))
23677 (setq line
23678 (concat (substring line 0 (match-beginning 2))
23679 "<span class=\""
23680 (if (member (match-string 2 line)
23681 org-done-keywords)
23682 "done" "todo")
23683 "\">" (match-string 2 line)
23684 "</span>" (substring line (match-end 2)))))
23686 ;; Does this contain a reference to a footnote?
23687 (when org-export-with-footnotes
23688 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
23689 (let ((n (match-string 2 line)))
23690 (setq line
23691 (replace-match
23692 (format
23693 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
23694 (match-string 1 line) n n n)
23695 t t line)))))
23697 (cond
23698 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23699 ;; This is a headline
23700 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23701 txt (match-string 2 line))
23702 (if (string-match quote-re0 txt)
23703 (setq txt (replace-match "" t t txt)))
23704 (if (<= level (max umax umax-toc))
23705 (setq head-count (+ head-count 1)))
23706 (when in-local-list
23707 ;; Close any local lists before inserting a new header line
23708 (while local-list-num
23709 (org-close-li)
23710 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23711 (pop local-list-num))
23712 (setq local-list-indent nil
23713 in-local-list nil))
23714 (setq first-heading-pos (or first-heading-pos (point)))
23715 (org-html-level-start level txt umax
23716 (and org-export-with-toc (<= level umax))
23717 head-count)
23718 ;; QUOTES
23719 (when (string-match quote-re line)
23720 (insert "<pre>")
23721 (setq inquote t)))
23723 ((and org-export-with-tables
23724 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23725 (if (not table-open)
23726 ;; New table starts
23727 (setq table-open t table-buffer nil table-orig-buffer nil))
23728 ;; Accumulate lines
23729 (setq table-buffer (cons line table-buffer)
23730 table-orig-buffer (cons origline table-orig-buffer))
23731 (when (or (not lines)
23732 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23733 (car lines))))
23734 (setq table-open nil
23735 table-buffer (nreverse table-buffer)
23736 table-orig-buffer (nreverse table-orig-buffer))
23737 (org-close-par-maybe)
23738 (insert (org-format-table-html table-buffer table-orig-buffer))))
23740 ;; Normal lines
23741 (when (string-match
23742 (cond
23743 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23744 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23745 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23746 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23747 line)
23748 (setq ind (org-get-string-indentation line)
23749 start-is-num (match-beginning 4)
23750 starter (if (match-beginning 2)
23751 (substring (match-string 2 line) 0 -1))
23752 line (substring line (match-beginning 5)))
23753 (unless (string-match "[^ \t]" line)
23754 ;; empty line. Pretend indentation is large.
23755 (setq ind (if org-empty-line-terminates-plain-lists
23757 (1+ (or (car local-list-indent) 1)))))
23758 (setq didclose nil)
23759 (while (and in-local-list
23760 (or (and (= ind (car local-list-indent))
23761 (not starter))
23762 (< ind (car local-list-indent))))
23763 (setq didclose t)
23764 (org-close-li)
23765 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23766 (pop local-list-num) (pop local-list-indent)
23767 (setq in-local-list local-list-indent))
23768 (cond
23769 ((and starter
23770 (or (not in-local-list)
23771 (> ind (car local-list-indent))))
23772 ;; Start new (level of) list
23773 (org-close-par-maybe)
23774 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23775 (push start-is-num local-list-num)
23776 (push ind local-list-indent)
23777 (setq in-local-list t))
23778 (starter
23779 ;; continue current list
23780 (org-close-li)
23781 (insert "<li>\n"))
23782 (didclose
23783 ;; we did close a list, normal text follows: need <p>
23784 (org-open-par)))
23785 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23786 (setq line
23787 (replace-match
23788 (if (equal (match-string 1 line) "X")
23789 "<b>[X]</b>"
23790 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23791 t t line))))
23793 ;; Empty lines start a new paragraph. If hand-formatted lists
23794 ;; are not fully interpreted, lines starting with "-", "+", "*"
23795 ;; also start a new paragraph.
23796 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23798 ;; Is this the start of a footnote?
23799 (when org-export-with-footnotes
23800 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23801 (org-close-par-maybe)
23802 (let ((n (match-string 1 line)))
23803 (setq line (replace-match
23804 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23806 ;; Check if the line break needs to be conserved
23807 (cond
23808 ((string-match "\\\\\\\\[ \t]*$" line)
23809 (setq line (replace-match "<br/>" t t line)))
23810 (org-export-preserve-breaks
23811 (setq line (concat line "<br/>"))))
23813 (insert line "\n")))))
23815 ;; Properly close all local lists and other lists
23816 (when inquote (insert "</pre>\n"))
23817 (when in-local-list
23818 ;; Close any local lists before inserting a new header line
23819 (while local-list-num
23820 (org-close-li)
23821 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23822 (pop local-list-num))
23823 (setq local-list-indent nil
23824 in-local-list nil))
23825 (org-html-level-start 0 nil umax
23826 (and org-export-with-toc (<= level umax))
23827 head-count)
23829 (unless body-only
23830 (when (plist-get opt-plist :auto-postamble)
23831 (insert "<div=\"postamble\">")
23832 (when (and org-export-author-info author)
23833 (insert "<p class=\"author\"> "
23834 (nth 1 lang-words) ": " author "\n")
23835 (when email
23836 (insert "<a href=\"mailto:" email "\">&lt;"
23837 email "&gt;</a>\n"))
23838 (insert "</p>\n"))
23839 (when (and date org-export-time-stamp-file)
23840 (insert "<p class=\"date\"> "
23841 (nth 2 lang-words) ": "
23842 date "</p>\n"))
23843 (insert "</div>"))
23845 (if org-export-html-with-timestamp
23846 (insert org-export-html-html-helper-timestamp))
23847 (insert (or (plist-get opt-plist :postamble) ""))
23848 (insert "</body>\n</html>\n"))
23850 (normal-mode)
23851 (if (eq major-mode default-major-mode) (html-mode))
23853 ;; insert the table of contents
23854 (goto-char (point-min))
23855 (when thetoc
23856 (if (or (re-search-forward
23857 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
23858 (re-search-forward
23859 "\\[TABLE-OF-CONTENTS\\]" nil t))
23860 (progn
23861 (goto-char (match-beginning 0))
23862 (replace-match ""))
23863 (goto-char first-heading-pos)
23864 (when (looking-at "\\s-*</p>")
23865 (goto-char (match-end 0))
23866 (insert "\n")))
23867 (insert "<div class=\"table-of-contents\">\n")
23868 (mapc 'insert thetoc)
23869 (insert "</div>\n"))
23870 ;; remove empty paragraphs and lists
23871 (goto-char (point-min))
23872 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
23873 (replace-match ""))
23874 (goto-char (point-min))
23875 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
23876 (replace-match ""))
23877 ;; Convert whitespace place holders
23878 (goto-char (point-min))
23879 (let (beg end n)
23880 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23881 (setq n (get-text-property beg 'org-whitespace)
23882 end (next-single-property-change beg 'org-whitespace))
23883 (goto-char beg)
23884 (delete-region beg end)
23885 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
23886 (make-string n ?x)))))
23888 (or to-buffer (save-buffer))
23889 (goto-char (point-min))
23890 (message "Exporting... done")
23891 (if (eq to-buffer 'string)
23892 (prog1 (buffer-substring (point-min) (point-max))
23893 (kill-buffer (current-buffer)))
23894 (current-buffer)))))
23896 (defvar org-table-colgroup-info nil)
23897 (defun org-format-table-ascii (lines)
23898 "Format a table for ascii export."
23899 (if (stringp lines)
23900 (setq lines (org-split-string lines "\n")))
23901 (if (not (string-match "^[ \t]*|" (car lines)))
23902 ;; Table made by table.el - test for spanning
23903 lines
23905 ;; A normal org table
23906 ;; Get rid of hlines at beginning and end
23907 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23908 (setq lines (nreverse lines))
23909 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23910 (setq lines (nreverse lines))
23911 (when org-export-table-remove-special-lines
23912 ;; Check if the table has a marking column. If yes remove the
23913 ;; column and the special lines
23914 (setq lines (org-table-clean-before-export lines)))
23915 ;; Get rid of the vertical lines except for grouping
23916 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
23917 rtn line vl1 start)
23918 (while (setq line (pop lines))
23919 (if (string-match org-table-hline-regexp line)
23920 (and (string-match "|\\(.*\\)|" line)
23921 (setq line (replace-match " \\1" t nil line)))
23922 (setq start 0 vl1 vl)
23923 (while (string-match "|" line start)
23924 (setq start (match-end 0))
23925 (or (pop vl1) (setq line (replace-match " " t t line)))))
23926 (push line rtn))
23927 (nreverse rtn))))
23929 (defun org-colgroup-info-to-vline-list (info)
23930 (let (vl new last)
23931 (while info
23932 (setq last new new (pop info))
23933 (if (or (memq last '(:end :startend))
23934 (memq new '(:start :startend)))
23935 (push t vl)
23936 (push nil vl)))
23937 (setq vl (nreverse vl))
23938 (and vl (setcar vl nil))
23939 vl))
23941 (defun org-format-table-html (lines olines)
23942 "Find out which HTML converter to use and return the HTML code."
23943 (if (stringp lines)
23944 (setq lines (org-split-string lines "\n")))
23945 (if (string-match "^[ \t]*|" (car lines))
23946 ;; A normal org table
23947 (org-format-org-table-html lines)
23948 ;; Table made by table.el - test for spanning
23949 (let* ((hlines (delq nil (mapcar
23950 (lambda (x)
23951 (if (string-match "^[ \t]*\\+-" x) x
23952 nil))
23953 lines)))
23954 (first (car hlines))
23955 (ll (and (string-match "\\S-+" first)
23956 (match-string 0 first)))
23957 (re (concat "^[ \t]*" (regexp-quote ll)))
23958 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
23959 hlines))))
23960 (if (and (not spanning)
23961 (not org-export-prefer-native-exporter-for-tables))
23962 ;; We can use my own converter with HTML conversions
23963 (org-format-table-table-html lines)
23964 ;; Need to use the code generator in table.el, with the original text.
23965 (org-format-table-table-html-using-table-generate-source olines)))))
23967 (defun org-format-org-table-html (lines &optional splice)
23968 "Format a table into HTML."
23969 ;; Get rid of hlines at beginning and end
23970 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23971 (setq lines (nreverse lines))
23972 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
23973 (setq lines (nreverse lines))
23974 (when org-export-table-remove-special-lines
23975 ;; Check if the table has a marking column. If yes remove the
23976 ;; column and the special lines
23977 (setq lines (org-table-clean-before-export lines)))
23979 (let ((head (and org-export-highlight-first-table-line
23980 (delq nil (mapcar
23981 (lambda (x) (string-match "^[ \t]*|-" x))
23982 (cdr lines)))))
23983 (nlines 0) fnum i
23984 tbopen line fields html gr colgropen)
23985 (if splice (setq head nil))
23986 (unless splice (push (if head "<thead>" "<tbody>") html))
23987 (setq tbopen t)
23988 (while (setq line (pop lines))
23989 (catch 'next-line
23990 (if (string-match "^[ \t]*|-" line)
23991 (progn
23992 (unless splice
23993 (push (if head "</thead>" "</tbody>") html)
23994 (if lines (push "<tbody>" html) (setq tbopen nil)))
23995 (setq head nil) ;; head ends here, first time around
23996 ;; ignore this line
23997 (throw 'next-line t)))
23998 ;; Break the line into fields
23999 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24000 (unless fnum (setq fnum (make-vector (length fields) 0)))
24001 (setq nlines (1+ nlines) i -1)
24002 (push (concat "<tr>"
24003 (mapconcat
24004 (lambda (x)
24005 (setq i (1+ i))
24006 (if (and (< i nlines)
24007 (string-match org-table-number-regexp x))
24008 (incf (aref fnum i)))
24009 (if head
24010 (concat (car org-export-table-header-tags) x
24011 (cdr org-export-table-header-tags))
24012 (concat (car org-export-table-data-tags) x
24013 (cdr org-export-table-data-tags))))
24014 fields "")
24015 "</tr>")
24016 html)))
24017 (unless splice (if tbopen (push "</tbody>" html)))
24018 (unless splice (push "</table>\n" html))
24019 (setq html (nreverse html))
24020 (unless splice
24021 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
24022 (push (mapconcat
24023 (lambda (x)
24024 (setq gr (pop org-table-colgroup-info))
24025 (format "%s<COL align=\"%s\"></COL>%s"
24026 (if (memq gr '(:start :startend))
24027 (prog1
24028 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24029 (setq colgropen t))
24031 (if (> (/ (float x) nlines) org-table-number-fraction)
24032 "right" "left")
24033 (if (memq gr '(:end :startend))
24034 (progn (setq colgropen nil) "</colgroup>")
24035 "")))
24036 fnum "")
24037 html)
24038 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24039 (push org-export-html-table-tag html))
24040 (concat (mapconcat 'identity html "\n") "\n")))
24042 (defun org-table-clean-before-export (lines)
24043 "Check if the table has a marking column.
24044 If yes remove the column and the special lines."
24045 (setq org-table-colgroup-info nil)
24046 (if (memq nil
24047 (mapcar
24048 (lambda (x) (or (string-match "^[ \t]*|-" x)
24049 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24050 lines))
24051 (progn
24052 (setq org-table-clean-did-remove-column nil)
24053 (delq nil
24054 (mapcar
24055 (lambda (x)
24056 (cond
24057 ((string-match "^[ \t]*| */ *|" x)
24058 (setq org-table-colgroup-info
24059 (mapcar (lambda (x)
24060 (cond ((member x '("<" "&lt;")) :start)
24061 ((member x '(">" "&gt;")) :end)
24062 ((member x '("<>" "&lt;&gt;")) :startend)
24063 (t nil)))
24064 (org-split-string x "[ \t]*|[ \t]*")))
24065 nil)
24066 (t x)))
24067 lines)))
24068 (setq org-table-clean-did-remove-column t)
24069 (delq nil
24070 (mapcar
24071 (lambda (x)
24072 (cond
24073 ((string-match "^[ \t]*| */ *|" x)
24074 (setq org-table-colgroup-info
24075 (mapcar (lambda (x)
24076 (cond ((member x '("<" "&lt;")) :start)
24077 ((member x '(">" "&gt;")) :end)
24078 ((member x '("<>" "&lt;&gt;")) :startend)
24079 (t nil)))
24080 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24081 nil)
24082 ((string-match "^[ \t]*| *[!_^/] *|" x)
24083 nil) ; ignore this line
24084 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24085 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24086 ;; remove the first column
24087 (replace-match "\\1|" t nil x))
24088 (t (error "This should not happen"))))
24089 lines))))
24091 (defun org-format-table-table-html (lines)
24092 "Format a table generated by table.el into HTML.
24093 This conversion does *not* use `table-generate-source' from table.el.
24094 This has the advantage that Org-mode's HTML conversions can be used.
24095 But it has the disadvantage, that no cell- or row-spanning is allowed."
24096 (let (line field-buffer
24097 (head org-export-highlight-first-table-line)
24098 fields html empty)
24099 (setq html (concat org-export-html-table-tag "\n"))
24100 (while (setq line (pop lines))
24101 (setq empty "&nbsp;")
24102 (catch 'next-line
24103 (if (string-match "^[ \t]*\\+-" line)
24104 (progn
24105 (if field-buffer
24106 (progn
24107 (setq
24108 html
24109 (concat
24110 html
24111 "<tr>"
24112 (mapconcat
24113 (lambda (x)
24114 (if (equal x "") (setq x empty))
24115 (if head
24116 (concat (car org-export-table-header-tags) x
24117 (cdr org-export-table-header-tags))
24118 (concat (car org-export-table-data-tags) x
24119 (cdr org-export-table-data-tags))))
24120 field-buffer "\n")
24121 "</tr>\n"))
24122 (setq head nil)
24123 (setq field-buffer nil)))
24124 ;; Ignore this line
24125 (throw 'next-line t)))
24126 ;; Break the line into fields and store the fields
24127 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24128 (if field-buffer
24129 (setq field-buffer (mapcar
24130 (lambda (x)
24131 (concat x "<br/>" (pop fields)))
24132 field-buffer))
24133 (setq field-buffer fields))))
24134 (setq html (concat html "</table>\n"))
24135 html))
24137 (defun org-format-table-table-html-using-table-generate-source (lines)
24138 "Format a table into html, using `table-generate-source' from table.el.
24139 This has the advantage that cell- or row-spanning is allowed.
24140 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24141 (require 'table)
24142 (with-current-buffer (get-buffer-create " org-tmp1 ")
24143 (erase-buffer)
24144 (insert (mapconcat 'identity lines "\n"))
24145 (goto-char (point-min))
24146 (if (not (re-search-forward "|[^+]" nil t))
24147 (error "Error processing table"))
24148 (table-recognize-table)
24149 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24150 (table-generate-source 'html " org-tmp2 ")
24151 (set-buffer " org-tmp2 ")
24152 (buffer-substring (point-min) (point-max))))
24154 (defun org-html-handle-time-stamps (s)
24155 "Format time stamps in string S, or remove them."
24156 (catch 'exit
24157 (let (r b)
24158 (while (string-match org-maybe-keyword-time-regexp s)
24159 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24160 ;; never export CLOCK
24161 (throw 'exit ""))
24162 (or b (setq b (substring s 0 (match-beginning 0))))
24163 (if (not org-export-with-timestamps)
24164 (setq r (concat r (substring s 0 (match-beginning 0)))
24165 s (substring s (match-end 0)))
24166 (setq r (concat
24167 r (substring s 0 (match-beginning 0))
24168 (if (match-end 1)
24169 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24170 (match-string 1 s)))
24171 (format " @<span class=\"timestamp\">%s@</span>"
24172 (substring
24173 (org-translate-time (match-string 3 s)) 1 -1)))
24174 s (substring s (match-end 0)))))
24175 ;; Line break if line started and ended with time stamp stuff
24176 (if (not r)
24178 (setq r (concat r s))
24179 (unless (string-match "\\S-" (concat b s))
24180 (setq r (concat r "@<br/>")))
24181 r))))
24183 (defun org-html-protect (s)
24184 ;; convert & to &amp;, < to &lt; and > to &gt;
24185 (let ((start 0))
24186 (while (string-match "&" s start)
24187 (setq s (replace-match "&amp;" t t s)
24188 start (1+ (match-beginning 0))))
24189 (while (string-match "<" s)
24190 (setq s (replace-match "&lt;" t t s)))
24191 (while (string-match ">" s)
24192 (setq s (replace-match "&gt;" t t s))))
24195 (defun org-export-cleanup-toc-line (s)
24196 "Remove tags and time staps from lines going into the toc."
24197 (when (memq org-export-with-tags '(not-in-toc nil))
24198 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24199 (setq s (replace-match "" t t s))))
24200 (when org-export-remove-timestamps-from-toc
24201 (while (string-match org-maybe-keyword-time-regexp s)
24202 (setq s (replace-match "" t t s))))
24203 (while (string-match org-bracket-link-regexp s)
24204 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24205 t t s)))
24208 (defun org-html-expand (string)
24209 "Prepare STRING for HTML export. Applies all active conversions.
24210 If there are links in the string, don't modify these."
24211 (let* (m s l res)
24212 (while (setq m (string-match org-bracket-link-regexp string))
24213 (setq s (substring string 0 m)
24214 l (match-string 0 string)
24215 string (substring string (match-end 0)))
24216 (push (org-html-do-expand s) res)
24217 (push l res))
24218 (push (org-html-do-expand string) res)
24219 (apply 'concat (nreverse res))))
24221 (defun org-html-do-expand (s)
24222 "Apply all active conversions to translate special ASCII to HTML."
24223 (setq s (org-html-protect s))
24224 (if org-export-html-expand
24225 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24226 (setq s (replace-match "<\\1>" t nil s))))
24227 (if org-export-with-emphasize
24228 (setq s (org-export-html-convert-emphasize s)))
24229 (if org-export-with-sub-superscripts
24230 (setq s (org-export-html-convert-sub-super s)))
24231 (if org-export-with-TeX-macros
24232 (let ((start 0) wd ass)
24233 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24234 (setq wd (match-string 1 s))
24235 (if (setq ass (assoc wd org-html-entities))
24236 (setq s (replace-match (or (cdr ass)
24237 (concat "&" (car ass) ";"))
24238 t t s))
24239 (setq start (+ start (length wd)))))))
24242 (defun org-create-multibrace-regexp (left right n)
24243 "Create a regular expression which will match a balanced sexp.
24244 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24245 as single character strings.
24246 The regexp returned will match the entire expression including the
24247 delimiters. It will also define a single group which contains the
24248 match except for the outermost delimiters. The maximum depth of
24249 stacked delimiters is N. Escaping delimiters is not possible."
24250 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24251 (or "\\|")
24252 (re nothing)
24253 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24254 (while (> n 1)
24255 (setq n (1- n)
24256 re (concat re or next)
24257 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24258 (concat left "\\(" re "\\)" right)))
24260 (defvar org-match-substring-regexp
24261 (concat
24262 "\\([^\\]\\)\\([_^]\\)\\("
24263 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24264 "\\|"
24265 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24266 "\\|"
24267 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24268 "The regular expression matching a sub- or superscript.")
24270 ;(let ((s "a\\_b"))
24271 ; (and (string-match org-match-substring-regexp s)
24272 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
24274 (defun org-export-html-convert-sub-super (string)
24275 "Convert sub- and superscripts in STRING to HTML."
24276 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24277 (while (string-match org-match-substring-regexp string s)
24278 (if (and requireb (match-end 8))
24279 (setq s (match-end 2))
24280 (setq s (match-end 1)
24281 key (if (string= (match-string 2 string) "_") "sub" "sup")
24282 c (or (match-string 8 string)
24283 (match-string 6 string)
24284 (match-string 5 string))
24285 string (replace-match
24286 (concat (match-string 1 string)
24287 "<" key ">" c "</" key ">")
24288 t t string))))
24289 (while (string-match "\\\\\\([_^]\\)" string)
24290 (setq string (replace-match (match-string 1 string) t t string)))
24291 string))
24293 (defun org-export-html-convert-emphasize (string)
24294 "Apply emphasis."
24295 (let ((s 0))
24296 (while (string-match org-emph-re string s)
24297 (if (not (equal
24298 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24299 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24300 (setq string (replace-match
24301 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24302 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
24303 "\\5") t nil string))
24304 (setq s (1+ s))))
24305 string))
24307 (defvar org-par-open nil)
24308 (defun org-open-par ()
24309 "Insert <p>, but first close previous paragraph if any."
24310 (org-close-par-maybe)
24311 (insert "\n<p>")
24312 (setq org-par-open t))
24313 (defun org-close-par-maybe ()
24314 "Close paragraph if there is one open."
24315 (when org-par-open
24316 (insert "</p>")
24317 (setq org-par-open nil)))
24318 (defun org-close-li ()
24319 "Close <li> if necessary."
24320 (org-close-par-maybe)
24321 (insert "</li>\n"))
24323 (defvar body-only) ; dynamically scoped into this.
24324 (defun org-html-level-start (level title umax with-toc head-count)
24325 "Insert a new level in HTML export.
24326 When TITLE is nil, just close all open levels."
24327 (org-close-par-maybe)
24328 (let ((l org-level-max))
24329 (while (>= l (1+ level))
24330 (if (aref org-levels-open (1- l))
24331 (progn
24332 (org-html-level-close l umax)
24333 (aset org-levels-open (1- l) nil)))
24334 (setq l (1- l)))
24335 (when title
24336 ;; If title is nil, this means this function is called to close
24337 ;; all levels, so the rest is done only if title is given
24338 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24339 (setq title (replace-match
24340 (if org-export-with-tags
24341 (save-match-data
24342 (concat
24343 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24344 (mapconcat 'identity (org-split-string
24345 (match-string 1 title) ":")
24346 "&nbsp;")
24347 "</span>"))
24349 t t title)))
24350 (if (> level umax)
24351 (progn
24352 (if (aref org-levels-open (1- level))
24353 (progn
24354 (org-close-li)
24355 (insert "<li>" title "<br/>\n"))
24356 (aset org-levels-open (1- level) t)
24357 (org-close-par-maybe)
24358 (insert "<ul>\n<li>" title "<br/>\n")))
24359 (aset org-levels-open (1- level) t)
24360 (if (and org-export-with-section-numbers (not body-only))
24361 (setq title (concat (org-section-number level) " " title)))
24362 (setq level (+ level org-export-html-toplevel-hlevel -1))
24363 (if with-toc
24364 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24365 level level head-count title level))
24366 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24367 (org-open-par)))))
24369 (defun org-html-level-close (level max-outline-level)
24370 "Terminate one level in HTML export."
24371 (if (<= level max-outline-level)
24372 (insert "</div>\n")
24373 (org-close-li)
24374 (insert "</ul>\n")))
24376 ;;; iCalendar export
24378 ;;;###autoload
24379 (defun org-export-icalendar-this-file ()
24380 "Export current file as an iCalendar file.
24381 The iCalendar file will be located in the same directory as the Org-mode
24382 file, but with extension `.ics'."
24383 (interactive)
24384 (org-export-icalendar nil buffer-file-name))
24386 ;;;###autoload
24387 (defun org-export-icalendar-all-agenda-files ()
24388 "Export all files in `org-agenda-files' to iCalendar .ics files.
24389 Each iCalendar file will be located in the same directory as the Org-mode
24390 file, but with extension `.ics'."
24391 (interactive)
24392 (apply 'org-export-icalendar nil (org-agenda-files t)))
24394 ;;;###autoload
24395 (defun org-export-icalendar-combine-agenda-files ()
24396 "Export all files in `org-agenda-files' to a single combined iCalendar file.
24397 The file is stored under the name `org-combined-agenda-icalendar-file'."
24398 (interactive)
24399 (apply 'org-export-icalendar t (org-agenda-files t)))
24401 (defun org-export-icalendar (combine &rest files)
24402 "Create iCalendar files for all elements of FILES.
24403 If COMBINE is non-nil, combine all calendar entries into a single large
24404 file and store it under the name `org-combined-agenda-icalendar-file'."
24405 (save-excursion
24406 (org-prepare-agenda-buffers files)
24407 (let* ((dir (org-export-directory
24408 :ical (list :publishing-directory
24409 org-export-publishing-directory)))
24410 file ical-file ical-buffer category started org-agenda-new-buffers)
24412 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
24413 (when combine
24414 (setq ical-file
24415 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
24416 org-combined-agenda-icalendar-file
24417 (expand-file-name org-combined-agenda-icalendar-file dir))
24418 ical-buffer (org-get-agenda-file-buffer ical-file))
24419 (set-buffer ical-buffer) (erase-buffer))
24420 (while (setq file (pop files))
24421 (catch 'nextfile
24422 (org-check-agenda-file file)
24423 (set-buffer (org-get-agenda-file-buffer file))
24424 (unless combine
24425 (setq ical-file (concat (file-name-as-directory dir)
24426 (file-name-sans-extension
24427 (file-name-nondirectory buffer-file-name))
24428 ".ics"))
24429 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
24430 (with-current-buffer ical-buffer (erase-buffer)))
24431 (setq category (or org-category
24432 (file-name-sans-extension
24433 (file-name-nondirectory buffer-file-name))))
24434 (if (symbolp category) (setq category (symbol-name category)))
24435 (let ((standard-output ical-buffer))
24436 (if combine
24437 (and (not started) (setq started t)
24438 (org-start-icalendar-file org-icalendar-combined-name))
24439 (org-start-icalendar-file category))
24440 (org-print-icalendar-entries combine)
24441 (when (or (and combine (not files)) (not combine))
24442 (org-finish-icalendar-file)
24443 (set-buffer ical-buffer)
24444 (save-buffer)
24445 (run-hooks 'org-after-save-iCalendar-file-hook)))))
24446 (org-release-buffers org-agenda-new-buffers))))
24448 (defvar org-after-save-iCalendar-file-hook nil
24449 "Hook run after an iCalendar file has been saved.
24450 The iCalendar buffer is still current when this hook is run.
24451 A good way to use this is to tell a desktop calenndar application to re-read
24452 the iCalendar file.")
24454 (defun org-print-icalendar-entries (&optional combine)
24455 "Print iCalendar entries for the current Org-mode file to `standard-output'.
24456 When COMBINE is non nil, add the category to each line."
24457 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
24458 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
24459 (dts (org-ical-ts-to-string
24460 (format-time-string (cdr org-time-stamp-formats) (current-time))
24461 "DTSTART"))
24462 hd ts ts2 state status (inc t) pos b sexp rrule
24463 scheduledp deadlinep tmp pri category entry location summary desc
24464 (sexp-buffer (get-buffer-create "*ical-tmp*")))
24465 (org-refresh-category-properties)
24466 (save-excursion
24467 (goto-char (point-min))
24468 (while (re-search-forward re1 nil t)
24469 (catch :skip
24470 (org-agenda-skip)
24471 (setq pos (match-beginning 0)
24472 ts (match-string 0)
24473 inc t
24474 hd (org-get-heading)
24475 summary (org-entry-get nil "SUMMARY")
24476 desc (or (org-entry-get nil "DESCRIPTION")
24477 (org-get-cleaned-entry org-icalendar-include-body))
24478 location (org-entry-get nil "LOCATION")
24479 category (org-get-category))
24480 (if (looking-at re2)
24481 (progn
24482 (goto-char (match-end 0))
24483 (setq ts2 (match-string 1) inc nil))
24484 (setq tmp (buffer-substring (max (point-min)
24485 (- pos org-ds-keyword-length))
24486 pos)
24487 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
24488 (progn
24489 (setq inc nil)
24490 (replace-match "\\1" t nil ts))
24492 deadlinep (string-match org-deadline-regexp tmp)
24493 scheduledp (string-match org-scheduled-regexp tmp)
24494 ;; donep (org-entry-is-done-p)
24496 (if (or (string-match org-tr-regexp hd)
24497 (string-match org-ts-regexp hd))
24498 (setq hd (replace-match "" t t hd)))
24499 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
24500 (setq rrule
24501 (concat "\nRRULE:FREQ="
24502 (cdr (assoc
24503 (match-string 2 ts)
24504 '(("d" . "DAILY")("w" . "WEEKLY")
24505 ("m" . "MONTHLY")("y" . "YEARLY"))))
24506 ";INTERVAL=" (match-string 1 ts)))
24507 (setq rrule ""))
24508 (setq summary (or summary hd))
24509 (if (string-match org-bracket-link-regexp summary)
24510 (setq summary
24511 (replace-match (if (match-end 3)
24512 (match-string 3 summary)
24513 (match-string 1 summary))
24514 t t summary)))
24515 (if deadlinep (setq summary (concat "DL: " summary)))
24516 (if scheduledp (setq summary (concat "S: " summary)))
24517 (if (string-match "\\`<%%" ts)
24518 (with-current-buffer sexp-buffer
24519 (insert (substring ts 1 -1) " " summary "\n"))
24520 (princ (format "BEGIN:VEVENT
24522 %s%s
24523 SUMMARY:%s%s%s
24524 CATEGORIES:%s
24525 END:VEVENT\n"
24526 (org-ical-ts-to-string ts "DTSTART")
24527 (org-ical-ts-to-string ts2 "DTEND" inc)
24528 rrule summary
24529 (if (and desc (string-match "\\S-" desc))
24530 (concat "\nDESCRIPTION: " desc) "")
24531 (if (and location (string-match "\\S-" location))
24532 (concat "\nLOCATION: " location) "")
24533 category)))))
24535 (when (and org-icalendar-include-sexps
24536 (condition-case nil (require 'icalendar) (error nil))
24537 (fboundp 'icalendar-export-region))
24538 ;; Get all the literal sexps
24539 (goto-char (point-min))
24540 (while (re-search-forward "^&?%%(" nil t)
24541 (catch :skip
24542 (org-agenda-skip)
24543 (setq b (match-beginning 0))
24544 (goto-char (1- (match-end 0)))
24545 (forward-sexp 1)
24546 (end-of-line 1)
24547 (setq sexp (buffer-substring b (point)))
24548 (with-current-buffer sexp-buffer
24549 (insert sexp "\n"))
24550 (princ (org-diary-to-ical-string sexp-buffer)))))
24552 (when org-icalendar-include-todo
24553 (goto-char (point-min))
24554 (while (re-search-forward org-todo-line-regexp nil t)
24555 (catch :skip
24556 (org-agenda-skip)
24557 (setq state (match-string 2))
24558 (setq status (if (member state org-done-keywords)
24559 "COMPLETED" "NEEDS-ACTION"))
24560 (when (and state
24561 (or (not (member state org-done-keywords))
24562 (eq org-icalendar-include-todo 'all))
24563 (not (member org-archive-tag (org-get-tags-at)))
24565 (setq hd (match-string 3)
24566 summary (org-entry-get nil "SUMMARY")
24567 desc (or (org-entry-get nil "DESCRIPTION")
24568 (org-get-cleaned-entry org-icalendar-include-body))
24569 location (org-entry-get nil "LOCATION"))
24570 (if (string-match org-bracket-link-regexp hd)
24571 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
24572 (match-string 1 hd))
24573 t t hd)))
24574 (if (string-match org-priority-regexp hd)
24575 (setq pri (string-to-char (match-string 2 hd))
24576 hd (concat (substring hd 0 (match-beginning 1))
24577 (substring hd (match-end 1))))
24578 (setq pri org-default-priority))
24579 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
24580 (- org-lowest-priority org-highest-priority))))))
24582 (princ (format "BEGIN:VTODO
24584 SUMMARY:%s%s%s
24585 CATEGORIES:%s
24586 SEQUENCE:1
24587 PRIORITY:%d
24588 STATUS:%s
24589 END:VTODO\n"
24591 (or summary hd)
24592 (if (and location (string-match "\\S-" location))
24593 (concat "\nLOCATION: " location) "")
24594 (if (and desc (string-match "\\S-" desc))
24595 (concat "\nDESCRIPTION: " desc) "")
24596 category pri status)))))))))
24598 (defun org-get-cleaned-entry (what)
24599 "Clean-up description string."
24600 (when what
24601 (save-excursion
24602 (org-back-to-heading t)
24603 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
24604 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
24605 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
24606 (while (string-match re s) (setq s (replace-match "" t t s)))
24607 (while (string-match re2 s) (setq s (replace-match "" t t s)))
24608 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
24609 (while (string-match "[ \t]*\n[ \t]*" s)
24610 (setq s (replace-match "\\n" t t s)))
24611 (setq s (org-trim s))
24612 (if (and (numberp what)
24613 (> (length s) what))
24614 (substring s 0 what)
24615 s)))))
24617 (defun org-start-icalendar-file (name)
24618 "Start an iCalendar file by inserting the header."
24619 (let ((user user-full-name)
24620 (name (or name "unknown"))
24621 (timezone (cadr (current-time-zone))))
24622 (princ
24623 (format "BEGIN:VCALENDAR
24624 VERSION:2.0
24625 X-WR-CALNAME:%s
24626 PRODID:-//%s//Emacs with Org-mode//EN
24627 X-WR-TIMEZONE:%s
24628 CALSCALE:GREGORIAN\n" name user timezone))))
24630 (defun org-finish-icalendar-file ()
24631 "Finish an iCalendar file by inserting the END statement."
24632 (princ "END:VCALENDAR\n"))
24634 (defun org-ical-ts-to-string (s keyword &optional inc)
24635 "Take a time string S and convert it to iCalendar format.
24636 KEYWORD is added in front, to make a complete line like DTSTART....
24637 When INC is non-nil, increase the hour by two (if time string contains
24638 a time), or the day by one (if it does not contain a time)."
24639 (let ((t1 (org-parse-time-string s 'nodefault))
24640 t2 fmt have-time time)
24641 (if (and (car t1) (nth 1 t1) (nth 2 t1))
24642 (setq t2 t1 have-time t)
24643 (setq t2 (org-parse-time-string s)))
24644 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
24645 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
24646 (when inc
24647 (if have-time
24648 (if org-agenda-default-appointment-duration
24649 (setq mi (+ org-agenda-default-appointment-duration mi))
24650 (setq h (+ 2 h)))
24651 (setq d (1+ d))))
24652 (setq time (encode-time s mi h d m y)))
24653 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
24654 (concat keyword (format-time-string fmt time))))
24656 ;;; XOXO export
24658 (defun org-export-as-xoxo-insert-into (buffer &rest output)
24659 (with-current-buffer buffer
24660 (apply 'insert output)))
24661 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
24663 (defun org-export-as-xoxo (&optional buffer)
24664 "Export the org buffer as XOXO.
24665 The XOXO buffer is named *xoxo-<source buffer name>*"
24666 (interactive (list (current-buffer)))
24667 ;; A quickie abstraction
24669 ;; Output everything as XOXO
24670 (with-current-buffer (get-buffer buffer)
24671 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
24672 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24673 (org-infile-export-plist)))
24674 (filename (concat (file-name-as-directory
24675 (org-export-directory :xoxo opt-plist))
24676 (file-name-sans-extension
24677 (file-name-nondirectory buffer-file-name))
24678 ".html"))
24679 (out (find-file-noselect filename))
24680 (last-level 1)
24681 (hanging-li nil))
24682 ;; Check the output buffer is empty.
24683 (with-current-buffer out (erase-buffer))
24684 ;; Kick off the output
24685 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
24686 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
24687 (let* ((hd (match-string-no-properties 1))
24688 (level (length hd))
24689 (text (concat
24690 (match-string-no-properties 2)
24691 (save-excursion
24692 (goto-char (match-end 0))
24693 (let ((str ""))
24694 (catch 'loop
24695 (while 't
24696 (forward-line)
24697 (if (looking-at "^[ \t]\\(.*\\)")
24698 (setq str (concat str (match-string-no-properties 1)))
24699 (throw 'loop str)))))))))
24701 ;; Handle level rendering
24702 (cond
24703 ((> level last-level)
24704 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
24706 ((< level last-level)
24707 (dotimes (- (- last-level level) 1)
24708 (if hanging-li
24709 (org-export-as-xoxo-insert-into out "</li>\n"))
24710 (org-export-as-xoxo-insert-into out "</ol>\n"))
24711 (when hanging-li
24712 (org-export-as-xoxo-insert-into out "</li>\n")
24713 (setq hanging-li nil)))
24715 ((equal level last-level)
24716 (if hanging-li
24717 (org-export-as-xoxo-insert-into out "</li>\n")))
24720 (setq last-level level)
24722 ;; And output the new li
24723 (setq hanging-li 't)
24724 (if (equal ?+ (elt text 0))
24725 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24726 (org-export-as-xoxo-insert-into out "<li>" text))))
24728 ;; Finally finish off the ol
24729 (dotimes (- last-level 1)
24730 (if hanging-li
24731 (org-export-as-xoxo-insert-into out "</li>\n"))
24732 (org-export-as-xoxo-insert-into out "</ol>\n"))
24734 ;; Finish the buffer off and clean it up.
24735 (switch-to-buffer-other-window out)
24736 (indent-region (point-min) (point-max) nil)
24737 (save-buffer)
24738 (goto-char (point-min))
24742 ;;;; Key bindings
24744 ;; Make `C-c C-x' a prefix key
24745 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24747 ;; TAB key with modifiers
24748 (org-defkey org-mode-map "\C-i" 'org-cycle)
24749 (org-defkey org-mode-map [(tab)] 'org-cycle)
24750 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24751 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24752 (org-defkey org-mode-map "\M-\t" 'org-complete)
24753 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24754 ;; The following line is necessary under Suse GNU/Linux
24755 (unless (featurep 'xemacs)
24756 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24757 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24758 (define-key org-mode-map [backtab] 'org-shifttab)
24760 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24761 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24762 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24764 ;; Cursor keys with modifiers
24765 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24766 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24767 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24768 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24770 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24771 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24772 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24773 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24775 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24776 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24777 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24778 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24780 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24781 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24783 ;;; Extra keys for tty access.
24784 ;; We only set them when really needed because otherwise the
24785 ;; menus don't show the simple keys
24787 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24788 (not window-system))
24789 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24790 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24791 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24792 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24793 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24794 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24795 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24796 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24797 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24798 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24799 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24800 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24801 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24802 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24803 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24804 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24805 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24806 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24807 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24808 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24809 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24810 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24812 ;; All the other keys
24814 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24815 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24816 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24817 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24818 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24819 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24820 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24821 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24822 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24823 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24824 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24825 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24826 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24827 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24828 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24829 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24830 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24831 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24832 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24833 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24834 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24835 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
24836 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
24837 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
24838 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
24839 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
24840 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
24841 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
24842 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
24843 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
24844 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
24845 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
24846 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
24847 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
24848 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
24849 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
24850 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
24851 (org-defkey org-mode-map "\C-c^" 'org-sort)
24852 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
24853 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
24854 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
24855 (org-defkey org-mode-map "\C-m" 'org-return)
24856 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
24857 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
24858 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
24859 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
24860 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
24861 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
24862 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
24863 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
24864 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
24865 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
24866 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
24867 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
24868 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
24869 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
24870 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
24871 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
24873 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
24874 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
24875 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
24876 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
24878 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
24879 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
24880 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
24881 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
24882 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
24883 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
24884 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
24885 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
24886 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
24887 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
24888 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
24889 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
24891 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
24893 (when (featurep 'xemacs)
24894 (org-defkey org-mode-map 'button3 'popup-mode-menu))
24896 (defsubst org-table-p () (org-at-table-p))
24898 (defun org-self-insert-command (N)
24899 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
24900 If the cursor is in a table looking at whitespace, the whitespace is
24901 overwritten, and the table is not marked as requiring realignment."
24902 (interactive "p")
24903 (if (and (org-table-p)
24904 (progn
24905 ;; check if we blank the field, and if that triggers align
24906 (and org-table-auto-blank-field
24907 (member last-command
24908 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
24909 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
24910 ;; got extra space, this field does not determine column width
24911 (let (org-table-may-need-update) (org-table-blank-field))
24912 ;; no extra space, this field may determine column width
24913 (org-table-blank-field)))
24915 (eq N 1)
24916 (looking-at "[^|\n]* |"))
24917 (let (org-table-may-need-update)
24918 (goto-char (1- (match-end 0)))
24919 (delete-backward-char 1)
24920 (goto-char (match-beginning 0))
24921 (self-insert-command N))
24922 (setq org-table-may-need-update t)
24923 (self-insert-command N)
24924 (org-fix-tags-on-the-fly)))
24926 (defun org-fix-tags-on-the-fly ()
24927 (when (and (equal (char-after (point-at-bol)) ?*)
24928 (org-on-heading-p))
24929 (org-align-tags-here org-tags-column)))
24931 (defun org-delete-backward-char (N)
24932 "Like `delete-backward-char', insert whitespace at field end in tables.
24933 When deleting backwards, in tables this function will insert whitespace in
24934 front of the next \"|\" separator, to keep the table aligned. The table will
24935 still be marked for re-alignment if the field did fill the entire column,
24936 because, in this case the deletion might narrow the column."
24937 (interactive "p")
24938 (if (and (org-table-p)
24939 (eq N 1)
24940 (string-match "|" (buffer-substring (point-at-bol) (point)))
24941 (looking-at ".*?|"))
24942 (let ((pos (point))
24943 (noalign (looking-at "[^|\n\r]* |"))
24944 (c org-table-may-need-update))
24945 (backward-delete-char N)
24946 (skip-chars-forward "^|")
24947 (insert " ")
24948 (goto-char (1- pos))
24949 ;; noalign: if there were two spaces at the end, this field
24950 ;; does not determine the width of the column.
24951 (if noalign (setq org-table-may-need-update c)))
24952 (backward-delete-char N)
24953 (org-fix-tags-on-the-fly)))
24955 (defun org-delete-char (N)
24956 "Like `delete-char', but insert whitespace at field end in tables.
24957 When deleting characters, in tables this function will insert whitespace in
24958 front of the next \"|\" separator, to keep the table aligned. The table will
24959 still be marked for re-alignment if the field did fill the entire column,
24960 because, in this case the deletion might narrow the column."
24961 (interactive "p")
24962 (if (and (org-table-p)
24963 (not (bolp))
24964 (not (= (char-after) ?|))
24965 (eq N 1))
24966 (if (looking-at ".*?|")
24967 (let ((pos (point))
24968 (noalign (looking-at "[^|\n\r]* |"))
24969 (c org-table-may-need-update))
24970 (replace-match (concat
24971 (substring (match-string 0) 1 -1)
24972 " |"))
24973 (goto-char pos)
24974 ;; noalign: if there were two spaces at the end, this field
24975 ;; does not determine the width of the column.
24976 (if noalign (setq org-table-may-need-update c)))
24977 (delete-char N))
24978 (delete-char N)
24979 (org-fix-tags-on-the-fly)))
24981 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
24982 (put 'org-self-insert-command 'delete-selection t)
24983 (put 'orgtbl-self-insert-command 'delete-selection t)
24984 (put 'org-delete-char 'delete-selection 'supersede)
24985 (put 'org-delete-backward-char 'delete-selection 'supersede)
24987 ;; Make `flyspell-mode' delay after some commands
24988 (put 'org-self-insert-command 'flyspell-delayed t)
24989 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
24990 (put 'org-delete-char 'flyspell-delayed t)
24991 (put 'org-delete-backward-char 'flyspell-delayed t)
24993 (eval-after-load "pabbrev"
24994 '(progn
24995 (add-to-list 'pabbrev-expand-after-command-list
24996 'orgtbl-self-insert-command t)
24997 (add-to-list 'pabbrev-expand-after-command-list
24998 'org-self-insert-command t)))
25000 ;; How to do this: Measure non-white length of current string
25001 ;; If equal to column width, we should realign.
25003 (defun org-remap (map &rest commands)
25004 "In MAP, remap the functions given in COMMANDS.
25005 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25006 (let (new old)
25007 (while commands
25008 (setq old (pop commands) new (pop commands))
25009 (if (fboundp 'command-remapping)
25010 (org-defkey map (vector 'remap old) new)
25011 (substitute-key-definition old new map global-map)))))
25013 (when (eq org-enable-table-editor 'optimized)
25014 ;; If the user wants maximum table support, we need to hijack
25015 ;; some standard editing functions
25016 (org-remap org-mode-map
25017 'self-insert-command 'org-self-insert-command
25018 'delete-char 'org-delete-char
25019 'delete-backward-char 'org-delete-backward-char)
25020 (org-defkey org-mode-map "|" 'org-force-self-insert))
25022 (defun org-shiftcursor-error ()
25023 "Throw an error because Shift-Cursor command was applied in wrong context."
25024 (error "This command is active in special context like tables, headlines or timestamps"))
25026 (defun org-shifttab (&optional arg)
25027 "Global visibility cycling or move to previous table field.
25028 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25029 on context.
25030 See the individual commands for more information."
25031 (interactive "P")
25032 (cond
25033 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25034 (arg (message "Content view to level: ")
25035 (org-content (prefix-numeric-value arg))
25036 (setq org-cycle-global-status 'overview))
25037 (t (call-interactively 'org-global-cycle))))
25039 (defun org-shiftmetaleft ()
25040 "Promote subtree or delete table column.
25041 Calls `org-promote-subtree', `org-outdent-item',
25042 or `org-table-delete-column', depending on context.
25043 See the individual commands for more information."
25044 (interactive)
25045 (cond
25046 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25047 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25048 ((org-at-item-p) (call-interactively 'org-outdent-item))
25049 (t (org-shiftcursor-error))))
25051 (defun org-shiftmetaright ()
25052 "Demote subtree or insert table column.
25053 Calls `org-demote-subtree', `org-indent-item',
25054 or `org-table-insert-column', depending on context.
25055 See the individual commands for more information."
25056 (interactive)
25057 (cond
25058 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25059 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25060 ((org-at-item-p) (call-interactively 'org-indent-item))
25061 (t (org-shiftcursor-error))))
25063 (defun org-shiftmetaup (&optional arg)
25064 "Move subtree up or kill table row.
25065 Calls `org-move-subtree-up' or `org-table-kill-row' or
25066 `org-move-item-up' depending on context. See the individual commands
25067 for more information."
25068 (interactive "P")
25069 (cond
25070 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25071 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25072 ((org-at-item-p) (call-interactively 'org-move-item-up))
25073 (t (org-shiftcursor-error))))
25074 (defun org-shiftmetadown (&optional arg)
25075 "Move subtree down or insert table row.
25076 Calls `org-move-subtree-down' or `org-table-insert-row' or
25077 `org-move-item-down', depending on context. See the individual
25078 commands for more information."
25079 (interactive "P")
25080 (cond
25081 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25082 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25083 ((org-at-item-p) (call-interactively 'org-move-item-down))
25084 (t (org-shiftcursor-error))))
25086 (defun org-metaleft (&optional arg)
25087 "Promote heading or move table column to left.
25088 Calls `org-do-promote' or `org-table-move-column', depending on context.
25089 With no specific context, calls the Emacs default `backward-word'.
25090 See the individual commands for more information."
25091 (interactive "P")
25092 (cond
25093 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25094 ((or (org-on-heading-p) (org-region-active-p))
25095 (call-interactively 'org-do-promote))
25096 ((org-at-item-p) (call-interactively 'org-outdent-item))
25097 (t (call-interactively 'backward-word))))
25099 (defun org-metaright (&optional arg)
25100 "Demote subtree or move table column to right.
25101 Calls `org-do-demote' or `org-table-move-column', depending on context.
25102 With no specific context, calls the Emacs default `forward-word'.
25103 See the individual commands for more information."
25104 (interactive "P")
25105 (cond
25106 ((org-at-table-p) (call-interactively 'org-table-move-column))
25107 ((or (org-on-heading-p) (org-region-active-p))
25108 (call-interactively 'org-do-demote))
25109 ((org-at-item-p) (call-interactively 'org-indent-item))
25110 (t (call-interactively 'forward-word))))
25112 (defun org-metaup (&optional arg)
25113 "Move subtree up or move table row up.
25114 Calls `org-move-subtree-up' or `org-table-move-row' or
25115 `org-move-item-up', depending on context. See the individual commands
25116 for more information."
25117 (interactive "P")
25118 (cond
25119 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25120 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25121 ((org-at-item-p) (call-interactively 'org-move-item-up))
25122 (t (transpose-lines 1) (beginning-of-line -1))))
25124 (defun org-metadown (&optional arg)
25125 "Move subtree down or move table row down.
25126 Calls `org-move-subtree-down' or `org-table-move-row' or
25127 `org-move-item-down', depending on context. See the individual
25128 commands for more information."
25129 (interactive "P")
25130 (cond
25131 ((org-at-table-p) (call-interactively 'org-table-move-row))
25132 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25133 ((org-at-item-p) (call-interactively 'org-move-item-down))
25134 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25136 (defun org-shiftup (&optional arg)
25137 "Increase item in timestamp or increase priority of current headline.
25138 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25139 depending on context. See the individual commands for more information."
25140 (interactive "P")
25141 (cond
25142 ((org-at-timestamp-p t)
25143 (call-interactively (if org-edit-timestamp-down-means-later
25144 'org-timestamp-down 'org-timestamp-up)))
25145 ((org-on-heading-p) (call-interactively 'org-priority-up))
25146 ((org-at-item-p) (call-interactively 'org-previous-item))
25147 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25149 (defun org-shiftdown (&optional arg)
25150 "Decrease item in timestamp or decrease priority of current headline.
25151 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25152 depending on context. See the individual commands for more information."
25153 (interactive "P")
25154 (cond
25155 ((org-at-timestamp-p t)
25156 (call-interactively (if org-edit-timestamp-down-means-later
25157 'org-timestamp-up 'org-timestamp-down)))
25158 ((org-on-heading-p) (call-interactively 'org-priority-down))
25159 (t (call-interactively 'org-next-item))))
25161 (defun org-shiftright ()
25162 "Next TODO keyword or timestamp one day later, depending on context."
25163 (interactive)
25164 (cond
25165 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25166 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25167 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25168 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25169 (t (org-shiftcursor-error))))
25171 (defun org-shiftleft ()
25172 "Previous TODO keyword or timestamp one day earlier, depending on context."
25173 (interactive)
25174 (cond
25175 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25176 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25177 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25178 ((org-at-property-p)
25179 (call-interactively 'org-property-previous-allowed-value))
25180 (t (org-shiftcursor-error))))
25182 (defun org-shiftcontrolright ()
25183 "Switch to next TODO set."
25184 (interactive)
25185 (cond
25186 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25187 (t (org-shiftcursor-error))))
25189 (defun org-shiftcontrolleft ()
25190 "Switch to previous TODO set."
25191 (interactive)
25192 (cond
25193 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25194 (t (org-shiftcursor-error))))
25196 (defun org-ctrl-c-ret ()
25197 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25198 (interactive)
25199 (cond
25200 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25201 (t (call-interactively 'org-insert-heading))))
25203 (defun org-copy-special ()
25204 "Copy region in table or copy current subtree.
25205 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25206 See the individual commands for more information."
25207 (interactive)
25208 (call-interactively
25209 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25211 (defun org-cut-special ()
25212 "Cut region in table or cut current subtree.
25213 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25214 See the individual commands for more information."
25215 (interactive)
25216 (call-interactively
25217 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25219 (defun org-paste-special (arg)
25220 "Paste rectangular region into table, or past subtree relative to level.
25221 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25222 See the individual commands for more information."
25223 (interactive "P")
25224 (if (org-at-table-p)
25225 (org-table-paste-rectangle)
25226 (org-paste-subtree arg)))
25228 (defun org-ctrl-c-ctrl-c (&optional arg)
25229 "Set tags in headline, or update according to changed information at point.
25231 This command does many different things, depending on context:
25233 - If the cursor is in a headline, prompt for tags and insert them
25234 into the current line, aligned to `org-tags-column'. When called
25235 with prefix arg, realign all tags in the current buffer.
25237 - If the cursor is in one of the special #+KEYWORD lines, this
25238 triggers scanning the buffer for these lines and updating the
25239 information.
25241 - If the cursor is inside a table, realign the table. This command
25242 works even if the automatic table editor has been turned off.
25244 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25245 the entire table.
25247 - If the cursor is a the beginning of a dynamic block, update it.
25249 - If the cursor is inside a table created by the table.el package,
25250 activate that table.
25252 - If the current buffer is a remember buffer, close note and file it.
25253 with a prefix argument, file it without further interaction to the default
25254 location.
25256 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25257 links in this buffer.
25259 - If the cursor is on a numbered item in a plain list, renumber the
25260 ordered list."
25261 (interactive "P")
25262 (let ((org-enable-table-editor t))
25263 (cond
25264 ((or org-clock-overlays
25265 org-occur-highlights
25266 org-latex-fragment-image-overlays)
25267 (org-remove-clock-overlays)
25268 (org-remove-occur-highlights)
25269 (org-remove-latex-fragment-image-overlays)
25270 (message "Temporary highlights/overlays removed from current buffer"))
25271 ((and (local-variable-p 'org-finish-function (current-buffer))
25272 (fboundp org-finish-function))
25273 (funcall org-finish-function))
25274 ((org-at-property-p)
25275 (call-interactively 'org-property-action))
25276 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25277 ((org-on-heading-p) (call-interactively 'org-set-tags))
25278 ((org-at-table.el-p)
25279 (require 'table)
25280 (beginning-of-line 1)
25281 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25282 (call-interactively 'table-recognize-table))
25283 ((org-at-table-p)
25284 (org-table-maybe-eval-formula)
25285 (if arg
25286 (call-interactively 'org-table-recalculate)
25287 (org-table-maybe-recalculate-line))
25288 (call-interactively 'org-table-align))
25289 ((org-at-item-checkbox-p)
25290 (call-interactively 'org-toggle-checkbox))
25291 ((org-at-item-p)
25292 (call-interactively 'org-maybe-renumber-ordered-list))
25293 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25294 ;; Dynamic block
25295 (beginning-of-line 1)
25296 (org-update-dblock))
25297 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25298 (cond
25299 ((equal (match-string 1) "TBLFM")
25300 ;; Recalculate the table before this line
25301 (save-excursion
25302 (beginning-of-line 1)
25303 (skip-chars-backward " \r\n\t")
25304 (if (org-at-table-p)
25305 (org-call-with-arg 'org-table-recalculate t))))
25307 (call-interactively 'org-mode-restart))))
25308 (t (error "C-c C-c can do nothing useful at this location.")))))
25310 (defun org-mode-restart ()
25311 "Restart Org-mode, to scan again for special lines.
25312 Also updates the keyword regular expressions."
25313 (interactive)
25314 (let ((org-inhibit-startup t)) (org-mode))
25315 (message "Org-mode restarted to refresh keyword and special line setup"))
25317 (defun org-kill-note-or-show-branches ()
25318 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25319 (interactive)
25320 (if (not org-finish-function)
25321 (call-interactively 'show-branches)
25322 (let ((org-note-abort t))
25323 (funcall org-finish-function))))
25325 (defun org-return ()
25326 "Goto next table row or insert a newline.
25327 Calls `org-table-next-row' or `newline', depending on context.
25328 See the individual commands for more information."
25329 (interactive)
25330 (cond
25331 ((bobp) (newline))
25332 ((org-at-table-p)
25333 (org-table-justify-field-maybe)
25334 (call-interactively 'org-table-next-row))
25335 (t (newline))))
25338 (defun org-ctrl-c-minus ()
25339 "Insert separator line in table or modify bullet type in list.
25340 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25341 depending on context."
25342 (interactive)
25343 (cond
25344 ((org-at-table-p)
25345 (call-interactively 'org-table-insert-hline))
25346 ((org-on-heading-p)
25347 ;; Convert to item
25348 (save-excursion
25349 (beginning-of-line 1)
25350 (if (looking-at "\\*+ ")
25351 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
25352 ((org-in-item-p)
25353 (call-interactively 'org-cycle-list-bullet))
25354 (t (error "`C-c -' does have no function here."))))
25356 (defun org-meta-return (&optional arg)
25357 "Insert a new heading or wrap a region in a table.
25358 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
25359 See the individual commands for more information."
25360 (interactive "P")
25361 (cond
25362 ((org-at-table-p)
25363 (call-interactively 'org-table-wrap-region))
25364 (t (call-interactively 'org-insert-heading))))
25366 ;;; Menu entries
25368 ;; Define the Org-mode menus
25369 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
25370 '("Tbl"
25371 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
25372 ["Next Field" org-cycle (org-at-table-p)]
25373 ["Previous Field" org-shifttab (org-at-table-p)]
25374 ["Next Row" org-return (org-at-table-p)]
25375 "--"
25376 ["Blank Field" org-table-blank-field (org-at-table-p)]
25377 ["Edit Field" org-table-edit-field (org-at-table-p)]
25378 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
25379 "--"
25380 ("Column"
25381 ["Move Column Left" org-metaleft (org-at-table-p)]
25382 ["Move Column Right" org-metaright (org-at-table-p)]
25383 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
25384 ["Insert Column" org-shiftmetaright (org-at-table-p)])
25385 ("Row"
25386 ["Move Row Up" org-metaup (org-at-table-p)]
25387 ["Move Row Down" org-metadown (org-at-table-p)]
25388 ["Delete Row" org-shiftmetaup (org-at-table-p)]
25389 ["Insert Row" org-shiftmetadown (org-at-table-p)]
25390 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
25391 "--"
25392 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
25393 ("Rectangle"
25394 ["Copy Rectangle" org-copy-special (org-at-table-p)]
25395 ["Cut Rectangle" org-cut-special (org-at-table-p)]
25396 ["Paste Rectangle" org-paste-special (org-at-table-p)]
25397 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
25398 "--"
25399 ("Calculate"
25400 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
25401 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
25402 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
25403 "--"
25404 ["Recalculate line" org-table-recalculate (org-at-table-p)]
25405 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
25406 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
25407 "--"
25408 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
25409 "--"
25410 ["Sum Column/Rectangle" org-table-sum
25411 (or (org-at-table-p) (org-region-active-p))]
25412 ["Which Column?" org-table-current-column (org-at-table-p)])
25413 ["Debug Formulas"
25414 org-table-toggle-formula-debugger
25415 :style toggle :selected org-table-formula-debug]
25416 ["Show Col/Row Numbers"
25417 org-table-toggle-coordinate-overlays
25418 :style toggle :selected org-table-overlay-coordinates]
25419 "--"
25420 ["Create" org-table-create (and (not (org-at-table-p))
25421 org-enable-table-editor)]
25422 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
25423 ["Import from File" org-table-import (not (org-at-table-p))]
25424 ["Export to File" org-table-export (org-at-table-p)]
25425 "--"
25426 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
25428 (easy-menu-define org-org-menu org-mode-map "Org menu"
25429 '("Org"
25430 ("Show/Hide"
25431 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
25432 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
25433 ["Sparse Tree" org-occur t]
25434 ["Reveal Context" org-reveal t]
25435 ["Show All" show-all t]
25436 "--"
25437 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
25438 "--"
25439 ["New Heading" org-insert-heading t]
25440 ("Navigate Headings"
25441 ["Up" outline-up-heading t]
25442 ["Next" outline-next-visible-heading t]
25443 ["Previous" outline-previous-visible-heading t]
25444 ["Next Same Level" outline-forward-same-level t]
25445 ["Previous Same Level" outline-backward-same-level t]
25446 "--"
25447 ["Jump" org-goto t])
25448 ("Edit Structure"
25449 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
25450 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
25451 "--"
25452 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
25453 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
25454 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
25455 "--"
25456 ["Promote Heading" org-metaleft (not (org-at-table-p))]
25457 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
25458 ["Demote Heading" org-metaright (not (org-at-table-p))]
25459 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
25460 "--"
25461 ["Sort Region/Children" org-sort (not (org-at-table-p))]
25462 "--"
25463 ["Convert to odd levels" org-convert-to-odd-levels t]
25464 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
25465 ("Editing"
25466 ["Emphasis..." org-emphasize t])
25467 ("Archive"
25468 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
25469 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
25470 ; :active t :keys "C-u C-c C-x C-a"]
25471 ["Sparse trees open ARCHIVE trees"
25472 (setq org-sparse-tree-open-archived-trees
25473 (not org-sparse-tree-open-archived-trees))
25474 :style toggle :selected org-sparse-tree-open-archived-trees]
25475 ["Cycling opens ARCHIVE trees"
25476 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
25477 :style toggle :selected org-cycle-open-archived-trees]
25478 ["Agenda includes ARCHIVE trees"
25479 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
25480 :style toggle :selected (not org-agenda-skip-archived-trees)]
25481 "--"
25482 ["Move Subtree to Archive" org-advertized-archive-subtree t]
25483 ; ["Check and Move Children" (org-archive-subtree '(4))
25484 ; :active t :keys "C-u C-c C-x C-s"]
25486 "--"
25487 ("TODO Lists"
25488 ["TODO/DONE/-" org-todo t]
25489 ("Select keyword"
25490 ["Next keyword" org-shiftright (org-on-heading-p)]
25491 ["Previous keyword" org-shiftleft (org-on-heading-p)]
25492 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
25493 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
25494 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
25495 ["Show TODO Tree" org-show-todo-tree t]
25496 ["Global TODO list" org-todo-list t]
25497 "--"
25498 ["Set Priority" org-priority t]
25499 ["Priority Up" org-shiftup t]
25500 ["Priority Down" org-shiftdown t])
25501 ("TAGS and Properties"
25502 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
25503 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
25504 "--"
25505 ["Set property" 'org-set-property t]
25506 ["Column view of properties" org-columns t]
25507 ["Insert Column View DBlock" org-insert-columns-dblock t])
25508 ("Dates and Scheduling"
25509 ["Timestamp" org-time-stamp t]
25510 ["Timestamp (inactive)" org-time-stamp-inactive t]
25511 ("Change Date"
25512 ["1 Day Later" org-shiftright t]
25513 ["1 Day Earlier" org-shiftleft t]
25514 ["1 ... Later" org-shiftup t]
25515 ["1 ... Earlier" org-shiftdown t])
25516 ["Compute Time Range" org-evaluate-time-range t]
25517 ["Schedule Item" org-schedule t]
25518 ["Deadline" org-deadline t]
25519 "--"
25520 ["Custom time format" org-toggle-time-stamp-overlays
25521 :style radio :selected org-display-custom-times]
25522 "--"
25523 ["Goto Calendar" org-goto-calendar t]
25524 ["Date from Calendar" org-date-from-calendar t])
25525 ("Logging work"
25526 ["Clock in" org-clock-in t]
25527 ["Clock out" org-clock-out t]
25528 ["Clock cancel" org-clock-cancel t]
25529 ["Goto running clock" org-clock-goto t]
25530 ["Display times" org-clock-display t]
25531 ["Create clock table" org-clock-report t]
25532 "--"
25533 ["Record DONE time"
25534 (progn (setq org-log-done (not org-log-done))
25535 (message "Switching to %s will %s record a timestamp"
25536 (car org-done-keywords)
25537 (if org-log-done "automatically" "not")))
25538 :style toggle :selected org-log-done])
25539 "--"
25540 ["Agenda Command..." org-agenda t]
25541 ("File List for Agenda")
25542 ("Special views current file"
25543 ["TODO Tree" org-show-todo-tree t]
25544 ["Check Deadlines" org-check-deadlines t]
25545 ["Timeline" org-timeline t]
25546 ["Tags Tree" org-tags-sparse-tree t])
25547 "--"
25548 ("Hyperlinks"
25549 ["Store Link (Global)" org-store-link t]
25550 ["Insert Link" org-insert-link t]
25551 ["Follow Link" org-open-at-point t]
25552 "--"
25553 ["Next link" org-next-link t]
25554 ["Previous link" org-previous-link t]
25555 "--"
25556 ["Descriptive Links"
25557 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
25558 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
25559 ["Literal Links"
25560 (progn
25561 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
25562 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
25563 "--"
25564 ["Export/Publish..." org-export t]
25565 ("LaTeX"
25566 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
25567 :selected org-cdlatex-mode]
25568 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
25569 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
25570 ["Modify math symbol" org-cdlatex-math-modify
25571 (org-inside-LaTeX-fragment-p)]
25572 ["Export LaTeX fragments as images"
25573 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
25574 :style toggle :selected org-export-with-LaTeX-fragments])
25575 "--"
25576 ("Documentation"
25577 ["Show Version" org-version t]
25578 ["Info Documentation" org-info t])
25579 ("Customize"
25580 ["Browse Org Group" org-customize t]
25581 "--"
25582 ["Expand This Menu" org-create-customize-menu
25583 (fboundp 'customize-menu-create)])
25584 "--"
25585 ["Refresh setup" org-mode-restart t]
25588 (defun org-info (&optional node)
25589 "Read documentation for Org-mode in the info system.
25590 With optional NODE, go directly to that node."
25591 (interactive)
25592 (require 'info)
25593 (Info-goto-node (format "(org)%s" (or node ""))))
25595 (defun org-install-agenda-files-menu ()
25596 (let ((bl (buffer-list)))
25597 (save-excursion
25598 (while bl
25599 (set-buffer (pop bl))
25600 (if (org-mode-p) (setq bl nil)))
25601 (when (org-mode-p)
25602 (easy-menu-change
25603 '("Org") "File List for Agenda"
25604 (append
25605 (list
25606 ["Edit File List" (org-edit-agenda-file-list) t]
25607 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
25608 ["Remove Current File from List" org-remove-file t]
25609 ["Cycle through agenda files" org-cycle-agenda-files t]
25610 ["Occur in all agenda files" org-occur-in-agenda-files t]
25611 "--")
25612 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
25614 ;;;; Documentation
25616 (defun org-customize ()
25617 "Call the customize function with org as argument."
25618 (interactive)
25619 (customize-browse 'org))
25621 (defun org-create-customize-menu ()
25622 "Create a full customization menu for Org-mode, insert it into the menu."
25623 (interactive)
25624 (if (fboundp 'customize-menu-create)
25625 (progn
25626 (easy-menu-change
25627 '("Org") "Customize"
25628 `(["Browse Org group" org-customize t]
25629 "--"
25630 ,(customize-menu-create 'org)
25631 ["Set" Custom-set t]
25632 ["Save" Custom-save t]
25633 ["Reset to Current" Custom-reset-current t]
25634 ["Reset to Saved" Custom-reset-saved t]
25635 ["Reset to Standard Settings" Custom-reset-standard t]))
25636 (message "\"Org\"-menu now contains full customization menu"))
25637 (error "Cannot expand menu (outdated version of cus-edit.el)")))
25639 ;;;; Miscellaneous stuff
25642 ;;; Generally useful functions
25644 (defun org-context ()
25645 "Return a list of contexts of the current cursor position.
25646 If several contexts apply, all are returned.
25647 Each context entry is a list with a symbol naming the context, and
25648 two positions indicating start and end of the context. Possible
25649 contexts are:
25651 :headline anywhere in a headline
25652 :headline-stars on the leading stars in a headline
25653 :todo-keyword on a TODO keyword (including DONE) in a headline
25654 :tags on the TAGS in a headline
25655 :priority on the priority cookie in a headline
25656 :item on the first line of a plain list item
25657 :item-bullet on the bullet/number of a plain list item
25658 :checkbox on the checkbox in a plain list item
25659 :table in an org-mode table
25660 :table-special on a special filed in a table
25661 :table-table in a table.el table
25662 :link on a hyperlink
25663 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
25664 :target on a <<target>>
25665 :radio-target on a <<<radio-target>>>
25666 :latex-fragment on a LaTeX fragment
25667 :latex-preview on a LaTeX fragment with overlayed preview image
25669 This function expects the position to be visible because it uses font-lock
25670 faces as a help to recognize the following contexts: :table-special, :link,
25671 and :keyword."
25672 (let* ((f (get-text-property (point) 'face))
25673 (faces (if (listp f) f (list f)))
25674 (p (point)) clist o)
25675 ;; First the large context
25676 (cond
25677 ((org-on-heading-p t)
25678 (push (list :headline (point-at-bol) (point-at-eol)) clist)
25679 (when (progn
25680 (beginning-of-line 1)
25681 (looking-at org-todo-line-tags-regexp))
25682 (push (org-point-in-group p 1 :headline-stars) clist)
25683 (push (org-point-in-group p 2 :todo-keyword) clist)
25684 (push (org-point-in-group p 4 :tags) clist))
25685 (goto-char p)
25686 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
25687 (if (looking-at "\\[#[A-Z0-9]\\]")
25688 (push (org-point-in-group p 0 :priority) clist)))
25690 ((org-at-item-p)
25691 (push (org-point-in-group p 2 :item-bullet) clist)
25692 (push (list :item (point-at-bol)
25693 (save-excursion (org-end-of-item) (point)))
25694 clist)
25695 (and (org-at-item-checkbox-p)
25696 (push (org-point-in-group p 0 :checkbox) clist)))
25698 ((org-at-table-p)
25699 (push (list :table (org-table-begin) (org-table-end)) clist)
25700 (if (memq 'org-formula faces)
25701 (push (list :table-special
25702 (previous-single-property-change p 'face)
25703 (next-single-property-change p 'face)) clist)))
25704 ((org-at-table-p 'any)
25705 (push (list :table-table) clist)))
25706 (goto-char p)
25708 ;; Now the small context
25709 (cond
25710 ((org-at-timestamp-p)
25711 (push (org-point-in-group p 0 :timestamp) clist))
25712 ((memq 'org-link faces)
25713 (push (list :link
25714 (previous-single-property-change p 'face)
25715 (next-single-property-change p 'face)) clist))
25716 ((memq 'org-special-keyword faces)
25717 (push (list :keyword
25718 (previous-single-property-change p 'face)
25719 (next-single-property-change p 'face)) clist))
25720 ((org-on-target-p)
25721 (push (org-point-in-group p 0 :target) clist)
25722 (goto-char (1- (match-beginning 0)))
25723 (if (looking-at org-radio-target-regexp)
25724 (push (org-point-in-group p 0 :radio-target) clist))
25725 (goto-char p))
25726 ((setq o (car (delq nil
25727 (mapcar
25728 (lambda (x)
25729 (if (memq x org-latex-fragment-image-overlays) x))
25730 (org-overlays-at (point))))))
25731 (push (list :latex-fragment
25732 (org-overlay-start o) (org-overlay-end o)) clist)
25733 (push (list :latex-preview
25734 (org-overlay-start o) (org-overlay-end o)) clist))
25735 ((org-inside-LaTeX-fragment-p)
25736 ;; FIXME: positions wrong.
25737 (push (list :latex-fragment (point) (point)) clist)))
25739 (setq clist (nreverse (delq nil clist)))
25740 clist))
25742 ;; FIXME: Compare with at-regexp-p Do we need both?
25743 (defun org-in-regexp (re &optional nlines visually)
25744 "Check if point is inside a match of regexp.
25745 Normally only the current line is checked, but you can include NLINES extra
25746 lines both before and after point into the search.
25747 If VISUALLY is set, require that the cursor is not after the match but
25748 really on, so that the block visually is on the match."
25749 (catch 'exit
25750 (let ((pos (point))
25751 (eol (point-at-eol (+ 1 (or nlines 0))))
25752 (inc (if visually 1 0)))
25753 (save-excursion
25754 (beginning-of-line (- 1 (or nlines 0)))
25755 (while (re-search-forward re eol t)
25756 (if (and (<= (match-beginning 0) pos)
25757 (>= (+ inc (match-end 0)) pos))
25758 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25760 (defun org-at-regexp-p (regexp)
25761 "Is point inside a match of REGEXP in the current line?"
25762 (catch 'exit
25763 (save-excursion
25764 (let ((pos (point)) (end (point-at-eol)))
25765 (beginning-of-line 1)
25766 (while (re-search-forward regexp end t)
25767 (if (and (<= (match-beginning 0) pos)
25768 (>= (match-end 0) pos))
25769 (throw 'exit t)))
25770 nil))))
25772 (defun org-occur-in-agenda-files (regexp &optional nlines)
25773 "Call `multi-occur' with buffers for all agenda files."
25774 (interactive "sOrg-files matching: \np")
25775 (let* ((files (org-agenda-files))
25776 (tnames (mapcar 'file-truename files))
25777 (extra org-agenda-multi-occur-extra-files)
25779 (while (setq f (pop extra))
25780 (unless (member (file-truename f) tnames)
25781 (add-to-list 'files f 'append)
25782 (add-to-list 'tnames (file-truename f) 'append)))
25783 (multi-occur
25784 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25785 regexp)))
25787 (defun org-uniquify (list)
25788 "Remove duplicate elements from LIST."
25789 (let (res)
25790 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25791 res))
25793 (defun org-delete-all (elts list)
25794 "Remove all elements in ELTS from LIST."
25795 (while elts
25796 (setq list (delete (pop elts) list)))
25797 list)
25799 (defun org-point-in-group (point group &optional context)
25800 "Check if POINT is in match-group GROUP.
25801 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25802 match. If the match group does ot exist or point is not inside it,
25803 return nil."
25804 (and (match-beginning group)
25805 (>= point (match-beginning group))
25806 (<= point (match-end group))
25807 (if context
25808 (list context (match-beginning group) (match-end group))
25809 t)))
25811 (defun org-switch-to-buffer-other-window (&rest args)
25812 "Switch to buffer in a second window on the current frame.
25813 In particular, do not allow pop-up frames."
25814 (let (pop-up-frames special-display-buffer-names special-display-regexps
25815 special-display-function)
25816 (apply 'switch-to-buffer-other-window args)))
25818 (defun org-combine-plists (&rest plists)
25819 "Create a single property list from all plists in PLISTS.
25820 The process starts by copying the first list, and then setting properties
25821 from the other lists. Settings in the last list are the most significant
25822 ones and overrule settings in the other lists."
25823 (let ((rtn (copy-sequence (pop plists)))
25824 p v ls)
25825 (while plists
25826 (setq ls (pop plists))
25827 (while ls
25828 (setq p (pop ls) v (pop ls))
25829 (setq rtn (plist-put rtn p v))))
25830 rtn))
25832 (defun org-move-line-down (arg)
25833 "Move the current line down. With prefix argument, move it past ARG lines."
25834 (interactive "p")
25835 (let ((col (current-column))
25836 beg end pos)
25837 (beginning-of-line 1) (setq beg (point))
25838 (beginning-of-line 2) (setq end (point))
25839 (beginning-of-line (+ 1 arg))
25840 (setq pos (move-marker (make-marker) (point)))
25841 (insert (delete-and-extract-region beg end))
25842 (goto-char pos)
25843 (move-to-column col)))
25845 (defun org-move-line-up (arg)
25846 "Move the current line up. With prefix argument, move it past ARG lines."
25847 (interactive "p")
25848 (let ((col (current-column))
25849 beg end pos)
25850 (beginning-of-line 1) (setq beg (point))
25851 (beginning-of-line 2) (setq end (point))
25852 (beginning-of-line (- arg))
25853 (setq pos (move-marker (make-marker) (point)))
25854 (insert (delete-and-extract-region beg end))
25855 (goto-char pos)
25856 (move-to-column col)))
25858 (defun org-replace-escapes (string table)
25859 "Replace %-escapes in STRING with values in TABLE.
25860 TABLE is an association list with keys like \"%a\" and string values.
25861 The sequences in STRING may contain normal field width and padding information,
25862 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
25863 so values can contain further %-escapes if they are define later in TABLE."
25864 (let ((case-fold-search nil)
25865 e re rpl)
25866 (while (setq e (pop table))
25867 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
25868 (while (string-match re string)
25869 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
25870 (cdr e)))
25871 (setq string (replace-match rpl t t string))))
25872 string))
25875 (defun org-sublist (list start end)
25876 "Return a section of LIST, from START to END.
25877 Counting starts at 1."
25878 (let (rtn (c start))
25879 (setq list (nthcdr (1- start) list))
25880 (while (and list (<= c end))
25881 (push (pop list) rtn)
25882 (setq c (1+ c)))
25883 (nreverse rtn)))
25885 (defun org-find-base-buffer-visiting (file)
25886 "Like `find-buffer-visiting' but alway return the base buffer and
25887 not an indirect buffer"
25888 (let ((buf (find-buffer-visiting file)))
25889 (if buf
25890 (or (buffer-base-buffer buf) buf)
25891 nil)))
25893 (defun org-image-file-name-regexp ()
25894 "Return regexp matching the file names of images."
25895 (if (fboundp 'image-file-name-regexp)
25896 (image-file-name-regexp)
25897 (let ((image-file-name-extensions
25898 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
25899 "xbm" "xpm" "pbm" "pgm" "ppm")))
25900 (concat "\\."
25901 (regexp-opt (nconc (mapcar 'upcase
25902 image-file-name-extensions)
25903 image-file-name-extensions)
25905 "\\'"))))
25907 (defun org-file-image-p (file)
25908 "Return non-nil if FILE is an image."
25909 (save-match-data
25910 (string-match (org-image-file-name-regexp) file)))
25912 ;;; Paragraph filling stuff.
25913 ;; We want this to be just right, so use the full arsenal.
25915 (defun org-indent-line-function ()
25916 "Indent line like previous, but further if previous was headline or item."
25917 (interactive)
25918 (let* ((pos (point))
25919 (itemp (org-at-item-p))
25920 column bpos bcol tpos tcol bullet btype bullet-type)
25921 ;; Find the previous relevant line
25922 (beginning-of-line 1)
25923 (cond
25924 ((looking-at "#") (setq column 0))
25925 ((looking-at "\\*+ ") (setq column 0))
25927 (beginning-of-line 0)
25928 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
25929 (beginning-of-line 0))
25930 (cond
25931 ((looking-at "\\*+[ \t]+")
25932 (goto-char (match-end 0))
25933 (setq column (current-column)))
25934 ((org-in-item-p)
25935 (org-beginning-of-item)
25936 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25937 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
25938 (setq bpos (match-beginning 1) tpos (match-end 0)
25939 bcol (progn (goto-char bpos) (current-column))
25940 tcol (progn (goto-char tpos) (current-column))
25941 bullet (match-string 1)
25942 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
25943 (if (not itemp)
25944 (setq column tcol)
25945 (goto-char pos)
25946 (beginning-of-line 1)
25947 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
25948 (setq bullet (match-string 1)
25949 btype (if (string-match "[0-9]" bullet) "n" bullet))
25950 (setq column (if (equal btype bullet-type) bcol tcol))))
25951 (t (setq column (org-get-indentation))))))
25952 (goto-char pos)
25953 (if (<= (current-column) (current-indentation))
25954 (indent-line-to column)
25955 (save-excursion (indent-line-to column)))
25956 (setq column (current-column))
25957 (beginning-of-line 1)
25958 (if (looking-at
25959 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
25960 (replace-match (concat "\\1" (format org-property-format
25961 (match-string 2) (match-string 3)))
25962 t nil))
25963 (move-to-column column)))
25965 (defun org-set-autofill-regexps ()
25966 (interactive)
25967 ;; In the paragraph separator we include headlines, because filling
25968 ;; text in a line directly attached to a headline would otherwise
25969 ;; fill the headline as well.
25970 (org-set-local 'comment-start-skip "^#+[ \t]*")
25971 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
25972 ;; The paragraph starter includes hand-formatted lists.
25973 (org-set-local 'paragraph-start
25974 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
25975 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
25976 ;; But only if the user has not turned off tables or fixed-width regions
25977 (org-set-local
25978 'auto-fill-inhibit-regexp
25979 (concat "\\*+ \\|#\\+"
25980 "\\|[ \t]*" org-keyword-time-regexp
25981 (if (or org-enable-table-editor org-enable-fixed-width-editor)
25982 (concat
25983 "\\|[ \t]*["
25984 (if org-enable-table-editor "|" "")
25985 (if org-enable-fixed-width-editor ":" "")
25986 "]"))))
25987 ;; We use our own fill-paragraph function, to make sure that tables
25988 ;; and fixed-width regions are not wrapped. That function will pass
25989 ;; through to `fill-paragraph' when appropriate.
25990 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
25991 ; Adaptive filling: To get full control, first make sure that
25992 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
25993 (org-set-local 'adaptive-fill-regexp "\000")
25994 (org-set-local 'adaptive-fill-function
25995 'org-adaptive-fill-function))
25997 (defun org-fill-paragraph (&optional justify)
25998 "Re-align a table, pass through to fill-paragraph if no table."
25999 (let ((table-p (org-at-table-p))
26000 (table.el-p (org-at-table.el-p)))
26001 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26002 (table.el-p t) ; skip table.el tables
26003 (table-p (org-table-align) t) ; align org-mode tables
26004 (t nil)))) ; call paragraph-fill
26006 ;; For reference, this is the default value of adaptive-fill-regexp
26007 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26009 (defun org-adaptive-fill-function ()
26010 "Return a fill prefix for org-mode files.
26011 In particular, this makes sure hanging paragraphs for hand-formatted lists
26012 work correctly."
26013 (cond ((looking-at "#[ \t]+")
26014 (match-string 0))
26015 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26016 (save-excursion
26017 (goto-char (match-end 0))
26018 (make-string (current-column) ?\ )))
26019 (t nil)))
26021 ;;;; Functions extending outline functionality
26023 (defun org-beginning-of-line (&optional arg)
26024 "Go to the beginning of the current line. If that is invisible, continue
26025 to a visible line beginning. This makes the function of C-a more intuitive.
26026 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26027 first attempt, and only move to after the tags when the cursor is already
26028 beyond the end of the headline."
26029 (interactive "P")
26030 (let ((pos (point)))
26031 (beginning-of-line 1)
26032 (if (bobp)
26034 (backward-char 1)
26035 (if (org-invisible-p)
26036 (while (and (not (bobp)) (org-invisible-p))
26037 (backward-char 1)
26038 (beginning-of-line 1))
26039 (forward-char 1)))
26040 (when org-special-ctrl-a/e
26041 (cond
26042 ((and (looking-at org-todo-line-regexp)
26043 (= (char-after (match-end 1)) ?\ ))
26044 (goto-char
26045 (if (eq org-special-ctrl-a/e t)
26046 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26047 ((= pos (point)) (match-beginning 3))
26048 (t (point)))
26049 (cond ((> pos (point)) (point))
26050 ((not (eq last-command this-command)) (point))
26051 (t (match-beginning 3))))))
26052 ((org-at-item-p)
26053 (goto-char
26054 (if (eq org-special-ctrl-a/e t)
26055 (cond ((> pos (match-end 4)) (match-end 4))
26056 ((= pos (point)) (match-end 4))
26057 (t (point)))
26058 (cond ((> pos (point)) (point))
26059 ((not (eq last-command this-command)) (point))
26060 (t (match-end 4))))))))))
26062 (defun org-end-of-line (&optional arg)
26063 "Go to the end of the line.
26064 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26065 first attempt, and only move to after the tags when the cursor is already
26066 beyond the end of the headline."
26067 (interactive "P")
26068 (if (or (not org-special-ctrl-a/e)
26069 (not (org-on-heading-p)))
26070 (end-of-line arg)
26071 (let ((pos (point)))
26072 (beginning-of-line 1)
26073 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26074 (if (eq org-special-ctrl-a/e t)
26075 (if (or (< pos (match-beginning 1))
26076 (= pos (match-end 0)))
26077 (goto-char (match-beginning 1))
26078 (goto-char (match-end 0)))
26079 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26080 (goto-char (match-end 0))
26081 (goto-char (match-beginning 1))))
26082 (end-of-line arg)))))
26084 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26085 (define-key org-mode-map "\C-e" 'org-end-of-line)
26087 (defun org-invisible-p ()
26088 "Check if point is at a character currently not visible."
26089 ;; Early versions of noutline don't have `outline-invisible-p'.
26090 (if (fboundp 'outline-invisible-p)
26091 (outline-invisible-p)
26092 (get-char-property (point) 'invisible)))
26094 (defun org-invisible-p2 ()
26095 "Check if point is at a character currently not visible."
26096 (save-excursion
26097 (if (and (eolp) (not (bobp))) (backward-char 1))
26098 ;; Early versions of noutline don't have `outline-invisible-p'.
26099 (if (fboundp 'outline-invisible-p)
26100 (outline-invisible-p)
26101 (get-char-property (point) 'invisible))))
26103 (defalias 'org-back-to-heading 'outline-back-to-heading)
26104 (defalias 'org-on-heading-p 'outline-on-heading-p)
26105 (defalias 'org-at-heading-p 'outline-on-heading-p)
26106 (defun org-at-heading-or-item-p ()
26107 (or (org-on-heading-p) (org-at-item-p)))
26109 (defun org-on-target-p ()
26110 (or (org-in-regexp org-radio-target-regexp)
26111 (org-in-regexp org-target-regexp)))
26113 (defun org-up-heading-all (arg)
26114 "Move to the heading line of which the present line is a subheading.
26115 This function considers both visible and invisible heading lines.
26116 With argument, move up ARG levels."
26117 (if (fboundp 'outline-up-heading-all)
26118 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26119 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26121 (defun org-up-heading-safe ()
26122 "Move to the heading line of which the present line is a subheading.
26123 This version will not throw an error. It will return the level of the
26124 headline found, or nil if no higher level is found."
26125 (let ((pos (point)) start-level level
26126 (re (concat "^" outline-regexp)))
26127 (catch 'exit
26128 (outline-back-to-heading t)
26129 (setq start-level (funcall outline-level))
26130 (if (equal start-level 1) (throw 'exit nil))
26131 (while (re-search-backward re nil t)
26132 (setq level (funcall outline-level))
26133 (if (< level start-level) (throw 'exit level)))
26134 nil)))
26136 (defun org-goto-sibling (&optional previous)
26137 "Goto the next sibling, even if it is invisible.
26138 When PREVIOUS is set, go to the previous sibling instead. Returns t
26139 when a sibling was found. When none is found, return nil and don't
26140 move point."
26141 (let ((fun (if previous 're-search-backward 're-search-forward))
26142 (pos (point))
26143 (re (concat "^" outline-regexp))
26144 level l)
26145 (when (condition-case nil (org-back-to-heading t) (error nil))
26146 (setq level (funcall outline-level))
26147 (catch 'exit
26148 (or previous (forward-char 1))
26149 (while (funcall fun re nil t)
26150 (setq l (funcall outline-level))
26151 (when (< l level) (goto-char pos) (throw 'exit nil))
26152 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26153 (goto-char pos)
26154 nil))))
26156 (defun org-show-siblings ()
26157 "Show all siblings of the current headline."
26158 (save-excursion
26159 (while (org-goto-sibling) (org-flag-heading nil)))
26160 (save-excursion
26161 (while (org-goto-sibling 'previous)
26162 (org-flag-heading nil))))
26164 (defun org-show-hidden-entry ()
26165 "Show an entry where even the heading is hidden."
26166 (save-excursion
26167 (org-show-entry)))
26169 (defun org-flag-heading (flag &optional entry)
26170 "Flag the current heading. FLAG non-nil means make invisible.
26171 When ENTRY is non-nil, show the entire entry."
26172 (save-excursion
26173 (org-back-to-heading t)
26174 ;; Check if we should show the entire entry
26175 (if entry
26176 (progn
26177 (org-show-entry)
26178 (save-excursion
26179 (and (outline-next-heading)
26180 (org-flag-heading nil))))
26181 (outline-flag-region (max (point-min) (1- (point)))
26182 (save-excursion (outline-end-of-heading) (point))
26183 flag))))
26185 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26186 ;; This is an exact copy of the original function, but it uses
26187 ;; `org-back-to-heading', to make it work also in invisible
26188 ;; trees. And is uses an invisible-OK argument.
26189 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26190 (org-back-to-heading invisible-OK)
26191 (let ((first t)
26192 (level (funcall outline-level)))
26193 (while (and (not (eobp))
26194 (or first (> (funcall outline-level) level)))
26195 (setq first nil)
26196 (outline-next-heading))
26197 (unless to-heading
26198 (if (memq (preceding-char) '(?\n ?\^M))
26199 (progn
26200 ;; Go to end of line before heading
26201 (forward-char -1)
26202 (if (memq (preceding-char) '(?\n ?\^M))
26203 ;; leave blank line before heading
26204 (forward-char -1))))))
26205 (point))
26207 (defun org-show-subtree ()
26208 "Show everything after this heading at deeper levels."
26209 (outline-flag-region
26210 (point)
26211 (save-excursion
26212 (outline-end-of-subtree) (outline-next-heading) (point))
26213 nil))
26215 (defun org-show-entry ()
26216 "Show the body directly following this heading.
26217 Show the heading too, if it is currently invisible."
26218 (interactive)
26219 (save-excursion
26220 (condition-case nil
26221 (progn
26222 (org-back-to-heading t)
26223 (outline-flag-region
26224 (max (point-min) (1- (point)))
26225 (save-excursion
26226 (re-search-forward
26227 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26228 (or (match-beginning 1) (point-max)))
26229 nil))
26230 (error nil))))
26232 (defun org-make-options-regexp (kwds)
26233 "Make a regular expression for keyword lines."
26234 (concat
26236 "#?[ \t]*\\+\\("
26237 (mapconcat 'regexp-quote kwds "\\|")
26238 "\\):[ \t]*"
26239 "\\(.+\\)"))
26241 ;; Make isearch reveal the necessary context
26242 (defun org-isearch-end ()
26243 "Reveal context after isearch exits."
26244 (when isearch-success ; only if search was successful
26245 (if (featurep 'xemacs)
26246 ;; Under XEmacs, the hook is run in the correct place,
26247 ;; we directly show the context.
26248 (org-show-context 'isearch)
26249 ;; In Emacs the hook runs *before* restoring the overlays.
26250 ;; So we have to use a one-time post-command-hook to do this.
26251 ;; (Emacs 22 has a special variable, see function `org-mode')
26252 (unless (and (boundp 'isearch-mode-end-hook-quit)
26253 isearch-mode-end-hook-quit)
26254 ;; Only when the isearch was not quitted.
26255 (org-add-hook 'post-command-hook 'org-isearch-post-command
26256 'append 'local)))))
26258 (defun org-isearch-post-command ()
26259 "Remove self from hook, and show context."
26260 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26261 (org-show-context 'isearch))
26264 ;;;; Address problems with some other packages
26266 ;; Make flyspell not check words in links, to not mess up our keymap
26267 (defun org-mode-flyspell-verify ()
26268 "Don't let flyspell put overlays at active buttons."
26269 (not (get-text-property (point) 'keymap)))
26271 ;; Make `bookmark-jump' show the jump location if it was hidden.
26272 (eval-after-load "bookmark"
26273 '(if (boundp 'bookmark-after-jump-hook)
26274 ;; We can use the hook
26275 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26276 ;; Hook not available, use advice
26277 (defadvice bookmark-jump (after org-make-visible activate)
26278 "Make the position visible."
26279 (org-bookmark-jump-unhide))))
26281 (defun org-bookmark-jump-unhide ()
26282 "Unhide the current position, to show the bookmark location."
26283 (and (org-mode-p)
26284 (or (org-invisible-p)
26285 (save-excursion (goto-char (max (point-min) (1- (point))))
26286 (org-invisible-p)))
26287 (org-show-context 'bookmark-jump)))
26289 ;; Make session.el ignore our circular variable
26290 (eval-after-load "session"
26291 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26293 ;;;; Experimental code
26295 (defun org-closed-in-range ()
26296 "Sparse tree of items closed in a certain time range.
26297 Still experimental, may disappear in the furture."
26298 (interactive)
26299 ;; Get the time interval from the user.
26300 (let* ((time1 (time-to-seconds
26301 (org-read-date nil 'to-time nil "Starting date: ")))
26302 (time2 (time-to-seconds
26303 (org-read-date nil 'to-time nil "End date:")))
26304 ;; callback function
26305 (callback (lambda ()
26306 (let ((time
26307 (time-to-seconds
26308 (apply 'encode-time
26309 (org-parse-time-string
26310 (match-string 1))))))
26311 ;; check if time in interval
26312 (and (>= time time1) (<= time time2))))))
26313 ;; make tree, check each match with the callback
26314 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26316 (defun org-fill-paragraph-experimental (&optional justify)
26317 "Re-align a table, pass through to fill-paragraph if no table."
26318 (let ((table-p (org-at-table-p))
26319 (table.el-p (org-at-table.el-p)))
26320 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26321 (table.el-p t) ; skip table.el tables
26322 (table-p (org-table-align) t) ; align org-mode tables
26323 ((save-excursion
26324 (let ((pos (1+ (point-at-eol))))
26325 (backward-paragraph 1)
26326 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26327 (save-excursion
26328 (save-restriction
26329 (narrow-to-region (1+ (match-end 0)) (point-max))
26330 (fill-paragraph nil)
26331 t)))
26332 (t nil)))) ; call paragraph-fill
26334 ;; FIXME: this needs a much better algorithm
26335 (defun org-assign-fast-keys (alist)
26336 "Assign fast keys to a keyword-key alist.
26337 Respect keys that are already there."
26338 (let (new e k c c1 c2 (char ?a))
26339 (while (setq e (pop alist))
26340 (cond
26341 ((equal e '(:startgroup)) (push e new))
26342 ((equal e '(:endgroup)) (push e new))
26344 (setq k (car e) c2 nil)
26345 (if (cdr e)
26346 (setq c (cdr e))
26347 ;; automatically assign a character.
26348 (setq c1 (string-to-char
26349 (downcase (substring
26350 k (if (= (string-to-char k) ?@) 1 0)))))
26351 (if (or (rassoc c1 new) (rassoc c1 alist))
26352 (while (or (rassoc char new) (rassoc char alist))
26353 (setq char (1+ char)))
26354 (setq c2 c1))
26355 (setq c (or c2 char)))
26356 (push (cons k c) new))))
26357 (nreverse new)))
26359 ;;;; Finish up
26361 (provide 'org)
26363 (run-hooks 'org-load-hook)
26365 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
26366 ;;; org.el ends here